Programs & Examples On #Custom authentication

Java 8 Streams FlatMap method example

A very simple example: Split a list of full names to get a list of names, regardless of first or last

 List<String> fullNames = Arrays.asList("Barry Allen", "Bruce Wayne", "Clark Kent");

 fullNames.stream()
            .flatMap(fullName -> Pattern.compile(" ").splitAsStream(fullName))
            .forEach(System.out::println);

This prints out:

Barry
Allen
Bruce
Wayne
Clark
Kent

How to convert InputStream to FileInputStream

Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.

URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...

If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.

Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...

That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.

What's the difference between align-content and align-items?

The align-items property of flex-box aligns the items inside a flex container along the cross axis just like justify-content does along the main axis. (For the default flex-direction: row the cross axis corresponds to vertical and the main axis corresponds to horizontal. With flex-direction: column those two are interchanged respectively).

Here's an example of how align-items:center looks:

align-items: center

But align-content is for multi line flexible boxes. It has no effect when items are in a single line. It aligns the whole structure according to its value. Here's an example for align-content: space-around;: enter image description here

And here's how align-content: space-around; with align-items:center looks: enter image description here

Note the 3rd box and all other boxes in first line change to vertically centered in that line.

Here are some codepen links to play with:

http://codepen.io/asim-coder/pen/MKQWbb

http://codepen.io/asim-coder/pen/WrMNWR

Here's a super cool pen which shows and lets you play with almost everything in flexbox.

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

This function found here, works fine for me

function jsonRemoveUnicodeSequences($struct) {
   return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}

initialize a const array in a class initializer in C++

How about emulating a const array via an accessor function? It's non-static (as you requested), and it doesn't require stl or any other library:

class a {
    int privateB[2];
public:
    a(int b0,b1) { privateB[0]=b0; privateB[1]=b1; }
    int b(const int idx) { return privateB[idx]; }
}

Because a::privateB is private, it is effectively constant outside a::, and you can access it similar to an array, e.g.

a aobj(2,3);    // initialize "constant array" b[]
n = aobj.b(1);  // read b[1] (write impossible from here)

If you are willing to use a pair of classes, you could additionally protect privateB from member functions. This could be done by inheriting a; but I think I prefer John Harrison's comp.lang.c++ post using a const class.

Sql Query to list all views in an SQL Server 2005 database

select v.name
from INFORMATION_SCHEMA.VIEWS iv
join sys.views v on v.name = iv.Table_Name
where iv.Table_Catalog = 'Your database name'

CSS transition when class removed

CSS transitions work by defining two states for the object using CSS. In your case, you define how the object looks when it has the class "saved" and you define how it looks when it doesn't have the class "saved" (it's normal look). When you remove the class "saved", it will transition to the other state according to the transition settings in place for the object without the "saved" class.

If the CSS transition settings apply to the object (without the "saved" class), then they will apply to both transitions.

We could help more specifically if you included all relevant CSS you're using to with the HTML you've provided.

My guess from looking at your HTML is that your transition CSS settings only apply to .saved and thus when you remove it, there are no controls to specify a CSS setting. You may want to add another class ".fade" that you leave on the object all the time and you can specify your CSS transition settings on that class so they are always in effect.

How to add a column in TSQL after a specific column?

Unfortunately you can't.

If you really want them in that order you'll have to create a new table with the columns in that order and copy data. Or rename columns etc. There is no easy way.

In Java, remove empty elements from a list of Strings

Its a very late answer, but you can also use the Collections.singleton:

List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
list.removeAll(Collections.singleton(null));
list.removeAll(Collections.singleton(""));

Convert a String In C++ To Upper Case

std::string str = "STriNg oF mIxID CasE lETteRS"

C++ 11

  • Using for_each

    std::for_each(str.begin(), str.end(), [](char & c){ c = ::toupper(c); });

  • Using transform

    std::transform(str.begin(), str.end(), str.begin(), ::toupper);

C++ (Winodws Only)

_strupr_s(str, str.length());

C++ (Using Boost Library)

boost::to_upper_copy(str)

Hour from DateTime? in 24 hours format

You can get the desired result with the code below. Two'H' in HH is for 24-hour format.

return fechaHora.Value.ToString("HH:mm");

Why does git status show branch is up-to-date when changes exist upstream?

in this case use git add and integrate all pending files and then use git commit and then git push

git add - integrate all pedent files

git commit - save the commit

git push - save to repository

Fire event on enter key press for a textbox

ASPX:

<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox>    
<asp:Button ID="Button1" runat="server" style="display:none" Text="Button" />

JS:

function EnterEvent(e) {
        if (e.keyCode == 13) {
            __doPostBack('<%=Button1.UniqueID%>', "");
        }
    }

CS:

protected void Button1_Click1(object sender, EventArgs e)
    {

    }

How to break a while loop from an if condition inside the while loop?

An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".

If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

go to tsconfig.json and comment the line the //strict:true this worked for me

Counting the number of True Booleans in a Python List

After reading all the answers and comments on this question, I thought to do a small experiment.

I generated 50,000 random booleans and called sum and count on them.

Here are my results:

>>> a = [bool(random.getrandbits(1)) for x in range(50000)]
>>> len(a)
50000
>>> a.count(False)
24884
>>> a.count(True)
25116
>>> def count_it(a):
...   curr = time.time()
...   counting = a.count(True)
...   print("Count it = " + str(time.time() - curr))
...   return counting
... 
>>> def sum_it(a):
...   curr = time.time()
...   counting = sum(a)
...   print("Sum it = " + str(time.time() - curr))
...   return counting
... 
>>> count_it(a)
Count it = 0.00121307373046875
25015
>>> sum_it(a)
Sum it = 0.004102230072021484
25015

Just to be sure, I repeated it several more times:

>>> count_it(a)
Count it = 0.0013530254364013672
25015
>>> count_it(a)
Count it = 0.0014507770538330078
25015
>>> count_it(a)
Count it = 0.0013344287872314453
25015
>>> sum_it(a)
Sum it = 0.003480195999145508
25015
>>> sum_it(a)
Sum it = 0.0035257339477539062
25015
>>> sum_it(a)
Sum it = 0.003350496292114258
25015
>>> sum_it(a)
Sum it = 0.003744363784790039
25015

And as you can see, count is 3 times faster than sum. So I would suggest to use count as I did in count_it.

Python version: 3.6.7
CPU cores: 4
RAM size: 16 GB
OS: Ubuntu 18.04.1 LTS

How to split a string with angularJS

You could try this:

$scope.testdata = [{ 'name': 'name,id' }, {'name':'someName,someId'}]
$scope.array= [];
angular.forEach($scope.testdata, function (value, key) {
    $scope.array.push({ 'name': value.name.split(',')[0], 'id': value.name.split(',')[1] });
});
console.log($scope.array)

This way you can save the data for later use and acces it by using an ng-repeat like this:

<div ng-repeat="item in array">{{item.name}}{{item.id}}</div>


I hope this helped someone,
Plunker link: here
All credits go to @jwpfox and @Mohideen ibn Mohammed from the answer above.

"Cannot instantiate the type..."

Queue is an Interface so you can not initiate it directly. Initiate it by one of its implementing classes.

From the docs all known implementing classes:

  • AbstractQueue
  • ArrayBlockingQueue
  • ArrayDeque
  • ConcurrentLinkedQueue
  • DelayQueue
  • LinkedBlockingDeque
  • LinkedBlockingQueue
  • LinkedList
  • PriorityBlockingQueue
  • PriorityQueue
  • SynchronousQueue

You can use any of above based on your requirement to initiate a Queue object.

How to find all the tables in MySQL with specific column names in them?

To get all tables with columns columnA or ColumnB in the database YourDatabase:

SELECT DISTINCT TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME IN ('columnA','ColumnB')
        AND TABLE_SCHEMA='YourDatabase';

Decimal to Hexadecimal Converter in Java

Consider dec2m method below for conversion from dec to hex, oct or bin.

Sample output is

28 dec == 11100 bin 28 dec == 34 oct 28 dec == 1C hex

public class Conversion {
    public static void main(String[] argv) {
        int x = 28;                           // sample number
        if (argv.length > 0)
            x = Integer.parseInt(argv[0]);    // number from command line

        System.out.printf("%d dec == %s bin\n", i, dec2m(x, 2));
        System.out.printf("%d dec == %s oct\n", i, dec2m(x, 8));
        System.out.printf("%d dec == %s hex\n", i, dec2m(x, 16));
    }

    static String dec2m(int N, int m) {
        String s = "";
        for (int n = N; n > 0; n /= m) {
            int r = n % m;
            s = r < 10 ? r + s : (char) ('A' - 10 + r) + s;
        }
        return s;
    }
}

BULK INSERT with identity (auto-increment) column

Don't BULK INSERT into your real tables directly.

I would always

  1. insert into a staging table dbo.Employee_Staging (without the IDENTITY column) from the CSV file
  2. possibly edit / clean up / manipulate your imported data
  3. and then copy the data across to the real table with a T-SQL statement like:

    INSERT INTO dbo.Employee(Name, Address) 
       SELECT Name, Address
       FROM dbo.Employee_Staging
    

PHP - remove all non-numeric characters from a string

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);

PostgreSQL database default location on Linux

On Centos 6.5/PostgreSQL 9.3:

Change the value of "PGDATA=/var/lib/pgsql/data" to whatever location you want in the initial script file /etc/init.d/postgresql.

Remember to chmod 700 and chown postgres:postgres to the new location and you're the boss.

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

SELECT convert(datetime, '23/07/2009', 103)

How to install python-dateutil on Windows?

If you are offline and have untared the package, you can use command prompt.

Navigate to the untared folder and run:

python setup.py install

Java abstract interface

Every interface is implicitly abstract.
This modifier is obsolete and should not be used in new programs.

[The Java Language Specification - 9.1.1.1 abstract Interfaces]

Also note that interface member methods are implicitly public abstract.
[The Java Language Specification - 9.2 Interface Members]

Why are those modifiers implicit? There is no other modifier (not even the 'no modifier'-modifier) that would be useful here, so you don't explicitly have to type it.

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

[Solved for me]

Eclipse project properties->Java build path->Order and export

Uncheck Android private libraries.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

Another simple way to exclude the auto configuration classes,

Add below similar configuration to your application.yml file,

---
spring:
  profiles: test
  autoconfigure.exclude: org.springframework.boot.autoconfigure.session.SessionAutoConfiguration

How to drop a unique constraint from table column?

If you know the name of your constraint then you can directly use the command like

alter table users drop constraint constraint_name;

If you don't know the constraint name, you can get the constraint by using this command

select constraint_name,constraint_type from user_constraints where table_name = 'YOUR TABLE NAME';

Artisan migrate could not find driver

whilst sometimes you might have multiple php versions, you might also have a held-back version of php-mysql.. do a sudo dpkg -l | grep mysql | grep php and compare what you get from php -v

Getting the Facebook like/share count for a given URL

For latest 2.1 Graph API, an example to get likes for imdb.com will be

