Programs & Examples On #Quicksilver

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

See this http://blog.stevenlevithan.com/archives/date-time-format

you can do anything with date.

file : http://stevenlevithan.com/assets/misc/date.format.js

add this to your html code using script tag and to use you can use it as :

var now = new Date();

now.format("m/dd/yy");
// Returns, e.g., 6/09/07

Error: Cannot invoke an expression whose type lacks a call signature

Let's break this down:

  1. The error says

    Cannot invoke an expression whose type lacks a call signature.

  2. The code:

The problem is in this line public toggleBody: string; &

it's relation to these lines:

...
return this.toggleBody(true);
...
return this.toggleBody(false);
  1. The result:

Your saying toggleBody is a string but then your treating it like something that has a call signature (i.e. the structure of something that can be called: lambdas, proc, functions, methods, etc. In JS just function tho.). You need to change the declaration to be public toggleBody: (arg: boolean) => boolean;.

Extra Details:

"invoke" means your calling or applying a function.

"an expression" in Javascript is basically something that produces a value, so this.toggleBody() counts as an expression.

"type" is declared on this line public toggleBody: string

"lacks a call signature" this is because your trying to call something this.toggleBody() that doesn't have signature(i.e. the structure of something that can be called: lambdas, proc, functions, methods, etc.) that can be called. You said this.toggleBody is something that acts like a string.

In other words the error is saying

Cannot call an expression (this.toggleBody) because it's type (:string) lacks a call signature (bc it has a string signature.)

How to write log base(2) in c/c++

If you're looking for an integral result, you can just determine the highest bit set in the value and return its position.

Comparing strings, c++

string cat = "cat";
string human = "human";

cout << cat.compare(human) << endl; 

This code will give -1 as a result. This is due to the first non-matching character of the compared string 'h' is lower or appears after 'c' in alphabetical order, even though the compared string, 'human' is longer than 'cat'.

I find the return value described in cplusplus.com is more accurate which are-:

0 : They compare equal

<0 : Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.

more than 0 : Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.

Moreover, IMO cppreference.com's description is simpler and so far best describe to my own experience.

negative value if *this appears before the character sequence specified by the arguments, in lexicographical order

zero if both character sequences compare equivalent

positive value if *this appears after the character sequence specified by the arguments, in lexicographical order

How to use target in location.href

Why not have a hidden anchor tag on the page with the target set as you need, then simulate clicking it when you need the pop out?

How can I simulate a click to an anchor tag?

This would work in the cases where the window.open did not work

Selecting multiple classes with jQuery

I use $('.myClass.myOtherClass').removeClass('theclass');

New lines inside paragraph in README.md

You can use a backslash at the end of a line.
So this:

a\
b\
c

will then look like:

a
b
c

Notice that there is no backslash at the end of the last line (after the 'c' character).

Convert int to char in java

It seems like you are looking for the Character.forDigit method:

final int RADIX = 10;
int i = 4;
char ch = Character.forDigit(i, RADIX);
System.out.println(ch); // Prints '4'

There is also a method that can convert from a char back to an int:

int i2 = Character.digit(ch, RADIX);
System.out.println(i2); // Prints '4'

Note that by changing the RADIX you can also support hexadecimal (radix 16) and any radix up to 36 (or Character.MAX_RADIX as it is also known as).

Viewing PDF in Windows forms using C#

you can use System.Diagnostics.Process.Start as well as WIN32 ShellExecute function by means of interop, for opening PDF files using the default viewer:

System.Diagnostics.Process.Start("SOMEAPP.EXE","Path/SomeFile.Ext");

[System.Runtime.InteropServices.DllImport("shell32. dll")]
private static extern long ShellExecute(Int32 hWnd, string lpOperation, 
                                    string lpFile, string lpParameters, 
                                        string lpDirectory, long nShowCmd);

Another approach is to place a WebBrowser Control into your Form and then use the Navigate method for opening the PDF file:

ThewebBrowserControl.Navigate(@"c:\the_file.pdf");

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

When is the @JsonProperty property used and what is it used for?

In addition to all the answers above, don't forget the part of the documentation that says

Marker annotation that can be used to define a non-static method as a "setter" or "getter" for a logical property (depending on its signature), or non-static object field to be used (serialized, deserialized) as a logical property.

If you have a non-static method in your class that is not a conventional getter or setter then you can make it act like a getter and setter by using the annotation on it. See the example below

public class Testing {
    private Integer id;
    private String username;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getIdAndUsername() {
        return id + "." + username; 
    }

    public String concatenateIdAndUsername() {
        return id + "." + username; 
    }
}

When the above object is serialized, then response will contain

  • username from getUsername()
  • id from getId()
  • idAndUsername from getIdAndUsername*

Since the method getIdAndUsername starts with get then it's treated as normal getter hence, why you could annotate such with @JsonIgnore.

If you have noticed the concatenateIdAndUsername is not returned and that's because it name does not start with get and if you wish the result of that method to be included in the response then you can use @JsonProperty("...") and it would be treated as normal getter/setter as mentioned in the above highlighted documentation.

How to add a href link in PHP?

you have problems with " :

 <a href=<?php echo "'www.someotherwebsite.com'><img src='". url::file_loc('img'). "media/img/twitter.png' style='vertical-align: middle' border='0'></a>"; ?>

How do I escape reserved words used as column names? MySQL/Create Table

