Programs & Examples On #Private

Private is a way of encapsulation in object-oriented programming.

Private Variables and Methods in Python

Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.

Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.

How to read the value of a private field from a different class in Java?

One other option that hasn't been mentioned yet: use Groovy. Groovy allows you to access private instance variables as a side effect of the design of the language. Whether or not you have a getter for the field, you can just use

def obj = new IWasDesignedPoorly()
def hashTable = obj.getStuffIWant()

JUnit Testing private variables?

Yeah you can use reflections to access private variables. Altough not a good idea.

Check this out:

http://en.wikibooks.org/wiki/Java_Programming/Reflection/Accessing_Private_Features_with_Reflection

Any way to Invoke a private method?

One more variant is using very powerfull JOOR library https://github.com/jOOQ/jOOR

MyObject myObject = new MyObject()
on(myObject).get("privateField");  

It allows to modify any fields like final static constants and call yne protected methods without specifying concrete class in the inheritance hierarhy

<!-- https://mvnrepository.com/artifact/org.jooq/joor-java-8 -->
<dependency>
     <groupId>org.jooq</groupId>
     <artifactId>joor-java-8</artifactId>
     <version>0.9.7</version>
</dependency>

How to access private data members outside the class without making "friend"s?

iData is a private member of the class. Now, the word private have a very definite meaning, in C++ as well as in real life. It means you can't touch it. It's not a recommendation, it's the law. If you don't change the class declaration, you are not allowed to manipulate that member in any way, shape or form.

private final static attribute vs private final attribute

As already Jon said, a static variable, also referred to as a class variable, is a variable which exists across instances of a class.

I found an example of this here:

public class StaticVariable
{
  static int noOfInstances;
  StaticVariable()
  {
    noOfInstances++;
  }
  public static void main(String[] args)
  {
    StaticVariable sv1 = new StaticVariable();
    System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);

    StaticVariable sv2 = new StaticVariable();
    System.out.println("No. of instances for sv1 : "  + sv1.noOfInstances);
    System.out.println("No. of instances for st2 : "  + sv2.noOfInstances);

    StaticVariable sv3 = new StaticVariable();
    System.out.println("No. of instances for sv1 : "  + sv1.noOfInstances);
    System.out.println("No. of instances for sv2 : "  + sv2.noOfInstances);
    System.out.println("No. of instances for sv3 : "  + sv3.noOfInstances);
  }
}

Output of the program is given below:

As we can see in this example each object has its own copy of class variable.

C:\java>java StaticVariable
No. of instances for sv1 : 1
No. of instances for sv1 : 2
No. of instances for st2 : 2
No. of instances for sv1 : 3
No. of instances for sv2 : 3
No. of instances for sv3 : 3

Private class declaration

private modifier will make your class inaccessible from outside, so there wouldn't be any advantage of this and I think that is why it is illegal and only public, abstract & final are permitted.

Note : Even you can not make it protected.

Internal vs. Private Access Modifiers

private - encapsulations in class/scope/struct ect'.

internal - encapsulation in assemblies.

Change private static final field using Java reflection

Just saw that question on one of the interview question, if possible to change final variable with reflection or in runtime. Got really interested, so that what I became with:

 /**
 * @author Dmitrijs Lobanovskis
 * @since 03/03/2016.
 */
public class SomeClass {

    private final String str;

    SomeClass(){
        this.str = "This is the string that never changes!";
    }

    public String getStr() {
        return str;
    }

    @Override
    public String toString() {
        return "Class name: " + getClass() + " Value: " + getStr();
    }
}

Some simple class with final String variable. So in the main class import java.lang.reflect.Field;

/**
 * @author Dmitrijs Lobanovskis
 * @since 03/03/2016.
 */
public class Main {


    public static void main(String[] args) throws Exception{

        SomeClass someClass = new SomeClass();
        System.out.println(someClass);

        Field field = someClass.getClass().getDeclaredField("str");
        field.setAccessible(true);

        field.set(someClass, "There you are");

        System.out.println(someClass);
    }
}

The output will be as follows:

Class name: class SomeClass Value: This is the string that never changes!
Class name: class SomeClass Value: There you are

Process finished with exit code 0

According to documentation https://docs.oracle.com/javase/tutorial/reflect/member/fieldValues.html

static constructors in C++? I need to initialize private static objects

Wow, I can't believe no one mentioned the most obvious answer, and one that most closely mimics C#'s static-constructor behavior, i.e. it doesn't get called until the first object of that type is created.

std::call_once() is available in C++11; if you can't use that, it can be done with a static boolean class-variable, and a compare-and-exchange atomic-operation. In your constructor, see if you can atomically change the class-static flag from false to true, and if so, you can run the static-construction code.

For extra credit, make it a 3-way flag instead of a boolean, i.e. not run, running, and done running. Then all other instances of that class can spin-lock until the instance running the static-constructor has finished (i.e. issue a memory-fence, then set the state to "done running"). Your spin-lock should execute the processor's "pause" instruction, double the wait each time up until a threshold, etc. — pretty standard spin-locking technique.

In the absence of C++11, this should get you started.

Here's some pseudocode to guide you. Put this in your class definition:

enum EStaticConstructor { kNotRun, kRunning, kDone };
static volatile EStaticConstructor sm_eClass = kNotRun;

And this in your constructor:

while (sm_eClass == kNotRun)
{
    if (atomic_compare_exchange_weak(&sm_eClass, kNotRun, kRunning))
    {
        /* Perform static initialization here. */

        atomic_thread_fence(memory_order_release);
        sm_eClass = kDone;
    }
}
while (sm_eClass != kDone)
    atomic_pause();

Does Python have “private” variables in classes?

"In java, we have been taught about public/private/protected variables"

"Why is that not required in python?"

For the same reason, it's not required in Java.

You're free to use -- or not use private and protected.

As a Python and Java programmer, I've found that private and protected are very, very important design concepts. But as a practical matter, in tens of thousands of lines of Java and Python, I've never actually used private or protected.

Why not?

Here's my question "protected from whom?"

Other programmers on my team? They have the source. What does protected mean when they can change it?

Other programmers on other teams? They work for the same company. They can -- with a phone call -- get the source.

Clients? It's work-for-hire programming (generally). The clients (generally) own the code.

So, who -- precisely -- am I protecting it from?

What is the difference between private and protected members of C++ classes?

Public members of a class A are accessible for all and everyone.

Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.

Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.

So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?

By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.

What is the difference between public, private, and protected?

Reviving an old question, but I think a really good way to think of this is in terms of the API that you are defining.

  • public - Everything marked public is part of the API that anyone using your class/interface/other will use and rely on.

  • protected - Don't be fooled, this is also part of the API! People can subclass, extend your code and use anything marked protected.

  • private - Private properties and methods can be changed as much as you like. No one else can use these. These are the only things you can change without making breaking changes.

Or in Semver terms:

  • Changes to anything public or protected should be considered MAJOR changes.

  • Anything new public or protected should be (at least) MINOR

  • Only new/changes to anything private can be PATCH

So in terms of maintaining code, its good to be careful about what things you make public or protected because these are the things you are promising to your users.

Can a constructor in Java be private?

According to me we can declare constructor as a private and also we can get the instance of that class in the subclass by using static method in class in which we declare constructor and then return class object. we class this method from to the sub class by using classname.method name bcz it is static method and the we will get the instance of class in which we declare const.

What is the use of a private static variable in Java?

For some people this makes more sense if they see it in a couple different languages so I wrote an example in Java, and PHP on my page where I explain some of these modifiers. You might be thinking about this incorrectly.

You should look at my examples if it doesn't make sense below. Go here http://www.siteconsortium.com/h/D0000D.php

The bottom line though is that it is pretty much exactly what it says it is. It's a static member variable that is private. For example if you wanted to create a Singleton object why would you want to make the SingletonExample.instance variable public. If you did a person who was using the class could easily overwrite the value.

That's all it is.


    public class SingletonExample {
      private static SingletonExample instance = null;
      private static int value = 0;
      private SingletonExample() {
        ++this.value;
      }
      public static SingletonExample getInstance() {
        if(instance!=null)
        return instance;
        synchronized(SingletonExample.class) {
        instance = new SingletonExample();
        return instance;
        }
      }
      public void printValue() {
        System.out.print( this.value );
      }

      public static void main(String [] args) {
        SingletonExample instance = getInstance();
        instance.printValue();
        instance = getInstance();
        instance.printValue();
         }
    }

Python read-only property

While I like the class decorator from Oz123, you could also do the following, which uses an explicit class wrapper and __new__ with a class Factory method returning the class within a closure:

class B(object):
    def __new__(cls, val):
        return cls.factory(val)

@classmethod
def factory(cls, val):
    private = {'var': 'test'}

    class InnerB(object):
        def __init__(self):
            self.variable = val
            pass

        @property
        def var(self):
            return private['var']

    return InnerB()

Defining private module functions in python

embedded with closures or functions is one way. This is common in JS although not required for non-browser platforms or browser workers.

In Python it seems a bit strange, but if something really needs to be hidden than that might be the way. More to the point using the python API and keeping things that require to be hidden in the C (or other language) is probably the best way. Failing that I would go for putting the code inside a function, calling that and having it return the items you want to export.

Do subclasses inherit private fields?

Well, my answer to interviewer's question is - Private members are not inherited in sub-classes but they are accessible to subclass or subclass's object only via public getter or setter methods or any such appropriate methods of original class. The normal practice is to keep the members private and access them using getter and setter methods which are public. So whats the point in only inheriting getter and setter methods when the private member they deal with are not available to the object? Here 'inherited' simply means it is available directly in the sub-class to play around by newly introduced methods in sub-class.

Save the below file as ParentClass.java and try it yourself ->

public class ParentClass {
  private int x;

  public int getX() {
    return x;
  }

  public void setX(int x) {
    this.x = x;
  }
}

class SubClass extends ParentClass {
  private int y;

  public int getY() {
    return y;
  }

  public void setY(int y) {
    this.y = y;
  }

  public void setXofParent(int x) {
    setX(x); 
  }
}

class Main {
  public static void main(String[] args) {
    SubClass s = new SubClass();
    s.setX(10);
    s.setY(12);
    System.out.println("X is :"+s.getX());
    System.out.println("Y is :"+s.getY());
    s.setXofParent(13);
    System.out.println("Now X is :"+s.getX());
  }
}

Output:
X is :10
Y is :12
Now X is :13

If we try to use private variable x of ParentClass in SubClass's method then it is not directly accessible for any modifications (means not inherited). But x can be modified in SubClass via setX() method of original class as done in setXofParent() method OR it can be modified using ChildClass object using setX() method or setXofParent() method which ultimately calls setX(). So here setX() and getX() are kind of gates to the private member x of a ParentClass.

Another simple example is Clock superclass has hours and mins as private members and appropriate getter and setter methods as public. Then comes DigitalClock as a sub-class of Clock. Here if the DigitalClock's object doesn't contain hours and mins members then things are screwed up.

What are access specifiers? Should I inherit with private, protected or public?

The explanation from Scott Meyers in Effective C++ might help understand when to use them:

Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.

How do you unit test private methods?

If you want to unit test a private method, something may be wrong. Unit tests are (generally speaking) meant to test the interface of a class, meaning its public (and protected) methods. You can of course "hack" a solution to this (even if just by making the methods public), but you may also want to consider:

  1. If the method you'd like to test is really worth testing, it may be worth to move it into its own class.
  2. Add more tests to the public methods that call the private method, testing the private method's functionality. (As the commentators indicated, you should only do this if these private methods's functionality is really a part in with the public interface. If they actually perform functions that are hidden from the user (i.e. the unit test), this is probably bad).

Cloning a private Github repo

This worked for me:

git clone https://[email protected]/username/repo_name

What is the difference between public, protected, package-private and private in Java?

Private: Limited access to class only

Default (no modifier): Limited access to class and package

Protected: Limited access to class, package and subclasses (both inside and outside package)

Public: Accessible to class, package (all), and subclasses... In short, everywhere.

Centering the image in Bootstrap

.img-responsive {
     margin: 0 auto;
 }

you can write like above code in your document so no need to add one another class in image tag.

How to get substring in C

If you just want to print the substrings ...

char s[] = "THESTRINGHASNOSPACES";
size_t i, slen = strlen(s);
for (i = 0; i < slen; i += 4) {
  printf("%.4s\n", s + i);
}

Convert audio files to mp3 using ffmpeg

For batch processing files in folder:

for i in *.wav; do ffmpeg -i "$i" -f mp3 "${i%}.mp3"; done

This script converts all "wav" files in folder to mp3 files and adds mp3 extension

ffmpeg have to be installed. (See other answers)

JTable - Selected Row click event

To learn what row was selected, add a ListSelectionListener, as shown in How to Use Tables in the example SimpleTableSelectionDemo. A JList can be constructed directly from the linked list's toArray() method, and you can add a suitable listener to it for details.