Using this to get the id https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%253A%252F%252Fwww.imdb.com%3Ffields%3Dlikes&version=v2.1

and then get the likes

https://developers.facebook.com/tools/explorer/?method=GET&path=414652589771%2Flikes&version=v2.1

Document

URL /?id={url}

Represents an external URL as it relates to the Facebook social graph - shares and comments from the URL on Facebook, and any Open Graph objects associated with the URL.

Reference http://harshtechtalk.com/how-get-likes-count-posts-comments-facebook-graph-api/

Recursively list files in Java

Apart from the recursive traversal one can use a Visitor based approach as well.

Below code is uses Visitor based approach for the traversal.It is expected that the input to the program is the root directory to traverse.

public interface Visitor {
    void visit(DirElement d);
    void visit(FileElement f);
}

public abstract class Element {
    protected File rootPath;
    abstract void accept(Visitor v);

    @Override
    public String toString() {
        return rootPath.getAbsolutePath();
    }
}

public class FileElement extends Element {
    FileElement(final String path) {
        rootPath = new File(path);
    }

    @Override
    void accept(final Visitor v) {
        v.visit(this);
    }
}

public class DirElement extends Element implements Iterable<Element> {
    private final List<Element> elemList;
    DirElement(final String path) {
        elemList = new ArrayList<Element>();
        rootPath = new File(path);
        for (File f : rootPath.listFiles()) {
            if (f.isDirectory()) {
                elemList.add(new DirElement(f.getAbsolutePath()));
            } else if (f.isFile()) {
                elemList.add(new FileElement(f.getAbsolutePath()));
            }
        }
    }

    @Override
    void accept(final Visitor v) {
        v.visit(this);
    }

    public Iterator<Element> iterator() {
        return elemList.iterator();
    }
}

public class ElementWalker {
    private final String rootDir;
    ElementWalker(final String dir) {
        rootDir = dir;
    }

    private void traverse() {
        Element d = new DirElement(rootDir);
        d.accept(new Walker());
    }

    public static void main(final String[] args) {
        ElementWalker t = new ElementWalker("C:\\temp");
        t.traverse();
    }

    private class Walker implements Visitor {
        public void visit(final DirElement d) {
            System.out.println(d);
            for(Element e:d) {
                e.accept(this);
            }
        }

        public void visit(final FileElement f) {
            System.out.println(f);
        }
    }
}

What is the right way to debug in iPython notebook?

A native debugger is being made available as an extension to JupyterLab. Released a few weeks ago, this can be installed by getting the relevant extension, as well as xeus-python kernel (which notably comes without the magics well-known to ipykernel users):

jupyter labextension install @jupyterlab/debugger
conda install xeus-python -c conda-forge

This enables a visual debugging experience well-known from other IDEs.

enter image description here

Source: A visual debugger for Jupyter

How do I access (read, write) Google Sheets spreadsheets with Python?

I think you're looking at the cell-based feeds section in that API doc page. Then you can just use the PUT/ GET requests within your Python script, using either commands.getstatusoutput or subprocess.

Make Frequency Histogram for Factor Variables

You could also use lattice::histogram()

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

Changing Fonts Size in Matlab Plots

Jonas's answer is good, but I had to modify it slightly to get every piece of text on the screen to change:

set(gca,'FontSize',30,'fontWeight','bold')

set(findall(gcf,'type','text'),'FontSize',30,'fontWeight','bold')

How to send authorization header with axios

Install the cors middleware. We were trying to solve it with our own code, but all attempts failed miserably.

This made it work:

cors = require('cors')
app.use(cors());

Original link

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

All what you have to do is to select and download the bootstrap.css and bootstrap.js files from Bootswatch website, and then replace the original files with them.

Of course you have to add the paths to your layout page after the jQuery path that is all.

Google Maps how to Show city or an Area outline

I have try twitter geo api, failed.

Google map api, failed, so far, no way you can get city limit by any api.

twitter api geo endpoint will NOT give you city boundary,

what they provide you is ONLY bounding box with 5 point(lat, long)

this is what I get from twitter api geo for San Francisco enter image description here

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

Finding Android SDK on Mac and adding to PATH

AndroidStudioFrontScreenI simply double clicked the Android dmg install file that I saved on the hard drive and when the initial screen came up I dragged the icon for Android Studio into the Applications folder, now I know where it is!!! Also when you run it, be sure to right click the Android Studio while on the Dock and select "Options" -> "Keep on Dock". Everything else works. Dr. Roger Webster

How to create strings containing double quotes in Excel formulas?

In the event that you need to do this with JSON:

=CONCATENATE("'{""service"": { ""field"": "&A2&"}}'")

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

What does "atomic" mean in programming?

It's something that "appears to the rest of the system to occur instantaneously", and falls under categorisation of Linearizability in computing processes. To quote that linked article further:

Atomicity is a guarantee of isolation from concurrent processes. Additionally, atomic operations commonly have a succeed-or-fail definition — they either successfully change the state of the system, or have no apparent effect.

So, for instance, in the context of a database system, one can have 'atomic commits', meaning that you can push a changeset of updates to a relational database and those changes will either all be submitted, or none of them at all in the event of failure, in this way data does not become corrupt, and consequential of locks and/or queues, the next operation will be a different write or a read, but only after the fact. In the context of variables and threading this is much the same, applied to memory.

Your quote highlights that this need not be expected behaviour in all instances.

How to set session timeout in web.config

The value you are setting in the timeout attribute is the one of the correct ways to set the session timeout value.

The timeout attribute specifies the number of minutes a session can be idle before it is abandoned. The default value for this attribute is 20.

By assigning a value of 1 to this attribute, you've set the session to be abandoned in 1 minute after its idle.

To test this, create a simple aspx page, and write this code in the Page_Load event,

Response.Write(Session.SessionID);

Open a browser and go to this page. A session id will be printed. Wait for a minute to pass, then hit refresh. The session id will change.

Now, if my guess is correct, you want to make your users log out as soon as the session times out. For doing this, you can rig up a login page which will verify the user credentials, and create a session variable like this -

Session["UserId"] = 1;

Now, you will have to perform a check on every page for this variable like this -

if(Session["UserId"] == null)
    Response.Redirect("login.aspx");

This is a bare-bones example of how this will work.

But, for making your production quality secure apps, use Roles & Membership classes provided by ASP.NET. They provide Forms-based authentication which is much more reliabletha the normal Session-based authentication you are trying to use.

How does one check if a table exists in an Android SQLite database?

i faced that and deal with it by try catch as simple as that i do what i want in table if it not exist will cause error so catch it by exceptions and create it :)

SQLiteDatabase db=this.getWritableDatabase();
        try{
            db.execSQL("INSERT INTO o_vacations SELECT * FROM vacations");
            db.execSQL("DELETE FROM vacations");
        }catch (SQLiteException e){
            db.execSQL("create table o_vacations (id integer primary key ,name text ,vacation text,date text,MONTH text)");
            db.execSQL("INSERT INTO o_vacations SELECT * FROM vacations");
            db.execSQL("DELETE FROM vacations");
        }

How to wait for a JavaScript Promise to resolve before resuming function?

You can do it manually. (I know, that that isn't great solution, but..) use while loop till the result hasn't a value

kickOff().then(function(result) {
   while(true){
       if (result === undefined) continue;
       else {
            $("#output").append(result);
            return;
       }
   }
});

The calling thread must be STA, because many UI components require this

For me, this error occurred because of a null parameter being passed. Checking the variable values fixed my issue without having to change the code. I used BackgroundWorker.

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

I had the same problem with pip==1.5.6. I had to correct my system time.

# date -s "2014-12-09 10:09:50"

How to get the filename without the extension from a path in Python?

You can make your own with:

>>> import os
>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'

Important note: If there is more than one . in the filename, only the last one is removed. For example:

/root/dir/sub/file.ext.zip -> file.ext

/root/dir/sub/file.ext.tar.gz -> file.ext.tar

See below for other answers that address that.

Print a variable in hexadecimal in Python

Another answer with later print/format style is:

res[0]=12
res[1]=23
print("my num is 0x{0:02x}{1:02x}".format(res[0],res[1]))

Add my custom http header to Spring RestTemplate request / extend RestTemplate

Here's a method I wrote to check if an URL exists or not. I had a requirement to add a request header. It's Groovy but should be fairly simple to adapt to Java. Essentially I'm using the org.springframework.web.client.RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor<T>, java.lang.Object...) API method. I guess the solution you arrive at depends at least in part on the HTTP method you want to execute. The key take away from example below is that I'm passing a Groovy closure (The third parameter to method restTemplate.execute(), which is more or less, loosely speaking a Lambda in Java world) that is executed by the Spring API as a callback to be able to manipulate the request object before Spring executes the command,

boolean isUrlExists(String url) {
    try {
      return (restTemplate.execute(url, HttpMethod.HEAD,
              { ClientHttpRequest request -> request.headers.add('header-name', 'header-value') },
              { ClientHttpResponse response -> response.headers }) as HttpHeaders)?.get('some-response-header-name')?.contains('some-response-header-value')
    } catch (Exception e) {
      log.warn("Problem checking if $url exists", e)
    }
    false
  }

How do I finish the merge after resolving my merge conflicts?

Whenever You merge two branches using command git merge brancha branchb , There are two possibilities:

  1. One branch (lets say brancha) can be reached by the other branch (lets say branchb) by following its commits history.In this case git simply fast-forward the head to point to the recent branch (in this case branchb).

    2.But if the two branches have diverged at some older point then git creates a new snapshot and add a new commit that points to it. So in case there is no conflict between the branches you are merging, git smoothly creates a new commit.

Run git log to see the commit after you have merged two non-conflicting branches.

Now coming back to the interesting case when there are merge conflicts between the merging branches. I quote this from the page https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

Git hasn’t automatically created a new merge commit. It has paused the process while you resolve the conflict. If you want to see which files are unmerged at any point after a merge conflict, you can run git status


So in case there are merge conflicts, you need to resolve the conflict then add the changes you have made to the staging area using git add filename and then commit the changes by using the command git commit which was paused by git because of the conflict.I hope this explains your query. Also do visit the link above for a detailed understanding. In case of any query please comment below , I'll be happy to help.

Printing 2D array in matrix format

Your can do it like this in short hands.

        int[,] values=new int[2,3]{{2,4,5},{4,5,2}};

        for (int i = 0; i < values.GetLength(0); i++)
        {
            for (int k = 0; k < values.GetLength(1); k++) {
                Console.Write(values[i,k]);
            }

            Console.WriteLine();
        }

Inserting code in this LaTeX document with indentation

Here is how to add inline code:

You can add inline code with {\tt code } or \texttt{ code }. If you want to format the inline code, then it would be best to make your own command

\newcommand{\code}[1]{\texttt{#1}}

Also, note that code blocks can be loaded from other files with

\lstinputlisting[breaklines]{source.c}

breaklines isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{ listings } for this one.

Update: The listings package also includes the \lstinline command, which has the same syntax highlighting features as the \lstlisting and \lstinputlisting commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline command. Like \lstinline, \mintinline provides the same syntax highlighting as a regular minted code block:

\documentclass{article}

\usepackage{minted}

\begin{document}
  This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

How to unnest a nested list

the first case can also be easily done as:

A=A[0]

Change a web.config programmatically with C# (.NET)

This is a method that I use to update AppSettings, works for both web and desktop applications. If you need to edit connectionStrings you can get that value from System.Configuration.ConnectionStringSettings config = configFile.ConnectionStrings.ConnectionStrings["YourConnectionStringName"]; and then set a new value with config.ConnectionString = "your connection string";. Note that if you have any comments in the connectionStrings section in Web.Config these will be removed.

private void UpdateAppSettings(string key, string value)
{
    System.Configuration.Configuration configFile = null;
    if (System.Web.HttpContext.Current != null)
    {
        configFile =
            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
    }
    else
    {
        configFile =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    }
    var settings = configFile.AppSettings.Settings;
    if (settings[key] == null)
    {
        settings.Add(key, value);
    }
    else
    {
        settings[key].Value = value;
    }
    configFile.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}

Initialize array of strings

There is no right way, but you can initialize an array of literals:

char **values = (char *[]){"a", "b", "c"};

or you can allocate each and initialize it:

char **values = malloc(sizeof(char*) * s);
for(...)
{
    values[i] = malloc(sizeof(char) * l);
    //or
    values[i] = "hello";
}

How to make canvas responsive

There's a better way to do this in modern browsers using the vh and vw units.

vh is the viewport height.

So you can try something like this:

<style>
canvas {
  border: solid 2px purple;
  background-color: green;
  width: 100%;
  height: 80vh;
}
</style>

This will distort the aspect ration.

You can keep the aspect ratio by using the same unit for each. Here's an example with a 2:1 aspect ratio:

<style>
canvas {
  width: 40vh;
  height: 80vh;
}
</style>

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

calling a java servlet from javascript

So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:

<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            alert(data);
        }
    }
    xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
    xhr.send(null);
</script>

This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $.get('${pageContext.request.contextPath}/myservlet', function(data) {
        alert(data);
    });
</script>

Either way, the Servlet on the server should be mapped on an url-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:

String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);