You should use back tick character (`) eg:

create table if not exists misc_info (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL)ENGINE=INNODB;

ggplot2 plot without axes, legends, etc

Current answers are either incomplete or inefficient. Here is (perhaps) the shortest way to achieve the outcome (using theme_void():

data(diamonds) # Data example
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut)) +
      theme_void() + theme(legend.position="none")

The outcome is:

enter image description here


If you are interested in just eliminating the labels, labs(x="", y="") does the trick:

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut)) + 
      labs(x="", y="")

"unrecognized selector sent to instance" error in Objective-C

In my case, in iOS 13, I only had to implement the whole function and selector calling parts put in to main thread.

How to add an empty column to a dataframe?

an even simpler solution is:

df = df.reindex(columns = header_list)                

where "header_list" is a list of the headers you want to appear.

any header included in the list that is not found already in the dataframe will be added with blank cells below.

so if

header_list = ['a','b','c', 'd']

then c and d will be added as columns with blank cells

Why do we use web.xml?

Generally speaking, this is the configuration file of web applications in java. It instructs the servlet container (tomcat for ex.) which classes to load, what parameters to set in the context, and how to intercept requests coming from browsers.

There you specify:

  • what servlets (and filters) you want to use and what URLs you want to map them to
  • listeners - classes that are notified when some events happen (context starts, session created, etc)
  • configuration parameters (context-params)
  • error pages, welcome files
  • security constraints

In servlet 3.0 many of the web.xml parts are optional. These configurations can be done via annotations (@WebServlet, @WebListener)

What does "if (rs.next())" mean?

As to the concrete problem with that SQLException, you need to replace

ResultSet rs = stmt.executeQuery(sql);

by

ResultSet rs = stmt.executeQuery();

because you're using the PreparedStatement subclass instead of Statement. When using PreparedStatement, you've already passed in the SQL string to Connection#prepareStatement(). You just have to set the parameters on it and then call executeQuery() method directly without re-passing the SQL string.

See also:


As to the concrete question about rs.next(), it shifts the cursor to the next row of the result set from the database and returns true if there is any row, otherwise false. In combination with the if statement (instead of the while) this means that the programmer is expecting or interested in only one row, the first row.

See also:

Javascript String to int conversion

This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:

0 + 1; //1
'0' + 1; // '01'

To solve this, use the + unary operator, or use parseInt():

+'0' + 1; // 1
parseInt('0', 10) + 1; // 1

The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).

The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:

parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what

There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.

How to set a cell to NaN in a pandas dataframe

You can try these snippets.

In [16]:mydata = {'x' : [10, 50, 18, 32, 47, 20], 'y' : ['12', '11', 'N/A', '13', '15', 'N/A']}
In [17]:df=pd.DataFrame(mydata)

In [18]:df.y[df.y=="N/A"]=np.nan

Out[19]:df 
    x    y
0  10   12
1  50   11
2  18  NaN
3  32   13
4  47   15
5  20  NaN

Register DLL file on Windows Server 2008 R2

I have found similar issue while registering my activeX (OCX) into windows server 2008 R2.To solve this i used http://www.chestysoft.com/dllregsvr/default.asp tool.There is some dependance problem with my ocx so I am getting "The module temp12.dll failed to load. Make sure the binary is stored at the specified path or debut it to check for problems with the binary or dependent .DLL files. The specified module could not be found" error message. When you try to registered your OCX with this tool it will prompt message if the ocx is having dependency or you will get success message.I got message for mfc70.dll and msvcr70.dll dependency.so i paste these dll into system32 folder of C:\windows and its done.After that I register my ocx sucessfully.I used 32 bit version of chestysoft tool (dllregsvr.exe) on windows server 2008 R2 64bit machine.

Create a CSV File for a user in PHP

First make data as a String with comma as the delimiter (separated with ","). Something like this

$CSV_string="No,Date,Email,Sender Name,Sender Email \n"; //making string, So "\n" is used for newLine

$rand = rand(1,50); //Make a random int number between 1 to 50.
$file ="export/export".$rand.".csv"; //For avoiding cache in the client and on the server 
                                     //side it is recommended that the file name be different.

file_put_contents($file,$CSV_string);

/* Or try this code if $CSV_string is an array
    fh =fopen($file, 'w');
    fputcsv($fh , $CSV_string , ","  , "\n" ); // "," is delimiter // "\n" is new line.
    fclose($fh);
*/

Difference between clean, gradlew clean

  1. ./gradlew clean

    Uses your project's gradle wrapper to execute your project's clean task. Usually, this just means the deletion of the build directory.

  2. ./gradlew clean assembleDebug

    Again, uses your project's gradle wrapper to execute the clean and assembleDebug tasks, respectively. So, it will clean first, then execute assembleDebug, after any non-up-to-date dependent tasks.

  3. ./gradlew clean :assembleDebug

    Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.

  4. Android Studio --> Build --> Clean

    Is essentially the same as ./gradlew clean. See here.

For more info, I suggest taking the time to read through the Android docs, especially this one.

Erase whole array Python

Well yes arrays do exist, and no they're not different to lists when it comes to things like del and append:

>>> from array import array
>>> foo = array('i', range(5))
>>> foo
array('i', [0, 1, 2, 3, 4])
>>> del foo[:]
>>> foo
array('i')
>>> foo.append(42)
>>> foo
array('i', [42])
>>>

Differences worth noting: you need to specify the type when creating the array, and you save storage at the expense of extra time converting between the C type and the Python type when you do arr[i] = expression or arr.append(expression), and lvalue = arr[i]

How to create a circular ImageView in Android?

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

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

public class RoundedImageView extends ImageView {

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

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

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

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

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

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

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

    }

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

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

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

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

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

        return output;
    }

}

TypeError: method() takes 1 positional argument but 2 were given

In my case, I forgot to add the ()

I was calling the method like this

obj = className.myMethod

But it should be is like this

obj = className.myMethod()

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

I had the same problem and I annotated the method as @Transactional and it worked.

UPDATE: checking the spring documentation it looks like by default the PersistenceContext is of type Transaction, so that's why the method has to be transactional (http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html):

The @PersistenceContext annotation has an optional attribute type, which defaults to PersistenceContextType.TRANSACTION. This default is what you need to receive a shared EntityManager proxy. The alternative, PersistenceContextType.EXTENDED, is a completely different affair: This results in a so-called extended EntityManager, which is not thread-safe and hence must not be used in a concurrently accessed component such as a Spring-managed singleton bean. Extended EntityManagers are only supposed to be used in stateful components that, for example, reside in a session, with the lifecycle of the EntityManager not tied to a current transaction but rather being completely up to the application.

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

I was getting this exception, fixed it by adding throwIfV1Schema: false to my DbContext constructor:

public class AppDb : IdentityDbContext<User>
{
    public AppDb()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }
}

any tool for java object to object mapping?

You can also try mapping framework based on Dozer, but with Excel mapping declaration. They've got some tools and additional cool features. Check at http://openl-tablets.sf.net/mapper

Error when testing on iOS simulator: Couldn't register with the bootstrap server

I think this is caused by force-quitting your app on the iPhone prior to pressing the stop button in Xcode. Sometimes when you press the stop button in Xcode, then it takes extra time to quit the app if it hung. But just be patient, it will eventually quit most of the time.

Iterate through every file in one directory

This is my favorite method for being easy to read:

Dir.glob("*/*.txt") do |my_text_file|
  puts "working on: #{my_text_file}..."
end

And you can even extend this to work on all files in subdirs:

Dir.glob("**/*.txt") do |my_text_file| # note one extra "*"
  puts "working on: #{my_text_file}..."
end

Dynamically load a function from a DLL

This is not exactly a hot topic, but I have a factory class that allows a dll to create an instance and return it as a DLL. It is what I came looking for but couldn't find exactly.

It is called like,

IHTTP_Server *server = SN::SN_Factory<IHTTP_Server>::CreateObject();
IHTTP_Server *server2 =
      SN::SN_Factory<IHTTP_Server>::CreateObject(IHTTP_Server_special_entry);

where IHTTP_Server is the pure virtual interface for a class created either in another DLL, or the same one.

DEFINE_INTERFACE is used to give a class id an interface. Place inside interface;

An interface class looks like,

class IMyInterface
{
    DEFINE_INTERFACE(IMyInterface);

public:
    virtual ~IMyInterface() {};

    virtual void MyMethod1() = 0;
    ...
};

The header file is like this

#if !defined(SN_FACTORY_H_INCLUDED)
#define SN_FACTORY_H_INCLUDED

#pragma once

The libraries are listed in this macro definition. One line per library/executable. It would be cool if we could call into another executable.

#define SN_APPLY_LIBRARIES(L, A)                          \
    L(A, sn, "sn.dll")                                    \
    L(A, http_server_lib, "http_server_lib.dll")          \
    L(A, http_server, "")

Then for each dll/exe you define a macro and list its implementations. Def means that it is the default implementation for the interface. If it is not the default, you give a name for the interface used to identify it. Ie, special, and the name will be IHTTP_Server_special_entry.

#define SN_APPLY_ENTRYPOINTS_sn(M)                                     \
    M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, def)                   \
    M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, special)

#define SN_APPLY_ENTRYPOINTS_http_server_lib(M)                        \
    M(IHTTP_Server, HTTP::server::server, http_server_lib, def)

#define SN_APPLY_ENTRYPOINTS_http_server(M)

With the libraries all setup, the header file uses the macro definitions to define the needful.

#define APPLY_ENTRY(A, N, L) \
    SN_APPLY_ENTRYPOINTS_##N(A)

#define DEFINE_INTERFACE(I) \
    public: \
        static const long Id = SN::I##_def_entry; \
    private:

namespace SN
{
    #define DEFINE_LIBRARY_ENUM(A, N, L) \
        N##_library,

This creates an enum for the libraries.

    enum LibraryValues
    {
        SN_APPLY_LIBRARIES(DEFINE_LIBRARY_ENUM, "")
        LastLibrary
    };

    #define DEFINE_ENTRY_ENUM(I, C, L, D) \
        I##_##D##_entry,

This creates an enum for interface implementations.

    enum EntryValues
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_ENUM)
        LastEntry
    };

    long CallEntryPoint(long id, long interfaceId);

This defines the factory class. Not much to it here.

    template <class I>
    class SN_Factory
    {
    public:
        SN_Factory()
        {
        }

        static I *CreateObject(long id = I::Id )
        {
            return (I *)CallEntryPoint(id, I::Id);
        }
    };
}

#endif //SN_FACTORY_H_INCLUDED

Then the CPP is,

#include "sn_factory.h"

#include <windows.h>

Create the external entry point. You can check that it exists using depends.exe.

extern "C"
{
    __declspec(dllexport) long entrypoint(long id)
    {
        #define CREATE_OBJECT(I, C, L, D) \
            case SN::I##_##D##_entry: return (int) new C();

        switch (id)
        {
            SN_APPLY_CURRENT_LIBRARY(APPLY_ENTRY, CREATE_OBJECT)
        case -1:
        default:
            return 0;
        }
    }
}

The macros set up all the data needed.

namespace SN
{
    bool loaded = false;

    char * libraryPathArray[SN::LastLibrary];
    #define DEFINE_LIBRARY_PATH(A, N, L) \
        libraryPathArray[N##_library] = L;

    static void LoadLibraryPaths()
    {
        SN_APPLY_LIBRARIES(DEFINE_LIBRARY_PATH, "")
    }

    typedef long(*f_entrypoint)(long id);

    f_entrypoint libraryFunctionArray[LastLibrary - 1];
    void InitlibraryFunctionArray()
    {
        for (long j = 0; j < LastLibrary; j++)
        {
            libraryFunctionArray[j] = 0;
        }

        #define DEFAULT_LIBRARY_ENTRY(A, N, L) \
            libraryFunctionArray[N##_library] = &entrypoint;

        SN_APPLY_CURRENT_LIBRARY(DEFAULT_LIBRARY_ENTRY, "")
    }

    enum SN::LibraryValues libraryForEntryPointArray[SN::LastEntry];
    #define DEFINE_ENTRY_POINT_LIBRARY(I, C, L, D) \
            libraryForEntryPointArray[I##_##D##_entry] = L##_library;
    void LoadLibraryForEntryPointArray()
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_POINT_LIBRARY)
    }

    enum SN::EntryValues defaultEntryArray[SN::LastEntry];
        #define DEFINE_ENTRY_DEFAULT(I, C, L, D) \
            defaultEntryArray[I##_##D##_entry] = I##_def_entry;

    void LoadDefaultEntries()
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_DEFAULT)
    }

    void Initialize()
    {
        if (!loaded)
        {
            loaded = true;
            LoadLibraryPaths();
            InitlibraryFunctionArray();
            LoadLibraryForEntryPointArray();
            LoadDefaultEntries();
        }
    }

    long CallEntryPoint(long id, long interfaceId)
    {
        Initialize();

        // assert(defaultEntryArray[id] == interfaceId, "Request to create an object for the wrong interface.")
        enum SN::LibraryValues l = libraryForEntryPointArray[id];

        f_entrypoint f = libraryFunctionArray[l];
        if (!f)
        {
            HINSTANCE hGetProcIDDLL = LoadLibraryA(libraryPathArray[l]);

            if (!hGetProcIDDLL) {
                return NULL;
            }

            // resolve function address here
            f = (f_entrypoint)GetProcAddress(hGetProcIDDLL, "entrypoint");
            if (!f) {
                return NULL;
            }
            libraryFunctionArray[l] = f;
        }
        return f(id);
    }
}

Each library includes this "cpp" with a stub cpp for each library/executable. Any specific compiled header stuff.

#include "sn_pch.h"

Setup this library.

#define SN_APPLY_CURRENT_LIBRARY(L, A) \
    L(A, sn, "sn.dll")

An include for the main cpp. I guess this cpp could be a .h. But there are different ways you could do this. This approach worked for me.

#include "../inc/sn_factory.cpp"

php $_GET and undefined index

Avoid if, else and elseifs!

$loadMethod = "";
if(isset($_GET['s'])){
    switch($_GET['s']){
        case 'jwshxnsyllabus':
            $loadMethod = "loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')";
        break;
        case 'aquinas':
            $loadMethod = "loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')";
        break;
        case 'POP2':
            $loadMethod = "loadSyllabi('POP2')";
    }
}

echo '<body onload="'.$loadMethod.'">';

clean, readable code is maintainable code

finding the type of an element using jQuery

It is worth noting that @Marius's second answer could be used as pure Javascript solution.

document.getElementById('elementId').tagName

Stack, Static, and Heap in C++

Stack memory allocation (function variables, local variables) can be problematic when your stack is too "deep" and you overflow the memory available to stack allocations. The heap is for objects that need to be accessed from multiple threads or throughout the program lifecycle. You can write an entire program without using the heap.

You can leak memory quite easily without a garbage collector, but you can also dictate when objects and memory is freed. I have run in to issues with Java when it runs the GC and I have a real time process, because the GC is an exclusive thread (nothing else can run). So if performance is critical and you can guarantee there are no leaked objects, not using a GC is very helpful. Otherwise it just makes you hate life when your application consumes memory and you have to track down the source of a leak.

How to detect when cancel is clicked on file input?

The easiest way is to check if there are any files in temporary memory. If you want to get the change event every time user clicks the file input you can trigger it.

var yourFileInput = $("#yourFileInput");

yourFileInput.on('mouseup', function() {
    $(this).trigger("change");
}).on('change', function() {
    if (this.files.length) {
        //User chose a picture
    } else {
        //User clicked cancel
    }
});

Giving multiple URL patterns to Servlet Filter

In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml), you can do so by just putting an array of mappings in the @WebFilter annotation:

/**
 * Filter implementation class LoginFilter
 */
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
    ...

And just as an FYI, this same thing works for servlets using the servlet annotation too:

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
    ...

XML Schema How to Restrict Attribute by Enumeration

New answer to old question

None of the existing answers to this old question address the real problem.

The real problem was that xs:complexType cannot directly have a xs:extension as a child in XSD. The fix is to use xs:simpleContent first. Details follow...


Your XML,

<price currency="euros">20000.00</price>

will be valid against either of the following corrected XSDs:

Locally defined attribute type

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:decimal">
          <xs:attribute name="currency">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="pounds" />
                <xs:enumeration value="euros" />
                <xs:enumeration value="dollars" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Globally defined attribute type

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="currencyType">
    <xs:restriction base="xs:string">
      <xs:enumeration value="pounds" />
      <xs:enumeration value="euros" />
      <xs:enumeration value="dollars" />
    </xs:restriction>
  </xs:simpleType>

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:decimal">
          <xs:attribute name="currency" type="currencyType"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Notes

  • As commented by @Paul, these do change the content type of price from xs:string to xs:decimal, but this is not strictly necessary and was not the real problem.
  • As answered by @user998692, you could separate out the definition of currency, and you could change to xs:decimal, but this too was not the real problem.

The real problem was that xs:complexType cannot directly have a xs:extension as a child in XSD; xs:simpleContent is needed first.

A related matter (that wasn't asked but may have confused other answers):

How could price be restricted given that it has an attribute?

In this case, a separate, global definition of priceType would be needed; it is not possible to do this with only local type definitions.

How to restrict element content when element has attribute

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="priceType">  
    <xs:restriction base="xs:decimal">  
      <xs:minInclusive value="0.00"/>  
      <xs:maxInclusive value="99999.99"/>  
    </xs:restriction>  
  </xs:simpleType>

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="priceType">
          <xs:attribute name="currency">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="pounds" />
                <xs:enumeration value="euros" />
                <xs:enumeration value="dollars" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

How to cast int to enum in C++?

Spinning off the closing question, "how do I convert a to type Test::A" rather than being rigid about the requirement to have a cast in there, and answering several years late only because this seems to be a popular question and nobody else has mentioned the alternative, per the C++11 standard:

5.2.9 Static cast

... an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.

Therefore directly using the form t(e) will also work, and you might prefer it for neatness:

auto result = Test(a);

Python loop that also accesses previous and next values

using conditional expressions for conciseness for python >= 2.5

def prenext(l,v) : 
   i=l.index(v)
   return l[i-1] if i>0 else None,l[i+1] if i<len(l)-1 else None


# example
x=range(10)
prenext(x,3)
>>> (2,4)
prenext(x,0)
>>> (None,2)
prenext(x,9)
>>> (8,None)

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

As string data types have variable length, it is by default stored as object type. I faced this problem after treating missing values too. Converting all those columns to type 'category' before label encoding worked in my case.

df[cat]=df[cat].astype('category')

And then check df.dtypes and perform label encoding.

JDK on OSX 10.7 Lion

You can download jdk6 here http://support.apple.com/kb/DL1573

Wish it helps

Excel VBA Automation Error: The object invoked has disconnected from its clients

You must have used the object, released it ("disconnect"), and used it again. Release object only after you're finished with it, or when calling Form_Closing.

SQL GROUP BY CASE statement with aggregate function

I think the answer is pretty simple (unless I'm missing something?)

SELECT    
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END AS some_product
FROM some_table
GROUP BY
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END

You can put the CASE STATEMENT in the GROUP BY verbatim (minus the alias column name)

Allow only numbers and dot in script

Just add the code below in your input text:

onkeypress='return event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)'

How to run html file on localhost?

On macOS:

Open Terminal (or iTerm) install Homebrew then run brew install live-server and run live-server.

You also can install Python 3 and run python3 -m http.server PORT.

On Windows:

If you have VS Code installed open it and install extension liveserver, then click Go Live in the bottom right corner.

Alternatively you can install WSL2 and follow the macOS steps via apt (sudo apt-get).

On Linux:

Open your favorite terminal emulator and follow the macOS steps via apt (sudo apt-get).

Rebase array keys after unsetting elements

Use array_splice rather than unset:

$array = array(1,2,3,4,5);
foreach($array as $i => $info)
{
  if($info == 1 || $info == 2)
  {
    array_splice($array, $i, 1);
  }
}

print_r($array);

Working sample here.

TypeScript, Looping through a dictionary

There is one caveat to the key/value loop that Ian mentioned. If it is possible that the Objects may have attributes attached to their Prototype, and when you use the in operator, these attributes will be included. So you will want to make sure that the key is an attribute of your instance, and not of the prototype. Older IEs are known for having indexof(v) show up as a key.

for (const key in myDictionary) {
    if (myDictionary.hasOwnProperty(key)) {
        let value = myDictionary[key];
    }
}

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

jQuery vs. javascript?

Personally i think you should learn the hard way first. It will make you a better programmer and you will be able to solve that one of a kind issue when it comes up. After you can do it with pure JavaScript then using jQuery to speed up development is just an added bonus.

If you can do it the hard way then you can do it the easy way, it doesn't work the other way around. That applies to any programming paradigm.

Display a float with two decimal places in Python

Using python string formatting.

>>> "%0.2f" % 3
'3.00'

how to loop through json array in jquery?

Try this:

var data = jQuery.parseJSON(response);
$.each(data, function(key, item) 
{
   console.log(item.com);
});

or

var data = $.parseJSON(response);

$(data).each(function(i,val)
 {
    $.each(val,function(key,val)
  {
          console.log(key + " : " + val);     
  });
});

SQL: How To Select Earliest Row

In this case a relatively simple GROUP BY can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER():

Runnable example (Wofkflow20 error in original data corrected)

;WITH partitioned AS (
    SELECT company
        ,workflow
        ,date
        ,other_columns
        ,ROW_NUMBER() OVER(PARTITION BY company, workflow
                            ORDER BY date) AS seq
    FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1

passing argument to DialogFragment

I used to send some values from my listview

How to send

mListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            Favorite clickedObj = (Favorite) parent.getItemAtPosition(position);

            Bundle args = new Bundle();
            args.putString("tar_name", clickedObj.getNameTarife());
            args.putString("fav_name", clickedObj.getName());

            FragmentManager fragmentManager = getSupportFragmentManager();
            TarifeDetayPopup userPopUp = new TarifeDetayPopup();
            userPopUp.setArguments(args);
            userPopUp.show(fragmentManager, "sam");

            return false;
        }
    });

How to receive inside onCreate() method of DialogFragment

    Bundle mArgs = getArguments();
    String nameTrife = mArgs.getString("tar_name");
    String nameFav = mArgs.getString("fav_name");
    String name = "";

// Kotlin upload

 val fm = supportFragmentManager
        val dialogFragment = AddProgFargmentDialog() // my custom FargmentDialog
        var args: Bundle? = null
        args?.putString("title", model.title);
        dialogFragment.setArguments(args)
        dialogFragment.show(fm, "Sample Fragment")

// receive

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (getArguments() != null) {
            val mArgs = arguments
            var myDay= mArgs.getString("title")
        }
    }

multiple packages in context:component-scan, spring config

If x.y.z is the common package then you can use:

<context:component-scan base-package="x.y.z.*">

it will include all the package that is start with x.y.z like: x.y.z.controller,x.y.z.service etc.

Converting to upper and lower case in Java

String a = "ABCD"

using this

a.toLowerCase();

all letters will convert to simple, "abcd"
using this

a.toUpperCase()

all letters will convert to Capital, "ABCD"

this conver first letter to capital:

a.substring(0,1).toUpperCase()

this conver other letter Simple

a.substring(1).toLowerCase();

we can get sum of these two

a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();

result = "Abcd"

how to get the current working directory's absolute path from irb

This will give you the working directory of the current file.

File.dirname(__FILE__)

Example:

current_file: "/Users/nemrow/SITM/folder1/folder2/amazon.rb"

result: "/Users/nemrow/SITM/folder1/folder2"

Matplotlib - How to plot a high resolution graph?

You can save your graph as svg for a lossless quality:

import matplotlib.pylab as plt

x = range(10)

plt.figure()
plt.plot(x,x)
plt.savefig("graph.svg")

Comma separated results in SQL

Use FOR XML PATH('') - which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result

SELECT  STUFF((SELECT  ',' + INSTITUTIONNAME
            FROM EDUCATION EE
            WHERE  EE.STUDENTNUMBER=E.STUDENTNUMBER
            ORDER BY sortOrder
        FOR XML PATH('')), 1, 1, '') AS listStr

FROM EDUCATION E
GROUP BY E.STUDENTNUMBER

Here is the FIDDLE

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

Another solution if you don't want to modify your settings:

Download jms-1.1.jar from JBoss repository then:

mvn install:install-file -DgroupId=javax.jms -DartifactId=jms -Dversion=1.1 -Dpackaging=jar -Dfile=jms-1.1.jar

How to set cookies in laravel 5 independently inside controller

You may try this:

Cookie::queue($name, $value, $minutes);

This will queue the cookie to use it later and later it will be added with the response when response is ready to be sent. You may check the documentation on Laravel website.

Update (Retrieving A Cookie Value):

$value = Cookie::get('name');

Note: If you set a cookie in the current request then you'll be able to retrieve it on the next subsequent request.

How do you change video src using jQuery?

I've tried using the autoplay tag, and .load() .play() still need to be called at least in chrome (maybe its my settings).

the simplest cross browser way to do this with jquery using your example would be

var $video = $('#divVideo video'),
videoSrc = $('source', $video).attr('src', videoFile);
$video[0].load();
$video[0].play();

However the way I'd suggest you do it (for legibility and simplicity) is

var video = $('#divVideo video')[0];
video.src = videoFile;
video.load();
video.play();

Further Reading http://msdn.microsoft.com/en-us/library/ie/hh924823(v=vs.85).aspx#ManagingPlaybackInJavascript

Additional info: .load() only works if there is an html source element inside the video element (i.e. <source src="demo.mp4" type="video/mp4" />)

The non jquery way would be:

HTML

<div id="divVideo">
  <video id="videoID" controls>
    <source src="test1.mp4" type="video/mp4" />
  </video>
</div>

JS

var video = document.getElementById('videoID');
video.src = videoFile;
video.load();
video.play();

How to print an exception in Python?

One has pretty much control on which information from the traceback to be displayed/logged when catching exceptions.

The code

with open("not_existing_file.txt", 'r') as text:
    pass

would produce the following traceback:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

Print/Log the full traceback

As others already mentioned, you can catch the whole traceback by using the traceback module:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()

This will produce the following output:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

You can achieve the same by using logging:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)

Output:

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

Print/log error name/message only

You might not be interested in the whole traceback, but only in the most important information, such as Exception name and Exception message, use:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))

Output:

Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'

How can I generate an ObjectId with mongoose?

I needed to generate mongodb ids on client side.

After digging into the mongodb source code i found they generate ObjectIDs using npm bson lib.

If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bson library :

const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2

Note: There is also an npm project named bson-objectid being even lighter

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

In the eclipse environment where you execute your java programs, take the following steps:

  1. Click on Project just above the menu bar in eclipse.
  2. Click on properties.
  3. Select libraries, click on the existing library and click Remove on the right of the window.
  4. Repeat the process and now click add library, then select JRE system library and click OK.

How to create a oracle sql script spool file

This will spool the output from the anonymous block into a file called output_<YYYYMMDD>.txt located in the root of the local PC C: drive where <YYYYMMDD> is the current date:

SET SERVEROUTPUT ON FORMAT WRAPPED
SET VERIFY OFF

SET FEEDBACK OFF
SET TERMOUT OFF

column date_column new_value today_var
select to_char(sysdate, 'yyyymmdd') date_column
  from dual
/
DBMS_OUTPUT.ENABLE(1000000);

SPOOL C:\output_&today_var..txt

DECLARE
   ab varchar2(10) := 'Raj';
   cd varchar2(10);
   a  number := 10;
   c  number;
   d  number; 
BEGIN
   c := a+10;
   --
   SELECT ab, c 
     INTO cd, d 
     FROM dual;
   --
   DBMS_OUTPUT.put_line('cd: '||cd);
   DBMS_OUTPUT.put_line('d: '||d);
END; 

SPOOL OFF

SET TERMOUT ON
SET FEEDBACK ON
SET VERIFY ON

PROMPT
PROMPT Done, please see file C:\output_&today_var..txt
PROMPT

Hope it helps...

EDIT:

After your comment to output a value for every iteration of a cursor (I realise each value will be the same in this example but you should get the gist of what i'm doing):

BEGIN
   c := a+10;
   --
   FOR i IN 1 .. 10
   LOOP
      c := a+10;
      -- Output the value of C
      DBMS_OUTPUT.put_line('c: '||c);
   END LOOP;
   --
END; 

Best PHP IDE for Mac? (Preferably free!)

Komodo is wonderful, and it runs on OS X; they have a free version, Komodo Edit.

UPDATE from 2015: I've switched to PHPStorm from Jetbrains, the same folks that built IntelliJ IDEA and Resharper. It's better. Not just better. It's well worth the money.

How to properly URL encode a string in PHP?

The cunningly-named urlencode() and urldecode().

However, you shouldn't need to use urldecode() on variables that appear in $_POST and $_GET.

Access nested dictionary items via a list of keys?

Use reduce() to traverse the dictionary:

from functools import reduce  # forward compatibility for Python 3
import operator

def getFromDict(dataDict, mapList):
    return reduce(operator.getitem, mapList, dataDict)

and reuse getFromDict to find the location to store the value for setInDict():

def setInDict(dataDict, mapList, value):
    getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value

All but the last element in mapList is needed to find the 'parent' dictionary to add the value to, then use the last element to set the value to the right key.

Demo:

>>> getFromDict(dataDict, ["a", "r"])
1
>>> getFromDict(dataDict, ["b", "v", "y"])
2
>>> setInDict(dataDict, ["b", "v", "w"], 4)
>>> import pprint
>>> pprint.pprint(dataDict)
{'a': {'r': 1, 's': 2, 't': 3},
 'b': {'u': 1, 'v': {'w': 4, 'x': 1, 'y': 2, 'z': 3}, 'w': 3}}

Note that the Python PEP8 style guide prescribes snake_case names for functions. The above works equally well for lists or a mix of dictionaries and lists, so the names should really be get_by_path() and set_by_path():

from functools import reduce  # forward compatibility for Python 3
import operator

def get_by_path(root, items):
    """Access a nested object in root by item sequence."""
    return reduce(operator.getitem, items, root)

def set_by_path(root, items, value):
    """Set a value in a nested object in root by item sequence."""
    get_by_path(root, items[:-1])[items[-1]] = value

And for completion's sake, a function to delete a key:

def del_by_path(root, items):
    """Delete a key-value in a nested object in root by item sequence."""
    del get_by_path(root, items[:-1])[items[-1]]

MySQL ORDER BY rand(), name ASC

SELECT  *
FROM    (
        SELECT  *
        FROM    users
        WHERE   1
        ORDER BY
                rand()
        LIMIT 20
        ) q
ORDER BY
        name

Simplest way to do a recursive self-join?

Using CTEs you can do it this way

DECLARE @Table TABLE(
        PersonID INT,
        Initials VARCHAR(20),
        ParentID INT
)

INSERT INTO @Table SELECT     1,'CJ',NULL
INSERT INTO @Table SELECT     2,'EB',1
INSERT INTO @Table SELECT     3,'MB',1
INSERT INTO @Table SELECT     4,'SW',2
INSERT INTO @Table SELECT     5,'YT',NULL
INSERT INTO @Table SELECT     6,'IS',5

DECLARE @PersonID INT

SELECT @PersonID = 1

;WITH Selects AS (
        SELECT *
        FROM    @Table
        WHERE   PersonID = @PersonID
        UNION ALL
        SELECT  t.*
        FROM    @Table t INNER JOIN
                Selects s ON t.ParentID = s.PersonID
)
SELECT  *
FROm    Selects

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

I had the same problem and I figured it out. To make life much simpler, I wrote an util class to handle runtime permissions.

public class PermissionUtil {
    /*
    * Check if version is marshmallow and above.
    * Used in deciding to ask runtime permission
    * */
    public static boolean shouldAskPermission() {
        return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);
    }
private static boolean shouldAskPermission(Context context, String permission){
        if (shouldAskPermission()) {
            int permissionResult = ActivityCompat.checkSelfPermission(context, permission);
            if (permissionResult != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }
public static void checkPermission(Context context, String permission, PermissionAskListener listener){
/*
        * If permission is not granted
        * */
        if (shouldAskPermission(context, permission)){
/*
            * If permission denied previously
            * */
            if (((Activity)context).shouldShowRequestPermissionRationale(permission)) {
                listener.onPermissionPreviouslyDenied();
            } else {
                /*
                * Permission denied or first time requested
                * */
if (PreferencesUtil.isFirstTimeAskingPermission(context, permission)) {
                    PreferencesUtil.firstTimeAskingPermission(context, permission, false);
                    listener.onPermissionAsk();
                } else {
                    /*
                    * Handle the feature without permission or ask user to manually allow permission
                    * */
                    listener.onPermissionDisabled();
                }
            }
        } else {
            listener.onPermissionGranted();
        }
    }
/*
    * Callback on various cases on checking permission
    *
    * 1.  Below M, runtime permission not needed. In that case onPermissionGranted() would be called.
    *     If permission is already granted, onPermissionGranted() would be called.
    *
    * 2.  Above M, if the permission is being asked first time onPermissionAsk() would be called.
    *
    * 3.  Above M, if the permission is previously asked but not granted, onPermissionPreviouslyDenied()
    *     would be called.
    *
    * 4.  Above M, if the permission is disabled by device policy or the user checked "Never ask again"
    *     check box on previous request permission, onPermissionDisabled() would be called.
    * */
    public interface PermissionAskListener {
/*
        * Callback to ask permission
        * */
        void onPermissionAsk();
/*
        * Callback on permission denied
        * */
        void onPermissionPreviouslyDenied();
/*
        * Callback on permission "Never show again" checked and denied
        * */
        void onPermissionDisabled();
/*
        * Callback on permission granted
        * */
        void onPermissionGranted();
    }
}

And the PreferenceUtil methods are as follows.

public static void firstTimeAskingPermission(Context context, String permission, boolean isFirstTime){
SharedPreferences sharedPreference = context.getSharedPreferences(PREFS_FILE_NAME, MODE_PRIVATE;
 sharedPreference.edit().putBoolean(permission, isFirstTime).apply();
 }
public static boolean isFirstTimeAskingPermission(Context context, String permission){
return context.getSharedPreferences(PREFS_FILE_NAME, MODE_PRIVATE).getBoolean(permission, true);
}

Now, all you need is to use the method * checkPermission* with proper arguments.

Here is an example,

PermissionUtil.checkPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    new PermissionUtil.PermissionAskListener() {
                        @Override
                        public void onPermissionAsk() {
                            ActivityCompat.requestPermissions(
                                    thisActivity,
              new String[]{Manifest.permission.READ_CONTACTS},
                            REQUEST_EXTERNAL_STORAGE
                            );
                        }
@Override
                        public void onPermissionPreviouslyDenied() {
                       //show a dialog explaining permission and then request permission
                        }
@Override
                        public void onPermissionDisabled() {
Toast.makeText(context, "Permission Disabled.", Toast.LENGTH_SHORT).show();
                        }
@Override
                        public void onPermissionGranted() {
                            readContacts();
                        }
                    });

how does my app know whether the user has checked the "Never ask again"?

If user checked Never ask again, you'll get callback on onPermissionDisabled.

Happy coding :)

Add an object to a python list

while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy

Contain an image within a div?

#container img{
 height:100%;
 width:100%;   
}

How to call external JavaScript function in HTML

In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-

caller.html

<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">

external.js

function letMeCallYou()
{
    alert("Bazinga!!!  you called letMeCallYou")
}

Result : enter image description here

How to set an iframe src attribute from a variable in AngularJS

You need also $sce.trustAsResourceUrl or it won't open the website inside the iframe:

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
    .controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
    $scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
    $scope.changeIt = function () {_x000D_
        $scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
    }_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
    <iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
    <br>_x000D_
    <button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting the filenames of all files in a folder

You could do it like that:

File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
    System.out.println("File " + listOfFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    System.out.println("Directory " + listOfFiles[i].getName());
  }
}

Do you want to only get JPEG files or all files?

Absolute Positioning & Text Alignment

This should work:

#my-div { 
  left: 0; 
  width: 100%; 
}

Difference between numpy.array shape (R, 1) and (R,)

1) The reason not to prefer a shape of (R, 1) over (R,) is that it unnecessarily complicates things. Besides, why would it be preferable to have shape (R, 1) by default for a length-R vector instead of (1, R)? It's better to keep it simple and be explicit when you require additional dimensions.

2) For your example, you are computing an outer product so you can do this without a reshape call by using np.outer:

np.outer(M[:,0], numpy.ones((1, R)))

How to get the list of all installed color schemes in Vim?

Looking at my system's menu.vim (look for 'Color Scheme submenu') and @chappar's answer, I came up with the following function:

" Returns the list of available color schemes
function! GetColorSchemes()
   return uniq(sort(map(
   \  globpath(&runtimepath, "colors/*.vim", 0, 1),  
   \  'fnamemodify(v:val, ":t:r")'
   \)))
endfunction

It does the following:

  1. Gets the list of available color scheme scripts under all runtime paths (globpath, runtimepath)
  2. Maps the script paths to their base names (strips parent dirs and extension) (map, fnamemodify)
  3. Sorts and removes duplicates (uniq, sort)

Then to use the function I do something like this:

let s:schemes = GetColorSchemes()
if index(s:schemes, 'solarized') >= 0
   colorscheme solarized
elseif index(s:schemes, 'darkblue') >= 0
   colorscheme darkblue
endif

Which means I prefer the 'solarized' and then the 'darkblue' schemes; if none of them is available, do nothing.

AngularJS: Basic example to use authentication in Single Page Application

I've created a github repo summing up this article basically: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec

ng-login Github repo

Plunker

I'll try to explain as good as possible, hope I help some of you out there:

(1) app.js: Creation of authentication constants on app definition

var loginApp = angular.module('loginApp', ['ui.router', 'ui.bootstrap'])
/*Constants regarding user login defined here*/
.constant('USER_ROLES', {
    all : '*',
    admin : 'admin',
    editor : 'editor',
    guest : 'guest'
}).constant('AUTH_EVENTS', {
    loginSuccess : 'auth-login-success',
    loginFailed : 'auth-login-failed',
    logoutSuccess : 'auth-logout-success',
    sessionTimeout : 'auth-session-timeout',
    notAuthenticated : 'auth-not-authenticated',
    notAuthorized : 'auth-not-authorized'
})

(2) Auth Service: All following functions are implemented in auth.js service. The $http service is used to communicate with the server for the authentication procedures. Also contains functions on authorization, that is if the user is allowed to perform a certain action.

angular.module('loginApp')
.factory('Auth', [ '$http', '$rootScope', '$window', 'Session', 'AUTH_EVENTS', 
function($http, $rootScope, $window, Session, AUTH_EVENTS) {

authService.login() = [...]
authService.isAuthenticated() = [...]
authService.isAuthorized() = [...]
authService.logout() = [...]

return authService;
} ]);

(3) Session: A singleton to keep user data. The implementation here depends on you.

angular.module('loginApp').service('Session', function($rootScope, USER_ROLES) {

    this.create = function(user) {
        this.user = user;
        this.userRole = user.userRole;
    };
    this.destroy = function() {
        this.user = null;
        this.userRole = null;
    };
    return this;
});

(4) Parent controller: Consider this as the "main" function of your application, all controllers inherit from this controller, and it's the backbone of the authentication of this app.

<body ng-controller="ParentController">
[...]
</body>

(5) Access control: To deny access on certain routes 2 steps have to be implemented:

a) Add data of the roles allowed to access each route, on ui router's $stateProvider service as can be seen below (same can work for ngRoute).

.config(function ($stateProvider, USER_ROLES) {
  $stateProvider.state('dashboard', {
    url: '/dashboard',
    templateUrl: 'dashboard/index.html',
    data: {
      authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor]
    }
  });
})

b) On $rootScope.$on('$stateChangeStart') add the function to prevent state change if the user is not authorized.

$rootScope.$on('$stateChangeStart', function (event, next) {
    var authorizedRoles = next.data.authorizedRoles;
    if (!Auth.isAuthorized(authorizedRoles)) {
      event.preventDefault();
      if (Auth.isAuthenticated()) {
        // user is not allowed
        $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
      } else {
        // user is not logged in
        $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
      }
    }
});

(6) Auth interceptor: This is implemented, but can't be checked on the scope of this code. After each $http request, this interceptor checks the status code, if one of the below is returned, then it broadcasts an event to force the user to log-in again.

angular.module('loginApp')
.factory('AuthInterceptor', [ '$rootScope', '$q', 'Session', 'AUTH_EVENTS',
function($rootScope, $q, Session, AUTH_EVENTS) {
    return {
        responseError : function(response) {
            $rootScope.$broadcast({
                401 : AUTH_EVENTS.notAuthenticated,
                403 : AUTH_EVENTS.notAuthorized,
                419 : AUTH_EVENTS.sessionTimeout,
                440 : AUTH_EVENTS.sessionTimeout
            }[response.status], response);
            return $q.reject(response);
        }
    };
} ]);

P.S. A bug with the form data autofill as stated on the 1st article can be easily avoided by adding the directive that is included in directives.js.

P.S.2 This code can be easily tweaked by the user, to allow different routes to be seen, or display content that was not meant to be displayed. The logic MUST be implemented server-side, this is just a way to show things properly on your ng-app.

Saving image to file

You can save image , save the file in your current directory application and move the file to any directory .

 Bitmap btm = new Bitmap(image.width,image.height);
    Image img = btm;
                        img.Save(@"img_" + x + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        FileInfo img__ = new FileInfo(@"img_" + x + ".jpg");
                        img__.MoveTo("myVideo\\img_" + x + ".jpg");

Can a website detect when you are using Selenium with chromedriver?

Replacing cdc_ string

You can use vim or perl to replace the cdc_ string in chromedriver. See answer by @Erti-Chris Eelmaa to learn more about that string and how it's a detection point.

Using vim or perl prevents you from having to recompile source code or use a hex-editor.

Make sure to make a copy of the original chromedriver before attempting to edit it.

Our goal is to alter the cdc_ string, which looks something like $cdc_lasutopfhvcZLmcfl.

The methods below were tested on chromedriver version 2.41.578706.


Using Vim

vim /path/to/chromedriver

After running the line above, you'll probably see a bunch of gibberish. Do the following:

  1. Replace all instances of cdc_ with dog_ by typing :%s/cdc_/dog_/g.
    • dog_ is just an example. You can choose anything as long as it has the same amount of characters as the search string (e.g., cdc_), otherwise the chromedriver will fail.
  2. To save the changes and quit, type :wq! and press return.
    • If you need to quit without saving changes, type :q! and press return.

Using Perl

The line below replaces all cdc_ occurrences with dog_. Credit to Vic Seedoubleyew:

perl -pi -e 's/cdc_/dog_/g' /path/to/chromedriver

Make sure that the replacement string (e.g., dog_) has the same number of characters as the search string (e.g., cdc_), otherwise the chromedriver will fail.


Wrapping Up

To verify that all occurrences of cdc_ were replaced:

grep "cdc_" /path/to/chromedriver

If no output was returned, the replacement was successful.

Go to the altered chromedriver and double click on it. A terminal window should open up. If you don't see killed in the output, you've successfully altered the driver.

Make sure that the name of the altered chromedriver binary is chromedriver, and that the original binary is either moved from its original location or renamed.


My Experience With This Method

I was previously being detected on a website while trying to log in, but after replacing cdc_ with an equal sized string, I was able to log in. Like others have said though, if you've already been detected, you might get blocked for a plethora of other reasons even after using this method. So you may have to try accessing the site that was detecting you using a VPN, different network, etc.

Reporting Services Remove Time from DateTime in Expression

If you have to display the field on report header then try this... RightClick on Textbox > Properties > Category > date > select *Format (Note this will maintain the regional settings).

Since this question has been viewed many times, I'm posting it... Hope it helps.

enter image description here

CSS vertical-align: text-bottom;

Sometimes you can play with padding and margin top, add line-height, etc.

See fiddle.

Style and text forked from @aspirinemaga

.parent
{
    width:300px;
    line-height:30px;
    border:1px solid red;
    padding-top:20px;
}

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Probably in this case you obtained your account object using the merge logic, and persist is used to persist new objects and it will complain if the hierarchy is having an already persisted object. You should use saveOrUpdate in such cases, instead of persist.

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

in OpenSuse 12.1 the only thing required was:

zypper in php5-openssl

android - setting LayoutParams programmatically

For Xamarin Android align to the left of an object

int dp24 = (int)TypedValue.ApplyDimension( ComplexUnitType.Dip, 24, Resources.System.DisplayMetrics );
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( dp24, dp24 );
            lp.AddRule( LayoutRules.CenterInParent, 1 );
            lp.AddRule( LayoutRules.LeftOf, //Id of the field Eg m_Button.Id ); 
            m_Button.LayoutParameters = lp;

JavaScript: filter() for Objects

ES6 approach...

Imagine you have this object below:

const developers = {
  1: {
   id: 1,
   name: "Brendan", 
   family: "Eich"
  },
  2: {
   id: 2,
   name: "John", 
   family: "Resig"
  },  
  3: {
   id: 3,
   name: "Alireza", 
   family: "Dezfoolian"
 }
};

Create a function:

const filterObject = (obj, filter, filterValue) => 
   Object.keys(obj).reduce((acc, val) => 
   (obj[val][filter] === filterValue ? acc : {
       ...acc,
       [val]: obj[val]
   }                                        
), {});

And call it:

filterObject(developers, "name", "Alireza");

and will return:

{
  1: {
  id: 1,
  name: "Brendan", 
  family: "Eich"
  },
  2: {
   id: 2,
   name: "John", 
   family: "Resig"
  }
}

Fast ceiling of an integer division in C / C++

simplified generic form,

int div_up(int n, int d) {
    return n / d + (((n < 0) ^ (d > 0)) && (n % d));
} //i.e. +1 iff (not exact int && positive result)

For a more generic answer, C++ functions for integer division with well defined rounding strategy

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

How to get folder path for ClickOnce application

path is pointing to a subfolder under c:\Documents & Settings

That's right. ClickOnce applications are installed under the profile of the user who installed them. Did you take the path that retrieving the info from the executing assembly gave you, and go check it out?

On windows Vista and Windows 7, you will find the ClickOnce cache here:

c:\users\username\AppData\Local\Apps\2.0\obfuscatedfoldername\obfuscatedfoldername

On Windows XP, you will find it here:

C:\Documents and Settings\username\LocalSettings\Apps\2.0\obfuscatedfoldername\obfuscatedfoldername

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

There are multiple ways how to present a timespan in the database.

time

This datatype is supported since SQL Server 2008 and is the prefered way to store a TimeSpan. There is no mapping needed. It also works well with SQL code.

public TimeSpan ValidityPeriod { get; set; }

However, as stated in the original question, this datatype is limited to 24 hours.

datetimeoffset

The datetimeoffset datatype maps directly to System.DateTimeOffset. It's used to express the offset between a datetime/datetime2 to UTC, but you can also use it for TimeSpan.

However, since the datatype suggests a very specific semantic, so you should also consider other options.

datetime / datetime2

One approach might be to use the datetime or datetime2 types. This is best in scenarios where you need to process the values in the database directly, ie. for views, stored procedures, or reports. The drawback is that you need to substract the value DateTime(1900,01,01,00,00,00) from the date to get back the timespan in your business logic.

public DateTime ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return ValidityPeriod - DateTime(1900,01,01,00,00,00); }
    set { ValidityPeriod = DateTime(1900,01,01,00,00,00) + value; }
}

bigint

Another approach might be to convert the TimeSpan into ticks and use the bigint datatype. However, this approach has the drawback that it's cumbersome to use in SQL queries.

public long ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return TimeSpan.FromTicks(ValidityPeriod); }
    set { ValidityPeriod = value.Ticks; }
}

varchar(N)

This is best for cases where the value should be readable by humans. You might also use this format in SQL queries by utilizing the CONVERT(datetime, ValidityPeriod) function. Dependent on the required precision, you will need between 8 and 25 characters.

public string ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return TimeSpan.Parse(ValidityPeriod); }
    set { ValidityPeriod = value.ToString("HH:mm:ss"); }
}

Bonus: Period and Duration

Using a string, you can also store NodaTime datatypes, especially Duration and Period. The first is basically the same as a TimeSpan, while the later respects that some days and months are longer or shorter than others (ie. January has 31 days and February has 28 or 29; some days are longer or shorter because of daylight saving time). In such cases, using a TimeSpan is the wrong choice.

You can use this code to convert Periods:

using NodaTime;
using NodaTime.Serialization.JsonNet;

internal static class PeriodExtensions
{
    public static Period ToPeriod(this string input)
    {
        var js = JsonSerializer.Create(new JsonSerializerSettings());
        js.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
        var quoted = string.Concat(@"""", input, @"""");
        return js.Deserialize<Period>(new JsonTextReader(new StringReader(quoted)));
    }
}

And then use it like

public string ValidityPeriod { get; set; }

[NotMapped]
public Period ValidityPeriodPeriod
{
    get => ValidityPeriod.ToPeriod();
    set => ValidityPeriod = value.ToString();
}

I really like NodaTime and it often saves me from tricky bugs and lots of headache. The drawback here is that you really can't use it in SQL queries and need to do calculations in-memory.

CLR User-Defined Type

You also have the option to use a custom datatype and support a custom TimeSpan class directly. See CLR User-Defined Types for details.

The drawback here is that the datatype might not behave well with SQL Reports. Also, some versions of SQL Server (Azure, Linux, Data Warehouse) are not supported.

Value Conversions

Starting with EntityFramework Core 2.1, you have the option to use Value Conversions.

However, when using this, EF will not be able to convert many queries into SQL, causing queries to run in-memory; potentially transfering lots and lots of data to your application.

So at least for now, it might be better not to use it, and just map the query result with Automapper.

Include PHP file into HTML file

Create a .htaccess file in directory and add this code to .htaccess file

AddHandler x-httpd-php .html .htm

or

AddType application/x-httpd-php .html .htm

It will force Apache server to parse HTML or HTM files as PHP Script

Understanding ASP.NET Eval() and Bind()

The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

*Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture is the strongly type object (from EF model). We then replace:

Bind(property) -> BindItem.property
Eval(property) -> Item.property

So this:

<%# Bind("Title") %>      
<%# Bind("Description") %>         
<%#  Eval("Title") %> 
<%# Eval("Description") %>

Would become this:

<%# BindItem.Title %>         
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>

Advantages over Eval & Bind:

  • IntelliSense can find the correct property of the object your're working withenter image description here
  • If property is renamed/deleted, you will get an error before page is viewed in browser
  • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

Source: from this excellent book

String array initialization in Java

You can do the following during declaration:

String names[] = {"Ankit","Bohra","Xyz"};

And if you want to do this somewhere after declaration:

String names[];
names = new String[] {"Ankit","Bohra","Xyz"};

could not extract ResultSet in hibernate

I Used the following properties in my application.properties file and the issue got resolved

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl

and

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

earlier was getting an error

There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; SQL [n/a]; nested exception is 
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:280)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:254)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)

Print a div content using Jquery

If you want to do this without an extra plugin (like printThis), I think this should work. The idea is to have a special div that will be printed, while everything else is hidden using CSS. This is easier to do if the div is a direct child of the body tag, so you will have to move whatever you want to print to a div like that. S So begin with creating a div with id print-me as a direct child to your body tag. Then use this code to print the div:

$("#btn").click(function () {
    //Copy the element you want to print to the print-me div.
    $("#printarea").clone().appendTo("#print-me");
    //Apply some styles to hide everything else while printing.
    $("body").addClass("printing");
    //Print the window.
    window.print();
    //Restore the styles.
    $("body").removeClass("printing");
    //Clear up the div.
    $("#print-me").empty();
});

The styles you need are these:

@media print {
    /* Hide everything in the body when printing... */
    body.printing * { display: none; }
    /* ...except our special div. */
    body.printing #print-me { display: block; }
}

@media screen {
    /* Hide the special layer from the screen. */
    #print-me { display: none; }
}

The reason why we should only apply the @print styles when the printing class is present is that the page should be printed as normally if the user prints the page by selecting File -> Print.

How to view kafka message

If you're wondering why the original answer is not working. Well it might be that you're not in the home directory. Try this:

$KAFKA_HOME/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning

How to start a background process in Python?

While jkp's solution works, the newer way of doing things (and the way the documentation recommends) is to use the subprocess module. For simple commands its equivalent, but it offers more options if you want to do something complicated.

Example for your case:

import subprocess
subprocess.Popen(["rm","-r","some.file"])

This will run rm -r some.file in the background. Note that calling .communicate() on the object returned from Popen will block until it completes, so don't do that if you want it to run in the background:

import subprocess
ls_output=subprocess.Popen(["sleep", "30"])
ls_output.communicate()  # Will block for 30 seconds

See the documentation here.

Also, a point of clarification: "Background" as you use it here is purely a shell concept; technically, what you mean is that you want to spawn a process without blocking while you wait for it to complete. However, I've used "background" here to refer to shell-background-like behavior.

How using try catch for exception handling is best practice

I can tell you something:

Snippet #1 is not acceptable because it's ignoring exception. (it's swallowing it like nothing happened).

So do not add catch block that do nothing or just rethrows.

Catch block should add some value. For example output message to end user or log error.

Do not use exception for normal flow program logic. For example:

e.g input validation. <- This is not valid exceptional situation, rather you should write method IsValid(myInput); to check whether input item is valid or not.

Design code to avoid exception. For example:

int Parse(string input);

If we pass value that cannot be parsed to int, this method would throw and exception, instead of that we might write something like this:

bool TryParse(string input,out int result); <- this method would return boolean indicating if parse was successfull.

Maybe this is little bit out of scope of this question, but I hope this will help you to make right decisions when it's about try {} catch(){} and exceptions.

How to write the Fibonacci Sequence?

These all look a bit more complicated than they need to be. My code is very simple and fast:

def fibonacci(x):

    List = []
    f = 1
    List.append(f)
    List.append(f) #because the fibonacci sequence has two 1's at first
    while f<=x:
        f = List[-1] + List[-2]   #says that f = the sum of the last two f's in the series
        List.append(f)
    else:
        List.remove(List[-1])  #because the code lists the fibonacci number one past x. Not necessary, but defines the code better
        for i in range(0, len(List)):
        print List[i]  #prints it in series form instead of list form. Also not necessary

How to wait in a batch script?

You can ping an address that doesn't exist and specify the desired timeout:

ping 192.0.2.2 -n 1 -w 10000 > nul

And since the address does not exist, it'll wait 10,000 ms (10 seconds) and return.

  • The -w 10000 part specifies the desired timeout in milliseconds.
  • The -n 1 part tells ping that it should only try once (normally it'd try 4 times).
  • The > nul part is appended so the ping command doesn't output anything to screen.

You can easily make a sleep command yourself by creating a sleep.bat somewhere in your PATH and using the above technique:

rem SLEEP.BAT - sleeps by the supplied number of seconds

@ping 192.0.2.2 -n 1 -w %1000 > nul

NOTE (September 2002): The 192.0.2.x address is reserved as per RFC 3330 so it definitely will not exist in the real world. Quoting from the spec:

192.0.2.0/24 - This block is assigned as "TEST-NET" for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol documentation. Addresses within this block should not appear on the public Internet.

Getting attributes of Enum's value

I've merged a couple of the answers here to create a little more extensible solution. I'm providing it just in case it's helpful to anyone else in the future. Original posting here.

using System;
using System.ComponentModel;

public static class EnumExtensions {

    // This extension method is broken out so you can use a similar pattern with 
    // other MetaData elements in the future. This is your base method for each.
    public static T GetAttribute<T>(this Enum value) where T : Attribute {
        var type = value.GetType();
        var memberInfo = type.GetMember(value.ToString());
        var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
        return attributes.Length > 0 
          ? (T)attributes[0]
          : null;
    }

    // This method creates a specific call to the above method, requesting the
    // Description MetaData attribute.
    public static string ToName(this Enum value) {
        var attribute = value.GetAttribute<DescriptionAttribute>();
        return attribute == null ? value.ToString() : attribute.Description;
    }

}

This solution creates a pair of extension methods on Enum. The first allows you to use reflection to retrieve any attribute associated with your value. The second specifically calls retrieves the DescriptionAttribute and returns it's Description value.

As an example, consider using the DescriptionAttribute attribute from System.ComponentModel

using System.ComponentModel;

public enum Days {
    [Description("Sunday")]
    Sun,
    [Description("Monday")]
    Mon,
    [Description("Tuesday")]
    Tue,
    [Description("Wednesday")]
    Wed,
    [Description("Thursday")]
    Thu,
    [Description("Friday")]
    Fri,
    [Description("Saturday")]
    Sat
}

To use the above extension method, you would now simply call the following:

Console.WriteLine(Days.Mon.ToName());

or

var day = Days.Mon;
Console.WriteLine(day.ToName());

How do I get the number of elements in a list?

The len() function can be used with several different types in Python - both built-in types and library types. For example:

>>> len([1, 2, 3])
3

how to open *.sdf files?

If you simply need to view the table and run queries on it you can use this third party sdf viewer. It is a lightweight viewer that has all the basic functionalities and is ready to use after install.

and ofcourse, its Free.

Laravel Eloquent update just if changes have been made

You can use getChanges() on Eloquent model even after persisting.

How to get a barplot with several variables side by side grouped by a factor

You can plot the means without resorting to external calculations and additional tables using stat_summary(...). In fact, stat_summary(...) was designed for exactly what you are doing.

library(ggplot2)
library(reshape2)            # for melt(...)
gg <- melt(df,id="gender")   # df is your original table
ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  scale_color_discrete("Gender")
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey80",position=position_dodge(1), width=.2)

To add "error bars" you cna also use stat_summary(...) (here, I'm using the min and max value rather than sd because you have so little data).

ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey40",position=position_dodge(1), width=.2) +
  scale_fill_discrete("Gender")

Simple timeout in java

What you are looking for can be found here. It may exist a more elegant way to accomplish that, but one possible approach is

Option 1 (preferred):

final Duration timeout = Duration.ofSeconds(30);
ExecutorService executor = Executors.newSingleThreadExecutor();

final Future<String> handler = executor.submit(new Callable() {
    @Override
    public String call() throws Exception {
        return requestDataFromModem();
    }
});

try {
    handler.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
    handler.cancel(true);
}

executor.shutdownNow();

Option 2:

final Duration timeout = Duration.ofSeconds(30);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

final Future<String> handler = executor.submit(new Callable() {
    @Override
    public String call() throws Exception {
        return requestDataFromModem();
    }
});

executor.schedule(new Runnable() {
    @Override
    public void run(){
        handler.cancel(true);
    }      
}, timeout.toMillis(), TimeUnit.MILLISECONDS);

executor.shutdownNow();

Those are only a draft so that you can get the main idea.

How to disable a link using only CSS?

Try this:

<style>
.btn-disable {
    display:inline-block;
    pointer-events: none;       
}
</style>

Cannot make a static reference to the non-static method

You can either make your variable non static

public final String TTT =  (String) getText(R.string.TTT);

or make the "getText" method static (if at all possible)

Adding ASP.NET MVC5 Identity Authentication to an existing project

Configuring Identity to your existing project is not hard thing. You must install some NuGet package and do some small configuration.

First install these NuGet packages with Package Manager Console:

PM> Install-Package Microsoft.AspNet.Identity.Owin 
PM> Install-Package Microsoft.AspNet.Identity.EntityFramework
PM> Install-Package Microsoft.Owin.Host.SystemWeb 

Add a user class and with IdentityUser inheritance:

public class AppUser : IdentityUser
{
    //add your custom properties which have not included in IdentityUser before
    public string MyExtraProperty { get; set; }  
}

Do same thing for role:

public class AppRole : IdentityRole
{
    public AppRole() : base() { }
    public AppRole(string name) : base(name) { }
    // extra properties here 
}

Change your DbContext parent from DbContext to IdentityDbContext<AppUser> like this:

public class MyDbContext : IdentityDbContext<AppUser>
{
    // Other part of codes still same 
    // You don't need to add AppUser and AppRole 
    // since automatically added by inheriting form IdentityDbContext<AppUser>
}

If you use the same connection string and enabled migration, EF will create necessary tables for you.

Optionally, you could extend UserManager to add your desired configuration and customization:

public class AppUserManager : UserManager<AppUser>
{
    public AppUserManager(IUserStore<AppUser> store)
        : base(store)
    {
    }

    // this method is called by Owin therefore this is the best place to configure your User Manager
    public static AppUserManager Create(
        IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
    {
        var manager = new AppUserManager(
            new UserStore<AppUser>(context.Get<MyDbContext>()));

        // optionally configure your manager
        // ...

        return manager;
    }
}

Since Identity is based on OWIN you need to configure OWIN too:

Add a class to App_Start folder (or anywhere else if you want). This class is used by OWIN. This will be your startup class.

namespace MyAppNamespace
{
    public class IdentityConfig
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => new MyDbContext());
            app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
            app.CreatePerOwinContext<RoleManager<AppRole>>((options, context) =>
                new RoleManager<AppRole>(
                    new RoleStore<AppRole>(context.Get<MyDbContext>())));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Home/Login"),
            });
        }
    }
}

Almost done just add this line of code to your web.config file so OWIN could find your startup class.

<appSettings>
    <!-- other setting here -->
    <add key="owin:AppStartup" value="MyAppNamespace.IdentityConfig" />
</appSettings>

Now in entire project you could use Identity just like any new project had already installed by VS. Consider login action for example

[HttpPost]
public ActionResult Login(LoginViewModel login)
{
    if (ModelState.IsValid)
    {
        var userManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
        var authManager = HttpContext.GetOwinContext().Authentication;

        AppUser user = userManager.Find(login.UserName, login.Password);
        if (user != null)
        {
            var ident = userManager.CreateIdentity(user, 
                DefaultAuthenticationTypes.ApplicationCookie);
            //use the instance that has been created. 
            authManager.SignIn(
                new AuthenticationProperties { IsPersistent = false }, ident);
            return Redirect(login.ReturnUrl ?? Url.Action("Index", "Home"));
        }
    }
    ModelState.AddModelError("", "Invalid username or password");
    return View(login);
}

You could make roles and add to your users:

public ActionResult CreateRole(string roleName)
{
    var roleManager=HttpContext.GetOwinContext().GetUserManager<RoleManager<AppRole>>();

    if (!roleManager.RoleExists(roleName))
        roleManager.Create(new AppRole(roleName));
    // rest of code
} 

You could also add a role to a user, like this:

UserManager.AddToRole(UserManager.FindByName("username").Id, "roleName");

By using Authorize you could guard your actions or controllers:

[Authorize]
public ActionResult MySecretAction() {}

or

[Authorize(Roles = "Admin")]]
public ActionResult MySecretAction() {}

You can also install additional packages and configure them to meet your requirement like Microsoft.Owin.Security.Facebook or whichever you want.

Note: Don't forget to add relevant namespaces to your files:

using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

You could also see my other answers like this and this for advanced use of Identity.

Python regular expressions return true/false

Match objects are always true, and None is returned if there is no match. Just test for trueness.

if re.match(...):

How to replace a character with a newline in Emacs?

M-x replace-string RET ; RET C-q C-j.

  • C-q for quoted-insert,

  • C-j is a newline.

Cheers!

How to update PATH variable permanently from Windows command line?

I caution against using the command

setx PATH "%PATH%;C:\Something\bin"

to modify the PATH variable because of a "feature" of its implementation. On many (most?) installations these days the variable will be lengthy - setx will truncate the stored string to 1024 bytes, potentially corrupting the PATH (see the discussion here).

(I signed up specifically to flag this issue, and so lack the site reputation to directly comment on the answer posted on May 2 '12. My thanks to beresfordt for adding such a comment)

How to update TypeScript to latest version with npm?

If you are using Windows with very old NodeJS, then uninstall previous NodeJs and NVM (Node Version Manager) in Control Panel (Win7) or Settings/Apps (Win10) if exists. Make sure that they are removed from the PATH.

Reinstall NodeJS: https://nodejs.org/en/download It will install NPM as well.

Install TypeScript globally:

npm install -g typescript

Verify installation:

tsc -v

How to iterate through a DataTable

The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:

foreach (DataRow row in dtData.Rows)
        {
            if (row["Column_name"].ToString() == txtBox.Text)
            {
                // Getting the sequence number from the textbox.
                string strName1 = txtRowDeletion.Text;

                // Creating the SqlCommand object to access the stored procedure
                // used to get the data for the grid.
                string strDeleteData = "Sp_name";
                SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
                cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;

                // Running the query.
                conn.Open();
                cmdDeleteData.ExecuteNonQuery();
                conn.Close();

                GetData();

                dtData = (DataTable)Session["GetData"];
                BindGrid(dtData);

                lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
                txtRowDeletion.Text = "";
                break;
            }
            else
            {
                lblMsgForDeletion.Text = "The row is not present ";
            }
        }

Bi-directional Map in Java?

Apache commons collections has a BidiMap

Oracle: is there a tool to trace queries, like Profiler for sql server?

Oracle, along with other databases, analyzes a given query to create an execution plan. This plan is the most efficient way of retrieving the data.

Oracle provides the 'explain plan' statement which analyzes the query but doesn't run it, instead populating a special table that you can query (the plan table).

The syntax (simple version, there are other options such as to mark the rows in the plan table with a special ID, or use a different plan table) is:

explain plan for <sql query>

The analysis of that data is left for another question, or your further research.

How do you push a tag to a remote repository using Git?

Tags are not sent to the remote repository by the git push command. We need to explicitly send these tags to the remote server by using the following command:

git push origin <tagname>

We can push all the tags at once by using the below command:

git push origin --tags

Here are some resources for complete details on git tagging:

http://www.cubearticle.com/articles/more/git/git-tag

http://wptheming.com/2011/04/add-remove-github-tags

Undefined symbols for architecture i386

Add the framework required for the method used in the project target in the "Link Binaries With Libraries" list of Build Phases, it will work easily. Like I have imported to my project

QuartzCore.framework

For the bug

Undefined symbols for architecture i386:

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

In my case xxxx.pubxml.user was not loaded when tried to publish the application. I deleted the file and restart the Visual studio then created a new profile to publish it, problem is solved and published successfully.

Delete newline in Vim

The problem is that multiples char 0A (\n) that are invisible may accumulate. Supose you want to clean up from line 100 to the end:

Typing ESC and : (terminal commander)

:110,$s/^\n//

In a vim script:

execute '110,$s/^\n//'

Explanation: from 110 till the end search for lines that start with new line (are blank) and remove them

How can I run a php without a web server?

PHP is a normal sripting language similar to bash or python or perl. So a script with shebang works, at least on linux.

Example PHP file:

#!/usr/bin/env php

<?php

echo("Hello World!\n")

?>

How to run it:

$ chmod 755 hello.php  # do this only once
$ ./hello.php

How do I center text vertically and horizontally in Flutter?

Overview: I used the Flex widget to center text on my page using the MainAxisAlignment.center along the horizontal axis. I use the container padding to create a margin space around my text.

  Flex(
            direction: Axis.horizontal,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
                Container(
                    padding: EdgeInsets.all(20),
                    child:
                        Text("No Records found", style: NoRecordFoundStyle))
  ])

How to get Spinner selected item value to string?

Try this:

String text = mySpinner.getSelectedItem().toString();

Like this you can get value for different Spinners.

Calculating width from percent to pixel then minus by pixel in LESS CSS

You can escape the calc arguments in order to prevent them from being evaluated on compilation.

Using your example, you would simply surround the arguments, like this:

calc(~'100% - 10px')

Demo : http://jsfiddle.net/c5aq20b6/


I find that I use this in one of the following three ways:

Basic Escaping

Everything inside the calc arguments is defined as a string, and is totally static until it's evaluated by the client:

LESS Input

div {
    > span {
        width: calc(~'100% - 10px');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Interpolation of Variables

You can insert a LESS variable into the string:

LESS Input

div {
    > span {
        @pad: 10px;
        width: calc(~'100% - @{pad}');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Mixing Escaped and Compiled Values

You may want to escape a percentage value, but go ahead and evaluate something on compilation:

LESS Input

@btnWidth: 40px;
div {
    > span {
        @pad: 10px;
        width: calc(~'(100% - @{pad})' - (@btnWidth * 2));
    }
}

CSS Output

div > span {
  width: calc((100% - 10px) - 80px);
}

Source: http://lesscss.org/functions/#string-functions-escape.

How do I exit from a function?

There are two ways to exit a method early (without quitting the program):

i) Use the return keyword.
ii) Throw an exception.

Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.

If your method returns void then you can write return without a value:

return;

How to access the value of a promise?

This example I find self-explanatory. Notice how await waits for the result and so you miss the Promise being returned.

cryA = crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
Promise {<pending>}
cryB = await crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
{publicKey: CryptoKey, privateKey: CryptoKey}

Visual Studio opens the default browser instead of Internet Explorer

Quick note if you don't have an .aspx in your project (i.e. its XBAP) but you still need to debug using IE, just add a htm page to your project and right click on that to set the default. It's hacky, but it works :P

How to bundle vendor scripts separately and require them as needed with Webpack?

Also not sure if I fully understand your case, but here is config snippet to create separate vendor chunks for each of your bundles:

entry: {
  bundle1: './build/bundles/bundle1.js',
  bundle2: './build/bundles/bundle2.js',
  'vendor-bundle1': [
    'react',
    'react-router'
  ],
  'vendor-bundle2': [
    'react',
    'react-router',
    'flummox',
    'immutable'
  ]
},

plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor-bundle1',
    chunks: ['bundle1'],
    filename: 'vendor-bundle1.js',
    minChunks: Infinity
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor-bundle2',
    chunks: ['bundle2'],
    filename: 'vendor-bundle2-whatever.js',
    minChunks: Infinity
  }),
]

And link to CommonsChunkPlugin docs: http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin

How can I change the thickness of my <hr> tag

I would recommend setting the HR itself to be 0px high and use its border to be visible instead. I have noticed that when you zoom in and out (ctrl + mouse wheel) the thickness of HR itself changes, while when you set the border it always stays the same:

hr {
    height: 0px;
    border: none;
    border-top: 1px solid black;
}

How to use querySelectorAll only for elements that have a specific attribute set?

Extra Tips:

Multiple "nots", input that is NOT hidden and NOT disabled:

:not([type="hidden"]):not([disabled])

Also did you know you can do this:

node.parentNode.querySelectorAll('div');

This is equivelent to jQuery's:

$(node).parent().find('div');

Which will effectively find all divs in "node" and below recursively, HOT DAMN!

How can I increment a char?

In Python 2.x, just use the ord and chr functions:

>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>> 

Python 3.x makes this more organized and interesting, due to its clear distinction between bytes and unicode. By default, a "string" is unicode, so the above works (ord receives Unicode chars and chr produces them).

But if you're interested in bytes (such as for processing some binary data stream), things are even simpler:

>>> bstr = bytes('abc', 'utf-8')
>>> bstr
b'abc'
>>> bstr[0]
97
>>> bytes([97, 98, 99])
b'abc'
>>> bytes([bstr[0] + 1, 98, 99])
b'bbc'

Find out a Git branch creator

I tweaked the previous answers by using the --sort flag and added some color/formatting:

git for-each-ref --format='%(color:cyan)%(authordate:format:%m/%d/%Y %I:%M %p)    %(align:25,left)%(color:yellow)%(authorname)%(end) %(color:reset)%(refname:strip=3)' --sort=authordate refs/remotes

Python sum() function with list parameter

In the last answer, you don't need to make a list from numbers; it is already a list:

numbers = [1, 2, 3]
numsum = sum(numbers)
print(numsum)

Check if item is in an array / list

You have to use .values for arrays. for example say you have dataframe which has a column name ie, test['Name'], you can do

if name in test['Name'].values :
   print(name)

for a normal list you dont have to use .values

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

What's the difference between IFrame and Frame?

IFrame is just an "internal frame". The reason why it can be considered less secure (than not using any kind of frame at all) is because you can include content that does not originate from your domain.

All this means is that you should trust whatever you include in an iFrame or a regular frame.

Frames and IFrames are equally secure (and insecure if you include content from an untrusted source).

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

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

// ...

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

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

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

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

// ...

Docker expose all ports or range of ports from 7000 to 8000

For anyone facing this issue and ending up on this post...the issue is still open - https://github.com/moby/moby/issues/11185

Why use the params keyword?

With params you can call your method like this:

addTwoEach(1, 2, 3, 4, 5);

Without params, you can’t.

Additionally, you can call the method with an array as a parameter in both cases:

addTwoEach(new int[] { 1, 2, 3, 4, 5 });

That is, params allows you to use a shortcut when calling the method.

Unrelated, you can drastically shorten your method:

public static int addTwoEach(params int[] args)
{
    return args.Sum() + 2 * args.Length;
}

Calculating time difference between 2 dates in minutes

ROUND(time_to_sec((TIMEDIFF(NOW(), "2015-06-10 20:15:00"))) / 60);

Embedding SVG into ReactJS

You can import svg and it use it like a image

import chatSVG from '../assets/images/undraw_typing_jie3.svg'

And ise it in img tag

<img src={chatSVG} className='iconChat' alt="Icon chat"/>

Remote Procedure call failed with sql server 2008 R2

I got the samilar issue, while both SQLServer and SQLServerAgent services are running. The error is fixed by a restart of services.

Server Manager > Service > 
    SQL Server > Stop
    SQL Server > Start
    SQL Server Agent > Start

How do I do logging in C# without using 3rd party libraries?

If you want your own custom Error Logging you can easily write your own code. I'll give you a snippet from one of my projects.

public void SaveLogFile(object method, Exception exception)
{
    string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\FolderName\";
    try
    {
        //Opens a new file stream which allows asynchronous reading and writing
        using (StreamWriter sw = new StreamWriter(new FileStream(location + @"log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
        {
            //Writes the method name with the exception and writes the exception underneath
            sw.WriteLine(String.Format("{0} ({1}) - Method: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), method.ToString()));
            sw.WriteLine(exception.ToString()); sw.WriteLine("");
        }
    }
    catch (IOException)
    {
        if (!File.Exists(location + @"log.txt"))
        {
            File.Create(location + @"log.txt");
        }
    }
}

Then to actually write to the error log just write (q being the caught exception)

SaveLogFile(MethodBase.GetCurrentMethod(), `q`);

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

What's the best way to parse command line arguments?

Argparse code can be longer than actual implementation code!

That's a problem I find with most popular argument parsing options is that if your parameters are only modest, the code to document them becomes disproportionately large to the benefit they provide.

A relative new-comer to the argument parsing scene (I think) is plac.

It makes some acknowledged trade-offs with argparse, but uses inline documentation and wraps simply around main() type function function:

def main(excel_file_path: "Path to input training file.",
     excel_sheet_name:"Name of the excel sheet containing training data including columns 'Label' and 'Description'.",
     existing_model_path: "Path to an existing model to refine."=None,
     batch_size_start: "The smallest size of any minibatch."=10.,
     batch_size_stop:  "The largest size of any minibatch."=250.,
     batch_size_step:  "The step for increase in minibatch size."=1.002,
     batch_test_steps: "Flag.  If True, show minibatch steps."=False):
"Train a Spacy (http://spacy.io/) text classification model with gold document and label data until the model nears convergence (LOSS < 0.5)."

    pass # Implementation code goes here!

if __name__ == '__main__':
    import plac; plac.call(main)

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

workmad3 is apparently out of date, at least for current gpg, as the --allow-secret-key-import is now obsolete and does nothing.

What happened to me was that I failed to export properly. Just doing gpg --export is not adequate, as it only exports the public keys. When exporting keys, you have to do

gpg --export-secret-keys >keyfile

Use python requests to download CSV

You can update the accepted answer with the iter_lines method of requests if the file is very large

import csv
import requests

CSV_URL = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'

with requests.Session() as s:
    download = s.get(CSV_URL)

    line_iterator = (x.decode('utf-8') for x in download.iter_lines(decode_unicode=True))

    cr = csv.reader(line_iterator, delimiter=',')
    my_list = list(cr)
    for row in my_list:
        print(row)

Extract data from XML Clob using SQL from Oracle Database

This should work

SELECT EXTRACTVALUE(column_name, '/DCResponse/ContextData/Decision') FROM traptabclob;

I have assumed the ** were just for highlighting?

Laravel Eloquent - Get one Row

You can do this too

Before you use this you must declare the DB facade in the controller Simply put this line for that

use Illuminate\Support\Facades\DB;

Now you can get a row using this

$getUserByEmail = DB::table('users')->where('email', $email)->first();

or by this too

$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['[email protected]']);

This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.

Hope this helps.

How to automatically update your docker containers, if base-images are updated

You can use Watchtower to watch for updates to the image a container is instantiated from and automatically pull the update and restart the container using the updated image. However, that doesn't solve the problem of rebuilding your own custom images when there's a change to the upstream image it's based on. You could view this as a two-part problem: (1) knowing when an upstream image has been updated, and (2) doing the actual image rebuild. (1) can be solved fairly easily, but (2) depends a lot on your local build environment/practices, so it's probably much harder to create a generalized solution for that.

If you're able to use Docker Hub's automated builds, the whole problem can be solved relatively cleanly using the repository links feature, which lets you trigger a rebuild automatically when a linked repository (probably an upstream one) is updated. You can also configure a webhook to notify you when an automated build occurs. If you want an email or SMS notification, you could connect the webhook to IFTTT Maker. I found the IFTTT user interface to be kind of confusing, but you would configure the Docker webhook to post to https://maker.ifttt.com/trigger/`docker_xyz_image_built`/with/key/`your_key`.

If you need to build locally, you can at least solve the problem of getting notifications when an upstream image is updated by creating a dummy repo in Docker Hub linked to your repo(s) of interest. The sole purpose of the dummy repo would be to trigger a webhook when it gets rebuilt (which implies one of its linked repos was updated). If you're able to receive this webhook, you could even use that to trigger a rebuild on your side.

What's the difference between KeyDown and KeyPress in .NET?

From MSDN:

Key events occur in the following order:

  1. KeyDown

  2. KeyPress

  3. KeyUp

Furthermore, KeyPress gives you a chance to declare the action as "handled" to prevent it from doing anything.

Excel add one hour

=A1+TIME(1,0,0)

Although, maybe this should be posted on Super User.

InputStream from a URL

(a) wwww.somewebsite.com/a.txt isn't a 'file URL'. It isn't a URL at all. If you put http:// on the front of it it would be an HTTP URL, which is clearly what you intend here.

(b) FileInputStream is for files, not URLs.

(c) The way to get an input stream from any URL is via URL.openStream(), or URL.getConnection().getInputStream(), which is equivalent but you might have other reasons to get the URLConnection and play with it first.

How to display a confirmation dialog when clicking an <a> link?

jAplus

You can do it, without writing JavaScript code

<head>
   <script src="/path/to/jquery.js" type="text/javascript" charset="utf-8"></script>
   <script src="/path/to/jquery.Aplus.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
...
   <a href="delete.php?id=22" class="confirm" title="Are you sure?">Link</a>
...
</body>

Demo page

How can I combine multiple rows into a comma-delimited list in Oracle?

The fastest way it is to use the Oracle collect function.

You can also do this:

select *
  2    from (
  3  select deptno,
  4         case when row_number() over (partition by deptno order by ename)=1
  5             then stragg(ename) over
  6                  (partition by deptno
  7                       order by ename
  8                         rows between unbounded preceding
  9                                  and unbounded following)
 10         end enames
 11    from emp
 12         )
 13   where enames is not null

Visit the site ask tom and search on 'stragg' or 'string concatenation' . Lots of examples. There is also a not-documented oracle function to achieve your needs.

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

What caused this error in my case was having two @GET methods with the same path in a single resource. Changing the @Path of one of the methods solved it for me.

How to split a string by spaces in a Windows batch file?

The following code will split a string with an arbitrary number of substrings:

@echo off
setlocal ENABLEDELAYEDEXPANSION

REM Set a string with an arbitrary number of substrings separated by semi colons
set teststring=The;rain;in;spain

REM Do something with each substring
:stringLOOP
    REM Stop when the string is empty
    if "!teststring!" EQU "" goto END

    for /f "delims=;" %%a in ("!teststring!") do set substring=%%a

        REM Do something with the substring - 
        REM we just echo it for the purposes of demo
        echo !substring!

REM Now strip off the leading substring
:striploop
    set stripchar=!teststring:~0,1!
    set teststring=!teststring:~1!

    if "!teststring!" EQU "" goto stringloop

    if "!stripchar!" NEQ ";" goto striploop

    goto stringloop
)

:END
endlocal

Qt: How do I handle the event of the user pressing the 'X' (close) button?

You can attach a SLOT to the

void aboutToQuit();

signal of your QApplication. This signal should be raised just before app closes.

How do I move an existing Git submodule within a Git repository?

Note: As mentioned in the comments this answer refers to the steps needed with older versions of git. Git now has native support for moving submodules:

Since git 1.8.5, git mv old/submod new/submod works as expected and does all the plumbing for you. You might want to use git 1.9.3 or newer, because it includes fixes for submodule moving.


The process is similar to how you'd remove a submodule (see How do I remove a submodule?):

  1. Edit .gitmodules and change the path of the submodule appropriately, and put it in the index with git add .gitmodules.
  2. If needed, create the parent directory of the new location of the submodule (mkdir -p new/parent).
  3. Move all content from the old to the new directory (mv -vi old/parent/submodule new/parent/submodule).
  4. Make sure Git tracks this directory (git add new/parent).
  5. Remove the old directory with git rm --cached old/parent/submodule.
  6. Move the directory .git/modules/old/parent/submodule with all its content to .git/modules/new/parent/submodule.
  7. Edit the .git/modules/new/parent/config file, make sure that worktree item points to the new locations, so in this example it should be worktree = ../../../../../new/parent/module. Typically there should be two more .. than directories in the direct path in that place.
  8. Edit the file new/parent/module/.git, make sure that the path in it points to the correct new location inside the main project .git folder, so in this example gitdir: ../../../.git/modules/new/parent/submodule.

    git status output looks like this for me afterwards:

    # On branch master
    # Changes to be committed:
    #   (use "git reset HEAD <file>..." to unstage)
    #
    #       modified:   .gitmodules
    #       renamed:    old/parent/submodule -> new/parent/submodule
    #
    
  9. Finally, commit the changes.

How to configure SMTP settings in web.config

Web.Config file:

<configuration>
 <system.net>
        <mailSettings>
            <smtp from="[email protected]">
                <network host="smtp.gmail.com" 
                 port="587" 
                 userName="[email protected]" 
                 password="yourpassword" 
                 enableSsl="true"/>
            </smtp>
        </mailSettings>
</system.net>
</configuration>

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

How to navigate back to the last cursor position in Visual Studio Code?

As an alternative to the keyboard shortcuts, here's an extension named "Back and Forward buttons" that adds the forward and back buttons to the status bar:

https://marketplace.visualstudio.com/items?itemName=grimmer.vscode-back-forward-button

Prevent BODY from scrolling when a modal is opened

The accepted answer doesn't work on mobile (iOS 7 w/ Safari 7, at least) and I don't want MOAR JavaScript running on my site when CSS will do.

This CSS will prevent the background page from scrolling under the modal:

body.modal-open {
    overflow: hidden;
    position: fixed;
}

However, it also has a slight side-affect of essentially scrolling to the top. position:absolute resolves this but, re-introduces the ability to scroll on mobile.

If you know your viewport (my plugin for adding viewport to the <body>) you can just add a css toggle for the position.

body.modal-open {
    // block scroll for mobile;
    // causes underlying page to jump to top;
    // prevents scrolling on all screens
    overflow: hidden;
    position: fixed;
}
body.viewport-lg {
    // block scroll for desktop;
    // will not jump to top;
    // will not prevent scroll on mobile
    position: absolute; 
}

I also add this to prevent the underlying page from jumping left/right when showing/hiding modals.

body {
    // STOP MOVING AROUND!
    overflow-x: hidden;
    overflow-y: scroll !important;
}

this answer is a x-post.

Run PHP function on html button click

A php file is run whenever you access it via an HTTP request be it GET,POST, PUT.

You can use JQuery/Ajax to send a request on a button click, or even just change the URL of the browser to navigate to the php address.

Depending on the data sent in the POST/GET you can have a switch statement running a different function.

Specifying Function via GET

You can utilize the code here: How to call PHP function from string stored in a Variable along with a switch statement to automatically call the appropriate function depending on data sent.

So on PHP side you can have something like this:

<?php

//see http://php.net/manual/en/function.call-user-func-array.php how to use extensively
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";

function test()
{
echo("test");
}

function hello()
{
echo("hello");
}

?>

and you can make the simplest get request using the address bar as testing:

http://127.0.0.1/test.php?runFunction=hellodddddd

results in:

Function not found or wrong input

http://127.0.0.1/test.php?runFunction=hello

results in:

hello

Sending the Data

GET Request via JQuery

See: http://api.jquery.com/jQuery.get/

$.get("test.cgi", { name: "John"})
.done(function(data) {
  alert("Data Loaded: " + data);
});

POST Request via JQuery

See: http://api.jquery.com/jQuery.post/

$.post("test.php", { name: "John"} );

GET Request via Javascript location

See: http://www.javascripter.net/faq/buttonli.htm

<input type=button 
value="insert button text here"
onClick="self.location='Your_URL_here.php?name=hello'">

Reading the Data (PHP)

See PHP Turotial for reading post and get: http://www.tizag.com/phpT/postget.php

Useful Links

http://php.net/manual/en/function.call-user-func.php http://php.net/manual/en/function.function-exists.php

How do I assert an Iterable contains elements with a certain property?

Alternatively to hasProperty you can try hamcrest-more-matchers where matcher with extracting function. In your case it will look like:

import static com.github.seregamorph.hamcrest.MoreMatchers.where;

assertThat(myClass.getMyItems(), contains(
    where(MyItem::getName, is("foo")), 
    where(MyItem::getName, is("bar"))
));

The advantages of this approach are:

  • It is not always possible to verify by field if the value is computed in get-method
  • In case of mismatch there should be a failure message with diagnostics (pay attention to resolved method reference MyItem.getName:
Expected: iterable containing [Object that matches is "foo" after call
MyItem.getName, Object that matches is "bar" after call MyItem.getName]
     but: item 0: was "wrong-name"
  • It works in Java 8, Java 11 and Java 14

Reactjs - Form input validation

With React Hook, form is made super easy (React Hook Form: https://github.com/bluebill1049/react-hook-form)

i have reused your html markup.

import React from "react";
import useForm from 'react-hook-form';

function Test() {
  const { useForm, register } = useForm();
  const contactSubmit = data => {
    console.log(data);
  };

  return (
    <form name="contactform" onSubmit={contactSubmit}>
      <div className="col-md-6">
        <fieldset>
          <input name="name" type="text" size="30" placeholder="Name" ref={register} />
          <br />
          <input name="email" type="text" size="30" placeholder="Email" ref={register} />
          <br />
          <input name="phone" type="text" size="30" placeholder="Phone" ref={register} />
          <br />
          <input name="address" type="text" size="30" placeholder="Address" ref={register} />
          <br />
        </fieldset>
      </div>
      <div className="col-md-6">
        <fieldset>
          <textarea name="message" cols="40" rows="20" className="comments" placeholder="Message" ref={register} />
        </fieldset>
      </div>
      <div className="col-md-12">
        <fieldset>
          <button className="btn btn-lg pro" id="submit" value="Submit">
            Send Message
          </button>
        </fieldset>
      </div>
    </form>
  );
}

get keys of json-object in JavaScript

The working code

_x000D_
_x000D_
var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
_x000D_
for(var obj in jsonData){_x000D_
    if(jsonData.hasOwnProperty(obj)){_x000D_
    for(var prop in jsonData[obj]){_x000D_
        if(jsonData[obj].hasOwnProperty(prop)){_x000D_
           alert(prop + ':' + jsonData[obj][prop]);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
}
_x000D_
_x000D_
_x000D_

LINQ Where with AND OR condition

Linq With Or Condition by using Lambda expression you can do as below

DataTable dtEmp = new DataTable();

dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));

dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);


var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
            == 1 || emp.Field<int>("EmpID") == 2);

foreach (DataRow row in res2)
{
    Label2.Text += "Emplyee ID: " + row[0] + "   &   Emplyee Name: " + row[1] + ",  ";
}

powershell is missing the terminator: "

This error will also occur if you call .ps1 file from a .bat file and file path has spaces.

The fix is to make sure there are no spaces in the path of .ps1 file.

Using "word-wrap: break-word" within a table

table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
              table-layout: fixed;">
  <tr>
    <td>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    </td>
  </tr>
</table>

Creating a REST API using PHP

Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.

Your best bet is to use a framework that already has this functionality ready and tested for you.

Some suggestions are:

Phalcon - REST API building - Easy to use all in one framework with huge performance

Apigility - A one size fits all API handling framework by Zend Technologies

Laravel API Building Tutorial

and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.

How to convert an address to a latitude/longitude?

You want a geocoding application. These are available either online or as an application backend.

Cannot overwrite model once compiled Mongoose

If you want to overwrite the existing class for different collection using typescript
then you have to inherit the existing class from different class.

export class User extends Typegoose{
  @prop
  username?:string
  password?:string
}


export class newUser extends User{
    constructor() {
        super();
    }
}

export const UserModel = new User ().getModelForClass(User , { schemaOptions: { collection: "collection1" } });

export const newUserModel = new newUser ().getModelForClass(newUser , { schemaOptions: { collection: "collection2" } });

ETag vs Header Expires

They are slightly different - the ETag does not have any information that the client can use to determine whether or not to make a request for that file again in the future. If ETag is all it has, it will always have to make a request. However, when the server reads the ETag from the client request, the server can then determine whether to send the file (HTTP 200) or tell the client to just use their local copy (HTTP 304). An ETag is basically just a checksum for a file that semantically changes when the content of the file changes.

The Expires header is used by the client (and proxies/caches) to determine whether or not it even needs to make a request to the server at all. The closer you are to the Expires date, the more likely it is the client (or proxy) will make an HTTP request for that file from the server.

So really what you want to do is use BOTH headers - set the Expires header to a reasonable value based on how often the content changes. Then configure ETags to be sent so that when clients DO send a request to the server, it can more easily determine whether or not to send the file back.

One last note about ETag - if you are using a load-balanced server setup with multiple machines running Apache you will probably want to turn off ETag generation. This is because inodes are used as part of the ETag hash algorithm which will be different between the servers. You can configure Apache to not use inodes as part of the calculation but then you'd want to make sure the timestamps on the files are exactly the same, to ensure the same ETag gets generated for all servers.

Set Culture in an ASP.Net MVC app

Being as it is a setting that is stored per-user, the session is an appropriate place to store the informtion.

I would change your controller to take the culture string as a parameter, rather than having a different action method for each potential culture. Adding a link to the page is easy, and you shouldn't need to write the same code repeatedly any time a new culture is required.

public class CultureController : Controller    
{
        public ActionResult SetCulture(string culture)
        {
            HttpContext.Session["culture"] = culture
            return RedirectToAction("Index", "Home");
        }        
}

<li><%= Html.ActionLink("French", "SetCulture", new {controller = "Culture", culture = "fr-FR"})%></li>
<li><%= Html.ActionLink("Spanish", "SetCulture", new {controller = "Culture", culture = "es-ES"})%></li>

How to get user name using Windows authentication in asp.net?

I think because of the below code you are not getting new credential

string fullName = Request.ServerVariables["LOGON_USER"];

You can try custom login page.

Fatal error: Call to a member function query() on null

put this line in parent construct : $this->load->database();

function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..

How to scroll to an element inside a div?

You would have to find the position of the element in the DIV you want to scroll to, and set the scrollTop property.

divElem.scrollTop = 0;

Update:

Sample code to move up or down

  function move_up() {
    document.getElementById('divElem').scrollTop += 10;
  }

  function move_down() {
    document.getElementById('divElem').scrollTop -= 10;
  }

Android RelativeLayout programmatically Set "centerInParent"

Completely untested, but this should work:

View positiveButton = findViewById(R.id.positiveButton);
RelativeLayout.LayoutParams layoutParams = 
    (RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
positiveButton.setLayoutParams(layoutParams);

add android:configChanges="orientation|screenSize" inside your activity in your manifest

Set value of hidden field in a form using jQuery's ".val()" doesn't work

If you're having trouble setting the value of a hidden field because you're passing an ID to it, this is the solution:

Instead of $("#hidden_field_id").val(id) just do $("input[id=hidden_field_id]").val(id). Not sure what the difference is, but it works.

What is the best way to programmatically detect porn images?

I shall not today attempt further to define the kinds of material I understand to be embraced within that shorthand description ["hard-core pornography"]; and perhaps I could never succeed in intelligibly doing so. But I know it when I see it, and the motion picture involved in this case is not that.

United States Supreme Court Justice Potter Stewart, 1964

What is the difference between encrypting and signing in asymmetric encryption?

When encrypting, you use their public key to write a message and they use their private key to read it.

When signing, you use your private key to write message's signature, and they use your public key to check if it's really yours.

I want to use my private key to generate messages so only I can possibly be the sender.

I want my public key to be used to read the messages and I do not care who reads them

This is signing, it is done with your private key.

I want to be able to encrypt certain information and use it as a product key for my software.

I only care that I am the only one who can generate these.

If you only need to know it to yourself, you don't need to mess with keys to do this. You may just generate random data and keep it in a database.

But if you want people to know that the keys are really yours, you need to generate random data, keep in it a database AND sign it with your key.

I would like to include my public key in my software to decrypt/read the signature of the key.

You'll probably need to purchase a certificate for your public key from a commercial provider like Verisign or Thawte, so that people may check that no one had forged your software and replaced your public key with theirs.

Get File Path (ends with folder)

Use the Application.FileDialog object

Sub SelectFolder()
    Dim diaFolder As FileDialog
    Dim selected As Boolean

    ' Open the file dialog
    Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
    diaFolder.AllowMultiSelect = False
    selected = diaFolder.Show

    If selected Then
        MsgBox diaFolder.SelectedItems(1)
    End If

    Set diaFolder = Nothing
End Sub

Add custom headers to WebView resource requests - android

You should be able to control all your headers by skipping loadUrl and writing your own loadPage using Java's HttpURLConnection. Then use the webview's loadData to display the response.

There is no access to the headers which Google provides. They are in a JNI call, deep in the WebView source.

How do I find the difference between two values without knowing which is larger?

use this function.

its the same convention you wanted. using the simple abs feature of python.

also - sometimes the answers are so simple we miss them, its okay :)

>>> def distance(x,y):
    return abs(x-y)

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

Center image horizontally within a div

yeah, the code like this work fine

<div>
 <img>
</div>

but just to remind u, the style for image

object-fit : *depend on u*

so the final code be like Example

<div style="border: 1px solid red;">
    <img
      src="./assets/images/truck-toy.jpg"
      alt=""
      srcset=""
      style="
       border-radius: 50%;
       height: 7.5rem;
       width: 7.5rem;
       object-fit: contain;"
    />
</div>

Final result

How do I get the height of a div's full content with jQuery?

scrollHeight is a property of a DOM object, not a function:

Height of the scroll view of an element; it includes the element padding but not its margin.

Given this:

<div id="x" style="height: 100px; overflow: hidden;">
    <div style="height: 200px;">
        pancakes
    </div>
</div>

This yields 200:

$('#x')[0].scrollHeight

For example: http://jsfiddle.net/ambiguous/u69kQ/2/ (run with the JavaScript console open).

Download File Using Javascript/jQuery

I ended up using the below snippet and it works in most browsers, not tested in IE though.

_x000D_
_x000D_
let data = JSON.stringify([{email: "[email protected]", name: "test"}, {email: "[email protected]", name: "anothertest"}]);_x000D_
_x000D_
let type = "application/json", name = "testfile.json";_x000D_
downloader(data, type, name)_x000D_
_x000D_
function downloader(data, type, name) {_x000D_
 let blob = new Blob([data], {type});_x000D_
 let url = window.URL.createObjectURL(blob);_x000D_
 downloadURI(url, name);_x000D_
 window.URL.revokeObjectURL(url);_x000D_
}_x000D_
_x000D_
function downloadURI(uri, name) {_x000D_
    let link = document.createElement("a");_x000D_
    link.download = name;_x000D_
    link.href = uri;_x000D_
    link.click();_x000D_
}
_x000D_
_x000D_
_x000D_

Update

function downloadURI(uri, name) {
    let link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.click();
}

function downloader(data, type, name) {
    let blob = new Blob([data], {type});
    let url = window.URL.createObjectURL(blob);
    downloadURI(url, name);
    window.URL.revokeObjectURL(url);
}

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After hours of searching and trying I found out that on a x64 server the MSOnline modules must be installed for x64, and some programs that need to run them are using the x86 PS version, so they will never find it.

[SOLUTION] What I did to solve the issue was:

Copy the folders called MSOnline and MSOnline Extended from the source

C:\Windows\System32\WindowsPowerShell\v1.0\Modules\

to the folder

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\

And then in PS run the Import-Module MSOnline, and it will automatically get the module :D

Get index of a row of a pandas dataframe as an integer

The easier is add [0] - select first value of list with one element:

dfb = df[df['A']==5].index.values.astype(int)[0]
dfbb = df[df['A']==8].index.values.astype(int)[0]

dfb = int(df[df['A']==5].index[0])
dfbb = int(df[df['A']==8].index[0])

But if possible some values not match, error is raised, because first value not exist.

Solution is use next with iter for get default parameetr if values not matched:

dfb = next(iter(df[df['A']==5].index), 'no match')
print (dfb)
4

dfb = next(iter(df[df['A']==50].index), 'no match')
print (dfb)
no match

Then it seems need substract 1:

print (df.loc[dfb:dfbb-1,'B'])
4    0.894525
5    0.978174
6    0.859449
Name: B, dtype: float64

Another solution with boolean indexing or query:

print (df[(df['A'] >= 5) & (df['A'] < 8)])
   A         B
4  5  0.894525
5  6  0.978174
6  7  0.859449

print (df.loc[(df['A'] >= 5) & (df['A'] < 8), 'B'])
4    0.894525
5    0.978174
6    0.859449
Name: B, dtype: float64

print (df.query('A >= 5 and A < 8'))
   A         B
4  5  0.894525
5  6  0.978174
6  7  0.859449

Cannot set property 'innerHTML' of null

I have done all the solutions mentionned here. but they didn't work until i have made this one using Jquery :

in my HTML page :

> <div  id="labelid" > </div>

and when i click on a button, i put this in my JS file :

$("#labelid").html("<label>Salam Alaykom</label>");

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

Problem

I had a similar problem using axes. The class parameter is frameon but the kwarg is frame_on. axes_api
>>> plt.gca().set(frameon=False)
AttributeError: Unknown property frameon

Solution

frame_on

Example

data = range(100)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(data)
#ax.set(frameon=False)  # Old
ax.set(frame_on=False)  # New
plt.show()

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters