Programs & Examples On #Include path

An include path is a set of directories that contain headers or library files that should be accessed with no prefixed directory. Include paths normally include the location of the standard library, locations of third party libraries, and locations of system headers.

How to make g++ search for header files in a specific directory?

Headers included with #include <> will be searched in all default directories , but you can also add your own location in the search path with -I command line arg.

I saw your edit you could install your headers in default locations usually

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

Confirm with compiler docs though.

PHP - Failed to open stream : No such file or directory

For me I got this error because I was trying to read a file which required HTTP auth, with a username and password. Hope that helps others. Might be another corner case.

Java, How to add library files in netbeans?

In Netbeans 8.2

1. Dowload the binaries from the web source. The Apache Commos are in: [http://commons.apache.org/components.html][1] In this case, you must select the "Logging" in the Components menu and follow the link to downloads in the Releases part. Direct URL: [http://commons.apache.org/proper/commons-logging/download_logging.cgi][2] For me, the correct download was the file: commons-logging-1.2-bin.zip from the Binaries.

2. Unzip downloaded content. Now, you can see several jar files inside the directory created from the zip file.

3. Add the library to the project. Right click in the project, select Properties and click in Libraries (in the left side). Click the button "Add Jar/Folder". Go to the previously unzipped contents and select the properly jar file. Clic in "Open" and click in"Ok". The library has been loaded!

Eclipse CDT: Symbol 'cout' could not be resolved

I had a similar problem with *std::shared_ptr* with Eclipse using MinGW and gcc 4.8.1. No matter what, Eclipse would not resolve *shared_ptr*. To fix this, I manually added the __cplusplus macro to the C++ symbols and - viola! - Eclipse can find it. Since I specified -std=c++11 as a compile option, I (ahem) assumed that the Eclipse code analyzer would use that option as well. So, to fix this:

  1. Project Context -> C/C++ General -> Paths and Symbols -> Symbols Tab
  2. Select C++ in the Languages panel.
  3. Add symbol __cplusplus with a value of 201103.

The only problem with this is that gcc will complain that the symbol is already defined(!) but the compile will complete as before.

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

If you look at the PHP constant PATH_SEPARATOR, you will see it being ":" for you.

If you break apart your string ".:/usr/share/pear:/usr/share/php" using that character, you will get 3 parts.

  • . (this means the current directory your code is in)
  • /usr/share/pear
  • /usr/share/php

Any attempts to include()/require() things, will look in these directories, in this order.

It is showing you that in the error message to let you know where it could NOT find the file you were trying to require()

For your first require, if that is being included from your index.php, then you dont need the dir stuff, just do...

require_once ( 'db/config.php');

How can I combine flexbox and vertical scroll in a full-height app?

Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.

The solution is setting a height to the vertical scrollable element. For example:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 0px;
}

The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px; that it is exactly the same as: min-height: 100px;

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    height: 100px; /* == min-height: 100px*/
}

So the best solution if you want a min-height in the vertical scroll:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 100px;
}

If you just want full vertical scroll in case there is no enough space to see the article:

#container article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 0px;
}

The final code: http://jsfiddle.net/ch7n6/867/

How to find good looking font color if background color is known?

Might be strange to answer my own question, but here is another really cool color picker I never saw before. It does not solve my problem either :-(((( however I think it's much cooler to these I know already.

http://www.colorjack.com/

On the right, under Tools select "Color Sphere", a very powerful and customizable sphere (see what you can do with the pop-ups on top), "Color Galaxy", I'm still not sure how this works, but looks cool and "Color Studio" is also nice. Further it can export to all kind of formats (e.g. Illustrator or Photoshop, etc.)

How about this, I choose my background color there, let it create a complimentary color (from the first pop up) - this should have highest contrast and thus be best readable, now select the complementary color as main color and select neutral? Hmmm... not too great either, but we are getting better ;-)

Get first row of dataframe in Python Pandas based on criteria

This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:

>>> df[condition]

This will return a slice of your dataframe which you can index using iloc. Here are your examples:

  1. Get first row where A > 3 (returns row 2)

    >>> df[df.A > 3].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

If what you actually want is the row number, rather than using iloc, it would be df[df.A > 3].index[0].

  1. Get first row where A > 4 AND B > 3:

    >>> df[(df.A > 4) & (df.B > 3)].iloc[0]
    A    5
    B    4
    C    5
    Name: 4, dtype: int64
    
  2. Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)

    >>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:

>>> def series_or_default(X, condition, default_col, ascending=False):
...     sliced = X[condition]
...     if sliced.shape[0] == 0:
...         return X.sort_values(default_col, ascending=ascending).iloc[0]
...     return sliced.iloc[0]
>>> 
>>> series_or_default(df, df.A > 6, 'A')
A    5
B    4
C    5
Name: 4, dtype: int64

As expected, it returns row 4.

async at console app in C#?

As a quick and very scoped solution:

Task.Result

Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.

When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.

notasync

Converting a String array into an int Array in java

Suppose, for example, that we have a arrays of strings:

String[] strings = {"1", "2", "3"};

With Lambda Expressions [1] [2] (since Java 8), you can do the next ?:

int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();

? This is another way:

int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();

—————————
Notes
1. Lambda Expressions in The Java Tutorials.
2. Java SE 8: Lambda Quick Start

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

This is supposedly because you trying to make cross-domain request, or something that is clarified as it. You could try adding header('Access-Control-Allow-Origin: *'); to the requested file.

Also, such problem is sometimes occurs on server-sent events implementation in case of using event-source or XHR polling in IE 8-10 (which confused me first time).

C char* to int conversion

atoi can do that for you

Example:

char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

Android camera intent

It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.

Request this permission on the AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

On your Activity, start by defining this:

static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;

Then fire this Intent in an onClick:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
    // Create the File where the photo should go
    File photoFile = null;
    try {
        photoFile = createImageFile();
    } catch (IOException ex) {
        // Error occurred while creating the File
        Log.i(TAG, "IOException");
    }
    // Continue only if the File was successfully created
    if (photoFile != null) {
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }
}

Add the following support method:

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  // prefix
            ".jpg",         // suffix
            storageDir      // directory
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

Then receive the result:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        try {
            mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
            mImageView.setImageBitmap(mImageBitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.

Find Facebook user (url to profile page) by known email address

Andreas, I've also been looking for an "email-to-id" ellegant solution and couldn't find one. However, as you said, screen scraping is not such a bad idea in this case, because emails are unique and you either get a single match or none. As long as Facebook don't change their search page drastically, the following will do the trick:

final static String USER_SEARCH_QUERY = "http://www.facebook.com/search.php?init=s:email&q=%s&type=users";
final static String USER_URL_PREFIX = "http://www.facebook.com/profile.php?id=";

public static String emailToID(String email)
{
    try
    {
        String html = getHTML(String.format(USER_SEARCH_QUERY, email));
        if (html != null)
        {
            int i = html.indexOf(USER_URL_PREFIX) + USER_URL_PREFIX.length();
            if (i > 0)
            {
                StringBuilder sb = new StringBuilder();
                char c;
                while (Character.isDigit(c = html.charAt(i++)))
                    sb.append(c);
                if (sb.length() > 0)
                    return sb.toString();
            }
        }
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;
}

private static String getHTML(String htmlUrl) throws MalformedURLException, IOException
{
    StringBuilder response = new StringBuilder();
    URL url = new URL(htmlUrl);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setRequestMethod("GET");
    if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
    {
        BufferedReader input = new BufferedReader(new InputStreamReader(httpConn.getInputStream()), 8192);
        String strLine = null;
        while ((strLine = input.readLine()) != null)
            response.append(strLine);
        input.close();
    }
    return (response.length() == 0) ? null : response.toString();
}

Read String line by line

You can also use:

String[] lines = someString.split("\n");

If that doesn't work try replacing \n with \r\n.

What does "while True" mean in Python?

while loops continue to loop until the condition is false. For instance (pseudocode):

i = 0
while i < 10
  i++

With each iteration of the loop, i will be incremented by 1, until it is 10. At that point, the condition i < 10 is no longer true, and the loop will complete.

Since the condition in while True is explicitly and always true, the loop will never end (until it is broken out of some other way, usually by a construct like break within the loop body).

How to use a DataAdapter with stored procedure and parameter

 SqlConnection con = new SqlConnection(@"Some Connection String");
 SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123;
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Django, creating a custom 500/404 error page

Try moving your error templates to .../Django/mysite/templates/ ?

I'm note sure about this one, but i think these need to be "global" to the website.

How can I include a YAML file inside another?

I make some examples for your reference.

import yaml

main_yaml = """
Package:
 - !include _shape_yaml    
 - !include _path_yaml
"""

_shape_yaml = """
# Define
Rectangle: &id_Rectangle
    name: Rectangle
    width: &Rectangle_width 20
    height: &Rectangle_height 10
    area: !product [*Rectangle_width, *Rectangle_height]

Circle: &id_Circle
    name: Circle
    radius: &Circle_radius 5
    area: !product [*Circle_radius, *Circle_radius, pi]

# Setting
Shape:
    property: *id_Rectangle
    color: red
"""

_path_yaml = """
# Define
Root: &BASE /path/src/

Paths: 
    a: &id_path_a !join [*BASE, a]
    b: &id_path_b !join [*BASE, b]

# Setting
Path:
    input_file: *id_path_a
"""


# define custom tag handler
def yaml_import(loader, node):
    other_yaml_file = loader.construct_scalar(node)
    return yaml.load(eval(other_yaml_file), Loader=yaml.SafeLoader)


def yaml_product(loader, node):
    import math
    list_data = loader.construct_sequence(node)
    result = 1
    pi = math.pi
    for val in list_data:
        result *= eval(val) if isinstance(val, str) else val
    return result


def yaml_join(loader, node):
    seq = loader.construct_sequence(node)
    return ''.join([str(i) for i in seq])


def yaml_ref(loader, node):
    ref = loader.construct_sequence(node)
    return ref[0]


def yaml_dict_ref(loader: yaml.loader.SafeLoader, node):
    dict_data, key, const_value = loader.construct_sequence(node)
    return dict_data[key] + str(const_value)


def main():
    # register the tag handler
    yaml.SafeLoader.add_constructor(tag='!include', constructor=yaml_import)
    yaml.SafeLoader.add_constructor(tag='!product', constructor=yaml_product)
    yaml.SafeLoader.add_constructor(tag='!join', constructor=yaml_join)
    yaml.SafeLoader.add_constructor(tag='!ref', constructor=yaml_ref)
    yaml.SafeLoader.add_constructor(tag='!dict_ref', constructor=yaml_dict_ref)

    config = yaml.load(main_yaml, Loader=yaml.SafeLoader)

    pk_shape, pk_path = config['Package']
    pk_shape, pk_path = pk_shape['Shape'], pk_path['Path']
    print(f"shape name: {pk_shape['property']['name']}")
    print(f"shape area: {pk_shape['property']['area']}")
    print(f"shape color: {pk_shape['color']}")

    print(f"input file: {pk_path['input_file']}")


if __name__ == '__main__':
    main()

output

shape name: Rectangle
shape area: 200
shape color: red
input file: /path/src/a

Update 2

and you can combine it, like this

# xxx.yaml
CREATE_FONT_PICTURE:
  PROJECTS:
    SUNG: &id_SUNG
      name: SUNG
      work_dir: SUNG
      output_dir: temp
      font_pixel: 24


  DEFINE: &id_define !ref [*id_SUNG]  # you can use config['CREATE_FONT_PICTURE']['DEFINE'][name, work_dir, ... font_pixel]
  AUTO_INIT:
    basename_suffix: !dict_ref [*id_define, name, !product [5, 3, 2]]  # SUNG30

# ? This is not correct.
# basename_suffix: !dict_ref [*id_define, name, !product [5, 3, 2]]  # It will build by Deep-level. id_define is Deep-level: 2. So you must put it after 2. otherwise, it can't refer to the correct value.

Adding a directory to PATH in Ubuntu

Actually I would advocate .profile if you need it to work from scripts, and in particular, scripts run by /bin/sh instead of Bash. If this is just for your own private interactive use, .bashrc is fine, though.

How can I get new selection in "select" in Angular 2?

I ran into this problem while doing the Angular 2 forms tutorial (TypeScript version) at https://angular.io/docs/ts/latest/guide/forms.html

The select/option block wasn't allowing the value of the selection to be changed by selecting one of the options.

Doing what Mark Rajcok suggested worked, although I'm wondering if there's something I missed in the original tutorial or if there was an update. In any case, adding

onChange(newVal) {
    this.model.power = newVal;
}

to hero-form.component.ts in the HeroFormComponent class

and

(change)="onChange($event.target.value)"

to hero-form.component.html in the <select> element made it work

String is immutable. What exactly is the meaning?

String is immutable means that you cannot change the object itself, but you can change the reference to the object.

When you execute a = "ty", you are actually changing the reference of a to a new object created by the String literal "ty".

Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods), for example:

Foo x = new Foo("the field");
x.setField("a new field");
System.out.println(x.getField()); // prints "a new field"

While in an immutable class (declared as final, to prevent modification via inheritance)(its methods cannot modify its fields, and also the fields are always private and recommended to be final), for example String, you cannot change the current String but you can return a new String, i.e:

String s = "some text";
s.substring(0,4);
System.out.println(s); // still printing "some text"
String a = s.substring(0,4);
System.out.println(a); // prints "some"

numpy: most efficient frequency counts for unique values in an array

numpy.bincount is the probably the best choice. If your array contains anything besides small dense integers it might be useful to wrap it something like this:

def count_unique(keys):
    uniq_keys = np.unique(keys)
    bins = uniq_keys.searchsorted(keys)
    return uniq_keys, np.bincount(bins)

For example:

>>> x = array([1,1,1,2,2,2,5,25,1,1])
>>> count_unique(x)
(array([ 1,  2,  5, 25]), array([5, 3, 1, 1]))

C# Set collection?

I use Iesi.Collections http://www.codeproject.com/KB/recipes/sets.aspx

It's used in lot of OSS projects, I first came across it in NHibernate

Pass Hidden parameters using response.sendRedirect()

TheNewIdiot's answer successfully explains the problem and the reason why you can't send attributes in request through a redirect. Possible solutions:

  1. Using forwarding. This will enable that request attributes could be passed to the view and you can use them in form of ServletRequest#getAttribute or by using Expression Language and JSTL. Short example (reusing TheNewIdiot's answer] code).

    Controller (your servlet)

    request.setAttribute("message", "Hello world");
    RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
    dispatcher.forward(request, response);
    

    View (your JSP)

    Using scriptlets:

    <%
        out.println(request.getAttribute("message"));
    %>
    

    This is just for information purposes. Scriptlets usage must be avoided: How to avoid Java code in JSP files?. Below there is the example using EL and JSTL.

    <c:out value="${message}" />
    
  2. If you can't use forwarding (because you don't like it or you don't feel it that way or because you must use a redirect) then an option would be saving a message as a session attribute, then redirect to your view, recover the session attribute in your view and remove it from session. Remember to always have your user session with only relevant data. Code example

    Controller

    //if request is not from HttpServletRequest, you should do a typecast before
    HttpSession session = request.getSession(false);
    //save message in session
    session.setAttribute("helloWorld", "Hello world");
    response.sendRedirect("/content/test.jsp");
    

    View

    Again, showing this using scriptlets and then EL + JSTL:

    <%
        out.println(session.getAttribute("message"));
        session.removeAttribute("message");
    %>
    
    <c:out value="${sessionScope.message}" />
    <c:remove var="message" scope="session" />
    

How to check if a character in a string is a digit or letter

This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0) now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.

here is a code for your program:

import java.util.Scanner;

class Practice
{
 public static void main(String[] args)
  {
   Scanner in = new Scanner(System.in);
   System.out.println("Input a letter"); 
   String line = in.nextLine();
   char c = line.charAt(0);
   if( Character.isDigit(c))
   System.out.println(c +" Is a digit");
   else if (Character.isLetter(c))
   System.out.println(c +" Is a Letter");
  }

}

Import functions from another js file. Javascript

By default, scripts can't handle imports like that directly. You're probably getting another error about not being able to get Course or not doing the import.

If you add type="module" to your <script> tag, and change the import to ./course.js (because browsers won't auto-append the .js portion), then the browser will pull down course for you and it'll probably work.

import './course.js';

function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
}

<html>
    <head>
        <script src="./models/student.js" type="module"></script>
    </head>
    <body>
        <div id="myDiv">
        </div>
        <script>
        window.onload= function() {
            var x = new Student();
            x.course.id = 1;
            document.getElementById('myDiv').innerHTML = x.course.id;
        }
        </script>
    </body>
</html>

If you're serving files over file://, it likely won't work. Some IDEs have a way to run a quick sever.

You can also write a quick express server to serve your files (install Node if you don't have it):

//package.json
{
  "scripts": { "start": "node server" },
  "dependencies": { "express": "latest" }
}

// server/index.js
const express = require('express');
const app = express();

app.use('/', express.static('PATH_TO_YOUR_FILES_HERE');
app.listen(8000);

With those two files, run npm install, then npm start and you'll have a server running over http://localhost:8000 which should point to your files.

Retrieve last 100 lines logs

len=`cat filename | wc -l`
len=$(( $len + 1 ))
l=$(( $len - 99 ))
sed -n "${l},${len}p" filename

first line takes the length (Total lines) of file then +1 in the total lines after that we have to fatch 100 records so, -99 from total length then just put the variables in the sed command to fetch the last 100 lines from file

I hope this will help you.

%matplotlib line magic causes SyntaxError in Python script

The syntax '%' in %matplotlib inline is recognized by iPython (where it is set up to handle the magic methods), but not Python itself, which gives a SyntaxError. Here is given one solution.

How to get Activity's content view?

You may want to try View.getRootView().

Getting Integer value from a String using javascript/jquery

For parseInt to work, your string should have only numerical data. Something like this:

 str1 = "123.00";
 str2 = "50.00";
 total = parseInt(str1)+parseInt(str2);
 alert(total);

Can you split the string before you start processing them for a total?

What is the syntax of the enhanced for loop in Java?

An enhanced for loop is just limiting the number of parameters inside the parenthesis.

for (int i = 0; i < myArray.length; i++) {
    System.out.println(myArray[i]);
}

Can be written as:

for (int myValue : myArray) {
    System.out.println(myValue);
}

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

Run a Command Prompt command from Desktop Shortcut

Yes, make the shortcut's path

%comspec% /k <command>

where

  • %comspec% is the environment variable for cmd.exe's full path, equivalent to C:\Windows\System32\cmd.exe on most (if not all) Windows installs
  • /k keeps the window open after the command has run, this may be replaced with /c if you want the window to close once the command is finished running
  • <command> is the command you wish to run

How to change the minSdkVersion of a project?

This is what worked for me:

In the build.gradle file, setting the minSdkVersion under defaultConfig:

enter image description here

Good Luck...

update package.json version automatically

Right answer

To do so, just npm version patch =)

My old answer

There is no pre-release hook originally in git. At least, man githooks does not show it.

If you're using git-extra (https://github.com/visionmedia/git-extras), for instance, you can use a pre-release hook which is implemented by it, as you can see at https://github.com/visionmedia/git-extras/blob/master/bin/git-release. It is needed only a .git/hook/pre-release.sh executable file which edits your package.json file. Committing, pushing and tagging will be done by the git release command.

If you're not using any extension for git, you can write a shell script (I'll name it git-release.sh) and than you can alias it to git release with something like:

git config --global alias.release '!sh path/to/pre-release.sh $1'

You can, than, use git release 0.4 which will execute path/to/pre-release.sh 0.4. Your script can edit package.json, create the tag and push it to the server.

Submit form using a button outside the <form> tag

Try this:

<input type="submit" onclick="document.forms[0].submit();" />

Although I would suggest adding an id to the form and accessing by that instead of document.forms[index].

AES Encrypt and Decrypt

Code provided by SHS didn't work for me, but this one apparently did (I used a Bridging Header: #import <CommonCrypto/CommonCrypto.h>):

extension String {

    func aesEncrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
        if let keyData = key.data(using: String.Encoding.utf8),
            let data = self.data(using: String.Encoding.utf8),
            let cryptData    = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {


            let keyLength              = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCEncrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options:   CCOptions   = UInt32(options)



            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation,
                                      algoritm,
                                      options,
                                      (keyData as NSData).bytes, keyLength,
                                      iv,
                                      (data as NSData).bytes, data.count,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
                return base64cryptString


            }
            else {
                return nil
            }
        }
        return nil
    }

    func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
        if let keyData = key.data(using: String.Encoding.utf8),
            let data = NSData(base64Encoded: self, options: .ignoreUnknownCharacters),
            let cryptData    = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {

            let keyLength              = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCDecrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options:   CCOptions   = UInt32(options)

            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation,
                                      algoritm,
                                      options,
                                      (keyData as NSData).bytes, keyLength,
                                      iv,
                                      data.bytes, data.length,
                                      cryptData.mutableBytes, cryptData.length,
                                      &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let unencryptedMessage = String(data: cryptData as Data, encoding:String.Encoding.utf8)
                return unencryptedMessage
            }
            else {
                return nil
            }
        }
        return nil
    }


}

From my ViewController:

 let encoded = message.aesEncrypt(key: keyString, iv: iv)
 let unencode = encoded?.aesDecrypt(key: keyString, iv: iv)

How can I execute PHP code from the command line?

Using PHP from the command line

Use " instead of ' on Windows when using the CLI version with -r:

php -r "echo 1;"

-- correct

php -r 'echo 1;'

-- incorrect

  PHP Parse error:  syntax error, unexpected ''echo' (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1

Don't forget the semicolon to close the line.

Disable Required validation attribute under certain circumstances

What @Darin said is what I would recommend as well. However I would add to it (and in response to one of the comments) that you can in fact also use this method for primitive types like bit, bool, even structures like Guid by simply making them nullable. Once you do this, the Required attribute functions as expected.

public UpdateViewView
{
    [Required]
    public Guid? Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public int? Age { get; set; }
    [Required]
    public bool? IsApproved { get; set; }
    //... some other properties
}

How do I include a Perl module that's in a different directory?

From perlfaq8:


How do I add the directory my program lives in to the module/library search path?

(contributed by brian d foy)

If you know the directory already, you can add it to @INC as you would for any other directory. You might use lib if you know the directory at compile time:

use lib $directory;

The trick in this task is to find the directory. Before your script does anything else (such as a chdir), you can get the current working directory with the Cwd module, which comes with Perl:

BEGIN {
    use Cwd;
    our $directory = cwd;
    }

use lib $directory;

You can do a similar thing with the value of $0, which holds the script name. That might hold a relative path, but rel2abs can turn it into an absolute path. Once you have the

BEGIN {
    use File::Spec::Functions qw(rel2abs);
    use File::Basename qw(dirname);

    my $path   = rel2abs( $0 );
    our $directory = dirname( $path );
    }

use lib $directory;

The FindBin module, which comes with Perl, might work. It finds the directory of the currently running script and puts it in $Bin, which you can then use to construct the right library path:

use FindBin qw($Bin);

Generate war file from tomcat webapp folder

Its just like creating a WAR file of your project, you can do it in several ways (from Eclipse, command line, maven).

If you want to do from command line, the command is

jar -cvf my_web_app.war * 

Which means, "compress everything in this directory into a file named my_web_app.war" (c=create, v=verbose, f=file)

How to use concerns in Rails 4

This post helped me understand concerns.

# app/models/trader.rb
class Trader
  include Shared::Schedule
end

# app/models/concerns/shared/schedule.rb
module Shared::Schedule
  extend ActiveSupport::Concern
  ...
end

Java Error: illegal start of expression

Declare

public static int[] locations={1,2,3};

outside of the main method.

set default schema for a sql query

A quick google pointed me to this page. It explains that from sql server 2005 onwards you can set the default schema of a user with the ALTER USER statement. Unfortunately, that means that you change it permanently, so if you need to switch between schemas, you would need to set it every time you execute a stored procedure or a batch of statements. Alternatively, you could use the technique described here.

If you are using sql server 2000 or older this page explains that users and schemas are then equivalent. If you don't prepend your table name with a schema\user, sql server will first look at the tables owned by the current user and then the ones owned by the dbo to resolve the table name. It seems that for all other tables you must prepend the schema\user.

jQuery UI accordion that keeps multiple sections open?

Simple: active the accordion to a class, and then create divs with this, like multiples instances of accordion.

Like this:

JS

$(function() {
    $( ".accordion" ).accordion({
        collapsible: true,
        clearStyle: true,
        active: false,
    })
});

HTML

<div class="accordion">
    <h3>Title</h3>
    <p>lorem</p>
</div>
<div class="accordion">
    <h3>Title</h3>
    <p>lorem</p>
</div>
<div class="accordion">
    <h3>Title</h3>
    <p>lorem</p>
</div>

https://jsfiddle.net/sparhawk_odin/pm91whz3/

Send mail via Gmail with PowerShell V2's Send-MailMessage

I am really new to PowerShell, and I was searching about gmailing from PowerShell. I took what you folks did in previous answers, and modified it a bit and have come up with a script which will check for attachments before adding them, and also to take an array of recipients.

## Send-Gmail.ps1 - Send a gmail message
## By Rodney Fisk - [email protected]
## 2 / 13 / 2011