Print page numbers on pages when printing html

This javascript will add absolute positioned div's with pagenumbers on the right bottom corner and works in all browsers.

A4 height = 297mm = 1123px(96dpi)

<html>
    <head>
        <style type="text/css">
            @page {
              size: A4;
              margin: 0; 
            }

            body {
              margin: 0;
            }
        </style>
    </head>
    <body>
        <script type="text/javascript">
          window.onload = addPageNumbers;

          function addPageNumbers() {
            var totalPages = Math.ceil(document.body.scrollHeight / 1123);  //842px A4 pageheight for 72dpi, 1123px A4 pageheight for 96dpi, 
            for (var i = 1; i <= totalPages; i++) {
              var pageNumberDiv = document.createElement("div");
              var pageNumber = document.createTextNode("Page " + i + " of " + totalPages);
              pageNumberDiv.style.position = "absolute";
              pageNumberDiv.style.top = "calc((" + i + " * (297mm - 0.5px)) - 40px)"; //297mm A4 pageheight; 0,5px unknown needed necessary correction value; additional wanted 40px margin from bottom(own element height included)
              pageNumberDiv.style.height = "16px";
              pageNumberDiv.appendChild(pageNumber);
              document.body.insertBefore(pageNumberDiv, document.getElementById("content"));
              pageNumberDiv.style.left = "calc(100% - (" + pageNumberDiv.offsetWidth + "px + 20px))";
            }
          }
        </script>
        <div id="content">
            Lorem ipsum....
        </div>
    </body>
</html>

jQuery & CSS - Remove/Add display:none

In JavaScript:

getElementById("id").style.display = null;

In jQuery:

$("#id").css("display","");

How can I use xargs to copy files that have spaces and quotes in their names?

Frame challenge — you're asking how to use xargs. The answer is: you don't use xargs, because you don't need it.

The comment by user80168 describes a way to do this directly with cp, without calling cp for every file:

find . -name '*FooBar*' -exec cp -t /tmp -- {} +