This should show Hello World! in the JavaScript alert.

You can of course also use doPost(), but then you should use 'POST' in xhr.open() or use $.post() instead of $.get() in jQuery.

Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a

<div id="data"></div>

in the HTML where you'd like to display the response data, then you can do so instead of alert(data) of the 1st example:

document.getElementById("data").firstChild.nodeValue = data;

In the jQuery example you could do this in a more concise and nice way:

$('#data').text(data);

To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?

How to log cron jobs?

Incase you're running some command with sudo, it won't allow it. Sudo needs a tty.

How to change XML Attribute

Mike; Everytime I need to modify an XML document I work it this way:

//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(xmlFile);

XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;

xmlDoc.Save(xmlFile);

//xmlFile is the path of your file to be modified

I hope you find it useful

Checking something isEmpty in Javascript?

Check for undefined:

if (typeof response.photo == "undefined")
{
    // do something
}

This would do the equivelant of vb's IsEmpty. If myvar contains any value, even null, empty string, or 0, it is not "empty".

To check if a variable or property exists, eg it's been declared, though it may be not have been defined, you can use the in operator.

if ("photo" in response)
{
    // do something
}

a = open("file", "r"); a.readline() output without \n

A solution, can be:

with open("file", "r") as fd:
    lines = fd.read().splitlines()

You get the list of lines without "\r\n" or "\n".

Or, use the classic way:

with open("file", "r") as fd:
    for line in fd:
        line = line.strip()

You read the file, line by line and drop the spaces and newlines.

If you only want to drop the newlines:

with open("file", "r") as fd:
    for line in fd:
        line = line.replace("\r", "").replace("\n", "")

Et voilà.

Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open.

See the documentation of io.open.

So, you can use:

with io.open("file", "r", newline=None) as fd:
    for line in fd:
        line = line.replace("\n", "")

When the newline parameter is None: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.

newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

Scroll to a specific Element Using html

Yes, you may use an anchor by specifying the id attribute of an element and then linking to it with a hash.

For example (taken from the W3 specification):

You may read more about this in <A href="#section2">Section Two</A>.
...later in the document
<H2 id="section2">Section Two</H2>
...later in the document
<P>Please refer to <A href="#section2">Section Two</A> above
for more details.

Is it possible to declare a public variable in vba and assign a default value?

You can define the variable in General Declarations and then initialise it in the first event that fires in your environment.

Alternatively, you could create yourself a class with the relevant properties and initialise them in the Initialise method

Where do I find the Instagram media ID of a image

Here's an even better way:

No API calls! And I threw in converting a media_id to a shortcode as an added bonus.

Based on slang's amazing work for figuring out the conversion. Nathan's work converting base10 to base64 in php. And rgbflawed's work converting it back the other way (with a modified alphabet). #teameffort

function mediaid_to_shortcode($mediaid){

    if(strpos($mediaid, '_') !== false){
        $pieces = explode('_', $mediaid);
        $mediaid = $pieces[0];
        $userid = $pieces[1];
    }

    $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
    $shortcode = '';
    while($mediaid > 0){
        $remainder = $mediaid % 64;
        $mediaid = ($mediaid-$remainder) / 64;
        $shortcode = $alphabet{$remainder} . $shortcode;
    };

    return $shortcode;

}

function shortcode_to_mediaid($shortcode){

    $alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';

    $mediaid = 0;

    foreach(str_split($shortcode) as $letter) {
        $mediaid = ($mediaid*64) + strpos($alphabet, $letter);
    }

    return $mediaid;

}

How to make git mark a deleted and a new file as a file move?

The other answers already cover that you can simply git add NEW && git rm OLD in order to make git recognize the move.

However, if you have already modified the file in the working directory, the add+rm approach will add the modifications to the index, which may be undesired in some cases (e.g. in case of substantial modifications, git might not recognize anymore that it is a file rename).

Let's assume you want to add the rename to the index, but not any modifications. The obvious way to achieve this, is to do a back and forth rename mv NEW OLD && git mv OLD NEW.

But there is also a (slighty more complicated) way to do this directly in the index without renaming the file in the working tree:

info=$(git ls-files -s -- "OLD" | cut -d' ' -f-2 | tr ' ' ,)
git update-index --add --cacheinfo "$info,NEW" &&
git rm --cached "$old"

This can also be put as an alias in your ~/.gitconfig:

[alias]
    mv-index = "!f() { \
      old=\"$1\"; \
      new=\"$2\"; \
      info=$(git ls-files -s -- \"$old\" | cut -d' ' -f-2 | tr ' ' ,); \
      git update-index --add --cacheinfo \"$info,$new\" && \
      git rm --cached \"$old\"; \
    }; f"

PHP - include a php file and also send query parameters

The simplest way to do this is like this

index.php

<?php $active = 'home'; include 'second.php'; ?>

second.php

<?php echo $active; ?>

You can share variables since you are including 2 files by using "include"

Android: how do I check if activity is running?

public static boolean isActivityActive(Activity activity) {
    return !activity.isFinishing() &&
            (SDK_INT < JELLY_BEAN_MR1 || !activity.isDestroyed());
}

Route [login] not defined

Route::post('login', 'LoginController@login')->name('login')

works very well and it is clean and self-explanatory

Can't connect to MySQL server on 'localhost' (10061)

I had difficulty accessing MySQL while connecting via a localhost connection on the standard port 3306, which worked fine when I installed and configured it for prior classes I had taken in MySQL and Java. I was getting errors like "error 2003" and "Cannot connect to MySql server on localhost (10061)". I tried connecting from both MySQL Workbench (5.2.35 CE) and Netbeans (7.2). I am using Windows 7 64 bit professional.

I tried typing in services.msc in the start menu search box, which opened the services dialog box to show all the services installed in windows. I scrolled down to MySQL and started this service. Subsequent attempts to connect to MySQL from MySQL WorkBench and from the command prompt succeeded.

Make the first character Uppercase in CSS

I would recommend that you use the following code in CSS:

    text-transform:uppercase; 

Make sure you put it in your class.

How do I negate a test with regular expressions in a bash script?

You had it right, just put a space between the ! and the [[ like if ! [[

Powershell: Get FQDN Hostname

[System.Net.Dns]::GetHostByName((hostname)).HostName

$env:computerName returns NetBIOS name of the host, so that both previous examples return netbioshostname.domainsuffix (not FQDN!) instead of dnshostname.domainsuffix (FQDN)

for example, host has FQDN aa-w2k12sv-storage.something.com and NetBIOS name aa-w2k12sv-stor (an easy case, I usually change NetBIOS name)

the hostname utility returns dnshostname, i.e., the first part of FQDN and code

[System.Net.Dns]::GetHostByName((hostname)).HostName

returns the right FQDN

Comment: never use the same NetBIOS and DNS names of AD domains and hosts. If your or 3rd party application writes to the log: "cannot connect to hostname.domainsuffix", what name it tries to resolve? If you see in the log "cannot connect to netbiosname.domainsuffix", no doubt, a lazy programmer added domain suffix to the NetBIOS name and you are sure, this is a bug, and can open a ticket to force them to fix the issue...

Why in C++ do we use DWORD rather than unsigned int?

DWORD is not a C++ type, it's defined in <windows.h>.

The reason is that DWORD has a specific range and format Windows functions rely on, so if you require that specific range use that type. (Or as they say "When in Rome, do as the Romans do.") For you, that happens to correspond to unsigned int, but that might not always be the case. To be safe, use DWORD when a DWORD is expected, regardless of what it may actually be.

For example, if they ever changed the range or format of unsigned int they could use a different type to underly DWORD to keep the same requirements, and all code using DWORD would be none-the-wiser. (Likewise, they could decide DWORD needs to be unsigned long long, change it, and all code using DWORD would be none-the-wiser.)


Also note unsigned int does not necessary have the range 0 to 4,294,967,295. See here.

How to clear cache in Yarn?

In addition to the answer, $ yarn cache clean removes all libraries from cache. If you want to remove a specific lib's cache run $ yarn cache dir to get the right yarn cache directory path for your OS, then $ cd to that directory and remove the folder with the name + version of the lib you want to cleanup.

How can I do an UPDATE statement with JOIN in SQL Server?

UPDATE tblAppraisalBasicData
SET tblAppraisalBasicData.ISCbo=1
FROM tblAppraisalBasicData SI INNER JOIN  aaa_test RAN ON SI.EmpID = RAN.ID

Python: convert string to byte array

for python 3 it worked for what @HYRY posted. I needed it for a returned data in a dbus.array. This is the only way it worked

s = "ABCD"

from array import array

a = array("B", s)

How to change collation of database, table, column?

I've just written a bash script to find all tables in a given database and covert them (and its columns).

Script is available here: https://github.com/Juddling/mysql-charset

Regex for string not ending with given suffix

If you are using grep or sed the syntax will be a little different. Notice that the sequential [^a][^b] method does not work here:

balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n'
jd8a
8$fb
q(c
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^a]$"
8$fb
q(c
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^b]$"
jd8a
q(c
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^c]$"
jd8a
8$fb
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^a][^b]$"
jd8a
q(c
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^a][^c]$"
jd8a
8$fb
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^a^b]$"
q(c
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^a^c]$"
8$fb
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^b^c]$"
jd8a
balter@spectre3:~$ printf 'jd8a\n8$fb\nq(c\n' | grep ".*[^b^c^a]$"

FWIW, I'm finding the same results in Regex101, which I think is JavaScript syntax.

Bad: https://regex101.com/r/MJGAmX/2
Good: https://regex101.com/r/LzrIBu/2

How do I make a column unique and index it in a Ruby on Rails migration?

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name.

How to get the hours difference between two date objects?

Try using getTime (mdn doc) :

var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }

Using Math.abs() we don't know which date is the smallest. This code is probably more relevant :

var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }

ESLint Parsing error: Unexpected token

Originally, the solution was to provide the following config as object destructuring used to be an experimental feature and not supported by default:

{
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true
    }
  }
}

Since version 5, this option has been deprecated.

Now it is enough just to declare a version of ES, which is new enough:

{
  "parserOptions": {
    "ecmaVersion": 2018
  }
}

Can I convert long to int?

It can convert by

Convert.ToInt32 method

But it will throw an OverflowException if it the value is outside range of the Int32 Type. A basic test will show us how it works:

long[] numbers = { Int64.MinValue, -1, 0, 121, 340, Int64.MaxValue };
int result;
foreach (long number in numbers)
{
   try {
         result = Convert.ToInt32(number);
        Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                    number.GetType().Name, number,
                    result.GetType().Name, result);
     }
     catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.",
                    number.GetType().Name, number);
     }
}
// The example displays the following output:
//    The Int64 value -9223372036854775808 is outside the range of the Int32 type.
//    Converted the Int64 value -1 to the Int32 value -1.
//    Converted the Int64 value 0 to the Int32 value 0.
//    Converted the Int64 value 121 to the Int32 value 121.
//    Converted the Int64 value 340 to the Int32 value 340.
//    The Int64 value 9223372036854775807 is outside the range of the Int32 type.

Here there is a longer explanation.

Render partial from different folder (not shared)

you should try this

~/Views/Shared/parts/UMFview.ascx

place the ~/Views/ before your code

ExtJs Gridpanel store refresh

Try refreshing the view:

Ext.getCmp('yourGridId').getView().refresh();

How to catch and print the full exception traceback without halting/exiting the program?

Some other answer have already pointed out the traceback module.

Please notice that with print_exc, in some corner cases, you will not obtain what you would expect. In Python 2.x:

import traceback

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_exc()

...will display the traceback of the last exception:

Traceback (most recent call last):
  File "e.py", line 7, in <module>
    raise TypeError("Again !?!")
TypeError: Again !?!

If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info in a local variable and display it using print_exception:

import traceback
import sys

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        exc_info = sys.exc_info()

        # do you usefull stuff here
        # (potentially raising an exception)
        try:
            raise TypeError("Again !?!")
        except:
            pass
        # end of useful stuff


    finally:
        # Display the *original* exception
        traceback.print_exception(*exc_info)
        del exc_info

Producing:

Traceback (most recent call last):
  File "t.py", line 6, in <module>
    raise TypeError("Oups!")
TypeError: Oups!

Few pitfalls with this though:

  • From the doc of sys_info:

    Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)

  • but, from the same doc:

    Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.


On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:

import traceback

try:
    raise TypeError("Oups!")
except Exception as err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_tb(err.__traceback__)

... will display:

  File "e3.py", line 4, in <module>
    raise TypeError("Oups!")

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

If you are trying to

  1. Use multiple delimiters
  2. Filter any empty strings
  3. Trim leading/trailing spaces

following should work:

string str = "Tom Cruise, Scott, ,Bob | at";
IEnumerable<string> names = str
                            .Split(new char[]{',', '|'})
                            .Where(x=>x!=null && x.Trim().Length > 0)
                            .Select(x=>x.Trim());

Output

  • Tom
  • Cruise
  • Scott
  • Bob
  • at

Now you can obviously reverse the order as others suggested.

jquery getting post action url

$('#signup').on("submit", function(event) {
    $form = $(this); //wrap this in jQuery

    alert('the action is: ' + $form.attr('action'));
});

How to find the first and second maximum number?

If you want the second highest number you can use

=LARGE(E4:E9;2)

although that doesn't account for duplicates so you could get the same result as the Max

If you want the largest number that is smaller than the maximum number you can use this version

=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)

printf() formatting for hex

You could always use "%p" in order to display 8 bit hex numbers.

int main (void)
{
    uint8_t a;
    uint32_t b;
    a=15;
    b=a<<28;
    printf("%p", b);
    return 0;
}

Output:

0xf0000000

Android ImageButton with a selected state?

This works for me:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- NOTE: order is important (the first matching state(s) is what is rendered) -->
    <item 
        android:state_selected="true" 
        android:drawable="@drawable/info_icon_solid_with_shadow" />
    <item 
        android:drawable="@drawable/info_icon_outline_with_shadow" />
 </selector>

And then in java:

//assign the image in code (or you can do this in your layout xml with the src attribute)
imageButton.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable....));

//set the click listener
imageButton.setOnClickListener(new OnClickListener() {

    public void onClick(View button) {
        //Set the button's appearance
        button.setSelected(!button.isSelected());

        if (button.isSelected()) {
            //Handle selected state change
        } else {
            //Handle de-select state change
        }

    }

});

For smooth transition you can also mention animation time:

<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime">

Convert a string to an enum in C#

Enum.Parse is your friend:

StatusEnum MyStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), "Active");

How to get the correct range to set the value to a cell?

Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')

Explanation :

Setting value in a cell in spreadsheet to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in sheet which is open currently and to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)

SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)

SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);

These are constants, you must define them yourself

SHEET_ID

SHEET_NAME

POSITION

VALUE

RANGE

By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.

Insert image after each list item

I think your problem is that the :after psuedo-element requires the content: property set inside it. You need to tell it to insert something. You could even just have it insert the image directly:

ul li:after {
    content: url('../images/small_triangle.png');
}

Error while trying to run project: Unable to start program. Cannot find the file specified

I encountered this error when "" was added by mistake to my command line arguments when altering properties for "All Configurations". Removing them from RightClickProject->Properties->Configuration Properties->Debugging->Command Arguments allowed it to run in the debugger again.

sorting dictionary python 3

Any modern solution to this problem? I worked around it with:

    order = sorted([ job['priority'] for job in self.joblist ])
    sorted_joblist = []
    while order:
        min_priority = min(order)
        for job in self.joblist:
            if job['priority'] == min_priority:
                sorted_joblist += [ job ]
                order.remove(min_priority)
    self.joblist = sorted_joblist

The joblist is formatted as: joblist = [ { 'priority' : 3, 'name' : 'foo', ... }, { 'priority' : 1, 'name' : 'bar', ... } ]

  • Basically I create a list (order) with all the elements by which I want to sort the dict
  • then I iterate this list and the dict, when I find the item on the dict I send it to a new dict and remove the item from 'order'.

Seems to be working, but I suppose there are better solutions.

Set database timeout in Entity Framework

For Database first Aproach:

We can still set it in a constructor, by override the ContextName.Context.tt T4 Template this way:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
    public <#=code.Escape(container)#>()
        : base("name=<#=container.Name#>")
    {
        Database.CommandTimeout = 180;
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
        this.Configuration.LazyLoadingEnabled = false;
<#
}

Database.CommandTimeout = 180; is the acutaly change.

The generated output is this:

public ContextName() : base("name=ContextName")
{
    Database.CommandTimeout = 180;
}

If you change your Database Model, this template stays, but the actualy class will be updated.

How to destroy Fragment?

Give a try to this

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    // TODO Auto-generated method stub

    FragmentManager manager = ((Fragment) object).getFragmentManager();
    FragmentTransaction trans = manager.beginTransaction();
    trans.remove((Fragment) object);
    trans.commit();

    super.destroyItem(container, position, object);
}

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.

This is the same question as Failed to connect to mailserver at "localhost" port 25

also check this php mail function not working

How to obtain the number of CPUs/cores in Linux from the command line?

This worked for me. tail -nX allows you to grab only the last X lines.

cat /proc/cpuinfo | awk '/^processor/{print $3}' | tail -1

If you have hyperthreading, this should work for grabbing the number of physical cores.

grep "^core id" /proc/cpuinfo | sort -u | wc -l

Change Timezone in Lumen or Laravel 5

There is an easy way to set the default timezone in laravel or lumen.

This is helpful while working in multiple environments where you can use different timezone based on each environment.

  1. Open .env file present inside the your project directory
  2. Add APP_TIMEZONE=Asia/Kolkata in .env (Your can choose any timezone from the supported timezones)
  3. Open app.php present inside bootstrap folder of your project directory
  4. Add date_default_timezone_set(env('APP_TIMEZONE', 'UTC')); in app.php.

With this change your project will take your .env set timezone and if there is nothing set then take UTC by default.

After modifying the time zone setting run command php artisan config:clear so that your changes reflect in your application

What are some uses of template template parameters?

Here's another practical example from my CUDA Convolutional neural network library. I have the following class template:

template <class T> class Tensor

which is actually implements n-dimensional matrices manipulation. There's also a child class template:

template <class T> class TensorGPU : public Tensor<T>

which implements the same functionality but in GPU. Both templates can work with all basic types, like float, double, int, etc And I also have a class template (simplified):

template <template <class> class TT, class T> class CLayerT: public Layer<TT<T> >
{
    TT<T> weights;
    TT<T> inputs;
    TT<int> connection_matrix;
}

The reason here to have template template syntax is because I can declare implementation of the class

class CLayerCuda: public CLayerT<TensorGPU, float>

which will have both weights and inputs of type float and on GPU, but connection_matrix will always be int, either on CPU (by specifying TT = Tensor) or on GPU (by specifying TT=TensorGPU).

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

Instead of setting a limit on length I would propose the following, which has worked for me.

Inside:

config/database.php

replace this line for mysql:

'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',

with:

'engine' => null,

How to pass parameter to a promise function

Even shorter

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

What is the lifetime of a static variable in a C++ function?

Motti is right about the order, but there are some other things to consider:

Compilers typically use a hidden flag variable to indicate if the local statics have already been initialized, and this flag is checked on every entry to the function. Obviously this is a small performance hit, but what's more of a concern is that this flag is not guaranteed to be thread-safe.

If you have a local static as above, and foo is called from multiple threads, you may have race conditions causing plonk to be initialized incorrectly or even multiple times. Also, in this case plonk may get destructed by a different thread than the one which constructed it.

Despite what the standard says, I'd be very wary of the actual order of local static destruction, because it's possible that you may unwittingly rely on a static being still valid after it's been destructed, and this is really difficult to track down.

Catch checked change event of a checkbox

$(document).ready(function(){
    checkUncheckAll("#select_all","[name='check_boxes[]']");
});

var NUM_BOXES = 10;
// last checkbox the user clicked
var last = -1;
function check(event) {
  // in IE, the event object is a property of the window object
  // in Mozilla, event object is passed to event handlers as a parameter
  event = event || window.event;

  var num = parseInt(/box\[(\d+)\]/.exec(this.name)[1]);
  if (event.shiftKey && last != -1) {
    var di = num > last ? 1 : -1;
    for (var i = last; i != num; i += di)
      document.forms.boxes['box[' + i + ']'].checked = true;
  }
  last = num;
}
function init() {
  for (var i = 0; i < NUM_BOXES; i++)
    document.forms.boxes['box[' + i + ']'].onclick = check;
}

HTML:

<body onload="init()">
  <form name="boxes">
    <input name="box[0]" type="checkbox">
    <input name="box[1]" type="checkbox">
    <input name="box[2]" type="checkbox">
    <input name="box[3]" type="checkbox">
    <input name="box[4]" type="checkbox">
    <input name="box[5]" type="checkbox">
    <input name="box[6]" type="checkbox">
    <input name="box[7]" type="checkbox">
    <input name="box[8]" type="checkbox">
    <input name="box[9]" type="checkbox">
  </form>
</body>

Emulating a do-while loop in Bash

Two simple solutions:

  1. Execute your code once before the while loop

    actions() {
       check_if_file_present
       # Do other stuff
    }
    
    actions #1st execution
    while [ current_time <= $cutoff ]; do
       actions # Loop execution
    done
    
  2. Or:

    while : ; do
        actions
        [[ current_time <= $cutoff ]] || break
    done
    

Google Maps Android API v2 Authorization failure

I followed the same step provided in the Google Doc but i was getting the same error. Later i realized that i was signing my app with my app.keystore and the SHA key that i was using to generate the API key was the debug one.

So i simply removed the signingConfig signingConfig.generic from by build.gradle file and my map started to work fine.

Hope this helps someone.

$lookup on ObjectId's in an array

I have to disagree, we can make $lookup work with IDs array if we preface it with $match stage.

_x000D_
_x000D_
// replace IDs array with lookup results_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
            localField: "products",_x000D_
            foreignField: "_id",_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

It becomes more complicated if we want to pass the lookup result to a pipeline. But then again there's a way to do so (already suggested by @user12164):

_x000D_
_x000D_
// replace IDs array with lookup results passed to pipeline_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
             let: { products: "$products"},_x000D_
             pipeline: [_x000D_
                 { $match: { $expr: {$in: ["$_id", "$$products"] } } },_x000D_
                 { $project: {_id: 0} } // suppress _id_x000D_
             ],_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

How to Disable landscape mode in Android?

You can do this for your entire application without having to make all your activities extend a common base class.

The trick is first to make sure you include an Application subclass in your project. In its onCreate(), called when your app first starts up, you register an ActivityLifecycleCallbacks object (API level 14+) to receive notifications of activity lifecycle events.

This gives you the opportunity to execute your own code whenever any activity in your app is started (or stopped, or resumed, or whatever). At this point you can call setRequestedOrientation() on the newly created activity.

And do not forget to add app:name=".MyApp" in your manifest file.

class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();  

        // register to be informed of activities starting up
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, 
                                          Bundle savedInstanceState) {

                // new activity created; force its orientation to portrait
                activity.setRequestedOrientation(
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            ....
        });
    }
}

Formatting Phone Numbers in PHP

I know the OP is requesting a 123-456-7890 format, but, based on John Dul's answer, I modified it to return the phone number in parentheses format, e.g. (123) 456-7890. This one only handles 7 and 10 digit numbers.

function format_phone_string( $raw_number ) {

    // remove everything but numbers
    $raw_number = preg_replace( '/\D/', '', $raw_number );

    // split each number into an array
    $arr_number = str_split($raw_number);

    // add a dummy value to the beginning of the array
    array_unshift( $arr_number, 'dummy' );

    // remove the dummy value so now the array keys start at 1
    unset($arr_number[0]);

    // get the number of numbers in the number
    $num_number = count($arr_number);

    // loop through each number backward starting at the end
    for ( $x = $num_number; $x >= 0; $x-- ) {

        if ( $x === $num_number - 4 ) {
            // before the fourth to last number

            $phone_number = "-" . $phone_number;
        }
        else if ( $x === $num_number - 7 && $num_number > 7 ) {
            // before the seventh to last number
            // and only if the number is more than 7 digits

            $phone_number = ") " . $phone_number;
        }
        else if ( $x === $num_number - 10 ) {
            // before the tenth to last number

            $phone_number = "(" . $phone_number;
        }

        // concatenate each number (possibly with modifications) back on
        $phone_number = $arr_number[$x] . $phone_number;
    }

    return $phone_number;
}

PostgreSQL Error: Relation already exists

In my case I was migrating from 9.5 to 9.6. So to restore a database, I was doing :

sudo -u postgres psql -d databse -f dump.sql

Of course it was executing on the old postgreSQL database where there are datas! If your new instance is on port 5433, the correct way is :

sudo -u postgres psql -d databse -f dump.sql -p 5433

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

This is an old post but still a problem within the Chrome dev tools. I find the best way to check mobile source locally is to open the site locally in Xcode's iOS Simulator. Then from there you open the Safari browser and enable dev tools, if you have not already done this (go to preferences -> advanced -> show develop menu in menu bar). Now you will see the develop option in the main menu and can go to develop -> iOS Simulator -> and the page you have open in Xcode's iOS Simulator will be there. Once you click on it, it will open the web inspector and you can edit as you would normally in the browser dev tools.

I'm afraid this solution will only work on a Mac though as it uses Xcode.

Select mysql query between date?

Late answer, but the accepted answer didn't work for me.
If you set both start and end dates manually (not using curdate()), make sure to specify the hours, minutes and seconds (2019-12-02 23:59:59) on the end date or you won't get any results from that day, i.e.:

This WILL include records from 2019-12-02:

SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02 23:59:59'

This WON'T include records from 2019-12-02:

SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02'

How to group an array of objects by key

Here is your very own groupBy function which is a generalization of the code from: https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore

_x000D_
_x000D_
function groupBy(xs, f) {_x000D_
  return xs.reduce((r, v, i, a, k = f(v)) => ((r[k] || (r[k] = [])).push(v), r), {});_x000D_
}_x000D_
_x000D_
const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }];_x000D_
_x000D_
const result = groupBy(cars, (c) => c.make);_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Running Groovy script from the command line

#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;

println("hello");

How to preview an image before and after upload?

meVeekay's answer was good and am just making it more improvised by doing 2 things.

  1. Check whether browser supports HTML5 FileReader() or not.

  2. Allow only image file to be upload by checking its extension.

HTML :

<div id="wrapper">
    <input id="fileUpload" type="file" />
    <br />
    <div id="image-holder"></div>
</div> 

jQuery :

$("#fileUpload").on('change', function () {

    var imgPath = $(this)[0].value;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();

    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
        if (typeof (FileReader) != "undefined") {

            var image_holder = $("#image-holder");
            image_holder.empty();

            var reader = new FileReader();
            reader.onload = function (e) {
                $("<img />", {
                    "src": e.target.result,
                        "class": "thumb-image"
                }).appendTo(image_holder);

            }
            image_holder.show();
            reader.readAsDataURL($(this)[0].files[0]);
        } else {
            alert("This browser does not support FileReader.");
        }
    } else {
        alert("Pls select only images");
    }
});

For detail understanding of FileReader()

Check this Article : Using FileReader() preview image before uploading.

jQuery selector for inputs with square brackets in the name attribute

The attribute selector syntax is [name=value] where name is the attribute name and value is the attribute value.

So if you want to select all input elements with the attribute name having the value inputName[]:

$('input[name="inputName[]"]')

And if you want to check for two attributes (here: name and value):

$('input[name="inputName[]"][value=someValue]')

Overwriting txt file in java

The easiest way to overwrite a text file is to use a public static field.