# Get command line arguments to fill in the fields
# Must be the first statement in the script
param(
    [Parameter(Mandatory = $true,
               Position = 0,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('From')] # This is the name of the parameter e.g. -From [email protected]
    [String]$EmailFrom, # This is the value [Don't forget the comma at the end!]

    [Parameter(Mandatory = $true,
               Position = 1,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('To')]
    [String[]]$Arry_EmailTo,

    [Parameter(Mandatory = $true,
               Position = 2,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Subj')]
    [String]$EmailSubj,

    [Parameter(Mandatory = $true,
               Position = 3,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Body')]
    [String]$EmailBody,

    [Parameter(Mandatory = $false,
               Position = 4,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Attachment')]
    [String[]]$Arry_EmailAttachments
)

# From Christian @ stackoverflow.com
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
$SMTPClient.EnableSSL = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");

# From Core @ stackoverflow.com
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
foreach ($recipient in $Arry_EmailTo)
{
    $emailMessage.To.Add($recipient)
}
$emailMessage.Subject = $EmailSubj
$emailMessage.Body = $EmailBody
# Do we have any attachments?
# If yes, then add them, if not, do nothing
if ($Arry_EmailAttachments.Count -ne $NULL)
{
    $emailMessage.Attachments.Add()
}
$SMTPClient.Send($emailMessage)

Of course, change the GMAIL_USERNAME and GMAIL_PASSWORD values to your particular user and password.

How to add a “readonly” attribute to an <input>?

Check the code below:

<input id="mail">

<script>

 document.getElementById('mail').readOnly = true; // makes input readonline
 document.getElementById('mail').readOnly = false; // makes input writeable again

</script>

cannot resolve symbol javafx.application in IntelliJ Idea IDE

You might have a lower project language level than your JDK.

Check if: "Projeckt structure/project/Project-> language level" is lower than your JDK. I had the same problem with JDK 9 and the language level was per default set to 6.

I set the Project Language Level to 9 and everything worked fine after that.

You might have the same issue.

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

If you had tried all available answers and still cannot find the answer this might solve issue. If you have different solutions configurations like Debug, Release etc then set project output path to 'bin' and compile project. Revert change after compiling.

Project Output Path

VS looks for dlls in bin folder

How to add bootstrap in angular 6 project?

npm install bootstrap --save

and add relevent files into angular.json file under the style property for css files and under scripts for JS files.

 "styles": [
  "../node_modules/bootstrap/dist/css/bootstrap.min.css",
   ....
]

Angular 4 default radio button checked by default

getting following error

_x000D_
_x000D_
It happens:  Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:
_x000D_
_x000D_
_x000D_

Passive Link in Angular 2 - <a href=""> equivalent

you need to prevent event's default behaviour as follows.

In html

<a href="" (click)="view($event)">view</a>

In ts file

view(event:Event){
 event.preventDefault();
 //remaining code goes here..
}

How to find a string inside a entire database?

Here is an easy and convenient cursor based solution

DECLARE
@search_string  VARCHAR(100),
@table_name     SYSNAME,
@table_id       INT,
@column_name    SYSNAME,
@sql_string     VARCHAR(2000)

SET @search_string = 'StringtoSearch'

DECLARE tables_cur CURSOR FOR SELECT name, object_id FROM sys.objects WHERE  type = 'U'

OPEN tables_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id

WHILE (@@FETCH_STATUS = 0)
BEGIN
    DECLARE columns_cur CURSOR FOR SELECT name FROM sys.columns WHERE object_id = @table_id 
        AND system_type_id IN (167, 175, 231, 239)

    OPEN columns_cur

    FETCH NEXT FROM columns_cur INTO @column_name
        WHILE (@@FETCH_STATUS = 0)
        BEGIN
            SET @sql_string = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [' + @column_name + '] 
            LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''

            EXECUTE(@sql_string)

        FETCH NEXT FROM columns_cur INTO @column_name
        END

    CLOSE columns_cur

DEALLOCATE columns_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id
END

CLOSE tables_cur
DEALLOCATE tables_cur

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

use Integer as the type and provide setter/getter accordingly..

private Integer num;

public Integer getNum()...

public void setNum(Integer num)...

What is the connection string for localdb for version 11

This is a fairly old thread, but since I was reinstalling my Visual Studio 2015 Community today, I thought I might add some info on what to use on VS2015, or what might work in general.

To see which instances were installed by default, type sqllocaldb info inside a command prompt. On my machine, I get two instances, the first one named MSSQLLocalDB.

C:\>sqllocaldb info
MSSQLLocalDB
ProjectsV13

You can also create a new instance if you wish, using sqllocaldb create "some_instance_name", but the default one will work just fine:

// if not using a verbatim string literal, don't forget to escape backslashes
@"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;"

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Simple example to achieve the below:

    ApplicationDbContext forumDB = new ApplicationDbContext();
    MonitorDbContext monitor = new MonitorDbContext();

Just scope the properties in the main context: (used to create and maintain the DB) Note: Just use protected: (Entity is not exposed here)

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("QAForum", throwIfV1Schema: false)
    {

    }
    protected DbSet<Diagnostic> Diagnostics { get; set; }
    public DbSet<Forum> Forums { get; set; }
    public DbSet<Post> Posts { get; set; }
    public DbSet<Thread> Threads { get; set; }
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

MonitorContext: Expose separate Entity here

public class MonitorDbContext: DbContext
{
    public MonitorDbContext()
        : base("QAForum")
    {

    }
    public DbSet<Diagnostic> Diagnostics { get; set; }
    // add more here
}

Diagnostics Model:

public class Diagnostic
{
    [Key]
    public Guid DiagnosticID { get; set; }
    public string ApplicationName { get; set; }
    public DateTime DiagnosticTime { get; set; }
    public string Data { get; set; }
}

If you like you could mark all entities as protected inside the main ApplicationDbContext, then create additional contexts as needed for each separation of schemas.

They all use the same connection string, however they use separate connections, so do not cross transactions and be aware of locking issues. Generally your designing separation so this shouldn't happen anyway.

What's the idiomatic syntax for prepending to a short python list?

What's the idiomatic syntax for prepending to a short python list?

You don't usually want to repetitively prepend to a list in Python.

If it's short, and you're not doing it a lot... then ok.

list.insert

The list.insert can be used this way.

list.insert(0, x)

But this is inefficient, because in Python, a list is an array of pointers, and Python must now take every pointer in the list and move it down by one to insert the pointer to your object in the first slot, so this is really only efficient for rather short lists, as you ask.

Here's a snippet from the CPython source where this is implemented - and as you can see, we start at the end of the array and move everything down by one for every insertion:

for (i = n; --i >= where; )
    items[i+1] = items[i];

If you want a container/list that's efficient at prepending elements, you want a linked list. Python has a doubly linked list, which can insert at the beginning and end quickly - it's called a deque.

deque.appendleft

A collections.deque has many of the methods of a list. list.sort is an exception, making deque definitively not entirely Liskov substitutable for list.

>>> set(dir(list)) - set(dir(deque))
{'sort'}

The deque also has an appendleft method (as well as popleft). The deque is a double-ended queue and a doubly-linked list - no matter the length, it always takes the same amount of time to preprend something. In big O notation, O(1) versus the O(n) time for lists. Here's the usage:

>>> import collections
>>> d = collections.deque('1234')
>>> d
deque(['1', '2', '3', '4'])
>>> d.appendleft('0')
>>> d
deque(['0', '1', '2', '3', '4'])

deque.extendleft

Also relevant is the deque's extendleft method, which iteratively prepends:

>>> from collections import deque
>>> d2 = deque('def')
>>> d2.extendleft('cba')
>>> d2
deque(['a', 'b', 'c', 'd', 'e', 'f'])

Note that each element will be prepended one at a time, thus effectively reversing their order.

Performance of list versus deque

First we setup with some iterative prepending:

import timeit
from collections import deque

def list_insert_0():
    l = []
    for i in range(20):
        l.insert(0, i)

def list_slice_insert():
    l = []
    for i in range(20):
        l[:0] = [i]      # semantically same as list.insert(0, i)

def list_add():
    l = []
    for i in range(20):
        l = [i] + l      # caveat: new list each time

def deque_appendleft():
    d = deque()
    for i in range(20):
        d.appendleft(i)  # semantically same as list.insert(0, i)

def deque_extendleft():
    d = deque()
    d.extendleft(range(20)) # semantically same as deque_appendleft above

and performance:

>>> min(timeit.repeat(list_insert_0))
2.8267281929729506
>>> min(timeit.repeat(list_slice_insert))
2.5210217320127413
>>> min(timeit.repeat(list_add))
2.0641671380144544
>>> min(timeit.repeat(deque_appendleft))
1.5863927800091915
>>> min(timeit.repeat(deque_extendleft))
0.5352169770048931

The deque is much faster. As the lists get longer, I would expect a deque to perform even better. If you can use deque's extendleft you'll probably get the best performance that way.

Difference between @Mock and @InjectMocks

Many people have given a great explanation here about @Mock vs @InjectMocks. I like it, but I think our tests and application should be written in such a way that we shouldn't need to use @InjectMocks.

Reference for further reading with examples: https://tedvinke.wordpress.com/2014/02/13/mockito-why-you-should-not-use-injectmocks-annotation-to-autowire-fields/

How to get HTTP response code for a URL in Java?

This is the full static method, which you can adapt to set waiting time and error code when IOException happens:

  public static int getResponseCode(String address) {
    return getResponseCode(address, 404);
  }

  public static int getResponseCode(String address, int defaultValue) {
    try {
      //Logger.getLogger(WebOperations.class.getName()).info("Fetching response code at " + address);
      URL url = new URL(address);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setConnectTimeout(1000 * 5); //wait 5 seconds the most
      connection.setReadTimeout(1000 * 5);
      connection.setRequestProperty("User-Agent", "Your Robot Name");
      int responseCode = connection.getResponseCode();
      connection.disconnect();
      return responseCode;
    } catch (IOException ex) {
      Logger.getLogger(WebOperations.class.getName()).log(Level.INFO, "Exception at {0} {1}", new Object[]{address, ex.toString()});
      return defaultValue;
    }
  }

jQuery detect if textarea is empty

You can simply try this and it should work in most cases, feel free to correct me if I am wrong :

function hereLies(obj) { 
  if(obj.val() != "") { 
    //Do this here 
  }
}

Where obj is the object of your textarea.

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<textarea placeholder="Insert text here..." rows="5" cols="12"></textarea>_x000D_
<button id="checkerx">Check</button>_x000D_
<p>Value is not null!</p>_x000D_
_x000D_
<script>_x000D_
  $("p").hide();_x000D_
  $("#checkerx").click(function(){_x000D_
      if($("textarea").val() != ""){_x000D_
        $("p").show();_x000D_
      }_x000D_
      else{_x000D_
       $("p").replaceWith("<p>Value is null!</p>");_x000D_
      }_x000D_
  });_x000D_
_x000D_
</script>_x000D_
</body></html>
_x000D_
_x000D_
_x000D_

Find nearest latitude/longitude with an SQL query

The original answers to the question are good, but newer versions of mysql (MySQL 5.7.6 on) support geo queries, so you can now use built in functionality rather than doing complex queries.

You can now do something like:

select *, ST_Distance_Sphere( point ('input_longitude', 'input_latitude'), 
                              point(longitude, latitude)) * .000621371192 
          as `distance_in_miles` 
  from `TableName`
having `distance_in_miles` <= 'input_max_distance'
 order by `distance_in_miles` asc

The results are returned in meters. So if you want in KM simply use .001 instead of .000621371192 (which is for miles).

MySql docs are here

Magento How to debug blank white screen

Same problem, I have just purged cache

rm -rf var/cache/* 

Et voila ! I don't understand what it was...

Android, Java: HTTP POST Request

You can reuse the implementation I added to ACRA: http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236

(See the doPost(Map, Url) method, working over http and https even with self signed certs)

how to check the jdk version used to compile a .class file

Does the -verbose flag to your java command yield any useful info? If not, maybe java -X reveals something specific to your version that might help?

How to count number of files in each directory?

You could arrange to find all the files, remove the file names, leaving you a line containing just the directory name for each file, and then count the number of times each directory appears:

find . -type f |
sed 's%/[^/]*$%%' |
sort |
uniq -c

The only gotcha in this is if you have any file names or directory names containing a newline character, which is fairly unlikely. If you really have to worry about newlines in file names or directory names, I suggest you find them, and fix them so they don't contain newlines (and quietly persuade the guilty party of the error of their ways).


If you're interested in the count of the files in each sub-directory of the current directory, counting any files in any sub-directories along with the files in the immediate sub-directory, then I'd adapt the sed command to print only the top-level directory:

find . -type f |
sed -e 's%^\(\./[^/]*/\).*$%\1%' -e 's%^\.\/[^/]*$%./%' |
sort |
uniq -c

The first pattern captures the start of the name, the dot, the slash, the name up to the next slash and the slash, and replaces the line with just the first part, so:

./dir1/dir2/file1

is replaced by

./dir1/

The second replace captures the files directly in the current directory; they don't have a slash at the end, and those are replace by ./. The sort and count then works on just the number of names.

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

Adding the System.Configuration as reference to all the projects will solve this.

  1. Go to Project -> Add Reference

  2. In the box that appears, click the All assemblies list tab in the left hand list.

  3. In the central list, scroll to System.Configuration and make sure the box is checked.

  4. Click ok to apply, and you'll now be able to access the ConfigurationManager class.

Node/Express file upload

I find this, simple and efficient:

const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();

// default options
app.use(fileUpload());

app.post('/upload', function(req, res) {
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }

  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
  let sampleFile = req.files.sampleFile;

  // Use the mv() method to place the file somewhere on your server
  sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
});

express-fileupload

Changing navigation bar color in Swift

Swift 3

UINavigationBar.appearance().barTintColor = UIColor(colorLiteralRed: 51/255, green: 90/255, blue: 149/255, alpha: 1)

This will set your navigation bar color like Facebook bar color :)

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

SBT solution stated above did not work for me. What worked for me is excluding slf4j-log4j12

_x000D_
_x000D_
//dependencies with exclusions_x000D_
libraryDependencies ++= Seq(_x000D_
    //depencies_x000D_
).map(_.exclude("org.slf4j","slf4j-log4j12"))
_x000D_
_x000D_
_x000D_

Export DataBase with MySQL Workbench with INSERT statements

You can do it using mysqldump tool in command-line:

mysqldump your_database_name > script.sql

This creates a file with database create statements together with insert statements.

More info about options for mysql dump: https://dev.mysql.com/doc/refman/5.7/en/mysqldump-sql-format.html

How to get the number of characters in a string

I should point out that none of the answers provided so far give you the number of characters as you would expect, especially when you're dealing with emojis (but also some languages like Thai, Korean, or Arabic). VonC's suggestions will output the following:

fmt.Println(utf8.RuneCountInString("??")) // Outputs "6".
fmt.Println(len([]rune("??"))) // Outputs "6".

That's because these methods only count Unicode code points. There are many characters which can be composed of multiple code points.

Same for using the Normalization package:

var ia norm.Iter
ia.InitString(norm.NFKD, "??")
nc := 0
for !ia.Done() {
    nc = nc + 1
    ia.Next()
}
fmt.Println(nc) // Outputs "6".

Normalization is not really the same as counting characters and many characters cannot be normalized into a one-code-point equivalent.

masakielastic's answer comes close but only handles modifiers (the rainbow flag contains a modifier which is thus not counted as its own code point):

fmt.Println(GraphemeCountInString("??"))  // Outputs "5".
fmt.Println(GraphemeCountInString2("??")) // Outputs "5".

The correct way to split Unicode strings into (user-perceived) characters, i.e. grapheme clusters, is defined in the Unicode Standard Annex #29. The rules can be found in Section 3.1.1. The github.com/rivo/uniseg package implements these rules so you can determine the correct number of characters in a string:

fmt.Println(uniseg.GraphemeClusterCount("??")) // Outputs "2".

What is the relative performance difference of if/else versus switch statement in Java?

A good explanation at the link below:
https://www.geeksforgeeks.org/switch-vs-else/

Test(c++17)
1 - If grouped
2 - If sequential
3 - Goto Array
4 - Switch Case - Jump Table
https://onlinegdb.com/Su7HNEBeG

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

It works for me...

if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
    {
    $certCallback = @"
        using System;
        using System.Net;
        using System.Net.Security;
        using System.Security.Cryptography.X509Certificates;
        public class ServerCertificateValidationCallback
        {
            public static void Ignore()
            {
                if(ServicePointManager.ServerCertificateValidationCallback ==null)
                {
                    ServicePointManager.ServerCertificateValidationCallback += 
                        delegate
                        (
                            Object obj, 
                            X509Certificate certificate, 
                            X509Chain chain, 
                            SslPolicyErrors errors
                        )
                        {
                            return true;
                        };
                }
            }
        }
    "@
        Add-Type $certCallback
     }
    [ServerCertificateValidationCallback]::Ignore()

Invoke-WebRequest -Uri https://apod.nasa.gov/apod/

For loop in Objective-C

The traditional for loop in Objective-C is inherited from standard C and takes the following form:

for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
    // Do something.
}

For example, to print the numbers from 1 to 10, you could use the for loop:

for (int i = 1; i <= 10; i++)
{
    NSLog(@"%d", i);
}

On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.

for (NSString* currentString in myArrayOfStrings)
{
    NSLog(@"%@", currentString);
}

This is logically equivilant to the following traditional for loop:

for (int i = 0; i < [myArrayOfStrings count]; i++)
{
    NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}

The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.

Hope this helps.

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

To generate a certificate on the Apple provisioning profile website, firstly you have to generate keys on your mac, then upload the public key. Apple will generate your certificates with this key. When you download your certificates, tu be able to use them you need to have the private key.

The error "XCode could not find a valid private-key/certificate pair for this profile in your keychain." means you don't have the private key.

Maybe because your Mac was reinstalled, maybe because this key was generated on another Mac. So to be able to use your certificates, you need to find this key and install it on the keychain.

If you can not find it you can generate new keys restart this process on the provisioning profile website and get new certificates you will able to use.

Is there any quick way to get the last two characters in a string?

In my case, I wanted the opposite. I wanted to strip off the last 2 characters in my string. This was pretty simple:

String myString = someString.substring(0, someString.length() - 2);

How to split() a delimited string to a List<String>

Just u can use with using System.Linq;

List<string> stringList = line.Split(',')     // this is array
 .ToList();     // this is a list which you can loop in all split string

Bootstrap: how do I change the width of the container?

Go to the Customize section on Bootstrap site and choose the size you prefer. You'll have to set @gridColumnWidth and @gridGutterWidth variables.

For example: @gridColumnWidth = 65px and @gridGutterWidth = 20px results on a 1000px layout.

Then download it.

./xx.py: line 1: import: command not found

I've experienced the same problem and now I just found my solution to this issue.

#!/usr/bin/python

import sys
import os

os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))

This is the code[1] for my case. When I tried this script I received error message like :

import: command not found

I found people talks about the shebang. As you see there is the shebang in my python code above. I tried these and those trials but didn't find a good solution.

I finally tried to type the shebang my self.

#!/usr/bin/python

and removed the copied one.

And my problem solved!!!

I copied the code from the internet[1].

And I guess there had been some unseeable(?) unseen special characters in the original copied shebang statement.

I use vim, sometimes I experience similar problems.. Especially when I copied some code snippet from the internet this kind of problems happen.. Web pages have some virus special characters!! I doubt. :-)

Journeyer

PS) I copied the code in Windows 7 - host OS - into the Windows clipboard and pasted it into my vim in Ubuntu - guest OS. VM is Oracle Virtual Machine.