This works because:

  • the cp -t flag allows to give the target directory near the beginning of cp, rather than near the end. From man cp:
   -t, --target-directory=DIRECTORY
         copy all SOURCE arguments into DIRECTORY
  • The -- flag tells cp to interpret everything after as a filename, not a flag, so files starting with - or -- do not confuse cp; you still need this because the -/-- characters are interpreted by cp, whereas any other special characters are interpreted by the shell.

  • The find -exec command {} + variant essentially does the same as xargs. From man find:

   -exec command {} +                                                     
         This  variant  of the -exec action runs the specified command on
         the selected files, but the command line is built  by  appending
         each  selected file name at the end; the total number of invoca-
         matched  files.   The command line is built in much the same way
         that xargs builds its command lines.  Only one instance of  `{}'
         is  allowed  within the command, and (when find is being invoked
         from a shell) it should be quoted (for example, '{}') to protect
         it  from  interpretation  by shells.  The command is executed in
         the starting directory.  If any invocation  returns  a  non-zero
         value  as exit status, then find returns a non-zero exit status.
         If find encounters an error, this can sometimes cause an immedi-
         ate  exit, so some pending commands may not be run at all.  This
         variant of -exec always returns true.

By using this in find directly, this avoids the need of a pipe or a shell invocation, such that you don't need to worry about any nasty characters in filenames.

Android - how to make a scrollable constraintlayout?

There is a type of constraint which breaks the scroll function:

Just make sure you are not using this constraint on any view when wanting your ConstraintLayout to be scrollable with ScrollView :

app:layout_constraintBottom_toBottomOf=“parent”

If you remove these your scroll should work.

Explanation:

Setting the height of the child to match that of a ScrollView parent is contradictory to what the component is meant to do. What we want most of the time is for some dynamic sized content to be scrollable when it is larger than a screen/frame; matching the height with the parent ScrollView would force all the content to be displayed into a fixed frame (the height of the parent) hence invalidating any scrolling functionality.

This also happens when regular direct child components are set to layout_height="match_parent".

If you want the child of the ScrollView to match the height of the parent when there is not enough content, simply set android:fillViewport to true for the ScrollView.

Can a Windows batch file determine its own file name?

Using the following script, based on SLaks answer, I determined that the correct answer is:

echo The name of this file is: %~n0%~x0
echo The name of this file is: %~nx0

And here is my test script:

@echo off
echo %0
echo %~0
echo %n0
echo %x0
echo %~n0
echo %dp0
echo %~dp0
pause

What I find interesting is that %nx0 won't work, given that we know the '~' char usually is used to strip/trim quotes off of a variable.

How to add Certificate Authority file in CentOS 7

Your CA file must have been in a binary X.509 format instead of Base64 encoding; it needs to be a regular DER or PEM in order for it to be added successfully to the list of trusted CAs on your server.

To proceed, do place your CA file inside your /usr/share/pki/ca-trust-source/anchors/ directory, then run the command line below (you might need sudo privileges based on your settings);

# CentOS 7, Red Hat 7, Oracle Linux 7
update-ca-trust

Please note that all trust settings available in the /usr/share/pki/ca-trust-source/anchors/ directory are interpreted with a lower priority compared to the ones placed under the /etc/pki/ca-trust/source/anchors/ directory which may be in the extended BEGIN TRUSTED file format.

For Ubuntu and Debian systems, /usr/local/share/ca-certificates/ is the preferred directory for that purpose.

As such, you need to place your CA file within the /usr/local/share/ca-certificates/ directory, then update the of trusted CAs by running, with sudo privileges where required, the command line below;

update-ca-certificates

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

if your application accepts errors raise from Oracle, then you can use it. we have an application, each time when an error happens, we call raise_application_error, the application will popup a red box to show the error message we provide through this method.

When using dotnet code, I just use "raise", dotnet exception mechanisim will automatically capture the error passed by Oracle ODP and shown inside my catch exception code.

Process with an ID #### is not running in visual studio professional 2013 update 3

What I did to make this go away:

Open C:\Users\gr_mext1\Documents\IISExpress\config\applicationhost.config and remove all <site> entries in <sites> do not remove <siteDefaults>!

In your project, go to Properties, Web and click "Create Virtual Directory".

Close and re-open visual studio, load your project and run

Fixed!

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

Take a look at svnmerge.py. It's command-line, can't be invoked by TortoiseSVN, but it's more powerful. From the FAQ:

Traditional subversion will let you merge changes, but it doesn't "remember" what you've already merged. It also doesn't provide a convenient way to exclude a change set from being merged. svnmerge.py automates some of the work, and simplifies it. Svnmerge also creates a commit message with the log messages from all of the things it merged.

Best way to convert text files between character sets?

Get-Content -Encoding UTF8 FILE-UTF8.TXT | Out-File -Encoding UTF7 FILE-UTF7.TXT

The shortest version, if you can assume that the input BOM is correct:

gc FILE.TXT | Out-File -en utf7 file-utf7.txt

PostgreSQL database default location on Linux

I think best method is to query pg_setting view:

 select s.name, s.setting, s.short_desc from pg_settings s where s.name='data_directory';

Output:

      name      |        setting         |            short_desc
----------------+------------------------+-----------------------------------
 data_directory | /var/lib/pgsql/10/data | Sets the server's data directory.
(1 row)

Setting dynamic scope variables in AngularJs - scope.<some_string>

The solution I have found is to use $parse.

"Converts Angular expression into a function."

If anyone has a better one please add a new answer to the question!

Here is the example:

var the_string = 'life.meaning';

// Get the model
var model = $parse(the_string);

// Assigns a value to it
model.assign($scope, 42);

// Apply it to the scope
// $scope.$apply(); <- According to comments, this is no longer needed

console.log($scope.life.meaning);  // logs 42

Cannot delete directory with Directory.Delete(path, true)

I've had this same problem with Windows Workflow Foundation on a build server with TFS2012. Internally, the workflow called Directory.Delete() with the recursive flag set to true. It appears to be network related in our case.

We were deleting a binary drop folder on a network share before re-creating and re-populating it with the latest binaries. Every other build would fail. When opening the drop folder after a failed build, the folder was empty, which indicates that every aspect of the Directory.Delete() call was successful except for deleting the actually directory.

The problem appears to be caused by the asynchronous nature of network file communications. The build server told the file server to delete all of the files and the file server reported that it had, even though it wasn't completely finished. Then the build server requested that the directory be deleted and the file server rejected the request because it hadn't completely finished deleting the files.

Two possible solutions in our case:

  • Build up the recursive deletion in our own code with delays and verifications between each step
  • Retry up to X times after an IOException, giving a delay before trying again

The latter method is quick and dirty but seems to do the trick.

Better way to shuffle two numpy arrays in unison

Shuffle any number of arrays together, in-place, using only NumPy.

import numpy as np


def shuffle_arrays(arrays, set_seed=-1):
    """Shuffles arrays in-place, in the same order, along axis=0

    Parameters:
    -----------
    arrays : List of NumPy arrays.
    set_seed : Seed value if int >= 0, else seed is random.
    """
    assert all(len(arr) == len(arrays[0]) for arr in arrays)
    seed = np.random.randint(0, 2**(32 - 1) - 1) if set_seed < 0 else set_seed

    for arr in arrays:
        rstate = np.random.RandomState(seed)
        rstate.shuffle(arr)

And can be used like this

a = np.array([1, 2, 3, 4, 5])
b = np.array([10,20,30,40,50])
c = np.array([[1,10,11], [2,20,22], [3,30,33], [4,40,44], [5,50,55]])

shuffle_arrays([a, b, c])

A few things to note:

  • The assert ensures that all input arrays have the same length along their first dimension.
  • Arrays shuffled in-place by their first dimension - nothing returned.
  • Random seed within positive int32 range.
  • If a repeatable shuffle is needed, seed value can be set.

After the shuffle, the data can be split using np.split or referenced using slices - depending on the application.

Access the css ":after" selector with jQuery

You can't manipulate :after, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after specified.

CSS:

.pageMenu .active.changed:after { 
/* this selector is more specific, so it takes precedence over the other :after */
    border-top-width: 22px;
    border-left-width: 22px;
    border-right-width: 22px;
}

JS:

$('.pageMenu .active').toggleClass('changed');

UPDATE: while it's impossible to directly modify the :after content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.

Exception is never thrown in body of corresponding try statement

A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}-block can throw (or a super class of that).

try {
    //do something that throws ExceptionA, e.g.
    throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
    //do something to handle the exception, e.g.
    System.out.println("Message: " + e.getMessage());
}

What you are trying to do is this:

try {
    throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
    System.out.println("Message: " + e.getMessage());
}

This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement.

Deploying website: 500 - Internal server error

If you are using IIS 8.5 it may be that you need to change the ApplicationPool ID setting from ApplicationPoolId to NetworkService

Right click the Application Pool in question, click on "Advanced Settings" and then scroll down to ID - it will probably be set to ApplicationPoolIdentity. Click the button (..) and select NetworkService from the dropdown list instead.

Also make sure that if it is a .NET 2.0 application that you are not referencing the 4.0 framework in your App Pool.

How can I show an image using the ImageView component in javafx and fxml?

Please find below example to load image using JavaFX.

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;

    public class LoadImage extends Application {

    public static void main(String[] args) {
    Application.launch(args);
    }
    @Override
    public void start(Stage primaryStage) {
    primaryStage.setTitle("Load Image");

    StackPane sp = new StackPane();
    Image img = new Image("javafx.jpg");
    ImageView imgView = new ImageView(img);
    sp.getChildren().add(imgView);

    //Adding HBox to the scene
    Scene scene = new Scene(sp);
    primaryStage.setScene(scene);
    primaryStage.show();
    }

  }

Create one source folder with name Image in your project and add your image to that folder otherwise you can directly load image from external URL like following.

Image img = new Image("http://mikecann.co.uk/wp-content/uploads/2009/12/javafx_logo_color_1.jpg");

Check if option is selected with jQuery, if not select a default

I was just looking for something similar and found this:

$('.mySelect:not(:has(option[selected])) option[value="2"]').attr('selected', true);

This finds all select menus in the class that don't already have an option selected, and selects the default option ("2" in this case).

I tried using :selected instead of [selected], but that didn't work because something is always selected, even if nothing has the attribute

Google OAuth 2 authorization - Error: redirect_uri_mismatch

Don't forget to include the path after your domain and ip. In my case, I forgot:

/oauth2callback

Making a drop down list using swift?

You have to be sure to use UIPickerViewDataSource and UIPickerViewDelegate protocols or it will throw an AppDelegate error as of swift 3

Also please take note of the change in syntax:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int

is now:

public func numberOfComponents(in pickerView: UIPickerView) -> Int

The following below worked for me.

import UIkit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    @IBOutlet weak var textBox: UITextField!
    @IBOutlet weak var dropDown: UIPickerView!

    var list = ["1", "2", "3"]

    public func numberOfComponents(in pickerView: UIPickerView) -> Int{
        return 1
    }

    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{

        return list.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        self.view.endEditing(true)
        return list[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        self.textBox.text = self.list[row]
        self.dropDown.isHidden = true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

        if textField == self.textBox {
            self.dropDown.isHidden = false
            //if you don't want the users to se the keyboard type:

            textField.endEditing(true)
        }
    }
}

BackgroundWorker vs background Thread

Some of my thoughts...

  1. Use BackgroundWorker if you have a single task that runs in the background and needs to interact with the UI. The task of marshalling data and method calls to the UI thread are handled automatically through its event-based model. Avoid BackgroundWorker if...
    • your assembly does not have or does not interact directly with the UI,
    • you need the thread to be a foreground thread, or
    • you need to manipulate the thread priority.
  2. Use a ThreadPool thread when efficiency is desired. The ThreadPool helps avoid the overhead associated with creating, starting, and stopping threads. Avoid using the ThreadPool if...
    • the task runs for the lifetime of your application,
    • you need the thread to be a foreground thread,
    • you need to manipulate the thread priority, or
    • you need the thread to have a fixed identity (aborting, suspending, discovering).
  3. Use the Thread class for long-running tasks and when you require features offered by a formal threading model, e.g., choosing between foreground and background threads, tweaking the thread priority, fine-grained control over thread execution, etc.

Get file name from URL

import java.io.*;

import java.net.*;

public class ConvertURLToFileName{


   public static void main(String[] args)throws IOException{
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Please enter the URL : ");

   String str = in.readLine();


   try{

     URL url = new URL(str);

     System.out.println("File : "+ url.getFile());
     System.out.println("Converting process Successfully");

   }  
   catch (MalformedURLException me){

      System.out.println("Converting process error");

 }

I hope this will help you.

How to extend a class in python?

Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.

I've done this to extend Python 2's str() class, for instance. str() is a particularly interesting target because of the implicit linkage to quoted data such as 'this' and 'that'.

Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad bit:

extend:testDottedQuad
def testDottedQuad(strObject):
    if not isinstance(strObject, basestring): return False
    listStrings = strObject.split('.')
    if len(listStrings) != 4: return False
    for strNum in listStrings:
        try:    val = int(strNum)
        except: return False
        if val < 0: return False
        if val > 255: return False
    return True

After which I can write in the code fed to the preprocessor:

if '192.168.1.100'.testDottedQuad():
    doSomething()

dq = '216.126.621.5'
if not dq.testDottedQuad():
    throwWarning();

dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
    print 'well, that was fun'

The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.

Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.

My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.

Catch multiple exceptions at once?

In c# 6.0,Exception Filters is improvements for exception handling

try
{
    DoSomeHttpRequest();
}
catch (System.Web.HttpException e)
{
    switch (e.GetHttpCode())
    {
        case 400:
            WriteLine("Bad Request");
        case 500:
            WriteLine("Internal Server Error");
        default:
            WriteLine("Generic Error");
    }
}

JavaScript .replace only replaces first Match

You need a /g on there, like this:

_x000D_
_x000D_
var textTitle = "this is a test";_x000D_
var result = textTitle.replace(/ /g, '%20');_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

You can play with it here, the default .replace() behavior is to replace only the first match, the /g modifier (global) tells it to replace all occurrences.

MongoDB vs. Cassandra

I'm probably going to be an odd man out, but I think you need to stay with MySQL. You haven't described a real problem you need to solve, and MySQL/InnoDB is an excellent storage back-end even for blob/json data.

There is a common trick among Web engineers to try to use more NoSQL as soon as realization comes that not all features of an RDBMS are used. This alone is not a good reason, since most often NoSQL databases have rather poor data engines (what MySQL calls a storage engine).

Now, if you're not of that kind, then please specify what is missing in MySQL and you're looking for in a different database (like, auto-sharding, automatic failover, multi-master replication, a weaker data consistency guarantee in cluster paying off in higher write throughput, etc).

Can I convert a boolean to Yes/No in a ASP.NET GridView

It's easy with Format()-Function

Format(aBoolean, "YES/NO")

Please find details here: https://msdn.microsoft.com/en-us/library/aa241719(v=vs.60).aspx

Why do we have to normalize the input for an artificial neural network?

On a high level, if you observe as to where normalization/standardization is mostly used, you will notice that, anytime there is a use of magnitude difference in model building process, it becomes necessary to standardize the inputs so as to ensure that important inputs with small magnitude don't loose their significance midway the model building process.

example:

v(3-1)^2+(1000-900)^2 ˜ v(1000-900)^2

Here, (3-1) contributes hardly a thing to the result and hence the input corresponding to these values is considered futile by the model.

Consider the following:

  1. Clustering uses euclidean or, other distance measures.
  2. NNs use optimization algorithm to minimise cost function(ex. - MSE).

Both distance measure(Clustering) and cost function(NNs) use magnitude difference in some way and hence standardization ensures that magnitude difference doesn't command over important input parameters and the algorithm works as expected.

"starting Tomcat server 7 at localhost has encountered a prob"

In eclipse->in server tap-> double click on Tomcat server at localhost-> Ports -> HTTP/1.1

Default port number will be 8080. Change this to 8081. Tomcat version7.0

I have configured tomcat server also in NetBeans IDE 7.4 for JSP. So am facing this issue.

How do I write a bash script to restart a process if it dies?

I've used the following script with great success on numerous servers:

pid=`jps -v | grep $INSTALLATION | awk '{print $1}'`
echo $INSTALLATION found at PID $pid 
while [ -e /proc/$pid ]; do sleep 0.1; done

notes:

  • It's looking for a java process, so I can use jps, this is much more consistent across distributions than ps
  • $INSTALLATION contains enough of the process path that's it's totally unambiguous
  • Use sleep while waiting for the process to die, avoid hogging resources :)

This script is actually used to shut down a running instance of tomcat, which I want to shut down (and wait for) at the command line, so launching it as a child process simply isn't an option for me.

Angular 2 change event on every keypress

In my case, the solution is:

[ngModel]="X?.Y" (ngModelChange)="X.Y=$event"

Where does this come from: -*- coding: utf-8 -*-

This way of specifying the encoding of a Python file comes from PEP 0263 - Defining Python Source Code Encodings.

It is also recognized by GNU Emacs (see Python Language Reference, 2.1.4 Encoding declarations), though I don't know if it was the first program to use that syntax.

Learning Ruby on Rails

Oh I almost forgot. Here are a few more Ruby screencast resources:

SD Ruby - the have a bunch of videos online - I found their Rest talks SD9 and SD10 to be among the best of the intros. Other rest talks assume you know everything. These ones are very introductory and to the point.

Obie Fernandez on InfoQ - Restful Rails. I've also read his Rails Way book and found it informative but really long winded and meandering and the quality is a bit inconsistent. I learned a lot from this book but felt it was a bit punishing to have to read through the repetition and irrelevant stuff to get to the good bits.

Netbeans is a nice hand holding IDE that can teach you a lot of language tricks if you have the patience to wait for its tooltips (it is a painfully slow IDE even on a really fast machine) and you can use the IDE to graphically browse through the available generators and stuff like that. Get the latest builds and you even have Rspec test running built in.

Bort is a prebuilt base app with a lot of the standard plugins already plugged in. If you download it and play with it and figure out how it is setup you are about halfway to creating your own full featured apps.

Copy multiple files from one directory to another from Linux shell

Use wildcards:

cp /home/ankur/folder/* /home/ankur/dest

If you don't want to copy all the files, you can use braces to select files:

cp /home/ankur/folder/{file{1,2},xyz,abc} /home/ankur/dest

This will copy file1, file2, xyz, and abc.

You should read the sections of the bash man page on Brace Expansion and Pathname Expansion for all the ways you can simplify this.

Another thing you can do is cd /home/ankur/folder. Then you can type just the filenames rather than the full pathnames, and you can use filename completion by typing Tab.

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

Add querystring parameters to link_to

The API docs on link_to show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?

link_to can also produce links with anchors or query strings:

link_to "Comment wall", profile_path(@profile, :anchor => "wall")
#=> <a href="/profiles/1#wall">Comment wall</a>

link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
#=> <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>

link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
#=> <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>

How to check if an array element exists?

You can use the function array_key_exists to do that.

For example,

$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }

PS : Example taken from here.

Can I force a UITableView to hide the separator between empty cells?

If you use iOS 7 SDK, this is very simple.

Just add this line in your viewDidLoad method:

self.yourTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

A better way to check if a path exists or not in PowerShell

This is my powershell newbie way of doing this

if ((Test-Path ".\Desktop\checkfile.txt") -ne "True") {
    Write-Host "Damn it"
} else {
    Write-Host "Yay"
}

How to insert logo with the title of a HTML page?

Are you referring to the favicon?

Upload a 16x16px ico to your site, and link it in your head section.

<link rel="shortcut icon" href="/favicon.ico" />

There are a multitude of sites that help you convert images into .ico format too. This is just the first one I saw on Google. http://www.favicon.cc/

How to express a One-To-Many relationship in Django

django is smart enough. Actually we don't need to define oneToMany field. It will be automatically generated by django for you :-). We only need to define foreignKey in related table. In other words, we only need to define ManyToOne relation by using foreignKey.

class Car(models.Model):
    // wheels = models.oneToMany() to get wheels of this car [**it is not required to define**].


class Wheel(models.Model):
    car = models.ForeignKey(Car, on_delete=models.CASCADE)  

if we want to get the list of wheels of particular car. we will use python's auto generated object wheel_set. For car c you will use c.wheel_set.all()

How to enable bulk permission in SQL Server

Note that the accepted answer or either of these two solutions work for Windows only.

GRANT ADMINISTER BULK OPERATIONS TO [login_name];
-- OR
ALTER SERVER ROLE [bulkadmin] ADD MEMBER [login_name];

If you run any of them on SQL Server based on a linux machine, you will get these errors:

Msg 16202, Level 15, State 1, Line 1
Keyword or statement option 'bulkadmin' is not supported on the 'Linux' platform.
Msg 16202, Level 15, State 3, Line 1
Keyword or statement option 'ADMINISTER BULK OPERATIONS' is not supported on the 'Linux' platform.

Check the docs.

Requires INSERT and ADMINISTER BULK OPERATIONS permissions. In Azure SQL Database, INSERT and ADMINISTER DATABASE BULK OPERATIONS permissions are required. ADMINISTER BULK OPERATIONS permissions or the bulkadmin role is not supported for SQL Server on Linux. Only the sysadmin can perform bulk inserts for SQL Server on Linux.

Solution for Linux

ALTER SERVER ROLE [sysadmin] ADD MEMBER [login_name];

Selecting multiple columns in a Pandas dataframe

I found this method to be very useful:

# iloc[row slicing, column slicing]
surveys_df.iloc [0:3, 1:4]

More details can be found here.

Naming conventions for Java methods that return boolean

I want to point a different view on this general naming convention, e.g.:

see java.util.Set: boolean add?(E e)

where the rationale is:

do some processing then report whether it succeeded or not.

While the return is indeed a boolean the method's name should point the processing to complete instead of the result type (boolean for this example).

Your createFreshSnapshot example seems for me more related to this point of view because seems to mean this: create a fresh-snapshot then report whether the create-operation succeeded. Considering this reasoning the name createFreshSnapshot seems to be the best one for your situation.

Switch case on type c#

Here's an option that stays as true I could make it to the OP's requirement to be able to switch on type. If you squint hard enough it almost looks like a real switch statement.

The calling code looks like this:

var @switch = this.Switch(new []
{
    this.Case<WebControl>(x => { /* WebControl code here */ }),
    this.Case<TextBox>(x => { /* TextBox code here */ }),
    this.Case<ComboBox>(x => { /* ComboBox code here */ }),
});

@switch(obj);

The x in each lambda above is strongly-typed. No casting required.

And to make this magic work you need these two methods:

private Action<object> Switch(params Func<object, Action>[] tests)
{
    return o =>
    {
        var @case = tests
            .Select(f => f(o))
            .FirstOrDefault(a => a != null);

        if (@case != null)
        {
            @case();
        }
    };
}

private Func<object, Action> Case<T>(Action<T> action)
{
    return o => o is T ? (Action)(() => action((T)o)) : (Action)null;
}

Almost brings tears to your eyes, right?

Nonetheless, it works. Enjoy.

How do I export html table data as .csv file?

You could use an extension for Chrome, that works well the times I have tried it.

https://chrome.google.com/webstore/search/html%20table%20to%20csv?_category=extensions

When installed and on any web page with a table if you click on this extension's icon it shows all the tables in the page, highlighting each as you roll over the tables it lists, clicking allows you to copy it to the clipboard or save it to a Google Doc.

It works perfectly for what I need, which is occasional conversion of web based tabular data into a spreadsheet I can work with.

C#: How to add subitems in ListView

Create a listview item

ListViewItem item1 = new ListViewItem("sdasdasdasd", 0)
item1.SubItems.Add("asdasdasd")

Writing to a file in a for loop

That is because you are opening , writing and closing the file 10 times inside your for loop

myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()

You should open and close your file outside for loop.

myfile = open('xyz.txt', 'w')
for line in lines:
    var1, var2 = line.split(",");
    myfile.write("%s\n" % var1)

myfile.close()
text_file.close()

You should also notice to use write and not writelines.

writelines writes a list of lines to your file.

Also you should check out the answers posted by folks here that uses with statement. That is the elegant way to do file read/write operations in Python

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

This is my experience for this problem maybe it could help you :

I copied all folders and files inside the /data folder to have a backup from my db .

When I switched to another Computer's Xampp and I started copying all folders and files copied before from previous phpmyadmin /data folder.

So when I was done this problem happened for me .

To solve this issue :

1 - I made a backup from /data folder of phpmyadmin by copying only only folders have same name with tables I want to make backup .

2 - Uninstall Xampp.

3 - Reinstall Xampp .

4 - Copy all folders Kept in step 1 inside mysql/data folder . this folders are only database tables and be careful don't touch another file and folder or replace anything when copying.

Convert wchar_t to char

Here's another way of doing it, remember to use free() on the result.

char* wchar_to_char(const wchar_t* pwchar)
{
    // get the number of characters in the string.
    int currentCharIndex = 0;
    char currentChar = pwchar[currentCharIndex];

    while (currentChar != '\0')
    {
        currentCharIndex++;
        currentChar = pwchar[currentCharIndex];
    }

    const int charCount = currentCharIndex + 1;

    // allocate a new block of memory size char (1 byte) instead of wide char (2 bytes)
    char* filePathC = (char*)malloc(sizeof(char) * charCount);

    for (int i = 0; i < charCount; i++)
    {
        // convert to char (1 byte)
        char character = pwchar[i];

        *filePathC = character;

        filePathC += sizeof(char);

    }
    filePathC += '\0';

    filePathC -= (sizeof(char) * charCount);

    return filePathC;
}

C library function to perform sort

There are several C sorting functions available in stdlib.h. You can do man 3 qsort on a unix machine to get a listing of them but they include:

  • heapsort
  • quicksort
  • mergesort

How to run a command as a specific user in an init script?

On RHEL systems, the /etc/rc.d/init.d/functions script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.

The specific function provided to help with this is daemon. If you are intending to use it to start a daemon-like program, a simple usage would be:

daemon --user=username command

If that is too heavy-handed for what you need, there is runuser (see man runuser for full info; some versions may need -u prior to the username):

/sbin/runuser username -s /bin/bash -c "command(s) to run as user username"

how to display excel sheet in html page

You can use iPushPull to push live data direct from an Excel session to the web where you can display it in an IFRAME (or using a WordPress plugin, if applicable). The data in the frame will update whenever the data on the sheet updates.

The iPush(...) in-cell function pushes data from Excel to the web.

This support page describes how to embed your Excel data in your website.

Disclaimer - I work for iPushPull.

Java finished with non-zero exit value 2 - Android Gradle

Just in case if someone still struggling with this and have no clue why is this happening and how to fix. In fact this error

Error:Execution failed for task ':app:dexDebug'. > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdkx.x.x_xx\bin\java.exe'' finished with non-zero exit value 2

can have many reasons to happen but certainly not something related to your JDK version so don't wast your time in wrong direction. These are two main reasons for this to happen

  1. You have same library or jar file included several places and some of them conflicting with each other.
  2. You are about to or already exceeded 65k method limit

First case can be fixed as follows: Find out which dependencies you have included multiple times. In order to do this run following command in android studio terminal

gradlew -q dependencies yourProjectName_usually_app:dependencies --configuration compile

this will return all the dependencies but jar files that you include from lib folder try to get rid of duplication marked with asterisk (*), this is not always possible but in some cases you still can do it, after this try to exclude modules that are included many times, you can do it like this

compile ('com.facebook.android:facebook-android-sdk:4.0.1'){
    exclude module: 'support-v4'
}

For the second case when you exceeding method limit suggestion is to try to minimize it by removing included libraries (note sounds like first solution) if no way to do it add multiDexEnabled true to your defaultConfig

defaultConfig {
   ...
   ...
   multiDexEnabled true
}

this increases method limit but it is not the best thing to do because of possible performance issues IMPORTANT adding only multiDexEnabled true to defaultConfig is not enough in fact on all devices running android <5 Lollipop it will result in unexpected behavior and NoClassDefFoundError. how to solve it is described here

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

How to correctly link php-fpm and Nginx Docker containers?

I know it is kind an old post, but I've had the same problem and couldn't understand why your code didn't work. After a LOT of tests I've found out why.

It seems like fpm receives the full path from nginx and tries to find the files in the fpm container, so it must be the exactly the same as server.root in the nginx config, even if it doesn't exist in the nginx container.

To demonstrate:

docker-compose.yml

nginx:
    build: .
    ports:
        - "80:80"
    links:
        - fpm
fpm:
    image: php:fpm
    ports:
        - ":9000"

    # seems like fpm receives the full path from nginx
    # and tries to find the files in this dock, so it must
    # be the same as nginx.root
    volumes:
        - ./:/complex/path/to/files/

/etc/nginx/conf.d/default.conf

server {
    listen  80;

    # this path MUST be exactly as docker-compose.fpm.volumes,
    # even if it doesn't exist in this dock.
    root /complex/path/to/files;

    location / {
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/.+\.php(/|$) {
        fastcgi_pass fpm:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Dockerfile

FROM nginx:latest
COPY ./default.conf /etc/nginx/conf.d/

"R cannot be resolved to a variable"?

Dont worry. First you may clean the project, then run the project. If this does not work then follow the following links:

How do you iterate through every file/directory recursively in standard C++?

A fast solution is using C's Dirent.h library.

Working code fragment from Wikipedia:

#include <stdio.h>
#include <dirent.h>

int listdir(const char *path) {
    struct dirent *entry;
    DIR *dp;

    dp = opendir(path);
    if (dp == NULL) {
        perror("opendir: Path does not exist or could not be read.");
        return -1;
    }

    while ((entry = readdir(dp)))
        puts(entry->d_name);

    closedir(dp);
    return 0;
}

Using sed, Insert a line above or below the pattern?

To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)

sed -i '/pattern/a \
line1 \
line2' inputfile

Output:

#cat inputfile
 pattern
 line1 line2 

To prepend the lines before:

sed -i '/pattern/i \
line1 \
line2' inputfile

Output:

#cat inputfile
 line1 line2 
 pattern

Using Postman to access OAuth 2.0 Google APIs

I figured out that I was not generating Credentials for the right app type.
If you're using Postman to test Google oAuth 2 APIs, select
Credentials -> Add credentials -> OAuth2.0 client ID -> Web Application.

enter image description here

In Node.js, how do I turn a string to a json?

use the JSON function >

JSON.parse(theString)

CURRENT_DATE/CURDATE() not working as default DATE value

Currently from MySQL 8 you can set the following to a DATE column:

In MySQL Workbench, in the Default field next to the column, write: (curdate())

If you put just curdate() it will fail. You need the extra ( and ) at the beginning and end.

Apache HttpClient Android (Gradle)

The accepted answer does not seem quite right to me. There is no point dragging a different version of HttpMime when one can depend on the same version of it.

compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5'
compile (group: 'org.apache.httpcomponents' , name: 'httpmime' , version: '4.3.5') {
    exclude module: 'org.apache.httpcomponents:httpclient'
}

Why doesn't CSS ellipsis work in table cell?

If you don't want to set max-width to td (like in this answer), you can set max-width to div:

function so_hack(){}

function so_hack(){} http://jsfiddle.net/fd3Zx/754/ function so_hack(){}

function so_hack(){}

Note: 100% doesn't work, but 99% does the trick in FF. Other modern browsers doesn't need silly div hacks.

td {
  border: 1px solid black;
    padding-left:5px;
    padding-right:5px;
}
td>div{
    max-width: 99%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

}

CSS align one item right with flexbox

To align some elements (headerElement) in the center and the last element to the right (headerEnd).

.headerElement {
    margin-right: 5%;
    margin-left: 5%;
}
.headerEnd{
    margin-left: auto;
}

MySQL Error 1093 - Can't specify target table for update in FROM clause

This is what I did for updating a Priority column value by 1 if it is >=1 in a table and in its WHERE clause using a subquery on same table to make sure that at least one row contains Priority=1 (because that was the condition to be checked while performing update) :


UPDATE My_Table
SET Priority=Priority + 1
WHERE Priority >= 1
AND (SELECT TRUE FROM (SELECT * FROM My_Table WHERE Priority=1 LIMIT 1) as t);

I know it's a bit ugly but it does works fine.

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

How to create .ipa file using Xcode?

Here is the steps I followed to export the .ipa

  • Validate the archive
  • Click on on distribute the app
  • Click the distribution method
  • Choose the export in the next screen (The screen shown only if the archive is validated)

Center-align a HTML table

Try this -

<table align="center" style="margin: 0px auto;"></table>

How to link external javascript file onclick of button

By loading the .js file first and then calling the function via onclick, there's less coding and it's fairly obvious what's going on. We'll call the JS file zipcodehelp.js.

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Button to call JS function.</title>
</head>
<body>
    <h1>Use Button to execute function in '.js' file.</h1>
    <script type="text/javascript" src="zipcodehelp.js"></script>
    <button onclick="ZipcodeHelp();">Get Zip Help!</button>
</body>
</html>

And the contents of zipcodehelp.js is :

function ZipcodeHelp() {
  alert("If Zipcode is missing in list at left, do: \n\n\
    1. Enter any zipcode and click Create Client. \n\
    2. Goto Zipcodes and create new zip code. \n\
    3. Edit this new client from the client list.\n\
    4. Select the new zipcode." );
}

Hope that helps! Cheers!

–Ken

How to get current date & time in MySQL?

Yes, you can use the CURRENT_TIMESTAMP() command.

See here: Date and Time Functions

Change NULL values in Datetime format to empty string

select case when IsNull(CONVERT(DATE, StartDate),'')='' then 'NA' else Convert(varchar(10),StartDate,121) end from table1

The import org.junit cannot be resolved

you need to add Junit dependency in pom.xml file, it means you need to update with latest version.

<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency> 

Disable button after click in JQuery

Consider also .attr()

$("#roommate_but").attr("disabled", true); worked for me.

How do I run a Java program from the command line on Windows?

Now (with JDK 9 onwards), you can just use java to get that executed. In order to execute "Hello.java" containing the main, one can use: java Hello.java

You do not need to compile using separately using javac anymore.

Squash my last X commits together using Git

In the branch you would like to combine the commits on, run:

git rebase -i HEAD~(n number of commits back to review)

example:

git rebase -i HEAD~1

This will open the text editor and you must switch the 'pick' in front of each commit with 'squash' if you would like these commits to be merged together. From documentation:

p, pick = use commit

s, squash = use commit, but meld into previous commit

For example, if you are looking to merge all the commits into one, the 'pick' is the first commit you made and all future ones (placed below the first) should be set to 'squash'. If using vim, use :x in insert mode to save and exit the editor.

Then to continue the rebase:

git rebase --continue

For more on this and other ways to rewrite your commit history see this helpful post

Toggle input disabled attribute using jQuery

Another simple option that updates on a click of the checkbox.

HTML:

<input type="checkbox" id="checkbox/>
<input disabled type="submit" id="item"/>

jQuery:

$('#checkbox').click(function() {
    if (this.checked) {
        $('#item').prop('disabled', false); // If checked enable item       
    } else {
        $('#item').prop('disabled', true); // If checked disable item                   
    }
});

In action: link

Correct way to focus an element in Selenium WebDriver using Java

You can use JS as below:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('elementid').focus();");

T-SQL: How to Select Values in Value List that are NOT IN the Table?

Use this : -- SQL Server 2008 or later

SELECT U.* 
FROM USERS AS U
Inner Join (
  SELECT   
    EMail, [Status]
  FROM
    (
      Values
        ('email1', 'Exist'),
        ('email2', 'Exist'),
        ('email3', 'Not Exist'),
        ('email4', 'Exist')
    )AS TempTableName (EMail, [Status])
  Where TempTableName.EMail IN ('email1','email2','email3')
) As TMP ON U.EMail = TMP.EMail

Save modifications in place with awk

@sudo_O has the right answer.

This can't work:

someprocess < file > file

The shell performs the redirections before handing control over to someprocess (redirections). The > redirection will truncate the file to zero size (redirecting output). Therefore, by the time someprocess gets launched and wants to read from the file, there is no data for it to read.

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

Web link to specific whatsapp contact

Phone Number will be a country code followed by WhatsApp mobile number without any symbol. Please refer below code.

<a href="https://api.whatsapp.com/send?phone=19998887878&text=Hi%20There!">WhatsApp Now</a>

Capturing mobile phone traffic on Wireshark

Wireshark + OSX + iOS:

Great overview so far, but if you want specifics for Wireshark + OSX + iOS:

  • install Wireshark on your computer
  • connect iOS device to computer via USB cable
  • connect iOS device and computer to the same WiFi network
  • run this command in a OSX terminal window: rvictl -s x where x is the UDID of your iOS device. You can find the UDID of your iOS device via iTunes (make sure you are using the UDID and not the serial number).
  • goto Wireshark Capture->Options, a dialog box appears, click on the line rvi0 then press the Start button.

Wireshark Capture Options Dialog Box

Now you will see all network traffic on the iOS device. It can be pretty overwhelming. A couple of pointers:

  • don't use iOS with a VPN, you don't be able to make sense of the encrypted traffic
  • use simple filters to focus on interesting traffic
  • ip.addr==204.144.14.134 views traffic with a source or destination address of 204.144.14.134
  • http views only http traffic

Here's a sample window depicting TCP traffic for for pdf download from 204.144.14.134:

Wireshark TCP traffic for pdf download from 204.144.14.134

Callback after all asynchronous forEach callbacks are completed

It's odd how many incorrect answers has been given to asynchronous case! It can be simply shown that checking index does not provide expected behavior:

// INCORRECT
var list = [4000, 2000];
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
    }, l);
});

output:

4000 started
2000 started
1: 2000
0: 4000

If we check for index === array.length - 1, callback will be called upon completion of first iteration, whilst first element is still pending!

To solve this problem without using external libraries such as async, I think your best bet is to save length of list and decrement if after each iteration. Since there's just one thread we're sure there no chance of race condition.

var list = [4000, 2000];
var counter = list.length;
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
        counter -= 1;
        if ( counter === 0)
            // call your callback here
    }, l);
});

Call one constructor from another

Yeah, you can call other method before of the call base or this!

public class MyException : Exception
{
    public MyException(int number) : base(ConvertToString(number)) 
    {
    }

    private static string ConvertToString(int number) 
    { 
      return number.toString()
    }

}

Windows batch: formatted date into variable

It is possible to use PowerShell and redirect its output to an environment variable by using a loop.

From the command line (cmd):

for /f "tokens=*" %a in ('powershell get-date -format "{yyyy-MM-dd+HH:mm}"') do set td=%a

echo %td%
2016-25-02+17:25

In a batch file you might escape %a as %%a:

for /f "tokens=*" %%a in ('powershell get-date -format "{yyyy-MM-dd+HH:mm}"') do set td=%%a

Make a simple fade in animation in Swift?

If you want repeatable fade animation you can do that by using CABasicAnimation like below :

First create handy UIView extension :

extension UIView {

    enum AnimationKeyPath: String {
        case opacity = "opacity"
    }

    func flash(animation: AnimationKeyPath ,withDuration duration: TimeInterval = 0.5, repeatCount: Float = 5){
        let flash = CABasicAnimation(keyPath: animation.rawValue)
        flash.duration = duration
        flash.fromValue = 1 // alpha
        flash.toValue = 0 // alpha
        flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        flash.autoreverses = true
        flash.repeatCount = repeatCount

        layer.add(flash, forKey: nil)
    }
}

How to use it:

    // You can use it with all kind of UIViews e.g. UIButton, UILabel, UIImage, UIImageView, ...
    imageView.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
    titleLabel.flash(animation: .opacity, withDuration: 1, repeatCount: 5)

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

IndentationError expected an indented block

You've mixed tabs and spaces. This can lead to some confusing errors.

I'd suggest using only tabs or only spaces for indentation.

Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.


As an aside, your code is more verbose than it needs to be. Instead of this:

if str_p == str_q:
    result = True
else:
    result = False
return result

Just do this:

return str_p == str_q

You also appear to have a bug on this line:

str_q = p[b+1:]

I'll leave you to figure out what the error is.

iOS for VirtualBox

VirtualBox is a virtualizer, not an emulator. (The name kinda gives it away.) I.e. it can only virtualize a CPU that is actually there, not emulate one that isn't. In particular, VirtualBox can only virtualize x86 and AMD64 CPUs. iOS only runs on ARM CPUs.

what is the size of an enum type data in C++?

The size is four bytes because the enum is stored as an int. With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.

0 0 0 0  January
0 0 0 1  February
0 0 1 0  March
0 0 1 1  April
0 1 0 0  May
0 1 0 1  June
0 1 1 0  July
0 1 1 1  August
1 0 0 0  September
1 0 0 1  October
1 0 1 0  November
1 0 1 1  December
1 1 0 0  ** unused **
1 1 0 1  ** unused **
1 1 1 0  ** unused **
1 1 1 1  ** unused **

Without enums, you might be tempted to use raw integers to represent the months. That would work and be efficient, but it would make your code hard to read. With enums, you get efficient storage and readability.

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

How can I generate Javadoc comments in Eclipse?

JAutoDoc:

an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers...

A top-like utility for monitoring CUDA activity on a GPU

You can use the monitoring program glances with its GPU monitoring plug-in:

  • open source
  • to install: sudo apt-get install -y python-pip; sudo pip install glances[gpu]
  • to launch: sudo glances

enter image description here

It also monitors the CPU, disk IO, disk space, network, and a few other things:

enter image description here

How to fill in proxy information in cntlm config file?

Update your user, domain, and proxy information in cntlm.ini, then test your proxy with this command (run in your Cntlm installation folder):

cntlm -c cntlm.ini -I -M http://google.ro

It will ask for your password, and hopefully print your required authentication information, which must be saved in your cntlm.ini

Sample cntlm.ini:

Username            user
Domain              domain

# provide actual value if autodetection fails
# Workstation         pc-name

Proxy               my_proxy_server.com:80
NoProxy             127.0.0.*, 192.168.*

Listen              127.0.0.1:54321
Listen              192.168.1.42:8080
Gateway             no

SOCKS5Proxy         5000
# provide socks auth info if you want it
# SOCKS5User          socks-user:socks-password

# printed authentication info from the previous step
Auth            NTLMv2
PassNTLMv2      98D6986BCFA9886E41698C1686B58A09

Note: on linux the config file is cntlm.conf

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.

pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')

Make XAMPP / Apache serve file outside of htdocs folder

A VirtualHost would also work for this and may work better for you as you can host several projects without the need for subdirectories. Here's how you do it:

httpd.conf (or extra\httpd-vhosts.conf relative to httpd.conf. Trailing slashes "\" might cause it not to work):

NameVirtualHost *:80
# ...
<VirtualHost *:80>  
    DocumentRoot C:\projects\transitCalculator\trunk\
    ServerName transitcalculator.localhost
    <Directory C:\projects\transitCalculator\trunk\>  
        Order allow,deny  
        Allow from all  
    </Directory>
</VirtualHost> 

HOSTS file (c:\windows\system32\drivers\etc\hosts usually):

# localhost entries
127.0.0.1 localhost transitcalculator.localhost

Now restart XAMPP and you should be able to access http://transitcalculator.localhost/ and it will map straight to that directory.

This can be helpful if you're trying to replicate a production environment where you're developing a site that will sit on the root of a domain name. You can, for example, point to files with absolute paths that will carry over to the server:

<img src="/images/logo.png" alt="My Logo" />

whereas in an environment using aliases or subdirectories, you'd need keep track of exactly where the "images" directory was relative to the current file.

"The system cannot find the file specified"

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

How do I remove duplicate items from an array in Perl?

Can be done with a simple Perl one liner.

my @in=qw(1 3 4  6 2 4  3 2 6  3 2 3 4 4 3 2 5 5 32 3); #Sample data 
my @out=keys %{{ map{$_=>1}@in}}; # Perform PFM
print join ' ', sort{$a<=>$b} @out;# Print data back out sorted and in order.

The PFM block does this:

Data in @in is fed into MAP. MAP builds an anonymous hash. Keys are extracted from the hash and feed into @out

Unzipping files

If anyone's reading images or other binary files from a zip file hosted at a remote server, you can use following snippet to download and create zip object using the jszip library.

// this function just get the public url of zip file.
let url = await getStorageUrl(path) 
console.log('public url is', url)
//get the zip file to client
axios.get(url, { responseType: 'arraybuffer' }).then((res) => {
  console.log('zip download status ', res.status)
//load contents into jszip and create an object
  jszip.loadAsync(new Blob([res.data], { type: 'application/zip' })).then((zip) => {
    const zipObj = zip
    $.each(zip.files, function (index, zipEntry) {
    console.log('filename', zipEntry.name)
    })
  })

Now using the zipObj you can access the files and create a src url for it.

var fname = 'myImage.jpg'
zipObj.file(fname).async('blob').then((blob) => {
var blobUrl = URL.createObjectURL(blob)

How to implement static class member functions in *.cpp file?

It is.

test.hpp:

class A {
public:
    static int a(int i);
};

test.cpp:

#include <iostream>
#include "test.hpp"


int A::a(int i) {
    return i + 2;
}

using namespace std;
int main() {
    cout << A::a(4) << endl;
}

They're not always inline, no, but the compiler can make them.

Matplotlib/pyplot: How to enforce axis range?

Try putting the call to axis after all plotting commands.

How to center a subview of UIView

In c# or Xamarin.ios, we can use like this

imageView.Center = new CGPoint(tempView.Frame.Size.Width / 2, tempView.Frame.Size.Height / 2);

XmlSerializer giving FileNotFoundException at constructor

Troubleshooting compilation errors on the other hand is very complicated. These problems manifest themselves in a FileNotFoundException with the message:

File or assembly name abcdef.dll, or one of its dependencies, was not found. File name: "abcdef.dll"
   at System.Reflection.Assembly.nLoad( ... )
   at System.Reflection.Assembly.InternalLoad( ... )
   at System.Reflection.Assembly.Load(...)
   at System.CodeDom.Compiler.CompilerResults.get_CompiledAssembly() 

You may wonder what a file not found exception has to do with instantiating a serializer object, but remember: the constructor writes C# files and tries to compile them. The call stack of this exception provides some good information to support that suspicion. The exception occurred while the XmlSerializer attempted to load an assembly generated by CodeDOM calling the System.Reflection.Assembly.Load method. The exception does not provide an explanation as to why the assembly that the XmlSerializer was supposed to create was not present. In general, the assembly is not present because the compilation failed, which may happen because, under rare circumstances, the serialization attributes produce code that the C# compiler fails to compile.

Note This error also occurs when the XmlSerializer runs under an account or a security environment that is not able to access the temp directory.

Source: http://msdn.microsoft.com/en-us/library/aa302290.aspx

get data from mysql database to use in javascript

To do with javascript you could do something like this:

<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>

Then you can use whatever you want in your javascript to put the text var into the textbox.

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

C# Version... note that I am getting color strings in this format #FF12AE34, and need to cut out the #FF.

    private string GetSmartShadeColorByBase(string s, float percent)
    {
        if (string.IsNullOrEmpty(s))
            return "";
        var r = s.Substring(3, 2);
        int rInt = int.Parse(r, NumberStyles.HexNumber);
        var g = s.Substring(5, 2);
        int gInt = int.Parse(g, NumberStyles.HexNumber);
        var b = s.Substring(7, 2);
        int bInt = int.Parse(b, NumberStyles.HexNumber);

        var t = percent < 0 ? 0 : 255;
        var p = percent < 0 ? percent*-1 : percent;

        int newR = Convert.ToInt32(Math.Round((t - rInt) * p) + rInt);
        var newG = Convert.ToInt32(Math.Round((t - gInt) * p) + gInt);
        var newB = Convert.ToInt32(Math.Round((t - bInt) * p) + bInt);

        return String.Format("#{0:X2}{1:X2}{2:X2}", newR, newG, newB);
    }

Python Inverse of a Matrix

You should have a look at numpy if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.

from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] )                  # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] )                      # Creates a matrix (like a row vector).
print A.T                                    # Transpose of A.
print A*x                                    # Matrix multiplication of A and x.
print A.I                                    # Inverse of A.
print linalg.solve(A, x)     # Solve the linear equation system.

You can also have a look at the array module, which is a much more efficient implementation of lists when you have to deal with only one data type.

Can I catch multiple Java exceptions in the same catch clause?

Within Java 7 you can define multiple catch clauses like:

catch (IllegalArgumentException | SecurityException e)
{
    ...
}

Convert absolute path into relative path given a current directory using Bash

#!/bin/bash
# both $1 and $2 are absolute paths
# returns $2 relative to $1

source=$1
target=$2

common_part=$source
back=
while [ "${target#$common_part}" = "${target}" ]; do
  common_part=$(dirname $common_part)
  back="../${back}"
done

echo ${back}${target#$common_part/}

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

According to this page https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html it is only available if (Enabled only in a UIWebView with the allowsInlineMediaPlayback property set to YES.) I understand in Mobile Safari this is YES on iPad and NO on iPhone and iPod Touch.

Trigger Change event when the Input value changed programmatically?

Vanilla JS solution:

var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));

Note that dispatchEvent doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).

So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional comments to warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for: typeof document.body.dispatchEvent === 'function'.

How can I determine the URL that a local Git repository was originally cloned from?

I think you can find it under .git/config and remote["origin"] if you didn't manipulate that.

What is the meaning of 'No bundle URL present' in react-native?

This is how I did it:

  • Open a terminal window
  • cd into YOUR_PROJECT/ios
  • Remove the build folder with rm -r build
  • Run react-native run-ios again

JAVA_HOME and PATH are set but java -version still shows the old one

Updating the ~/.profile or ~/.bash_profile does not work sometimes. I just deleted JDK 6 and sourced .bash_profile.

Try running this:

sudo rm -rd jdk1.6.0_* #it may not let you delete without sudo

Then, modify/add your JAVA_HOME and PATH variables.

source ~/.bash_profile #assuming you've updated $JAVA_HOME and $PATH

How to unpack and pack pkg file?

If you are experiencing errors during PKG installation following the accepted answer, I will give you another procedure that worked for me (please note the little changes to xar, cpio and mkbom commands):

mkdir Foo
cd Foo
xar -xf ../Foo.pkg
cd foo.pkg
cat Payload | gunzip -dc | cpio -i
# edit Foo.app/*
rm Payload
find ./Foo.app | cpio -o --format odc --owner 0:80 | gzip -c > Payload
mkbom -u 0 -g 80 Foo.app Bom # or edit Bom
# edit PackageInfo
rm -rf Foo.app
cd ..
xar --compression none -cf ../Foo-new.pkg

The resulted PKG will have no compression, cpio now uses odc format and specify the owner of the file as well as mkbom.

Read and write a text file in typescript

First you will need to install node definitions for Typescript. You can find the definitions file here:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts

Once you've got file, just add the reference to your .ts file like this:

/// <reference path="path/to/node.d.ts" />

Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this:

/// <reference path="path/to/node.d.ts" />

class MyClass {

    // Here we import the File System module of node
    private fs = require('fs');

    constructor() { }

    createFile() {

        this.fs.writeFile('file.txt', 'I am cool!',  function(err) {
            if (err) {
                return console.error(err);
            }
            console.log("File created!");
        });
    }

    showFile() {

        this.fs.readFile('file.txt', function (err, data) {
            if (err) {
                return console.error(err);
            }
            console.log("Asynchronous read: " + data.toString());
        });
    }
}

// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();

Once you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:

> node myClass.js

Compare two files and write it to "match" and "nomatch" files

//STEP01   EXEC SORT90MB                        
//SORTJNF1 DD DSN=INPUTFILE1,   
//            DISP=SHR                          
//SORTJNF2 DD DSN=INPUTFILE2,   
//            DISP=SHR                          
//SORTOUT  DD DSN=MISMATCH_OUTPUT_FILE, 
//            DISP=(,CATLG,DELETE),             
//            UNIT=TAPE,                        
//            DCB=(RECFM=FB,BLKSIZE=0),         
//            DSORG=PS                          
//SYSOUT   DD SYSOUT=*                          
//SYSIN    DD *                                 
  JOINKEYS FILE=F1,FIELDS=(1,79,A)              
  JOINKEYS FILE=F2,FIELDS=(1,79,A)              
  JOIN UNPAIRED,F1,ONLY                         
  SORT FIELDS=COPY                              
/*                                              

How to remove non UTF-8 characters from text file

Your method must read byte by byte and fully understand and appreciate the byte wise construction of characters. The simplest method is to use an editor which will read anything but only output UTF-8 characters. Textpad is one choice.

Select multiple value in DropDownList using ASP.NET and C#

Dropdown list wont allows multiple item select in dropdown.

If you need , you can use listbox control..

ASP.NET List Box

Does hosts file exist on the iPhone? How to change it?

I just edited my iPhone's 'hosts' file successfully (on Jailbroken iOS 4.0).

  • Installed OpenSSH onto iPhone via Cydia
  • Using a SFTP client like FileZilla on my computer, I connected to my iPhone
    • Address: [use your phone's IP address or hostname, eg. simophone.local]
    • Username: root
    • Password: alpine
  • Located the /etc/hosts file
  • Made a backup on my computer (in case I want to revert my changes later)
  • Edited the hosts file in a decent text editor (such as Notepad++). See here for an explanation of the hosts file.
  • Uploaded the changes, overwriting the hosts file on the iPhone

The phone does cache some webpages and DNS queries, so a reboot or clearing the cache may help. Hope that helps someone.

Simon.

Looking for simple Java in-memory cache

Try Ehcache? It allows you to plug in your own caching expiry algorithms so you could control your peek functionality.

You can serialize to disk, database, across a cluster etc...

PHP passing $_GET in linux command prompt

Sometimes you don't have the option of editing the php file to set $_GET to the parameters passed in, and sometimes you can't or don't want to install php-cgi.

I found this to be the best solution for that case:

php -r '$_GET["key"]="value"; require_once("script.php");' 

This avoids altering your php file and lets you use the plain php command. If you have php-cgi installed, by all means use that, but this is the next best thing. Thought this options was worthy of mention

the -r means run the php code in the string following. you set the $_GET value manually there, and then reference the file you want to run.

Its worth noting you should run this in the right folder, often but not always the folder the php file is in. Requires statements will use the location of your command to resolve relative urls, NOT the location of the file

HtmlSpecialChars equivalent in Javascript?

function htmlEscape(str){
    return str.replace(/[&<>'"]/g,x=>'&#'+x.charCodeAt(0)+';')
}

This solution uses the numerical code of the characters, for example < is replaced by &#60;.

Although its performance is slightly worse than the solution using a map, it has the advantages:

  • Not dependent on a library or DOM
  • Pretty easy to remember (you don't need to memorize the 5 HTML escape characters)
  • Little code
  • Reasonably fast (it's still faster than 5 chained replace)

Displaying a 3D model in JavaScript/HTML5

I also needed what you've been searching for and did some research.

I found JSC3D (https://code.google.com/p/jsc3d/). It's a project written entirely in Javascript and uses the HTML canvas. It has been tested for Opera, Chrome, Firefox, Safari, IE9 and more.

Then you have services as p3d.in and Sketchfab that give you a nice reader to view 3D models on a web page: they use HTML5 and WebGL. They both have a free version.

Different font size of strings in the same TextView

I have written my own function which takes 2 strings and 1 int (text size)

The full text and the part of the text you want to change the size of it.

It returns a SpannableStringBuilder which you can use it in text view.

  public static SpannableStringBuilder setSectionOfTextSize(String text, String textToChangeSize, int size){

        SpannableStringBuilder builder=new SpannableStringBuilder();

        if(textToChangeSize.length() > 0 && !textToChangeSize.trim().equals("")){

            //for counting start/end indexes
            String testText = text.toLowerCase(Locale.US);
            String testTextToBold = textToChangeSize.toLowerCase(Locale.US);
            int startingIndex = testText.indexOf(testTextToBold);
            int endingIndex = startingIndex + testTextToBold.length();
            //for counting start/end indexes

            if(startingIndex < 0 || endingIndex <0){
                return builder.append(text);
            }
            else if(startingIndex >= 0 && endingIndex >=0){

                builder.append(text);
                builder.setSpan(new AbsoluteSizeSpan(size, true), startingIndex, endingIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }else{
            return builder.append(text);
        }

        return builder;
    }

Ruby on Rails form_for select field with class

This work for me

<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>

Open Google Chrome from VBA/Excel

You can use the following vba code and input them into standard module in excel. A list of websites can be entered and should be entered like this on cell A1 in Excel - www.stackoverflow.com

ActiveSheet.Cells(1,2).Value merely takes the number of website links that you have on cell B1 in Excel and will loop the code again and again based on number of website links you have placed on the sheet. Therefore Chrome will open up a new tab for each website link.

I hope this helps with the dynamic website you have got.

Sub multiplechrome()

    Dim WebUrl As String
    Dim i As Integer

    For i = 1 To ActiveSheet.Cells(1, 2).Value
        WebUrl = "http://" & Cells(i, 1).Value & """"
        Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)

    Next
End Sub

How do I pass a class as a parameter in Java?

public void callingMethod(Class neededClass) {
    //Cast the class to the class you need
    //and call your method in the class
    ((ClassBeingCalled)neededClass).methodOfClass();
}

To call the method, you call it this way:

callingMethod(ClassBeingCalled.class);

How to calculate UILabel height dynamically?

This is the extension I use for calculating multiline UILabel heights, it's an adjusted snippet from a previous stack overflow post:

extension UILabel {
    func estimatedHeight(forWidth: CGFloat, text: String, ofSize: CGFloat) -> CGFloat {

        let size = CGSize(width: forWidth, height: CGFloat(MAXFLOAT))

        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)

        let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: ofSize)]

        let rectangleHeight = String(text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height

        return ceil(rectangleHeight)
    }
}

What is __gxx_personality_v0 for?

Exception handling is included in free standing implementations.

The reason of this is that you possibly use gcc to compile your code. If you compile with the option -### you will notice it is missing the linker-option -lstdc++ when it invokes the linker process . Compiling with g++ will include that library, and thus the symbols defined in it.

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {
}

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {
}

Extract text from a string

The following regex extract anything between the parenthesis:

PS> $prog = [regex]::match($s,'\(([^\)]+)\)').Groups[1].Value
PS> $prog
SUB RAD MSD 50R III


Explanation (created with RegexBuddy)

Match the character '(' literally «\(»
Match the regular expression below and capture its match into backreference number 1 «([^\)]+)»
   Match any character that is NOT a ) character «[^\)]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character ')' literally «\)»

Check these links:

http://www.regular-expressions.info

http://powershell.com/cs/blogs/tobias/archive/2011/10/27/regular-expressions-are-your-friend-part-1.aspx

http://powershell.com/cs/blogs/tobias/archive/2011/12/02/regular-expressions-are-your-friend-part-2.aspx

http://powershell.com/cs/blogs/tobias/archive/2011/12/02/regular-expressions-are-your-friend-part-3.aspx

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

How to check if a string is numeric?

Use this

public static boolean isNum(String strNum) {
    boolean ret = true;
    try {

        Double.parseDouble(strNum);

    }catch (NumberFormatException e) {
        ret = false;
    }
    return ret;
}

How to convert local time string to UTC?

For getting around day-light saving, etc.

None of the above answers particularly helped me. The code below works for GMT.

def get_utc_from_local(date_time, local_tz=None):
    assert date_time.__class__.__name__ == 'datetime'
    if local_tz is None:
        local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
    local_time = local_tz.normalize(local_tz.localize(date_time))
    return local_time.astimezone(pytz.utc)

import pytz
from datetime import datetime

summer_11_am = datetime(2011, 7, 1, 11)
get_utc_from_local(summer_11_am)
>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)

winter_11_am = datetime(2011, 11, 11, 11)
get_utc_from_local(winter_11_am)
>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)

Which keycode for escape key with jQuery

Try the jEscape plugin (download from google drive)

$(document).escape(function() { 
   alert('ESC button pressed'); 
});

or get keycode for cross browser

var code = (e.keyCode ? e.keyCode : e.which);
if (code === 27) alert('ESC');
if (code === 13) alert('ENTER');

maybe you can use switch

var code = (e.keyCode ? e.keyCode : e.which);
switch (code) {
    case 27:
       alert('ESC');
       break;
     case 13:
       alert('ENTER');
       break;
}

How to multiply a BigDecimal by an integer in Java

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

ValueError: unsupported format character while forming strings

Well, why do you have %20 url-quoting escapes in a formatting string in first place? Ideally you'd do the interpolation formatting first:

formatting_template = 'Hello World%s'
text = '!'
full_string = formatting_template % text

Then you url quote it afterwards:

result = urllib.quote(full_string)

That is better because it would quote all url-quotable things in your string, including stuff that is in the text part.

delete vs delete[] operators in C++

The operators delete and delete [] are used respectively to destroy the objects created with new and new[], returning to the allocated memory left available to the compiler's memory manager.

Objects created with new must necessarily be destroyed with delete, and that the arrays created with new[] should be deleted with delete[].

How can I write a heredoc to a file in Bash script?

To build on @Livven's answer, here are some useful combinations.

  1. variable substitution, leading tab retained, overwrite file, echo to stdout

    tee /path/to/file <<EOF
    ${variable}
    EOF
    
  2. no variable substitution, leading tab retained, overwrite file, echo to stdout

    tee /path/to/file <<'EOF'
    ${variable}
    EOF
    
  3. variable substitution, leading tab removed, overwrite file, echo to stdout

    tee /path/to/file <<-EOF
        ${variable}
    EOF
    
  4. variable substitution, leading tab retained, append to file, echo to stdout

    tee -a /path/to/file <<EOF
    ${variable}
    EOF
    
  5. variable substitution, leading tab retained, overwrite file, no echo to stdout

    tee /path/to/file <<EOF >/dev/null
    ${variable}
    EOF
    
  6. the above can be combined with sudo as well

    sudo -u USER tee /path/to/file <<EOF
    ${variable}
    EOF
    

Where does MySQL store database files on Windows and what are the names of the files?

It's usually in the folder specified below, but ProgramData is usually a hidden folder. To show it, go to control panel search for "folder" then under advanced settings tick show hidden files and click apply. C:/ProgramData/MySQL/MySQL Server 5.5/Data/

SQL Developer is returning only the date, not the time. How do I fix this?

Neither of these answers would work for me, not the Preferences NLS configuration option or the ALTER statement. This was the only approach that worked in my case:

dbms_session.set_nls('nls_date_format','''DD-MM-YYYY HH24:MI:SS''');

*added after the BEGIN statement

I am using PL/SQL Developer v9.03.1641

Hopefully this is of help to someone!

Decode JSON with unknown structure

package main

import "encoding/json"

func main() {
    in := []byte(`{ "votes": { "option_A": "3" } }`)
    var raw map[string]interface{}
    if err := json.Unmarshal(in, &raw); err != nil {
        panic(err)
    }
    raw["count"] = 1
    out, err := json.Marshal(raw)
    if err != nil {
        panic(err)
    }
    println(string(out))
}

https://play.golang.org/p/o8ZwvgsQmoO

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml from a file deployed at http://run.jsbin.com due to the same-origin policy.


As the source (aka origin) page and the target URL are at different domains (run.jsbin.com and www.ecb.europa.eu), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET.

In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.


Example:

A page at http://www.example.com/myPage.html can only directly request services that are at http://www.example.com, like http://www.example.com/api/myService. If the service is hosted at another domain (say http://www.ok.com/api/myService), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a (CORS) request* across different domains, your browser:

  • Will include an Origin header in the original request (with the page's domain as value) and perform it as usual; and then
  • Only if the server response to that request contains the adequate headers (Access-Control-Allow-Origin is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).


* The above depicts the steps in a simple request, such as a regular GET with no fancy headers. If the request is not simple (like a POST with application/json as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS request to the target URL. Like above, it only will continue if the response to this OPTIONS request contains the CORS headers. This OPTIONS call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers header.


How to fix it?

Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com it will only make regular calls to www.example.com! Other URLs, such as api.example.com or even example.com or www.example.com:8080 are considered different domains by the browser! Yes, if the port is different, then it is a different domain!

Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin) to the server's responses. (Each server/language has a way to do that - check some solutions here.)

Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.

How can I hide the Android keyboard using JavaScript?

I've fixed like this, with this "$(input).prop('readonly',true);" in beforeShow

Ex:

$('input.datepicker').datepicker(
                        {   
                            changeMonth: false,
                            changeYear: false,
                            beforeShow: function(input, instance) { 
                                $(input).datepicker('setDate', new Date());
                                $(input).prop('readonly',true);
                            }
                        }                         
                     ); 

Styling an input type="file" button

This is a nice way to do it with material / angular file upload. You could do the same with a bootstrap button.

Note I used <a> instead of <button> this allows the click events to bubble up.

<label>
    <input type="file" (change)="setFile($event)" style="display:none" />

    <a mat-raised-button color="primary">
      <mat-icon>file_upload</mat-icon>
      Upload Document
    </a>

  </label>

jQuery bind to Paste Event, how to get the content of the paste

This work on all browser to get pasted value. And also to creating common method for all text box.

$("#textareaid").bind("paste", function(e){       
    var pastedData = e.target.value;
    alert(pastedData);
} )

How can I start and check my MySQL log?

For me, general_log didn't worked. But adding this to my.ini worked

[mysqld]
log-output=FILE
slow_query_log = 1
slow_query_log_file = "d:/temp/developer.log"

Add line break to ::after or ::before pseudo-element content

You may try this

#headerAgentInfoDetailsPhone
{
    white-space:pre
}
#headerAgentInfoDetailsPhone:after {
    content:"Office: XXXXX \A Mobile: YYYYY ";
}

Js Fiddle

Angular2: custom pipe could not be found

This didnt worked for me. (Im with Angular 2.1.2). I had NOT to import MainPipeModule in app.module.ts and importe it instead in the module where the component Im using the pipe is imported too.

Looks like if your component is declared and imported in a different module, you need to include your PipeModule in that module too.

400 BAD request HTTP error code meaning?

A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.

In the case of a REST API with a JSON payload, 400's are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.

By that logic, both the scenarios you provided should be 400s.

Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation--either because of an undefined element or an improper element value. That would be a bad request. Same deal here.

Oracle client ORA-12541: TNS:no listener

According to oracle online documentation

ORA-12541: TNS:no listener

Cause: The connection request could not be completed because the listener is not running.

Action: Ensure that the supplied destination address matches one of the addresses used by 
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or  
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on 
the remote machine.

How to check a channel is closed or not without reading it?

From the documentation:

A channel may be closed with the built-in function close. The multi-valued assignment form of the receive operator reports whether a received value was sent before the channel was closed.

https://golang.org/ref/spec#Receive_operator

Example by Golang in Action shows this case:

// This sample program demonstrates how to use an unbuffered
// channel to simulate a game of tennis between two goroutines.
package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

// wg is used to wait for the program to finish.
var wg sync.WaitGroup

func init() {
    rand.Seed(time.Now().UnixNano())
}

// main is the entry point for all Go programs.
func main() {
    // Create an unbuffered channel.
    court := make(chan int)
    // Add a count of two, one for each goroutine.
    wg.Add(2)
    // Launch two players.
    go player("Nadal", court)
    go player("Djokovic", court)
    // Start the set.
    court <- 1
    // Wait for the game to finish.
    wg.Wait()
}

// player simulates a person playing the game of tennis.
func player(name string, court chan int) {
    // Schedule the call to Done to tell main we are done.
    defer wg.Done()
    for {
        // Wait for the ball to be hit back to us.
        ball, ok := <-court
        fmt.Printf("ok %t\n", ok)
        if !ok {
            // If the channel was closed we won.
            fmt.Printf("Player %s Won\n", name)
            return
        }
        // Pick a random number and see if we miss the ball.
        n := rand.Intn(100)
        if n%13 == 0 {
            fmt.Printf("Player %s Missed\n", name)
            // Close the channel to signal we lost.
            close(court)
            return
        }

        // Display and then increment the hit count by one.
        fmt.Printf("Player %s Hit %d\n", name, ball)
        ball++
        // Hit the ball back to the opposing player.
        court <- ball
    }
}

How to create a BKS (BouncyCastle) format Java Keystore that contains a client certificate chain

I don't think your problem is with the BouncyCastle keystore; I think the problem is with a broken javax.net.ssl package in Android. The BouncyCastle keystore is a supreme annoyance because Android changed a default Java behavior without documenting it anywhere -- and removed the default provider -- but it does work.

Note that for SSL authentication you may require 2 keystores. The "TrustManager" keystore, which contains the CA certs, and the "KeyManager" keystore, which contains your client-site public/private keys. (The documentation is somewhat vague on what needs to be in the KeyManager keystore.) In theory, you shouldn't need the TrustManager keystore if all of your certficates are signed by "well-known" Certifcate Authorities, e.g., Verisign, Thawte, and so on. Let me know how that works for you. Your server will also require the CA for whatever was used to sign your client.

I could not create an SSL connection using javax.net.ssl at all. I disabled the client SSL authentication on the server side, and I still could not create the connection. Since my end goal was an HTTPS GET, I punted and tried using the Apache HTTP Client that's bundled with Android. That sort-of worked. I could make the HTTPS conection, but I still could not use SSL auth. If I enabled the client SSL authentication on my server, the connection would fail. I haven't checked the Apache HTTP Client code, but I suspect they are using their own SSL implementation, and don't use javax.net.ssl.

How to convert unix timestamp to calendar date moment.js

new moment(timeStamp,'yyyyMMddHHmmssfff').toDate()

When is it acceptable to call GC.Collect?

If you are using a version of .net less than 4.5, manual collection may be inevitable (especially if you are dealing with many 'large objects').

this link describes why:

https://blogs.msdn.microsoft.com/dotnet/2011/10/03/large-object-heap-improvements-in-net-4-5/

MySQL Query GROUP BY day / month / year

I prefer to optimize the one year group selection like so:

SELECT COUNT(*)
  FROM stats
 WHERE record_date >= :year 
   AND record_date <  :year + INTERVAL 1 YEAR;

This way you can just bind the year in once, e.g. '2009', with a named parameter and don't need to worry about adding '-01-01' or passing in '2010' separately.

Also, as presumably we are just counting rows and id is never NULL, I prefer COUNT(*) to COUNT(id).

How to convert a Date to a formatted string in VB.net?

Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
objBL.date = Convert.ToDateTime(txtDate.Value).ToString(timeFormat)

How can I read user input from the console?

Console.Read() takes a character and returns the ascii value of that character.So if you want to take the symbol that was entered by the user instead of its ascii value (ex:if input is 5 then symbol = 5, ascii value is 53), you have to parse it using int.parse() but it raises a compilation error because the return value of Console.Read() is already int type. So you can get the work done by using Console.ReadLine() instead of Console.Read() as follows.

int userInput = int.parse(Console.ReadLine());

here, the output of the Console.ReadLine() would be a string containing a number such as "53".By passing it to the int.Parse() we can convert it to int type.

Java SSLHandshakeException "no cipher suites in common"

I got this error with this ... unfortunate... package I have to use and I don't have source for. After much digging (thank you, Stack Overflow) and trying endless combinations, I finally got things running by:

  1. Creating the JKS with the entire certificate chain.

  2. Making sure the key in the JKS had the alias of the FQDN of the machine.

  3. Renaming the alias of the certificate for my machine ${FQDN}.cert

This took endless experimentation with the java command line options:

-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager 
-Djava.security.debug=access:stack

My key and CSR were produced in OpenSSL so I had to import the key with:

openssl pkcs12 -export -in  cert.pem -inkey  cert.key -CAfile fullChain.pem -name ${FQDN} -out cert.p12
keytool -importkeystore -destkeystore cert.jks -srckeystore cert.p12 -srcstoretype PKCS12

keytool complains about the format so I converted the format followed by adding my cert chain:

keytool -importkeystore -srckeystore cert.jks -destkeystore cert_p12.jks -deststoretype pkcs12
keytool -import -trustcacerts -alias 'DigiCert Global Root G2 IntermediateCA' -keystore cert_p12.jks -file cert2.pem -storepass "$STOREPASS" -keypass "$KEYPASS" 
keytool -import -trustcacerts -alias 'DigiCert Global Root G2'                -keystore cert_p12.jks -file cert3.pem -storepass "$STOREPASS" -keypass "$KEYPASS"

(where cert2.pem and cert3.pem were downloaded from the DigiCert web site and converted to PEM format.) When I restarted the application with the resulting jks file, things started to work.

Something else I figured out as part of this. You can check the certificate chain by using:

openssl x509 -in cert2.pem -noout -text

for all your certificates and studying the output, paying attention to the X509v3 Authority Key Identifier: and X509v3 Authority Key Identifier: lines. The X509v3 Authority Key Identifier: of one level matches the X509v3 Subject Key Identifier: of the next higher level. You found the top of chain when the Issuer: string matches the Subject: string.

I hope this can save somebody some of the time it took me.

Where does the iPhone Simulator store its data?

Where Xcode stores simulators in 2019+ Catalina, Xcode 11.0

Runtimes

$ open ~/Library/Developer/CoreSimulator/Profiles/Runtimes

For example: iOS 13.0, watchOS 6.0 These take the most space, by far. Each one can be up to ~5GB

Devices

$ open ~/Library/Developer/CoreSimulator/Devices

For example: iPhone Xr, iPhone 11 Pro Max. These are typically <15 mb each.

Explanation

Simulators are split between runtimes and devices. If you run $ xcrun simctl list you can see an overview, but if you want to find the physical location of these simulators, look in these directories I've shown.

It's totally safe to delete runtimes you don't support. You can reinstall these later if you want.

Run batch file as a Windows service

Why not simply set it up as a Scheduled Task that is scheduled to run at start up?

Does java.util.List.isEmpty() check if the list itself is null?

You're trying to call the isEmpty() method on a null reference (as List test = null; ). This will surely throw a NullPointerException. You should do if(test!=null) instead (Checking for null first).

The method isEmpty() returns true, if an ArrayList object contains no elements; false otherwise (for that the List must first be instantiated that is in your case is null).

Edit:

You may want to see this question.

What are the differences between Mustache.js and Handlebars.js?

NOTE: This answer is outdated. It was true at the time it was posted, but no longer is.

Mustache has interpreters in many languages, while Handlebars is Javascript only.

How to get a random number in Ruby

rand(6)    #=> gives a random number between 0 and 6 inclusively 
rand(1..6) #=> gives a random number between 1 and 6 inclusively

Note that the range option is only available in newer(1.9+ I believe) versions of ruby.

Where is Java's Array indexOf?

Arrays themselves do not have that method. A List, however, does: indexOf

Where's my invalid character (ORA-00911)

One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .

What is username and password when starting Spring Boot with Tomcat?

If you can't find the password based on other answers that point to a default one, the log message wording in recent versions changed to

Using generated security password: <some UUID>

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

I get authenticated user by HttpServletRequest.getUserPrincipal();

Example:

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.support.RequestContext;

import foo.Form;

@Controller
@RequestMapping(value="/welcome")
public class IndexController {

    @RequestMapping(method=RequestMethod.GET)
    public String getCreateForm(Model model, HttpServletRequest request) {

        if(request.getUserPrincipal() != null) {
            String loginName = request.getUserPrincipal().getName();
            System.out.println("loginName : " + loginName );
        }

        model.addAttribute("form", new Form());
        return "welcome";
    }
}

nginx - read custom header from upstream server

I was facing the same issue. I tried both $http_my_custom_header and $sent_http_my_custom_header but it did not work for me.

Although solved this issue by using $upstream_http_my_custom_header.

How to check if a string starts with one of several prefixes?

No one mentioned Stream so far, so here it is:

if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri").anyMatch(s -> newStr4.startsWith(s)))

How to register multiple servlets in web.xml in one Spring application

As explained in this thread on the cxf-user mailing list, rather than having the CXFServlet load its own spring context from user-webservice-servlet.xml, you can just load the whole lot into the root context. Rename your existing user-webservice-servlet.xml to some other name (e.g. user-webservice-beans.xml) then change your contextConfigLocation parameter to something like:

<servlet>
  <servlet-name>myservlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>myservlet</servlet-name>
  <url-pattern>*.htm</url-pattern>
</servlet-mapping>

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
    /WEB-INF/applicationContext.xml
    /WEB-INF/user-webservice-beans.xml
  </param-value>
</context-param>

<servlet>
  <servlet-name>user-webservice</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>user-webservice</servlet-name>
  <url-pattern>/UserService/*</url-pattern>
</servlet-mapping>

How do you determine what SQL Tables have an identity column programmatically

Another way (for 2000 / 2005/2012/2014):

IF ((SELECT OBJECTPROPERTY( OBJECT_ID(N'table_name_here'), 'TableHasIdentity')) = 1)
    PRINT 'Yes'
ELSE
    PRINT 'No'

NOTE: table_name_here should be schema.table, unless the schema is dbo.

Single line if statement with 2 actions

userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";

should do the trick.

Check cell for a specific letter or set of letters

You can use RegExMatch:

=IF(RegExMatch(A1;"Bla");"YES";"NO")

Select All checkboxes using jQuery

Try the following simple code:

$('input[type=checkbox]').each(function() { this.checked = true; }); 

Source: How to reset all checkboxes using jQuery or pure JS?

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

Try this:

   import * as moment from 'moment';

     ngOnInit() {
     this.date = moment().format("YYYY Do MMM");
                }

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

--> (Absence of load-on-start-up) tag First of all when ever servlet is deployed in the server, It is the responsibility of the server to creates the servlet object. Eg: Suppose Servlet is deployed in the server ,(Servlet Object is not available in server) client sends the request to the servlet for the first time then server creates the servlet object with help of default constructor and immediately calls init() . From that when ever client sends the request only service method will get executed as object is already available

If load-on-start-up tag is used in deployment descriptor: At the time of deployment itself the server creates the servlet object for the servlets based on the positive value provided in between the tags. The Creation of objects for the servlet classes will follow from 0-128 0 number servlet will be created first and followed by other numbers.

If we provide same value for two servlets in web.xml then creation of objects will be done based on the position of classes in web.xml also varies from server to server.

If we provide negative value in between the load on start up tag then server wont create the servlet object.

Other Scenarios where server creates the object for servlet.

If we dont use load on start up tag in web.xml, then project is deployed when ever client sends the request for the first time server creates the object and server is responsible for calling its life cycle methods. Then if a .class is been modified in the server(tomcat). again client sends the request for modified servlet but in case of tomcat new object will not created and server make use of existing object unless restart of server takes place. But in class of web-logic when ever .class file is modified in the server with out restarting the server if it receives a request then server calls the destroy method on existing servlet and creates a new servlet object and calls init() for its initilization.

How do you attach and detach from Docker's process?

To detach from a running container, use ^P^Q (hold Ctrl, press P, press Q, release Ctrl).

There's a catch: this only works if the container was started with both -t and -i.

If you have a running container that was started without one (or both) of these options, and you attach with docker attach, you'll need to find another way to detach. Depending on the options you chose and the program that's running, ^C may work, or it may kill the whole container. You'll have to experiment.

Another catch: Depending on the programs you're using, your terminal, shell, SSH client, or multiplexer could be intercepting either ^P or ^Q (usually the latter). To test whether this is the issue, try running or attaching with the --detach-keys z argument. You should now be able to detach by pressing z, without any modifiers. If this works, another program is interfering. The easiest way to work around this is to set your own detach sequence using the --detach-keys argument. (For example, to exit with ^K, use --detach-keys 'ctrl-k'.) Alternatively, you can attempt to disable interception of the keys in your terminal or other interfering program. For example, stty start '' or stty start undef may prevent the terminal from intercepting ^Q on some POSIX systems, though I haven't found this to be helpful.

how to convert JSONArray to List of Object using camel-jackson

/*
 It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
 * put string into file jsonFileArr.json
 * [{"username":"Hello","email":"[email protected]","credits"
 * :"100","twitter_username":""},
 * {"username":"Goodbye","email":"[email protected]"
 * ,"credits":"0","twitter_username":""},
 * {"username":"mlsilva","email":"[email protected]"
 * ,"credits":"524","twitter_username":""},
 * {"username":"fsouza","email":"[email protected]"
 * ,"credits":"1052","twitter_username":""}]
 */

public class TestaGsonLista {

public static void main(String[] args) {
Gson gson = new Gson();
 try {
    BufferedReader br = new BufferedReader(new FileReader(
            "C:\\Temp\\jsonFileArr.json"));
    JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement str = jsonArray.get(i);
        Usuario obj = gson.fromJson(str, Usuario.class);
        //use the add method from the list and returns it.
        System.out.println(obj);
        System.out.println(str);
        System.out.println("-------");
    }
 } catch (IOException e) {
    e.printStackTrace();
 }
}

Java, reading a file from current directory?

Thanks @Laurence Gonsalves your answer helped me a lot. your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:

public class Run {
public static void main(String[] args) {
    File inputFile = new File("./src/main/java/input.txt");
    try {
        Scanner reader = new Scanner(inputFile);
        while (reader.hasNextLine()) {
            String data = reader.nextLine();
            System.out.println(data);
            
        }
        reader.close();
    } catch (FileNotFoundException e) {
        System.out.println("scanner error");
        e.printStackTrace();
    }
}

}

While my input.txt file is in same directory.

enter image description here

How to join three table by laravel eloquent model

With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.

We have three models:

1) Article (belongs to user and category)

2) Category (has many articles)

3) User (has many articles)


1) Article.php

<?php

namespace App\Models;
 use Eloquent;

class Article extends Eloquent{

    protected $table = 'articles';

    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }

    public function category()
    {
        return $this->belongsTo('App\Models\Category');
    }

}

2) Category.php

<?php

namespace App\Models;

use Eloquent;

class Category extends Eloquent
{
    protected $table = "categories";

    public function articles()
    {
        return $this->hasMany('App\Models\Article');
    }

}

3) User.php

<?php

namespace App\Models;
use Eloquent;

class User extends Eloquent
{
    protected $table = 'users';

    public function articles()
    {
        return $this->hasMany('App\Models\Article');
    }

}

You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.

For example, if you want to retrieve an article by using the user and category, you would need to write:

$article = \App\Models\Article::with(['user','category'])->first();

and you can use this like so:

//retrieve user name 
$article->user->user_name  

//retrieve category name 
$article->category->category_name

In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:

$categories = \App\Models\Category::with('articles')->get();

$users = \App\Models\Category::with('users')->get();

You can learn more at http://laravel.com/docs/5.0/eloquent

Mapping two integers to one, in a unique and deterministic way

If A and B can be expressed with 2 bytes, you can combine them on 4 bytes. Put A on the most significant half and B on the least significant half.

In C language this gives (assuming sizeof(short)=2 and sizeof(int)=4):

int combine(short A, short B)
{
    return A<<16 | B;
}

short getA(int C)
{
    return C>>16;
}

short getB(int C)
{
    return C & 0xFFFF;
}

Adjust width of input field to its input

To calculate the width of the current input, you'll have to embed it in a temporary span element, attach that thing to the DOM, get the computed width (in pixels) using the scrollWidth property and remove the span again. Of course you'll have to ensure that the same font family, font size, etc., is used in the input as well as in the span element. Therefore I assigned the same class to them.

I attached the function to the keyup event, as on keypress the input character is not yet added to the input value, so that will result in the wrong width. Unfortunately, I don't know how to get rid of the scrolling of the input field (when adding characters to the end of the field); it scrolls, because the character is added and shown before adjustWidthOfInput() is called. And, as said, I can't do this the other way round because then you'll have the value of the input field before the pressed character is inserted. I'll try to solve this issue later.

BTW, I only tested this in Firefox (3.6.8), but you'll get the point, I hope.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Get/set width of &lt;input&gt;</title>
    <style>
      body {
        background: #666;
      }

      .input-element {
        border: 0;
        padding: 2px;
        background: #fff;
        font: 12pt sans-serif;
      }

      .tmp-element {
        visibility: hidden;
        white-space: pre;
      }
    </style>
  </head>
  <body>
    <input id="theInput" type="text" class="input-element" value="1">
    <script>
      var inputEl = document.getElementById("theInput");

      function getWidthOfInput() {
        var tmp = document.createElement("span");
        tmp.className = "input-element tmp-element";
        tmp.innerHTML = inputEl.value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
        document.body.appendChild(tmp);
        var theWidth = tmp.getBoundingClientRect().width;
        document.body.removeChild(tmp);
        return theWidth;
      }

      function adjustWidthOfInput() {
        inputEl.style.width = getWidthOfInput() + "px";
      }

      adjustWidthOfInput();
      inputEl.onkeyup = adjustWidthOfInput;
    </script>
  </body>
</html>

H2 database error: Database may be already in use: "Locked by another process"

answer for this question => Exception in thread "main" org.h2.jdbc.JdbcSQLException: Database may be already in use: "Locked by another process". Possible solutions: close all other connection(s); use the server mode [90020-161]

close all tab from your browser where open h2 database also Exit h2 engine from your pc

TypeError: 'str' object is not callable (Python)

An issue I just had was accidentally calling a string

"Foo" ("Bar" if bar else "Baz")

You can concatenate string by just putting them next to each other like so

"Foo" "Bar"

however because of the open brace in the first example it thought I was trying to call "Foo"

How do I convert a long to a string in C++?

int main()
{
    long mylong = 123456789;
    string mystring;
    stringstream mystream;
    mystream << mylong;
    mystring = mystream.str();
    cout << mystring << "\n";
    return 0;
}

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

Declare an output cursor variable to the inner sp :

@c CURSOR VARYING OUTPUT

Then declare a cursor c to the select you want to return. Then open the cursor. Then set the reference:

DECLARE c CURSOR LOCAL FAST_FORWARD READ_ONLY FOR 
SELECT ...
OPEN c
SET @c = c 

DO NOT close or reallocate.

Now call the inner sp from the outer one supplying a cursor parameter like:

exec sp_abc a,b,c,, @cOUT OUTPUT

Once the inner sp executes, your @cOUT is ready to fetch. Loop and then close and deallocate.

Is there a stopwatch in Java?

Use System.currentTimeMillis() to get the start time and the end time and calculate the difference.

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

    long startTime = System.currentTimeMillis();

    long total = 0;
    for (int i = 0; i < 10000000; i++) {
      total += i;
    }

    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;
    System.out.println(elapsedTime);
  }
} 

More info at this tutorial

Configure Log4net to write to multiple files

Yes, just add multiple FileAppenders to your logger. For example:

<log4net>
    <appender name="File1Appender" type="log4net.Appender.FileAppender">
        <file value="log-file-1.txt" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %message%newline" />
        </layout>
    </appender>
    <appender name="File2Appender" type="log4net.Appender.FileAppender">
        <file value="log-file-2.txt" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %message%newline" />
        </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="File1Appender" />
        <appender-ref ref="File2Appender" />
    </root>
</log4net>