this will overwrite the file every time because your only using false the first time through.`

public static boolean appendFile;

Use it to allow only one time through the write sequence for the append field of the write code to be false.

// use your field before processing the write code

appendFile = False;

File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;

try {
     //change this line to read this

    // f2 = new FileWriter(fnew,false);

    // to read this
    f2 = new FileWriter(fnew,appendFile); // important part
    f2.write(source);

    // change field back to true so the rest of the new data will
    // append to the new file.

    appendFile = true;

    f2.close();
 } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
 }           

Visual Studio breakpoints not being hit

Right click on your project, then left click Properties, and select the Web tab.

Verify whether the correct server is selected for your case:

  • IIS Local

  • IIS Express

Difference between BYTE and CHAR in column datatypes

Depending on the system configuration, size of CHAR mesured in BYTES can vary. In your examples:

  1. Limits field to 11 BYTE
  2. Limits field to 11 CHARacters


Conclusion: 1 CHAR is not equal to 1 BYTE.

How to reset par(mfrow) in R

You can reset the plot by doing this:

dev.off()

linking jquery in html

Add your test.js file after the jQuery libraries. This way your test.js file can use the libraries.

How to view the current heap size that an application is using?

Use this code:

// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory(); 

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

 // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory(); 

It was useful to me to know it.

rejected master -> master (non-fast-forward)

NOTICE: This is never a recommended use of git. This will overwrite changes on the remote. Only do this if you know 100% that your local changes should be pushed to the remote master.

Try this: git push -f origin master

How can I return two values from a function in Python?

I would like to return two values from a function in two separate variables.

What would you expect it to look like on the calling end? You can't write a = select_choice(); b = select_choice() because that would call the function twice.

Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).

When i tried to to use return i, card, it returns a tuple and this is not what i want.

Actually, it's exactly what you want. All you have to do is take the tuple apart again.

And i want to be able to use these values separately.

So just grab the values out of the tuple.

The easiest way to do this is by unpacking:

a, b = select_choice()

libpng warning: iCCP: known incorrect sRGB profile

Extending the friederbluemle solution, download the pngcrush and then use the code like this if you are running it on multiple png files

path =r"C:\\project\\project\\images" # path to all .png images
import os

png_files =[]

for dirpath, subdirs, files in os.walk(path):
    for x in files:
        if x.endswith(".png"):
            png_files.append(os.path.join(dirpath, x))

file =r'C:\\Users\\user\\Downloads\\pngcrush_1_8_9_w64.exe' #pngcrush file 


for name in png_files:
    cmd = r'{} -ow -rem allb -reduce {}'.format(file,name)
    os.system(cmd)

here all the png file related to projects are in 1 folder.

Read pdf files with php

Not exactly php, but you could exec a program from php to convert the pdf to a temporary html file and then parse the resulting file with php. I've done something similar for a project of mine and this is the program I used:

PdfToHtml

The resulting HTML wraps text elements in < div > tags with absolute position coordinates. It seems like this is exactly what you are trying to do.

How can I pass command-line arguments to a Perl program?

You pass them in just like you're thinking, and in your script, you get them from the array @ARGV. Like so:

my $numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";

foreach my $argnum (0 .. $#ARGV) {

   print "$ARGV[$argnum]\n";

}

From here.

Call PHP function from jQuery?

Thanks all. I took bits of each of your solutions and made my own.

The final working solution is:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
            data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
            success: function(data) {
                $('#twitter-loader').remove();
                $('#twitter-container').html(data);
            }
        });
   });
</script>

What's the difference between struct and class in .NET?

A short summary of each:

Classes Only:

  • Can support inheritance
  • Are reference (pointer) types
  • The reference can be null
  • Have memory overhead per new instance

Structs Only:

  • Cannot support inheritance
  • Are value types
  • Are passed by value (like integers)
  • Cannot have a null reference (unless Nullable is used)
  • Do not have a memory overhead per new instance - unless 'boxed'

Both Classes and Structs:

  • Are compound data types typically used to contain a few variables that have some logical relationship
  • Can contain methods and events
  • Can support interfaces

Plot two graphs in same plot in R

You can use points for the overplot, that is.

plot(x1, y1,col='red')

points(x2,y2,col='blue')

How to check version of a CocoaPods framework

The Podfile.lock keeps track of the resolved versions of each Pod installed. If you want to double check that FlurrySDK is using 4.2.3, check that file.

Note: You should not edit this file. It is auto-generated when you run pod install or pod update

Is there a way to select sibling nodes?

There are a few ways to do it.

Either one of the following should do the trick.

// METHOD A (ARRAY.FILTER, STRING.INDEXOF)
var siblings = function(node, children) {
    siblingList = children.filter(function(val) {
        return [node].indexOf(val) != -1;
    });
    return siblingList;
}

// METHOD B (FOR LOOP, IF STATEMENT, ARRAY.PUSH)
var siblings = function(node, children) {
    var siblingList = [];
    for (var n = children.length - 1; n >= 0; n--) {
        if (children[n] != node) {
            siblingList.push(children[n]);
        }  
    }
    return siblingList;
}

// METHOD C (STRING.INDEXOF, ARRAY.SPLICE)
var siblings = function(node, children) {
   siblingList = children;
   index = siblingList.indexOf(node);
   if(index != -1) {
       siblingList.splice(index, 1);
   }
   return siblingList;
}

FYI: The jQuery code-base is a great resource for observing Grade A Javascript.

Here is an excellent tool that reveals the jQuery code-base in a very streamlined way. http://james.padolsey.com/jquery/

How to access pandas groupby dataframe by key

Rather than

gb.get_group('foo')

I prefer using gb.groups

df.loc[gb.groups['foo']]

Because in this way you can choose multiple columns as well. for example:

df.loc[gb.groups['foo'],('A','B')]

Python math module

import math #imports math module

import math as m
print(m.sqrt(25))

from math import sqrt #imports a method from math module
print(sqrt(25))

from math import sqrt as s
print(s(25))

from math import *
print(sqrt(25))

Initialize class fields in constructor or at declaration?

Not a direct answer to your question about the best practice but an important and related refresher point is that in the case of a generic class definition, either leave it on compiler to initialize with default values or we have to use a special method to initialize fields to their default values (if that is absolute necessary for code readability).

class MyGeneric<T>
{
    T data;
    //T data = ""; // <-- ERROR
    //T data = 0; // <-- ERROR
    //T data = null; // <-- ERROR        

    public MyGeneric()
    {
        // All of the above errors would be errors here in constructor as well
    }
}

And the special method to initialize a generic field to its default value is the following:

class MyGeneric<T>
{
    T data = default(T);

    public MyGeneric()
    {           
        // The same method can be used here in constructor
    }
}

What is the standard exception to throw in Java for not supported/implemented operations?

If you create a new (not yet implemented) function in NetBeans, then it generates a method body with the following statement:

throw new java.lang.UnsupportedOperationException("Not supported yet.");

Therefore, I recommend to use the UnsupportedOperationException.

How to generate XML from an Excel VBA macro?

Here is the example macro to convert the Excel worksheet to XML file.

#'vba code to convert excel to xml

Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
        xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False

End Sub

This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.

How to call multiple JavaScript functions in onclick event?

One addition, for maintainable JavaScript is using a named function.

This is the example of the anonymous function:

var el = document.getElementById('id');

// example using an anonymous function (not recommended):
el.addEventListener('click', function() { alert('hello world'); });
el.addEventListener('click', function() { alert('another event') });

But imagine you have a couple of them attached to that same element and want to remove one of them. It is not possible to remove a single anonymous function from that event listener.

Instead, you can use named functions:

var el = document.getElementById('id');

// create named functions:
function alertFirst() { alert('hello world'); };
function alertSecond() { alert('hello world'); };

// assign functions to the event listeners (recommended):
el.addEventListener('click', alertFirst);
el.addEventListener('click', alertSecond);

// then you could remove either one of the functions using:
el.removeEventListener('click', alertFirst);

This also keeps your code a lot easier to read and maintain. Especially if your function is larger.

Reading PDF content with itextsharp dll in VB.NET or C#

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;

public string ReadPdfFile(string fileName)
{
    StringBuilder text = new StringBuilder();

    if (File.Exists(fileName))
    {
        PdfReader pdfReader = new PdfReader(fileName);

        for (int page = 1; page <= pdfReader.NumberOfPages; page++)
        {
            ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
            string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

            currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
            text.Append(currentText);
        }
        pdfReader.Close();
    }
    return text.ToString();
}

How many times a substring occurs

import re
d = [m.start() for m in re.finditer(seaching, string)] 
print (d)

This finds the number of times sub string found in the string and displays index.

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

Checking Count() before the WHERE clause solved my problem. It is cheaper than ToList()

if (authUserList != null && _list.Count() > 0)
    _list = _list.Where(l => authUserList.Contains(l.CreateUserId));

(WAMP/XAMP) send Mail using SMTP localhost

Method 1 (Preferred) - Using hMailServer


After installation, you need the following configuration to properly send mail from wampserver:

1) When you first open hMailServer Administrator, you need to add a new domain.
2) Click on the "Add Domain ..." button at the Welcome page. 
3) Under the domain text field, enter your computer's IP, in this case it should be 127.0.0.1.
4) Click on the Save button.
5) Go to Settings>Protocols>SMTP and select "Delivery of Email" tab
6) Enter "localhost" in the localhost name field.
7) Click on the Save button.

If you need to send mail using a FROM addressee of another computer, you need to allow deliveries from External to External accounts. To do that, follow these steps:

1) Go to Settings>Advanced>IP Ranges and double click on "My Computer" which should have IP address of 127.0.0.1
2) Check the Allow Deliveries from External to External accounts checkbox.
3) Save settings using Save button.

(However, Windows Live/Hotmail has denied all emails coming from dynamic IPs, which most residential computers are using. The workaround is to use Gmail account )

Note to use Gmail users :

1) Go to Settings>Protocols>SMTP and select "Delivery of Email" tab
2) Enter "smtp.gmail.com" in the Remote Host name field.
3) Enter "465" as the port number
4) Check "Server requires authentication"
5) Enter gmail address in the Username
6) Enter gmail password in the password 
7) Check "Use SSL"

(Note, From field doesnt function with gmail)
*p.s. For some people it might also be needed to untick everything under require SMTP authentication in :

  • for local : Settings>Advanced>IP Ranges>"My Computer"
  • for external : Settings>Advanced>IP Ranges>"Internet"

Method 2 - Using SendMail

You can use SendMail installation.


Method 3 - Using different methods

Use any of these methods.

Access-Control-Allow-Origin and Angular.js $http

I'm new to AngularJS and I came across this CORS problem, almost lost my mind! Luckily i found a way to fix this. So here it goes....

My problem was, when I use AngularJS $resource in sending API requests I'm getting this error message XMLHttpRequest cannot load http://website.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. Yup, I already added callback="JSON_CALLBACK" and it didn't work.

What I did to fix it the problem, instead of using GET method or resorting to $http.get, I've used JSONP. Just replace GET method with JSONP and change the api response format to JSONP as well.

    myApp.factory('myFactory', ['$resource', function($resource) {

           return $resource( 'http://website.com/api/:apiMethod',
                        { callback: "JSON_CALLBACK", format:'jsonp' }, 
                        { 
                            method1: { 
                                method: 'JSONP', 
                                params: { 
                                            apiMethod: 'hello world'
                                        } 
                            },
                            method2: { 
                                method: 'JSONP', 
                                params: { 
                                            apiMethod: 'hey ho!'
                                        } 
                            }
            } );

    }]);

I hope someone find this helpful. :)

Git Pull While Ignoring Local Changes?

.gitignore

"Adding unwanted files to .gitignore works as long as you have not initially committed them to any branch. "

Also you can run:

git update-index --assume-unchanged filename

https://chamindac.blogspot.com/2017/07/ignoring-visual-studio-2017-created.html

How to check if a Ruby object is a Boolean

No. Not like you have your code. There isn't any class named Boolean. Now with all the answers you have you should be able to create one and use it. You do know how to create classes don't you? I only came here because I was just wondering this idea myself. Many people might say "Why? You have to just know how Ruby uses Boolean". Which is why you got the answers you did. So thanks for the question. Food for thought. Why doesn't Ruby have a Boolean class?

NameError: uninitialized constant Boolean

Keep in mind that Objects do not have types. They are classes. Objects have data. So that's why when you say data types it's a bit of a misnomer.

Also try rand 2 because rand 1 seems to always give 0. rand 2 will give 1 or 0 click run a few times here. https://repl.it/IOPx/7

Although I wouldn't know how to go about making a Boolean class myself. I've experimented with it but...

class Boolean < TrueClass
  self
end

true.is_a?(Boolean) # => false
false.is_a?(Boolean) # => false

At least we have that class now but who knows how to get the right values?

Google Map API - Removing Markers

Following code might be useful if someone is using React and has a different component of Marker and want to remove marker from map.

export default function useGoogleMapMarker(props) {
  const [marker, setMarker] = useState();

  useEffect(() => {
    // ...code
    const marker = new maps.Marker({ position, map, title, icon });
    // ...code
    setMarker(marker);
    return () => marker.setMap(null); // to remove markers when unmounts
  }, []);

  return marker;
}

What are the differences between numpy arrays and matrices? Which one should I use?

As per the official documents, it's not anymore advisable to use matrix class since it will be removed in the future.

https://numpy.org/doc/stable/reference/generated/numpy.matrix.html

As other answers already state that you can achieve all the operations with NumPy arrays.

How can I install Python's pip3 on my Mac?

Python 3 was working successfully, but without pip3. I tried advice from Stack Overflow, Quora and others (numerous installs and uninstalls).

Python 3 was always fine, but without pip3. Finally I downloaded Python3 from: https://www.python.org/downloads/

By simple mouse clicks and everything (Python 3 + pip3), it is working fine now.

Remove Last Comma from a string

long shot here

var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true)  {    
  currentIndex=pattern.lastIndex;
 }
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
 alert(sentence);

SSIS expression: convert date to string

for the sake of completeness, you could use:

(DT_STR,8, 1252) (YEAR(GetDate()) * 10000 + MONTH(GetDate()) * 100 + DAY(GetDate()))

for YYYYMMDD or

RIGHT("000000" + (DT_STR,8, 1252) (DAY(GetDate()) * 1000000 + MONTH(GetDate()) * 10000 + YEAR(GetDate())), 8)

for DDMMYYYY (without hyphens). If you want / need the date as integer (e.g. for _key-columns in DWHs), just remove the DT_STR / RIGTH function and do just the math.

Using PowerShell credentials without being prompted for a password

I have to run SCOM 2012 functions from a remote server that requires a different credential. I avoid clear-text passwords by passing the output of a password decryption function as input to ConvertTo-SecureString. For clarity, this is not shown here.

I like to strongly type my declarations. The type declaration for $strPass works correctly.

[object] $objCred = $null
[string] $strUser = 'domain\userID'
[System.Security.SecureString] $strPass = '' 

$strPass = ConvertTo-SecureString -String "password" -AsPlainText -Force
$objCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($strUser, $strPass)

Dialog with transparent background in Android

Make sure R.layout.themechanger has no background color because by default the dialog has a default background color.

You also need to add dialog.getWindow().setBackgroundDrawable(newColorDrawable(Color.TRANSPARENT));

And finally

<style name="TransparentDialog">
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowTitleStyle">@null</item>
</style>

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

Automated testing for REST Api

API test automation, up to once per minute, is a service available through theRightAPI. You create your test scenarios, and execute them. Once those tests do what you expect them to, you can then schedule them. Tests can be 'chained' together for scenarios that require authentication. For example, you can have a test that make an OAuth request to Twitter, and creates a shared token that can then be used by any other test. Tests can also have validation criteria attached to ensure http status codes, or even detailed inspection of the responses using javascript or schema validation. Once tests are scheduled, you can then have alerts notify you as soon as a particular test fails validation, or is behaving out of established ranges for response time or response size.

Android check null or empty string in Android

Incase all the answer given does not work, kindly try

String myString = null;

if(myString.trim().equalsIgnoreCase("null")){
    //do something
}

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

Refresh Excel VBA Function Results

This refreshes the calculation better than Range(A:B).Calculate:

Public Sub UpdateMyFunctions()
    Dim myRange As Range
    Dim rng As Range

    ' Assume the functions are in this range A1:B10.
    Set myRange = ActiveSheet.Range("A1:B10")

    For Each rng In myRange
        rng.Formula = rng.Formula
    Next
End Sub

How do you get a query string on Flask?

We can do this by using request.query_string.

Example:

Lets consider view.py

from my_script import get_url_params

@app.route('/web_url/', methods=('get', 'post'))
def get_url_params_index():
    return Response(get_url_params())

You also make it more modular by using Flask Blueprints - https://flask.palletsprojects.com/en/1.1.x/blueprints/

Lets consider first name is being passed as a part of query string /web_url/?first_name=john

## here is my_script.py

## import required flask packages
from flask import request
def get_url_params():
    ## you might further need to format the URL params through escape.    
    firstName = request.args.get('first_name') 
    return firstName
    

As you see this is just a small example - you can fetch multiple values + formate those and use it or pass it onto the template file.

Detecting Browser Autofill

Just in case someone is looking for a solution (just as I was today), to listen to a browser autofill change, here's a custom jquery method that I've built, just to simplify the proccess when adding a change listener to an input:

    $.fn.allchange = function (callback) {
        var me = this;
        var last = "";
        var infunc = function () {
            var text = $(me).val();
            if (text != last) {
                last = text;
                callback();
            }
            setTimeout(infunc, 100);
        }
        setTimeout(infunc, 100);
    };

You can call it like this:

$("#myInput").allchange(function () {
    alert("change!");
});

How to pass a value from Vue data to href?

If you want to display links coming from your state or store in Vue 2.0, you can do like this:

<a v-bind:href="''"> {{ url_link }} </a>

Can an html element have multiple ids?

No. Every DOM element, if it has an id, has a single, unique id. You could approximate it using something like:

<div id='enclosing_id_123'><span id='enclosed_id_123'></span></div>

and then use navigation to get what you really want.

If you are just looking to apply styles, class names are better.

How do you find all subclasses of a given class in Java?

It should be noted as well that this will of course only find all those subclasses that exist on your current classpath. Presumably this is OK for what you are currently looking at, and chances are you did consider this, but if you have at any point released a non-final class into the wild (for varying levels of "wild") then it is entirely feasible that someone else has written their own subclass that you will not know about.

Thus if you happened to be wanting to see all subclasses because you want to make a change and are going to see how it affects subclasses' behaviour - then bear in mind the subclasses that you can't see. Ideally all of your non-private methods, and the class itself should be well-documented; make changes according to this documentation without changing the semantics of methods/non-private fields and your changes should be backwards-compatible, for any subclass that followed your definition of the superclass at least.

How to run SQL in shell script

Code

PL_CONNECT_STRING="$DB_USERNAME/$DB_PASSWORD@$DB_SERVICE"

OUTPUT=$(sqlplus -s $PL_CONNECT_STRING <<-END-OF-SQL
           select count(*) from table;
exit;
END-OF-SQL)
echo "COMPLETED GATHER STATS $OUTPUT";

Explanation:

PL_CONNECT_STRING carry database username, password and it service name

sqlplus is used to connect the Database with PL_CONNECT_STRING details

END-OF-SQL tag contain the query which you want to execute

echo is used to print the output of the query

NOTE: You can give multiple Query inside the END-OF-SQL tag, so its useful for batch execution as well

Changing user agent on urllib2.urlopen

headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib2.Request('www.example.com', None, headers)
html = urllib2.urlopen(req).read()

Or, a bit shorter:

req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' })
html = urllib2.urlopen(req).read()

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

Breaking out of a for loop in Java

break; is what you need to break out of any looping statement like for, while or do-while.

In your case, its going to be like this:-

for(int x = 10; x < 20; x++) {
         // The below condition can be present before or after your sysouts, depending on your needs.
         if(x == 15){
             break; // A unlabeled break is enough. You don't need a labeled break here.
         }
         System.out.print("value of x : " + x );
         System.out.print("\n");
}

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

Remove property for all objects in array

ES6:

const newArray = array.map(({keepAttr1, keepAttr2}) => ({keepAttr1, newPropName: keepAttr2}))

Apply CSS rules if browser is IE

A fast approach is to use the following according to ie that you want to focus (check the comments), inside your css files (where margin-top, set whatever css attribute you like):

margin-top: 10px\9; /*It will apply to all ie from 8 and below */
*margin-top: 10px; /*It will apply to ie 7 and below */
_margin-top: 10px; /*It will apply to ie 6 and below*/

A better approach would be to check user agent or a conditional if, in order to avoid the loading of unnecessary CSS in other browsers.

Extend contigency table with proportions (percentages)

I made this for when doing aggregate functions and similar

per.fun <- function(x) {
    if(length(x)>1){
        denom <- length(x);
        num <- sum(x);
        percentage <- num/denom;
        percentage*100
        }
        else NA
    }

Android: Rotate image in imageview by an angle

Another simple way to rotate an ImageView:
UPDATE:
Required imports:

import android.graphics.Matrix;
import android.widget.ImageView;

Code: (Assuming imageView, angle, pivotX & pivotY are already defined)

Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX);   //required
matrix.postRotate((float) angle, pivotX, pivotY);
imageView.setImageMatrix(matrix);

This method does not require creating a new bitmap each time.

NOTE: To rotate an ImageView on ontouch at runtime you can set onTouchListener on ImageView & rotate it by adding last two lines(i.e. postRotate matrix & set it on imageView) in above code section in your touch listener ACTION_MOVE part.

Convert a String to a byte array and then back to the original String

I would suggest using the members of string, but with an explicit encoding:

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes() etc:

  • You're explicitly using a specific encoding, so you know which encoding to use later, rather than relying on the platform default.
  • You know it will support all of Unicode (as opposed to, say, ISO-Latin-1).

EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.

Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.

EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset instead. Using Guava I'd really use:

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);

Round a floating-point number down to the nearest integer?

If you don't want to import math, you could use:

int(round(x))

Here's a piece of documentation:

>>> help(round)
Help on built-in function round in module __builtin__:

round(...)
    round(number[, ndigits]) -> floating point number

    Round a number to a given precision in decimal digits (default 0 digits).
    This always returns a floating point number.  Precision may be negative.

Back to previous page with header( "Location: " ); in PHP

You have to save that location somehow.

Say it's a POST form, just put the current location in a hidden field and then use it in the header() Location.

How to override trait function and call it from the overridden function?

If the class implements the method directly, it will not use the traits version. Perhaps what you are thinking of is:

trait A {
    function calc($v) {
        return $v+1;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}

class MyChildClass extends MyClass{
}

class MyTraitChildClass extends MyClass{
    use A;
}

print (new MyChildClass())->calc(2); // will print 4

print (new MyTraitChildClass())->calc(2); // will print 3

Because the child classes do not implement the method directly, they will first use that of the trait if there otherwise use that of the parent class.

If you want, the trait can use method in the parent class (assuming you know the method would be there) e.g.

trait A {
    function calc($v) {
        return parent::calc($v*3);
    }
}
// .... other code from above
print (new MyTraitChildClass())->calc(2); // will print 8 (2*3 + 2)

You can also provide for ways to override, but still access the trait method as follows:

trait A {
    function trait_calc($v) {
        return $v*3;
    }
}

class MyClass {
    function calc($v) {
        return $v+2;
    }
}


class MyTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }
}


class MySecondTraitChildClass extends MyClass{
    use A {
      A::trait_calc as calc;
    }

    public function calc($v) {
      return $this->trait_calc($v)+.5;
    }
}


print (new MyTraitChildClass())->calc(2); // will print 6
echo "\n";
print (new MySecondTraitChildClass())->calc(2); // will print 6.5

You can see it work at http://sandbox.onlinephpfunctions.com/code/e53f6e8f9834aea5e038aec4766ac7e1c19cc2b5

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

I had parsing enum problem when i was trying to pass Nullable Enum that we get from Backend. Of course it was working when we get value, but it was problem when the null comes up.

java.lang.IllegalArgumentException: No enum constant

Also the problem was when we at Parcelize read moment write some short if.

My solution for this was

1.Create companion object with parsing method.

enum class CarsType {
    @Json(name = "SMALL")
    SMALL,
    @Json(name = "BIG")
    BIG;

    companion object {
        fun nullableValueOf(name: String?) = when (name) {
            null -> null
            else -> valueOf(name)
        }
    }
}

2. In Parcerable read place use it like this

data class CarData(
    val carId: String? = null,
    val carType: CarsType?,
    val data: String?
) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        CarsType.nullableValueOf(parcel.readString()),
        parcel.readString())

Python Create unix timestamp five minutes in the future

You can use datetime.strftime to get the time in Epoch form, using the %s format string:

def expires():
    future = datetime.datetime.now() + datetime.timedelta(seconds=5*60)
    return int(future.strftime("%s"))

Note: This only works under linux, and this method doesn't work with timezones.

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

How to list all methods for an object in Ruby?

Or just User.methods(false) to return only the methods defined within that class.

SELECT FOR UPDATE with SQL Server

Revisit all your queries, maybe you have some query that select without ROWLOCK/FOR UPDATE hint from the same table you have SELECT FOR UPDATE.


MSSQL often escalates those row locks to page-level locks (even table-level locks, if you don't have index on field you are querying), see this explanation. Since you ask for FOR UPDATE, i could assume that you need transacion-level(e.g. financial, inventory, etc) robustness. So the advice on that site is not applicable to your problem. It's just an insight why MSSQL escalates locks.


If you are already using MSSQL 2005(and up), they are MVCC-based, i think you should have no problem with row-level lock using ROWLOCK/UPDLOCK hint. But if you are already using MSSQL 2005 and up, try to check some of your queries which query the same table you want to FOR UPDATE if they escalate locks by checking the fields on their WHERE clause if they have index.


P.S.
I'm using PostgreSQL, it also uses MVCC have FOR UPDATE, i don't encounter same problem. Lock escalations is what MVCC solves, so i would be surprised if MSSQL 2005 still escalate locks on table with WHERE clauses that doesn't have index on its fields. If that(lock escalation) is still the case for MSSQL 2005, try to check the fields on WHERE clauses if they have index.

Disclaimer: my last use of MSSQL is version 2000 only.

ConnectivityManager getNetworkInfo(int) deprecated

connectivityManager.getActiveNetwork() is not found in below android M (API 28). networkInfo.getState() is deprecated above android L.

So, final answer is:

public static boolean isConnectingToInternet(Context mContext) {
    if (mContext == null) return false;

    ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            final Network network = connectivityManager.getActiveNetwork();
            if (network != null) {
                final NetworkCapabilities nc = connectivityManager.getNetworkCapabilities(network);

                return (nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                        nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI));
            }
        } else {
            NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
            for (NetworkInfo tempNetworkInfo : networkInfos) {
                if (tempNetworkInfo.isConnected()) {
                    return true;
                }
            }
        }
    }
    return false;
}

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

Pyspark: Exception: Java gateway process exited before sending the driver its port number

After spending hours and hours trying many different solutions, I can confirm that Java 10 SDK causes this error. On Mac, please navigate to /Library/Java/JavaVirtualMachines then run this command to uninstall Java JDK 10 completely:

sudo rm -rf jdk-10.jdk/

After that, please download JDK 8 then the problem will be solved.

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

Even though this thread is old but gold. QCustomPlot is very recommendable as well to complement this list.

How do you Encrypt and Decrypt a PHP String?

Before you do anything further, seek to understand the difference between encryption and authentication, and why you probably want authenticated encryption rather than just encryption.

To implement authenticated encryption, you want to Encrypt then MAC. The order of encryption and authentication is very important! One of the existing answers to this question made this mistake; as do many cryptography libraries written in PHP.

You should avoid implementing your own cryptography, and instead use a secure library written by and reviewed by cryptography experts.

Update: PHP 7.2 now provides libsodium! For best security, update your systems to use PHP 7.2 or higher and only follow the libsodium advice in this answer.

Use libsodium if you have PECL access (or sodium_compat if you want libsodium without PECL); otherwise...
Use defuse/php-encryption; don't roll your own cryptography!

Both of the libraries linked above make it easy and painless to implement authenticated encryption into your own libraries.

If you still want to write and deploy your own cryptography library, against the conventional wisdom of every cryptography expert on the Internet, these are the steps you would have to take.

Encryption:

  1. Encrypt using AES in CTR mode. You may also use GCM (which removes the need for a separate MAC). Additionally, ChaCha20 and Salsa20 (provided by libsodium) are stream ciphers and do not need special modes.
  2. Unless you chose GCM above, you should authenticate the ciphertext with HMAC-SHA-256 (or, for the stream ciphers, Poly1305 -- most libsodium APIs do this for you). The MAC should cover the IV as well as the ciphertext!

Decryption:

  1. Unless Poly1305 or GCM is used, recalculate the MAC of the ciphertext and compare it with the MAC that was sent using hash_equals(). If it fails, abort.
  2. Decrypt the message.

Other Design Considerations:

  1. Do not compress anything ever. Ciphertext is not compressible; compressing plaintext before encryption can lead to information leaks (e.g. CRIME and BREACH on TLS).
  2. Make sure you use mb_strlen() and mb_substr(), using the '8bit' character set mode to prevent mbstring.func_overload issues.
  3. IVs should be generating using a CSPRNG; If you're using mcrypt_create_iv(), DO NOT USE MCRYPT_RAND!
  4. Unless you're using an AEAD construct, ALWAYS encrypt then MAC!
  5. bin2hex(), base64_encode(), etc. may leak information about your encryption keys via cache timing. Avoid them if possible.

Even if you follow the advice given here, a lot can go wrong with cryptography. Always have a cryptography expert review your implementation. If you are not fortunate enough to be personal friends with a cryptography student at your local university, you can always try the Cryptography Stack Exchange forum for advice.

If you need a professional analysis of your implementation, you can always hire a reputable team of security consultants to review your PHP cryptography code (disclosure: my employer).

Important: When to Not Use Encryption

Don't encrypt passwords. You want to hash them instead, using one of these password-hashing algorithms:

Never use a general-purpose hash function (MD5, SHA256) for password storage.

Don't encrypt URL Parameters. It's the wrong tool for the job.

PHP String Encryption Example with Libsodium

If you are on PHP < 7.2 or otherwise do not have libsodium installed, you can use sodium_compat to accomplish the same result (albeit slower).

<?php
declare(strict_types=1);

/**
 * Encrypt a message
 * 
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 * @throws RangeException
 */
function safeEncrypt(string $message, string $key): string
{
    if (mb_strlen($key, '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
        throw new RangeException('Key is not the correct size (must be 32 bytes).');
    }
    $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    
    $cipher = base64_encode(
        $nonce.
        sodium_crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
    sodium_memzero($message);
    sodium_memzero($key);
    return $cipher;
}

/**
 * Decrypt a message
 * 
 * @param string $encrypted - message encrypted with safeEncrypt()
 * @param string $key - encryption key
 * @return string
 * @throws Exception
 */
function safeDecrypt(string $encrypted, string $key): string
{   
    $decoded = base64_decode($encrypted);
    $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
    
    $plain = sodium_crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
    if (!is_string($plain)) {
        throw new Exception('Invalid MAC');
    }
    sodium_memzero($ciphertext);
    sodium_memzero($key);
    return $plain;
}

Then to test it out:

<?php
// This refers to the previous code block.
require "safeCrypto.php"; 

// Do this once then store it somehow:
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
$message = 'We are all living in a yellow submarine';

$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

Halite - Libsodium Made Easier

One of the projects I've been working on is an encryption library called Halite, which aims to make libsodium easier and more intuitive.

<?php
use \ParagonIE\Halite\KeyFactory;
use \ParagonIE\Halite\Symmetric\Crypto as SymmetricCrypto;

// Generate a new random symmetric-key encryption key. You're going to want to store this:
$key = new KeyFactory::generateEncryptionKey();
// To save your encryption key:
KeyFactory::save($key, '/path/to/secret.key');
// To load it again:
$loadedkey = KeyFactory::loadEncryptionKey('/path/to/secret.key');

$message = 'We are all living in a yellow submarine';
$ciphertext = SymmetricCrypto::encrypt($message, $key);
$plaintext = SymmetricCrypto::decrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

All of the underlying cryptography is handled by libsodium.

Example with defuse/php-encryption

<?php
/**
 * This requires https://github.com/defuse/php-encryption
 * php composer.phar require defuse/php-encryption
 */

use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;

require "vendor/autoload.php";

// Do this once then store it somehow:
$key = Key::createNewRandomKey();

$message = 'We are all living in a yellow submarine';

$ciphertext = Crypto::encrypt($message, $key);
$plaintext = Crypto::decrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

Note: Crypto::encrypt() returns hex-encoded output.

Encryption Key Management

If you're tempted to use a "password", stop right now. You need a random 128-bit encryption key, not a human memorable password.

You can store an encryption key for long-term use like so:

$storeMe = bin2hex($key);

And, on demand, you can retrieve it like so:

$key = hex2bin($storeMe);

I strongly recommend just storing a randomly generated key for long-term use instead of any sort of password as the key (or to derive the key).

If you're using Defuse's library:

"But I really want to use a password."

That's a bad idea, but okay, here's how to do it safely.

First, generate a random key and store it in a constant.

/**
 * Replace this with your own salt! 
 * Use bin2hex() then add \x before every 2 hex characters, like so:
 */
define('MY_PBKDF2_SALT', "\x2d\xb7\x68\x1a\x28\x15\xbe\x06\x33\xa0\x7e\x0e\x8f\x79\xd5\xdf");

Note that you're adding extra work and could just use this constant as the key and save yourself a lot of heartache!

Then use PBKDF2 (like so) to derive a suitable encryption key from your password rather than encrypting with your password directly.

/**
 * Get an AES key from a static password and a secret salt
 * 
 * @param string $password Your weak password here
 * @param int $keysize Number of bytes in encryption key
 */
function getKeyFromPassword($password, $keysize = 16)
{
    return hash_pbkdf2(
        'sha256',
        $password,
        MY_PBKDF2_SALT,
        100000, // Number of iterations
        $keysize,
        true
    );
}

Don't just use a 16-character password. Your encryption key will be comically broken.

Set UIButton title UILabel font size programmatically

This way you can set the fontSize and can handle it in just one class.

1. Created an extension of UIButton and added following code:

- (void)awakeFromNib{

    [super awakeFromNib];

    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.titleLabel setFont:[UIFont fontWithName:@"font" 
                                     size:self.titleLabel.font.pointSize]];
    [self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
}

2.1 Create UIButton inside Code

Now if you create a UIButton inside your code, #import the extension of yourUIButton` and create the Button.

2.2 Create Button in Interface Builder

If you create the UIButton inside the Interface Builder, select the UIButton, go to the Identity Inspector and add the created extension as class for the UIButton.

Why doesn't RecyclerView have onItemClickListener()?

This worked for me:

@Override
public void onBindViewHolder(PlacesListViewAdapter.ViewHolder holder, int position) {
    ----
    ----
    ----
    // Set setOnClickListener(holder);
}


@Override
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    ----
    ----
    ----

    @Override
    public void onClick(View view) {
        // Use to get the item clicked getAdapterPosition()
    }
}