[1] http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy

How to view the stored procedure code in SQL Server Management Studio

You can view all the objects code stored in the database with this query:

    USE [test] --Database Name
SELECT
    sch.name+'.'+ob.name AS       [Object], 
    ob.create_date, 
    ob.modify_date, 
    ob.type_desc, 
    mod.definition
FROM 
     sys.objects AS ob
     LEFT JOIN sys.schemas AS sch ON
            sch.schema_id = ob.schema_id
     LEFT JOIN sys.sql_modules AS mod ON
            mod.object_id = ob.object_id
WHERE mod.definition IS NOT NULL --Selects only objects with the definition (code)

Get the last item in an array

Normally you are not supposed to mess with the prototype of built-in types but here is a hack/shortcut:

Object.defineProperty(Array.prototype, 'last', {
  get() {
    return this[this.length - 1]; 
  }
});

This will allow all array objects to have a last property, which you can use like so:

const letters = ['a', 'b', 'c', 'd', 'e'];
console.log(letters.last); // 'e'

You are not supposed to mess with a built-in type's prototype because you never when a new ES version will be released and in the event that a new version uses the same property name as your custom property, all sorts of breaks can happen. You COULD make the property to something that you know an ES version would, like lastItem but that is at the discretion of the developer.

Is it possible to run one logrotate check manually?

Edit /var/lib/logrotate.status (or /var/lib/loglogrotate/logrotate.status) to reset the 'last rotated' date on the log file you want to test.

Then run logrotate YOUR_CONFIG_FILE.

Or you can use the --force flag, but editing logrotate.status gives you more precision over what does and doesn't get rotated.

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

dont put break-point before await smtp.SendMailAsync(mail);

:)

when it waits with a break point giving this error when i remove break point it has worked

ERROR: Google Maps API error: MissingKeyMapError

you must create a project and collect the key in this way:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;language=en&key=()"></script>

get the data of uploaded file in javascript

The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.

<!DOCTYPE html>
<html>
  <head>
    <script src="script.js"></script>
  </head>

  <body onload="init()">
    <input id="fileInput" type="file" name="file" />
    <pre id="fileContent"></pre>
  </body>
</html>

script.js

function init(){
  document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}

function handleFileSelect(event){
  const reader = new FileReader()
  reader.onload = handleFileLoad;
  reader.readAsText(event.target.files[0])
}

function handleFileLoad(event){
  console.log(event);
  document.getElementById('fileContent').textContent = event.target.result;
}

Difference between "\n" and Environment.NewLine

Depends on the platform. On Windows it is actually "\r\n".

From MSDN:

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

@Override
public void onBackPressed() {
// Put your code here.
}

//I had to go back to the dashboard. Hence,

@Override
public void onBackPressed() {
    Intent intent = new Intent(this,Dashboard.class);
    startActivity(intent);
}
Just write this above or below the onCreate Method(within the class)

Changing user agent on urllib2.urlopen

I answered a similar question a couple weeks ago.

There is example code in that question, but basically you can do something like this: (Note the capitalization of User-Agent as of RFC 2616, section 14.43.)

opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('http://www.stackoverflow.com')

MySQL Job failed to start

In my case, i do:

  1. sudo nano /etc/mysql/my.cnf
  2. search for bind names and IPs
  3. remove the specific, and let only localhost 127.0.0.1 and the hostname

IF-THEN-ELSE statements in postgresql

case when field1>0 then field2/field1 else 0 end as field3

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

It would be interesting to know the values supplied for the two ? placeholders.

Express-js can't GET my static files, why?

if your setup

myApp
  |
  |__ public
  |     |
  |     |__  stylesheets
  |     |     |
  |     |     |__ style.css
  |     |
  |     |___ img
  |           |
  |           |__ logo.png
  |
  |__ app.js

then,
put in app.js

app.use('/static', express.static('public'));

and refer to your style.css: (in some .pug file):

link(rel='stylesheet', href='/static/stylesheets/style.css')

What is the difference between Bower and npm?

Found this useful explanation from http://ng-learn.org/2013/11/Bower-vs-npm/

On one hand npm was created to install modules used in a node.js environment, or development tools built using node.js such Karma, lint, minifiers and so on. npm can install modules locally in a project ( by default in node_modules ) or globally to be used by multiple projects. In large projects the way to specify dependencies is by creating a file called package.json which contains a list of dependencies. That list is recognized by npm when you run npm install, which then downloads and installs them for you.

On the other hand bower was created to manage your frontend dependencies. Libraries like jQuery, AngularJS, underscore, etc. Similar to npm it has a file in which you can specify a list of dependencies called bower.json. In this case your frontend dependencies are installed by running bower install which by default installs them in a folder called bower_components.

As you can see, although they perform a similar task they are targeted to a very different set of libraries.

How can I completely uninstall nodejs, npm and node in Ubuntu

sudo apt-get remove nodejs
sudo apt-get remove npm

Then go to /etc/apt/sources.list.d and remove any node list if you have. Then do a

sudo apt-get update

Check for any .npm or .node folder in your home folder and delete those.

If you type

which node

you can see the location of the node. Try which nodejs and which npm too.

I would recommend installing node using Node Version Manager(NVM). That saved a lot of headache for me. You can install nodejs and npm without sudo using nvm.

Editing specific line in text file in Python

I have been practising working on files this evening and realised that I can build on Jochen's answer to provide greater functionality for repeated/multiple use. Unfortunately my answer does not address issue of dealing with large files but does make life easier in smaller files.

with open('filetochange.txt', 'r+') as foo:
    data = foo.readlines()                  #reads file as list
    pos = int(input("Which position in list to edit? "))-1  #list position to edit
    data.insert(pos, "more foo"+"\n")           #inserts before item to edit
    x = data[pos+1]
    data.remove(x)                      #removes item to edit
    foo.seek(0)                     #seeks beginning of file
    for i in data:
        i.strip()                   #strips "\n" from list items
        foo.write(str(i))

_tkinter.TclError: no display name and no $DISPLAY environment variable

You can solve it by adding these two lines in the VERY beginning of your .py script.

import matplotlib
matplotlib.use('Agg')

PS: The error will still exists if these two lines are not added in the very beginning of the source code.

Types in Objective-C on iOS

Update for the new 64bit arch

Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

ORA-00979 not a group by expression

The group by is used to aggregate some data, depending on the aggregate function, and other than that you need to put column or columns to which you need the grouping.

for example:

select d.deptno, max(e.sal) 
from emp e, dept d
where e.deptno = d.deptno
group by d.deptno;

This will result in the departments maximum salary.

Now if we omit the d.deptno from group by clause it will give the same error.

Get a list of all functions and procedures in an Oracle database

 SELECT * FROM all_procedures WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE') 
 and owner = 'Schema_name' order by object_name

here 'Schema_name' is a name of schema, example i have a schema named PMIS, so the example will be

SELECT * FROM all_procedures WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE') 
and owner = 'PMIS' order by object_name

enter image description here

Ref: https://www.plsql.co/list-all-procedures-from-a-schema-of-oracle-database.html

struct.error: unpack requires a string argument of length 4

By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.

To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding:

>>> struct.calcsize('=BH')
3

The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

Laravel Eloquent - distinct() and count() not working properly together

Based on Laravel docs for raw queries I was able to get count for a select field to work with this code in the product model.

public function scopeShowProductCount($query)
{
    $query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
          ->groupBy('pid')
          ->orderBy('count_pid', 'desc');
}

This facade worked to get the same result in the controller:

$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();

The resulting dump for both queries was as follows:

#attributes: array:2 [
  "pid" => "1271"
  "count_pid" => 19
],
#attributes: array:2 [
  "pid" => "1273"
  "count_pid" => 12
],
#attributes: array:2 [
  "pid" => "1275"
  "count_pid" => 7
]

Update my gradle dependencies in eclipse

First, please check you have include eclipse gradle plugin. apply plugin : 'eclipse' Then go to your project directory in Terminal. Type gradle clean and then gradle eclipse. Then go to project in eclipse and refresh the project.

ReferenceError: Invalid left-hand side in assignment

You have to use == to compare (or even ===, if you want to compare types). A single = is for assignment.

if (one == 'rock' && two == 'rock') {
    console.log('Tie! Try again!');
}

tell pip to install the dependencies of packages listed in a requirement file

Any way to do this without manually re-installing the packages in a new virtualenv to get their dependencies ? This would be error-prone and I'd like to automate the process of cleaning the virtualenv from no-longer-needed old dependencies.

That's what pip-tools package is for (from https://github.com/jazzband/pip-tools):

Installation

$ pip install --upgrade pip  # pip-tools needs pip==6.1 or higher (!)
$ pip install pip-tools

Example usage for pip-compile

Suppose you have a Flask project, and want to pin it for production. Write the following line to a file:

# requirements.in
Flask

Now, run pip-compile requirements.in:

$ pip-compile requirements.in
#
# This file is autogenerated by pip-compile
# Make changes in requirements.in, then run this to update:
#
#    pip-compile requirements.in
#
flask==0.10.1
itsdangerous==0.24        # via flask
jinja2==2.7.3             # via flask
markupsafe==0.23          # via jinja2
werkzeug==0.10.4          # via flask

And it will produce your requirements.txt, with all the Flask dependencies (and all underlying dependencies) pinned. Put this file under version control as well and periodically re-run pip-compile to update the packages.

Example usage for pip-sync

Now that you have a requirements.txt, you can use pip-sync to update your virtual env to reflect exactly what's in there. Note: this will install/upgrade/uninstall everything necessary to match the requirements.txt contents.

$ pip-sync
Uninstalling flake8-2.4.1:
  Successfully uninstalled flake8-2.4.1
Collecting click==4.1
  Downloading click-4.1-py2.py3-none-any.whl (62kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 65kB 1.8MB/s
  Found existing installation: click 4.0
    Uninstalling click-4.0:
      Successfully uninstalled click-4.0
Successfully installed click-4.1

Get GPS location from the web browser

If you use the Geolocation API, it would be as simple as using the following code.

navigator.geolocation.getCurrentPosition(function(location) {
  console.log(location.coords.latitude);
  console.log(location.coords.longitude);
  console.log(location.coords.accuracy);
});

You may also be able to use Google's Client Location API.

This issue has been discussed in Is it possible to detect a mobile browser's GPS location? and Get position data from mobile browser. You can find more information there.

Is there an addHeaderView equivalent for RecyclerView?

You can achieve it using the library SectionedRecyclerViewAdapter, it has the concept of "Sections", where which Section has a Header, Footer and Content (list of items). In your case you might only need one Section but you can have many:

enter image description here

1) Create a custom Section class:

class MySection extends StatelessSection {

    List<String> myList = Arrays.asList(new String[] {"Item1", "Item2", "Item3" });

    public MySection() {
        // call constructor with layout resources for this Section header, footer and items 
        super(R.layout.section_header, R.layout.section_footer,  R.layout.section_item);
    }

    @Override
    public int getContentItemsTotal() {
        return myList.size(); // number of items of this section
    }

    @Override
    public RecyclerView.ViewHolder getItemViewHolder(View view) {
        // return a custom instance of ViewHolder for the items of this section
        return new MyItemViewHolder(view);
    }

    @Override
    public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyItemViewHolder itemHolder = (MyItemViewHolder) holder;

        // bind your view here
        itemHolder.tvItem.setText(myList.get(position));
    }
}

2) Create a custom ViewHolder for the items:

class MyItemViewHolder extends RecyclerView.ViewHolder {

    private final TextView tvItem;

    public MyItemViewHolder(View itemView) {
        super(itemView);

        tvItem = (TextView) itemView.findViewById(R.id.tvItem);
    }
}

3) Set up your ReclyclerView with the SectionedRecyclerViewAdapter

// Create an instance of SectionedRecyclerViewAdapter 
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

MySection mySection = new MySection();

// Add your Sections
sectionAdapter.addSection(mySection);

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);

Can I convert a C# string value to an escaped string literal

Code:

string someString1 = "\tHello\r\n\tWorld!\r\n";
string someString2 = @"\tHello\r\n\tWorld!\r\n";

Console.WriteLine(someString1);
Console.WriteLine(someString2);

Output:

    Hello
    World!

\tHello\r\n\tWorld!\r\n

Is this what you want?

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How to get the max of two values in MySQL?

Use GREATEST()

E.g.:

SELECT GREATEST(2,1);

Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)

When should you use constexpr capability in C++11?

From Stroustrup's speech at "Going Native 2012":

template<int M, int K, int S> struct Unit { // a unit in the MKS system
       enum { m=M, kg=K, s=S };
};

template<typename Unit> // a magnitude with a unit 
struct Value {
       double val;   // the magnitude 
       explicit Value(double d) : val(d) {} // construct a Value from a double 
};

using Speed = Value<Unit<1,0,-1>>;  // meters/second type
using Acceleration = Value<Unit<1,0,-2>>;  // meters/second/second type
using Second = Unit<0,0,1>;  // unit: sec
using Second2 = Unit<0,0,2>; // unit: second*second 

constexpr Value<Second> operator"" s(long double d)
   // a f-p literal suffixed by ‘s’
{
  return Value<Second> (d);  
}   

constexpr Value<Second2> operator"" s2(long double d)
  // a f-p literal  suffixed by ‘s2’ 
{
  return Value<Second2> (d); 
}

Speed sp1 = 100m/9.8s; // very fast for a human 
Speed sp2 = 100m/9.8s2; // error (m/s2 is acceleration)  
Speed sp3 = 100/9.8s; // error (speed is m/s and 100 has no unit) 
Acceleration acc = sp1/0.5s; // too fast for a human

How to install wget in macOS?

You need to do

./configure --with-ssl=openssl --with-libssl-prefix=/usr/local/ssl

Instead of this

./configure --with-ssl=openssl

YYYY-MM-DD format date in shell script

Try to use this command :

date | cut -d " " -f2-4 | tr " " "-" 

The output would be like: 21-Feb-2021

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

As the error mentioned the class does not have a default constructor.

Adding @NoArgsConstructor to the entity class should fix it.

Perl: Use s/ (replace) and return new string

print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;

Showing all session data at once?

print_r($this->session->userdata); 

or

print_r($this->session->all_userdata());

How to link to apps on the app store

If you want to link to a developer's apps and the developer's name has punctuation or spaces (e.g. Development Company, LLC) form your URL like this:

itms-apps://itunes.com/apps/DevelopmentCompanyLLC

Otherwise it returns "This request cannot be processed" on iOS 4.3.3

Saving lists to txt file

Assuming your Generic List is of type String:

TextWriter tw = new StreamWriter("SavedList.txt");

foreach (String s in Lists.verbList)
   tw.WriteLine(s);

tw.Close();

Alternatively, with the using keyword:

using(TextWriter tw = new StreamWriter("SavedList.txt"))
{
   foreach (String s in Lists.verbList)
      tw.WriteLine(s);
}

Is there a way to get the source code from an APK file?

The simplest way is using Apk OneClick Decompiler. That is a tool package to decompile & disassemble APKs (android packages).

FEATURES

  • All features are integrated into the right-click menu of Windows.
  • Decompile APK classes to Java source codes.
  • Disassemble APK to smali code and decode its resources.
  • Install APK to phone by right-click.
  • Recompile APK after editing smali code and/or resources. During recompile:
  • Optimize png images
  • Sign apks
  • Zipalign

REQUIREMENTS

Java Runtime Environment (JRE) must be installed.

You can download it from this link Apk OneClick Decompiler

Enjoy that.

How to prevent auto-closing of console after the execution of batch file

There are two ways to do it depend on use case

1) If you want Windows cmd prompt to stay open so that you can see execution result and close it afterwards; use

pause

2) if you want Windows cmd prompt to stay open and allow you to execute some command afterwords; use

cmd

enter image description here

Getting time elapsed in Objective-C

use the timeIntervalSince1970 function of the NSDate class like below:

double start = [startDate timeIntervalSince1970];
double end = [endDate timeIntervalSince1970];
double difference = end - start;

basically, this is what i use to compare the difference in seconds between 2 different dates. also check this link here

How to take keyboard input in JavaScript?

You can do this by registering an event handler on the document or any element you want to observe keystrokes on and examine the key related properties of the event object.

Example that works in FF and Webkit-based browsers:

document.addEventListener('keydown', function(event) {
    if(event.keyCode == 37) {
        alert('Left was pressed');
    }
    else if(event.keyCode == 39) {
        alert('Right was pressed');
    }
});

DEMO

Git mergetool generates unwanted .orig files

A possible solution from git config:

git config --global mergetool.keepBackup false

After performing a merge, the original file with conflict markers can be saved as a file with a .orig extension.
If this variable is set to false then this file is not preserved.
Defaults to true (i.e. keep the backup files).

The alternative being not adding or ignoring those files, as suggested in this gitguru article,

git mergetool saves the merge-conflict version of the file with a “.orig” suffix.
Make sure to delete it before adding and committing the merge or add *.orig to your .gitignore.

Berik suggests in the comments to use:

find . -name \*.orig 
find . -name \*.orig -delete

Charles Bailey advises in his answer to be aware of internal diff tool settings which could also generate those backup files, no matter what git settings are.

  • kdiff3 has its own settings (see "Directory merge" in its manual).
  • other tools like WinMerge can have their own backup file extension (WinMerge: .bak, as mentioned in its manual).

So you need to reset those settings as well.

Python can't find module in the same folder

I ran into this issue. I had three folders in the same directory so I had to specify which folder. Ex: from Folder import script

How to retrieve current workspace using Jenkins Pipeline Groovy script?

For me just ${workspace} worked without even initializing the variable 'workspace.'

Jenkins - passing variables between jobs?

You can use Parameterized Trigger Plugin which will let you pass parameters from one task to another.

You need also add this parameter you passed from upstream in downstream.

Resolve build errors due to circular dependency amongst classes

In some cases it is possible to define a method or a constructor of class B in the header file of class A to resolve circular dependencies involving definitions. In this way you can avoid having to put definitions in .cc files, for example if you want to implement a header only library.

// file: a.h
#include "b.h"
struct A {
  A(const B& b) : _b(b) { }
  B get() { return _b; }
  B _b;
};

// note that the get method of class B is defined in a.h
A B::get() {
  return A(*this);
}

// file: b.h
class A;
struct B {
  // here the get method is only declared
  A get();
};

// file: main.cc
#include "a.h"
int main(...) {
  B b;
  A a = b.get();
}

Angular ForEach in Angular4/Typescript?

arrayData.forEach((key : any, val: any) => {
                        key['index'] = val + 1;

                        arrayData2.forEach((keys : any, vals :any) => {
                            if (key.group_id == keys.id) {
                                key.group_name = keys.group_name;
                            }
                        })
                    })

check if array is empty (vba excel)

The problem with VBA is that there are both dynamic and static arrays...

Dynamic Array Example

Dim myDynamicArray() as Variant

Static Array Example

Dim myStaticArray(10) as Variant
Dim myOtherStaticArray(0 To 10) as Variant

Using error handling to check if the array is empty works for a Dynamic Array, but a static array is by definition not empty, there are entries in the array, even if all those entries are empty.

So for clarity's sake, I named my function "IsZeroLengthArray".

    Public Function IsZeroLengthArray(ByRef subject() As Variant) As Boolean
        'Tell VBA to proceed if there is an error to the next line.
        On Error Resume Next
    
        Dim UpperBound As Integer
        Dim ErrorNumber As Long
        Dim ErrorDescription As String
        Dim ErrorSource As String
    
        'If the array is empty this will throw an error because a zero-length 
          'array has no UpperBound (or LowerBound).
        'This only works for dynamic arrays.  If this was a static array there 
          'would be both an upper and lower bound.
        UpperBound = UBound(subject)


        'Store the Error Number and then clear the Error object 
         'because we want VBA to treat unintended errors normally
        ErrorNumber = Err.Number
        ErrorDescription = Err.Description
        ErrorSource = Err.Source
        Err.Clear
        On Error GoTo 0
    
        'Check the Error Object to see if we have a "subscript out of range" error.  
          'If we do (the number is 9) then we can assume that the array is zero-length.
        If ErrorNumber = 9 Then
            IsZeroLengthArray = True

        'If the Error number is something else then 9 we want to raise 
        'that error again...
        ElseIf ErrorNumber <> 0 Then
            Err.Raise ErrorNumber, ErrorSource, ErrorDescription

        'If the Error number is 0 then we have no error and can assume that the
         'array is not of zero-length
        ElseIf ErrorNumber = 0 Then
            IsZeroLengthArray = False
        End If
    End Function

I hope that this helps others as it helped me.

Maven: best way of linking custom external JAR to my project?

With Eclipse Oxygen you can do the below things:

  1. Place your libraries in WEB-INF/lib
  2. Project -> Configure Build Path -> Add Library -> Web App Library

Maven will take them when installing the project.

How do I use raw_input in Python 3

Starting with Python 3, raw_input() was renamed to input().

From What’s New In Python 3.0, Builtins section second item.

SQL Server 2008 can't login with newly created user

You'll likely need to check the SQL Server error logs to determine the actual state (it's not reported to the client for security reasons.) See here for details.

Adding a new SQL column with a default value

If you are learning it's helpful to use a GUI like SQLyog, make the changes using the program and then see the History tab for the DDL statements that made those changes.

postgresql sequence nextval in schema

The quoting rules are painful. I think you want:

SELECT nextval('foo."SQ_ID"');

to prevent case-folding of SQ_ID.

Convert integers to strings to create output filenames at run time

Here is my subroutine approach to this problem. it transforms an integer in the range 0 : 9999 as a character. For example, the INTEGER 123 is transformed into the character 0123. hope it helps.

P.S. - sorry for the comments; they make sense in Romanian :P

 subroutine nume_fisier (i,filename_tot)

   implicit none
   integer :: i

   integer :: integer_zeci,rest_zeci,integer_sute,rest_sute,integer_mii,rest_mii
   character(1) :: filename1,filename2,filename3,filename4
   character(4) :: filename_tot

! Subrutina ce transforma un INTEGER de la 0 la 9999 in o serie de CARACTERE cu acelasi numar

! pentru a fi folosite in numerotarea si denumirea fisierelor de rezultate.

 if(i<=9) then

  filename1=char(48+0)
  filename2=char(48+0)
  filename3=char(48+0)
  filename4=char(48+i)  

 elseif(i>=10.and.i<=99) then

  integer_zeci=int(i/10)
  rest_zeci=mod(i,10)
  filename1=char(48+0)
  filename2=char(48+0)
  filename3=char(48+integer_zeci)
  filename4=char(48+rest_zeci)

 elseif(i>=100.and.i<=999) then

  integer_sute=int(i/100)
  rest_sute=mod(i,100)
  integer_zeci=int(rest_sute/10)
  rest_zeci=mod(rest_sute,10)
  filename1=char(48+0)
  filename2=char(48+integer_sute)
  filename3=char(48+integer_zeci)
  filename4=char(48+rest_zeci)

 elseif(i>=1000.and.i<=9999) then

  integer_mii=int(i/1000)
  rest_mii=mod(i,1000)
  integer_sute=int(rest_mii/100)
  rest_sute=mod(rest_mii,100)
  integer_zeci=int(rest_sute/10)
  rest_zeci=mod(rest_sute,10)
  filename1=char(48+integer_mii)
  filename2=char(48+integer_sute)
  filename3=char(48+integer_zeci) 
  filename4=char(48+rest_zeci)

 endif

 filename_tot=''//filename1//''//filename2//''//filename3//''//filename4//''
 return
 end subroutine nume_fisier

Disable cache for some images

A common and simple solution to this problem that feels like a hack but is fairly portable is to add a randomly generated query string to each request for the dynamic image.

So, for example -

<img src="image.png" />

Would become

<img src="image.png?dummy=8484744" />

Or

<img src="image.png?dummy=371662" />

From the point of view of the web-server the same file is accessed, but from the point of view of the browser no caching can be performed.

The random number generation can happen either on the server when serving the page (just make sure the page itself isn't cached...), or on the client (using JavaScript).

You will need to verify whether your web-server can cope with this trick.

How to sort an array of associative arrays by value of a given key in PHP?

I use uasort like this

<?php
$users = [
    [
        'username' => 'joe',
        'age' => 11
    ],
    [
        'username' => 'rakoto',
        'age' => 21
    ],
    [
        'username' => 'rabe',
        'age' => 17
    ],
    [
        'username' => 'fy',
        'age' => 19
    ],    
];


uasort($users, function ($item, $compare) {
    return $item['username'] >= $compare['username']; 
});

var_dump($users);

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

How to read a .xlsx file using the pandas Library in iPython?

I usually create a dictionary containing a DataFrame for every sheet:

xl_file = pd.ExcelFile(file_name)

dfs = {sheet_name: xl_file.parse(sheet_name) 
          for sheet_name in xl_file.sheet_names}

Update: In pandas version 0.21.0+ you will get this behavior more cleanly by passing sheet_name=None to read_excel:

dfs = pd.read_excel(file_name, sheet_name=None)

In 0.20 and prior, this was sheetname rather than sheet_name (this is now deprecated in favor of the above):

dfs = pd.read_excel(file_name, sheetname=None)

Sending emails with Javascript

What about having a live validation on the textbox, and once it goes over 2000 (or whatever the maximum threshold is) then display 'This email is too long to be completed in the browser, please <span class="launchEmailClientLink">launch what you have in your email client</span>'

To which I'd have

.launchEmailClientLink {
cursor: pointer;
color: #00F;
}

and jQuery this into your onDomReady

$('.launchEmailClientLink').bind('click',sendMail);

Hive: how to show all partitions of a table?

CLI has some limit when ouput is displayed. I suggest to export output into local file:

$hive -e 'show partitions table;' > partitions

How do I concatenate two text files in PowerShell?

Do not use >; it messes up the character encoding. Use:

Get-Content files.* | Set-Content newfile.file

Is it possible to apply CSS to half of a character?

You can use below code. Here in this example I have used h1 tag and added an attribute data-title-text="Display Text" which will appear with different color text on h1 tag text element, which gives effect halfcolored text as shown in below example

enter image description here

_x000D_
_x000D_
body {_x000D_
  text-align: center;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  color: #111;_x000D_
  font-family: arial;_x000D_
  position: relative;_x000D_
  font-family: 'Oswald', sans-serif;_x000D_
  display: inline-block;_x000D_
  font-size: 2.5em;_x000D_
}_x000D_
_x000D_
h1::after {_x000D_
  content: attr(data-title-text);_x000D_
  color: #e5554e;_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  clip: rect(0, 1000px, 30px, 0);_x000D_
}
_x000D_
<h1 data-title-text="Display Text">Display Text</h1>
_x000D_
_x000D_
_x000D_

What's the difference between ng-model and ng-bind

ngModel

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope.

This directive executes at priority level 1.

Example Plunker

JAVASCRIPT

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', function($scope) {
     $scope.val = '1';
}]);

CSS

.my-input {
    -webkit-transition:all linear 0.5s;
    transition:all linear 0.5s;
    background: transparent;
}
.my-input.ng-invalid {
    color:white;
    background: red;
}

HTML

<p id="inputDescription">
   Update input to see transitions when valid/invalid.
   Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
    <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
         aria-describedby="inputDescription" />
</form>

ngModel is responsible for:

  • Binding the view into the model, which other directives such as input, textarea or select require.
  • Providing validation behavior (i.e. required, number, email, url).
  • Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  • Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched) including animations.
  • Registering the control with its parent form.

ngBind

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

This directive executes at priority level 0.

Example Plunker

JAVASCRIPT

angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
    $scope.name = 'Whirled';
}]);

HTML

<div ng-controller="ExampleController">
  <label>Enter name: <input type="text" ng-model="name"></label><br>
  Hello <span ng-bind="name"></span>!
</div>

ngBind is responsible for:

  • Replacing the text content of the specified HTML element with the value of a given expression.

Validate that end date is greater than start date with jQuery

this should work

_x000D_
_x000D_
$.validator.addMethod("endDate", function(value, element) {_x000D_
            var startDate = $('#date_open').val();_x000D_
            return Date.parse(startDate) <= Date.parse(value) || value == "";_x000D_
        }, "* End date must be after start date");
_x000D_
_x000D_
_x000D_

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

You should use Java's built in serialization mechanism. To use it, you need to do the following:

  1. Declare the Club class as implementing Serializable:

    public class Club implements Serializable {
        ...
    }
    

    This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.

  2. To write your list to a file do the following:

    FileOutputStream fos = new FileOutputStream("t.tmp");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(clubs);
    oos.close();
    
  3. To read the list from a file, do the following:

    FileInputStream fis = new FileInputStream("t.tmp");
    ObjectInputStream ois = new ObjectInputStream(fis);
    List<Club> clubs = (List<Club>) ois.readObject();
    ois.close();
    

how to fetch array keys with jQuery?

console.log( Object.keys( {'a':1,'b':2} ) );

ANTLR: Is there a simple example?

At https://github.com/BITPlan/com.bitplan.antlr you'll find an ANTLR java library with some useful helper classes and a few complete examples. It's ready to be used with maven and if you like eclipse and maven.

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/exp/Exp.g4

is a simple Expression language that can do multiply and add operations. https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestExpParser.java has the corresponding unit tests for it.

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/iri/IRIParser.g4 is an IRI parser that has been split into the three parts:

  1. parser grammar
  2. lexer grammar
  3. imported LexBasic grammar

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIRIParser.java has the unit tests for it.

Personally I found this the most tricky part to get right. See http://wiki.bitplan.com/index.php/ANTLR_maven_plugin

https://github.com/BITPlan/com.bitplan.antlr/tree/master/src/main/antlr4/com/bitplan/expr

contains three more examples that have been created for a performance issue of ANTLR4 in an earlier version. In the meantime this issues has been fixed as the testcase https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIssue994.java shows.

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

The only way that worked for me using code (not XML) is this one:

etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

just copy " _CRT_SECURE_NO_WARNINGS " paste it on projects->properties->c/c++->preprocessor->preprocessor definitions click ok.it will work

What's the difference between lists and tuples?

First of all, they both are the non-scalar objects (also known as a compound objects) in Python.

  • Tuples, ordered sequence of elements (which can contain any object with no aliasing issue)
    • Immutable (tuple, int, float, str)
    • Concatenation using + (brand new tuple will be created of course)
    • Indexing
    • Slicing
    • Singleton (3,) # -> (3) instead of (3) # -> 3
  • List (Array in other languages), ordered sequence of values
    • Mutable
    • Singleton [3]
    • Cloning new_array = origin_array[:]
    • List comprehension [x**2 for x in range(1,7)] gives you [1,4,9,16,25,36] (Not readable)

Using list may also cause an aliasing bug (two distinct paths pointing to the same object).

What are callee and caller saved registers?

I'm not really sure if this adds anything but,

Caller saved means that the caller has to save the registers because they will be clobbered in the call and have no choice but to be left in a clobbered state after the call returns (for instance, the return value being in eax for cdecl. It makes no sense for the return value to be restored to the value before the call by the callee, because it is a return value).

Callee saved means that the callee has to save the registers and then restore them at the end of the call because they have the guarantee to the caller of containing the same values after the function returns, and it is possible to restore them, even if they are clobbered at some point during the call.

The issue with the above definition though is that for instance on Wikipedia cdecl, it says eax, ecx and edx are caller saved and rest are callee saved, this suggests that the caller must save all 3 of these registers, when it might not if none of these registers were used by the caller in the first place. In which case caller 'saved' becomes a misnomer, but 'call clobbered' still correctly applies. This is the same with 'the rest' being called callee saved. It implies that all other x86 registers will be saved and restored by the callee when this is not the case if some of the registers are never used in the call anyway. With cdecl, eax:edx may be used to return a 64 bit value. I'm not sure why ecx is also caller saved if needed, but it is.

Centering the image in Bootstrap

Update 2018

Bootstrap 2.x

You could create a new CSS class such as:

.img-center {margin:0 auto;}

And then, add this to each IMG:

 <img src="images/2.png" class="img-responsive img-center">

OR, just override the .img-responsive if you're going to center all images..

 .img-responsive {margin:0 auto;}

Demo: http://bootply.com/86123

Bootstrap 3.x

EDIT - With the release of Bootstrap 3.0.1, the center-block class can now be used without any additional CSS..

 <img src="images/2.png" class="img-responsive center-block">

Bootstrap 4

In Bootstrap 4, the mx-auto class (auto x-axis margins) can be used to center images that are display:block. However, img is display:inline by default so text-center can be used on the parent.

<div class="container">
    <div class="row">
        <div class="col-12">
            <img class="mx-auto d-block" src="//placehold.it/200">  
        </div>
    </div>
    <div class="row">
        <div class="col-12 text-center">
            <img src="//placehold.it/200">  
        </div>
    </div>
</div>

Bootsrap 4 - center image demo

How to see query history in SQL Server Management Studio

[Since this question will likely be closed as a duplicate.]

If SQL Server hasn't been restarted (and the plan hasn't been evicted, etc.), you may be able to find the query in the plan cache.

SELECT t.[text]
FROM sys.dm_exec_cached_plans AS p
CROSS APPLY sys.dm_exec_sql_text(p.plan_handle) AS t
WHERE t.[text] LIKE N'%something unique about your query%';

If you lost the file because Management Studio crashed, you might be able to find recovery files here:

C:\Users\<you>\Documents\SQL Server Management Studio\Backup Files\

Otherwise you'll need to use something else going forward to help you save your query history, like SSMS Tools Pack as mentioned in Ed Harper's answer - though it isn't free in SQL Server 2012+. Or you can set up some lightweight tracing filtered on your login or host name (but please use a server-side trace, not Profiler, for this).


As @Nenad-Zivkovic commented, it might be helpful to join on sys.dm_exec_query_stats and order by last_execution_time:

SELECT t.[text], s.last_execution_time
FROM sys.dm_exec_cached_plans AS p
INNER JOIN sys.dm_exec_query_stats AS s
   ON p.plan_handle = s.plan_handle
CROSS APPLY sys.dm_exec_sql_text(p.plan_handle) AS t
WHERE t.[text] LIKE N'%something unique about your query%'
ORDER BY s.last_execution_time DESC;

Python map object is not subscriptable

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

Getting list of files in documents folder

A shorter syntax for SWIFT 3

func listFilesFromDocumentsFolder() -> [String]?
{
    let fileMngr = FileManager.default;

    // Full path to documents directory
    let docs = fileMngr.urls(for: .documentDirectory, in: .userDomainMask)[0].path

    // List all contents of directory and return as [String] OR nil if failed
    return try? fileMngr.contentsOfDirectory(atPath:docs)
}

Usage example:

override func viewDidLoad()
{
    print(listFilesFromDocumentsFolder())
}

Tested on xCode 8.2.3 for iPhone 7 with iOS 10.2 & iPad with iOS 9.3

Is there a simple, elegant way to define singletons?

I'm very unsure about this, but my project uses 'convention singletons' (not enforced singletons), that is, if I have a class called DataController, I define this in the same module:

_data_controller = None
def GetDataController():
    global _data_controller
    if _data_controller is None:
        _data_controller = DataController()
    return _data_controller

It is not elegant, since it's a full six lines. But all my singletons use this pattern, and it's at least very explicit (which is pythonic).

How to set or change the default Java (JDK) version on OS X?

If still u are not able to set it. using this command.

export JAVA_HOME=/usr/libexec/java_home -v 1.8

then you have to use this one.

export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

it will surely work.

How to refresh app upon shaking the device?

Here's yet another implementation that builds on some of the tips in here as well as the code from the Android developer site.

MainActivity.java

public class MainActivity extends Activity {

    private ShakeDetector mShakeDetector;
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // ShakeDetector initialization
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mShakeDetector = new ShakeDetector(new OnShakeListener() {
            @Override
            public void onShake() {
                // Do stuff!
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onPause() {
        mSensorManager.unregisterListener(mShakeDetector);
        super.onPause();
    }   
}

ShakeDetector.java

package com.example.test;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;

public class ShakeDetector implements SensorEventListener {

    // Minimum acceleration needed to count as a shake movement
    private static final int MIN_SHAKE_ACCELERATION = 5;

    // Minimum number of movements to register a shake
    private static final int MIN_MOVEMENTS = 2;

    // Maximum time (in milliseconds) for the whole shake to occur
    private static final int MAX_SHAKE_DURATION = 500;

    // Arrays to store gravity and linear acceleration values
    private float[] mGravity = { 0.0f, 0.0f, 0.0f };
    private float[] mLinearAcceleration = { 0.0f, 0.0f, 0.0f };

    // Indexes for x, y, and z values
    private static final int X = 0;
    private static final int Y = 1;
    private static final int Z = 2;

    // OnShakeListener that will be notified when the shake is detected
    private OnShakeListener mShakeListener;

    // Start time for the shake detection
    long startTime = 0;

    // Counter for shake movements
    int moveCount = 0;

    // Constructor that sets the shake listener
    public ShakeDetector(OnShakeListener shakeListener) {
        mShakeListener = shakeListener;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // This method will be called when the accelerometer detects a change.

        // Call a helper method that wraps code from the Android developer site
        setCurrentAcceleration(event);

        // Get the max linear acceleration in any direction
        float maxLinearAcceleration = getMaxCurrentLinearAcceleration();

        // Check if the acceleration is greater than our minimum threshold
        if (maxLinearAcceleration > MIN_SHAKE_ACCELERATION) {
            long now = System.currentTimeMillis();

            // Set the startTime if it was reset to zero
            if (startTime == 0) {
                startTime = now;
            }

            long elapsedTime = now - startTime;

            // Check if we're still in the shake window we defined
            if (elapsedTime > MAX_SHAKE_DURATION) {
                // Too much time has passed. Start over!
                resetShakeDetection();
            }
            else {
                // Keep track of all the movements
                moveCount++;

                // Check if enough movements have been made to qualify as a shake
                if (moveCount > MIN_MOVEMENTS) {
                    // It's a shake! Notify the listener.
                    mShakeListener.onShake();

                    // Reset for the next one!
                    resetShakeDetection();
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // Intentionally blank
    }

    private void setCurrentAcceleration(SensorEvent event) {
        /*
         *  BEGIN SECTION from Android developer site. This code accounts for 
         *  gravity using a high-pass filter
         */

        // alpha is calculated as t / (t + dT)
        // with t, the low-pass filter's time-constant
        // and dT, the event delivery rate

        final float alpha = 0.8f;

        // Gravity components of x, y, and z acceleration
        mGravity[X] = alpha * mGravity[X] + (1 - alpha) * event.values[X];
        mGravity[Y] = alpha * mGravity[Y] + (1 - alpha) * event.values[Y];
        mGravity[Z] = alpha * mGravity[Z] + (1 - alpha) * event.values[Z];

        // Linear acceleration along the x, y, and z axes (gravity effects removed)
        mLinearAcceleration[X] = event.values[X] - mGravity[X];
        mLinearAcceleration[Y] = event.values[Y] - mGravity[Y];
        mLinearAcceleration[Z] = event.values[Z] - mGravity[Z];

        /*
         *  END SECTION from Android developer site
         */
    }

    private float getMaxCurrentLinearAcceleration() {
        // Start by setting the value to the x value
        float maxLinearAcceleration = mLinearAcceleration[X];

        // Check if the y value is greater
        if (mLinearAcceleration[Y] > maxLinearAcceleration) {
            maxLinearAcceleration = mLinearAcceleration[Y];
        }

        // Check if the z value is greater
        if (mLinearAcceleration[Z] > maxLinearAcceleration) {
            maxLinearAcceleration = mLinearAcceleration[Z];
        }

        // Return the greatest value
        return maxLinearAcceleration;
    }

    private void resetShakeDetection() {
        startTime = 0;
        moveCount = 0;
    }

    // (I'd normally put this definition in it's own .java file)
    public interface OnShakeListener {
        public void onShake();
    }
}

Laravel use same form for create and edit

In Rails, it has form_for helper, so we could make a function like form_for.

We can make a Form macro, for example in resource/macro/html.php:

(if you don't know how to setup a macro, you can google "laravel 5 Macro")

Form::macro('start', function($record, $resource, $options = array()){
    if ((null === $record || !$record->exists()) ? 1 : 0) {
        $options['route'] = $resource .'.store';
        $options['method'] = 'POST';
        $str = Form::open($options);
    } else {
        $options['route'] = [$resource .'.update', $record->id];
        $options['method'] = 'PUT';
        $str = Form::model($record, $options);
    }
    return $str;
});

The Controller:

public function create()
{
    $category = null;
    return view('admin.category.create', compact('category'));
}

public function edit($id)
{
    $category = Category.find($id);
    return view('admin.category.edit', compact('category'));
}

Then in the view _form.blade.php:

{!! Form::start($category, 'admin.categories', ['class' => 'definewidth m20']) !!}
// here the Form fields
{{!! Form::close() !!}}

Then view create.blade.php:

@include '_form'

Then view edit.blade.php:

@include '_form'

Excel Reference To Current Cell

Create a named formula called THIS_CELL

  1. In the current worksheet, select cell A1 (this is important!)

  2. Open Name Manager (Ctl+F3)

  3. Click New...

  4. Enter "THIS_CELL" (or just "THIS", which is my preference) into Name:

  5. Enter the following formula into Refers to:

    =!A1

    NOTE: Be sure cell A1 is selected. This formula is relative to the ActiveCell.

  6. Under Scope: select Workbook.

  7. Click OK and close the Name Manager

Use the formula in the worksheet exactly as you wanted

=CELL("width",THIS_CELL)

EDIT: Better solution than using INDIRECT()

It's worth noting that the solution I've given should be preferred over any solution using the INDIRECT() function for two reasons:

  1. It is nonvolatile, while INDIRECT() is a volatile Excel function, and as a result will dramatically slow down workbook calculation when it is used a lot.
  2. It is much simpler, and does not require converting an address (in the form of ROW() COLUMN()) to a range reference to an address and back to a range reference again.

EDIT: Also see this question for more information on workbook-scoped, sheet dependent named ranges.

EDIT: Also see @imix's answer below for a variation on this idea (using RC style references). In that case, you could use =!RC for the THIS_CELL named range formula, or just use RC directly.

Difference between string and text in rails?

String translates to "Varchar" in your database, while text translates to "text". A varchar can contain far less items, a text can be of (almost) any length.

For an in-depth analysis with good references check http://www.pythian.com/news/7129/text-vs-varchar/

Edit: Some database engines can load varchar in one go, but store text (and blob) outside of the table. A SELECT name, amount FROM products could, be a lot slower when using text for name than when you use varchar. And since Rails, by default loads records with SELECT * FROM... your text-columns will be loaded. This will probably never be a real problem in your or my app, though (Premature optimization is ...). But knowing that text is not always "free" is good to know.

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

@NoCanDo: You cannot create an array with different data types because java only supports variables with a specific data type or object. When you are creating an array, you are pulling together an assortment of similar variables -- almost like an extended variable. All of the variables must be of the same type therefore. Java cannot differentiate the data type of your variable unless you tell it what it is. Ex: int tells all your variables declared to it are of data type int. What you could do is create 3 arrays with corresponding information.

int bookNumber[] = {1, 2, 3, 4, 5};
int bookName[] = {nameOfBook1, nameOfBook2, nameOfBook3, nameOfBook4, nameOfBook5} // etc.. etc..

Now, a single index number gives you all the info for that book. Ex: All of your arrays with index number 0 ([0]) have information for book 1.

Execute PowerShell Script from C# with Commandline Arguments

Here is a way to add Parameters to the script if you used

pipeline.Commands.AddScript(Script);

This is with using an HashMap as paramaters the key being the name of the variable in the script and the value is the value of the variable.

pipeline.Commands.AddScript(script));
FillVariables(pipeline, scriptParameter);
Collection<PSObject> results = pipeline.Invoke();

And the fill variable method is:

private static void FillVariables(Pipeline pipeline, Hashtable scriptParameters)
{
  // Add additional variables to PowerShell
  if (scriptParameters != null)
  {
    foreach (DictionaryEntry entry in scriptParameters)
    {
      CommandParameter Param = new CommandParameter(entry.Key as String, entry.Value);
      pipeline.Commands[0].Parameters.Add(Param);
    }
  }
}

this way you can easily add multiple parameters to a script. I've also noticed that if you want to get a value from a variable in you script like so:

Object resultcollection = runspace.SessionStateProxy.GetVariable("results");

//results being the name of the v

you'll have to do it the way I showed because for some reason if you do it the way Kosi2801 suggests the script variables list doesn't get filled with your own variables.

Tool to Unminify / Decompress JavaScript

In Firefox, SpiderMonkey and Rhino you can wrap any code into an anonymous function and call its toSource method, which will give you a nicely formatted source of the function.

toSource also strips comments.

E. g.:

(function () { /* Say hello. */ var x = 'Hello!'; print(x); }).toSource()

Will be converted to a string:

function () {
    var x = "Hello!";
    print(x);
}

P. S.: It's not an "online tool", but all questions about general beautifying techniques are closed as duplicates of this one.

error: Libtool library used but 'LIBTOOL' is undefined

A good answer for me was to install libtool:

sudo apt-get install libtool

Iterate over the lines of a string

I'm not sure what you mean by "then again by the parser". After the splitting has been done, there's no further traversal of the string, only a traversal of the list of split strings. This will probably actually be the fastest way to accomplish this, so long as the size of your string isn't absolutely huge. The fact that python uses immutable strings means that you must always create a new string, so this has to be done at some point anyway.

If your string is very large, the disadvantage is in memory usage: you'll have the original string and a list of split strings in memory at the same time, doubling the memory required. An iterator approach can save you this, building a string as needed, though it still pays the "splitting" penalty. However, if your string is that large, you generally want to avoid even the unsplit string being in memory. It would be better just to read the string from a file, which already allows you to iterate through it as lines.

However if you do have a huge string in memory already, one approach would be to use StringIO, which presents a file-like interface to a string, including allowing iterating by line (internally using .find to find the next newline). You then get:

import StringIO
s = StringIO.StringIO(myString)
for line in s:
    do_something_with(line)

How can I remount my Android/system as read-write in a bash script using adb?

Probable cause that remount fails is you are not running adb as root.

Shell Script should be as follow.

# Script to mount Android Device as read/write.
# List the Devices.
adb devices;

# Run adb as root (Needs root access).
adb root;

# Since you're running as root su is not required
adb shell mount -o rw,remount /;

If this fails, you could try the below:

# List the Devices.
adb devices;

# Run adb as root
adb root;

adb remount;
adb shell su -c "mount -o rw,remount /";

To find which user you are:

$ adb shell whoami

Fastest way to convert string to integer in PHP

I've just set up a quick benchmarking exercise:

Function             time to run 1 million iterations
--------------------------------------------
(int) "123":                0.55029
intval("123"):              1.0115  (183%)

(int) "0":                  0.42461
intval("0"):                0.95683 (225%)

(int) int:                  0.1502
intval(int):                0.65716 (438%)

(int) array("a", "b"):      0.91264
intval(array("a", "b")):    1.47681 (162%)

(int) "hello":              0.42208
intval("hello"):            0.93678 (222%)

On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.

I'd be interested to know why though.


Update: I've run the tests again, this time with coercion (0 + $var)

| INPUT ($x)      |  (int) $x  |intval($x) |  0 + $x   |
|-----------------|------------|-----------|-----------|
| "123"           |   0.51541  |  0.96924  |  0.33828  |
| "0"             |   0.42723  |  0.97418  |  0.31353  |
| 123             |   0.15011  |  0.61690  |  0.15452  |
| array("a", "b") |   0.8893   |  1.45109  |  err!     |
| "hello"         |   0.42618  |  0.88803  |  0.1691   |
|-----------------|------------|-----------|-----------|

Addendum: I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:

$x = "11";
(int) $x;      // int(11)
intval($x);    // int(11)
$x + 0;        // int(11)

$x = "0x11";
(int) $x;      // int(0)
intval($x);    // int(0)
$x + 0;        // int(17) !

$x = "011";
(int) $x;      // int(11)
intval($x);    // int(11)
$x + 0;        // int(11) (not 9)

Tested using PHP 5.3.1

VS 2017 Git Local Commit DB.lock error on every commit

I'm not using Git directly thru Visual Studio but using the Git Desktop client.

I did however get a similar error but solved it by closing Visual Studio before Committing changes to master.

int object is not iterable?

Don't make it a int(), but make it a range() will solve this problem.

inp = range(input("Enter a number: "))

Shorter syntax for casting from a List<X> to a List<Y>?

If X can really be cast to Y you should be able to use

List<Y> listOfY = listOfX.Cast<Y>().ToList();

Some things to be aware of (H/T to commenters!)

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


How can I create a simple message box in Python?

Not the best, here is my basic Message box using only tkinter.

#Python 3.4
from    tkinter import  messagebox  as  msg;
import  tkinter as      tk;

def MsgBox(title, text, style):
    box = [
        msg.showinfo,       msg.showwarning,    msg.showerror,
        msg.askquestion,    msg.askyesno,       msg.askokcancel,        msg.askretrycancel,
];

tk.Tk().withdraw(); #Hide Main Window.

if style in range(7):
    return box[style](title, text);

if __name__ == '__main__':

Return = MsgBox(#Use Like This.
    'Basic Error Exemple',

    ''.join( [
        'The Basic Error Exemple a problem with test',                      '\n',
        'and is unable to continue. The application must close.',           '\n\n',
        'Error code Test',                                                  '\n',
        'Would you like visit http://wwww.basic-error-exemple.com/ for',    '\n',
        'help?',
    ] ),

    2,
);

print( Return );

"""
Style   |   Type        |   Button      |   Return
------------------------------------------------------
0           Info            Ok              'ok'
1           Warning         Ok              'ok'
2           Error           Ok              'ok'
3           Question        Yes/No          'yes'/'no'
4           YesNo           Yes/No          True/False
5           OkCancel        Ok/Cancel       True/False
6           RetryCancal     Retry/Cancel    True/False
"""

Display image as grayscale using matplotlib

import matplotlib.pyplot as plt

You can also run once in your code

plt.gray()

This will show the images in grayscale as default

im = array(Image.open('I_am_batman.jpg').convert('L'))
plt.imshow(im)
plt.show()

Ruby objects and JSON serialization (without Rails)

If rendering performance is critical, you might also want to look at yajl-ruby, which is a binding to the C yajl library. The serialization API for that one looks like:

require 'yajl'
Yajl::Encoder.encode({"foo" => "bar"}) #=> "{\"foo\":\"bar\"}"

Map and Reduce in .NET

The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

var wordOccurrences = words
                .GroupBy(w => w)
                .Select(intermediate => new
                {
                    Word = intermediate.Key,
                    Frequency = intermediate.Sum(w => 1)
                })
                .Where(w => w.Frequency > 10)
                .OrderBy(w => w.Frequency);

For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

getting the screen density programmatically in android?

Another way to get the density loaded by the device:

Create values folders for each density

  • values (default mdpi)
  • values-hdpi
  • values-xhdpi
  • values-xxhdpi
  • values-xxxhdpi

Add a string resource in their respective strings.xml:

<string name="screen_density">MDPI</string>    <!-- ..\res\values\strings.xml -->
<string name="screen_density">HDPI</string>    <!-- ..\res\values-hdpi\strings.xml -->
<string name="screen_density">XHDPI</string>   <!-- ..\res\values-xhdpi\strings.xml -->
<string name="screen_density">XXHDPI</string>  <!-- ..\res\values-xxhdpi\strings.xml -->
<string name="screen_density">XXXHDPI</string> <!-- ..\res\values-xxxhdpi\strings.xml -->

Then simply get the string resource, and you have your density:

String screenDensity = getResources().getString(R.string.screen_density);

If the density is larger than XXXHDPI, it will default to XXXHDPI or if it is lower than HDPI it will default to MDPI

R.strings.screen_density values

I left out LDPI, because for my use case it isn't necessary.

Standard Android menu icons, for example refresh

Bear in mind, this is a practice that Google explicitly advises not to do:

Warning: Because these resources can change between platform versions, you should not reference these icons using the Android platform resource IDs (i.e. menu icons under android.R.drawable).

Rather, you are adviced to make a local copy:

If you want to use any icons or other internal drawable resources, you should store a local copy of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system's copy changes.

currently unable to handle this request HTTP ERROR 500

Have you included the statement include ("fileName.php"); ?

Are you sure that file is in the correct directory?

How can I throw a general exception in Java?

You could use IllegalArgumentException:

public void speedDown(int decrement)
{
    if(speed - decrement < 0){
        throw new IllegalArgumentException("Final speed can not be less than zero");
    }else{
        speed -= decrement;
    }
}

Programmatically scroll a UIScrollView

Another way is

scrollView.contentOffset = CGPointMake(x,y);

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

In CSS, for the font-weight property, the value: normal defaults to the numeric value 400, and bold to 700.

If you want to specify other weights, you need to give the number value. That number value needs to be supported for the font family that you are using.

For example you would define semi-bold like this:

font-weight: 600;

Here an JSFiddle using 'Open Sans' font family, loaded with the above weights.

Sanitizing user input before adding it to the DOM in Javascript

Never use escape(). It's nothing to do with HTML-encoding. It's more like URL-encoding, but it's not even properly that. It's a bizarre non-standard encoding available only in JavaScript.

If you want an HTML encoder, you'll have to write it yourself as JavaScript doesn't give you one. For example:

function encodeHTML(s) {
    return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

However whilst this is enough to put your user_id in places like the input value, it's not enough for id because IDs can only use a limited selection of characters. (And % isn't among them, so escape() or even encodeURIComponent() is no good.)

You could invent your own encoding scheme to put any characters in an ID, for example:

function encodeID(s) {
    if (s==='') return '_';
    return s.replace(/[^a-zA-Z0-9.-]/g, function(match) {
        return '_'+match[0].charCodeAt(0).toString(16)+'_';
    });
}

But you've still got a problem if the same user_id occurs twice. And to be honest, the whole thing with throwing around HTML strings is usually a bad idea. Use DOM methods instead, and retain JavaScript references to each element, so you don't have to keep calling getElementById, or worrying about how arbitrary strings are inserted into IDs.

eg.:

function addChut(user_id) {
    var log= document.createElement('div');
    log.className= 'log';
    var textarea= document.createElement('textarea');
    var input= document.createElement('input');
    input.value= user_id;
    input.readonly= True;
    var button= document.createElement('input');
    button.type= 'button';
    button.value= 'Message';

    var chut= document.createElement('div');
    chut.className= 'chut';
    chut.appendChild(log);
    chut.appendChild(textarea);
    chut.appendChild(input);
    chut.appendChild(button);
    document.getElementById('chuts').appendChild(chut);

    button.onclick= function() {
        alert('Send '+textarea.value+' to '+user_id);
    };

    return chut;
}

You could also use a convenience function or JS framework to cut down on the lengthiness of the create-set-appends calls there.

ETA:

I'm using jQuery at the moment as a framework

OK, then consider the jQuery 1.4 creation shortcuts, eg.:

var log= $('<div>', {className: 'log'});
var input= $('<input>', {readOnly: true, val: user_id});
...

The problem I have right now is that I use JSONP to add elements and events to a page, and so I can not know whether the elements already exist or not before showing a message.

You can keep a lookup of user_id to element nodes (or wrapper objects) in JavaScript, to save putting that information in the DOM itself, where the characters that can go in an id are restricted.

var chut_lookup= {};
...

function getChut(user_id) {
    var key= '_map_'+user_id;
    if (key in chut_lookup)
        return chut_lookup[key];
    return chut_lookup[key]= addChut(user_id);
}

(The _map_ prefix is because JavaScript objects don't quite work as a mapping of arbitrary strings. The empty string and, in IE, some Object member names, confuse it.)

How can I set the color of a selected row in DataGrid

I've tried ControlBrushKey but it didn't work for unselected rows. The background for the unselected row was still white. But I've managed to find out that I have to override the rowstyle.

<DataGrid x:Name="pbSelectionDataGrid" Height="201" Margin="10,0"
          FontSize="20" SelectionMode="Single" FontWeight="Bold">
    <DataGrid.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#FFFDD47C"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#FFA6E09C"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Red"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Violet"/>
    </DataGrid.Resources>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="LightBlue" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

Chart.js v2 - hiding grid lines

If you want them gone by default, you can set:

Chart.defaults.scale.gridLines.display = false;

How to add image in a TextView text?

This is partly based on this earlier answer above by @A Boschman. In that solution, I found that the input size of the image greatly affected the ability of makeImageSpan() to properly center-align the image. Additionally, I found that the solution affected text spacing by creating unnecessary line spacing.

I found BaseImageSpan (from Facebook's Fresco library) to do the job particularly well:

 /**
 * Create an ImageSpan for the given icon drawable. This also sets the image size. Works best
 * with a square icon because of the sizing
 *
 * @param context       The Android Context.
 * @param drawableResId A drawable resource Id.
 * @param size          The desired size (i.e. width and height) of the image icon in pixels.
 *                      Use the lineHeight of the TextView to make the image inline with the
 *                      surrounding text.
 * @return An ImageSpan, aligned with the bottom of the text.
 */
private static BetterImageSpan makeImageSpan(Context context, int drawableResId, int size) {
    final Drawable drawable = context.getResources().getDrawable(drawableResId);
    drawable.mutate();
    drawable.setBounds(0, 0, size, size);
    return new BetterImageSpan(drawable, BetterImageSpan.ALIGN_CENTER);
}

Then supply your betterImageSpan instance to spannable.setSpan() as usual

How to print an exception in Python?

(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)

I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:

except Exception as e:
    print(e)

will print the error output to sys.stdout by default. A more appropriate approach to error handling in general would be:

except Exception as e:
    print(e, file=sys.stderr)

(Note that you have to import sys for this to work.) This way, the error is printed to STDERR instead of STDOUT, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.

I haven't used the traceback module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.

Why are exclamation marks used in Ruby methods?

Simple explanation:

foo = "BEST DAY EVER" #assign a string to variable foo.

=> foo.downcase #call method downcase, this is without any exclamation.

"best day ever"  #returns the result in downcase, but no change in value of foo.

=> foo #call the variable foo now.

"BEST DAY EVER" #variable is unchanged.

=> foo.downcase! #call destructive version.

=> foo #call the variable foo now.

"best day ever" #variable has been mutated in place.

But if you ever called a method downcase! in the explanation above, foo would change to downcase permanently. downcase! would not return a new string object but replace the string in place, totally changing the foo to downcase. I suggest you don't use downcase! unless it is totally necessary.

Generate a sequence of numbers in Python

Assuming I've guessed the pattern correctly (alternating increments of 1 and 3), this should produce the desired result:

def sequence():
    res = []
    diff = 1
    x = 1
    while x <= 100:
        res.append(x)
        x += diff
        diff = 3 if diff == 1 else 1
    return ', '.join(res)

MySQL add days to a date

SELECT DATE_ADD(CURDATE(), INTERVAL 2 DAY)

Convert an array to string

My suggestion:

using System.Linq;

string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());

reference: https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c

Swift Bridging Header import issue

In my case this was actually an error as a result of a circular reference. I had a class imported in the bridging header, and that class' header file was importing the swift header (<MODULE_NAME>-Swift.h). I was doing this because in the Obj-C header file I needed to use a class that was declared in Swift, the solution was to simply use the @class declarative.

So basically the error said "Failed to import bridging header", the error above it said <MODULE_NAME>-Swift.h file not found, above that was an error pointing at a specific Obj-C Header file (namely a View Controller).

Inspecting this file I noticed that it had the -Swift.h declared inside the header. Moving this import to the implementation resolved the issue. So I needed to use an object, lets call it MyObject defined in Swift, so I simply changed the header to say

@class MyObject;

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

You need to stop all tracks (from webcam, microphone):

localStream.getTracks().forEach(track => track.stop());

How to display table data more clearly in oracle sqlplus

If you mean you want to see them like this:

WORKPLACEID NAME       ADDRESS        TELEPHONE
----------- ---------- -------------- ---------
          1 HSBC       Nugegoda Road      43434
          2 HNB Bank   Colombo Road      223423

then in SQL Plus you can set the column widths like this (for example):

column name format a10
column address format a20
column telephone format 999999999

You can also specify the line size and page size if necessary like this:

set linesize 100 pagesize 50

You do this by typing those commands into SQL Plus before running the query. Or you can put these commands and the query into a script file e.g. myscript.sql and run that. For example:

column name format a10
column address format a20
column telephone format 999999999

select name, address, telephone
from mytable;

Get a list of dates between two dates using a function

DECLARE @MinDate DATETIME = '2012-09-23 00:02:00.000',
    @MaxDate DATETIME = '2012-09-25 00:00:00.000';

SELECT  TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1) Dates = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate)
FROM sys.all_objects a CROSS JOIN sys.all_objects b;

include antiforgerytoken in ajax post ASP.NET MVC

it is so simple! when you use @Html.AntiForgeryToken() in your html code it means that server has signed this page and each request that is sent to server from this particular page has a sign that is prevented to send a fake request by hackers. so for this page to be authenticated by the server you should go through two steps:

1.send a parameter named __RequestVerificationToken and to gets its value use codes below:

<script type="text/javascript">
    function gettoken() {
        var token = '@Html.AntiForgeryToken()';
        token = $(token).val();
        return token;
   }
</script>

for example take an ajax call

$.ajax({
    type: "POST",
    url: "/Account/Login",
    data: {
        __RequestVerificationToken: gettoken(),
        uname: uname,
        pass: pass
    },
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    success: successFu,
});

and step 2 just decorate your action method by [ValidateAntiForgeryToken]