Programs & Examples On #Scripting language

A scripting language or script language is a programming language that supports the writing of scripts, programs written for a software environment that automate the execution of tasks which could alternatively be executed one by one by a human operator.

Scripting Language vs Programming Language

I think that what you are stating as the "difference" is actually a consequence of the real difference.

The actual difference is the target of the code written. Who is going to run this code.

A scripting language is used to write code that is going to target a software system. It's going to automate operations on that software system. The script is going to be a sequence of instructions to the target software system.

A programming language targets the computing system, which can be a real or virtual machine. The instructions are executed by the machine.

Of course, a real machine understands only binary code so you need to compile the code of a programming language. But this is a consequence of targeting a machine instead of a program.

In the other hand, the target software system of an script may compile the code or interpret it. Is up to the software system.

If we say that the real difference is whether it is compiled or not, then we have a problem because when Javascript runs in V8 is compiled and when it runs in Rhino is not.

It gets more confusing since scripting languages have evolved to become very powerful. So they are not limited to create small scripts to automate operations on another software system, you can create any rich applications with them.

Python code targets an interpreter so we can say that it "scripts" operations on that interpreter. But when you write Python code you don't see it as scripting an interpreter, you see it as creating an application. The interpreter is just there to code at a higher level among other things. So for me Python is more a programming language than an scripting language.

Count textarea characters

They say IE has issues with the input event but other than that, the solution is rather straightforward.

_x000D_
_x000D_
ta = document.querySelector("textarea");_x000D_
count = document.querySelector("label");_x000D_
_x000D_
ta.addEventListener("input", function (e) {_x000D_
  count.innerHTML = this.value.length;_x000D_
});
_x000D_
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">_x000D_
</textarea>_x000D_
<label for="my-textarea"></label>
_x000D_
_x000D_
_x000D_

How to create a circle icon button in Flutter?

RawMaterialButton is better suited I think.

RawMaterialButton(
  onPressed: () {},
  elevation: 2.0,
  fillColor: Colors.white,
  child: Icon(
    Icons.pause,
    size: 35.0,
  ),
  padding: EdgeInsets.all(15.0),
  shape: CircleBorder(),
)

Difference between window.location.href, window.location.replace and window.location.assign

The part about not being able to use the Back button is a common misinterpretation. window.location.replace(URL) throws out the top ONE entry from the page history list, by overwriting it with the new entry, so the user can't easily go Back to that ONE particular webpage. The function does NOT wipe out the entire page history list, nor does it make the Back button completely non-functional.

(NO function nor combination of parameters that I know of can change or overwrite history list entries that you don't own absolutely for certain - browsers generally impelement this security limitation by simply not even defining any operation that might at all affect any entry other than the top one in the page history list. I shudder to think what sorts of dastardly things malware might do if such a function existed.)

If you really want to make the Back button non-functional (probably not "user friendly": think again if that's really what you want to do), "open" a brand new window. (You can "open" a popup that doesn't even have a "Back" button too ...but popups aren't very popular these days:-) If you want to keep your page showing no matter what the user does (again the "user friendliness" is questionable), set up a window.onunload handler that just reloads your page all over again clear from the very beginning every time.

How to create a HTTP server in Android?

If you are using kotlin,consider these library. It's build for kotlin language.

AndroidHttpServer is a simple demo using ServerSocket to handle http request

https://github.com/weeChanc/AndroidHttpServer

https://github.com/ktorio/ktor

AndroidHttpServer is very small , but the feature is less as well.

Ktor is a very nice library,and the usage is simple too

Updating address bar with new URL without hash or reloading the page

You can now do this in most "modern" browsers!

Here is the original article I read (posted July 10, 2010): HTML5: Changing the browser-URL without refreshing page.

For a more in-depth look into pushState/replaceState/popstate (aka the HTML5 History API) see the MDN docs.

TL;DR, you can do this:

window.history.pushState("object or string", "Title", "/new-url");

See my answer to Modify the URL without reloading the page for a basic how-to.

How to remove part of a string?

Do the following

$string = 'REGISTER 11223344 here';

$content = preg_replace('/REGISTER(.*)here/','',$string);

This would return "REGISTERhere"

or

$string = 'REGISTER 11223344 here';

$content = preg_replace('/REGISTER (.*) here/','',$string);

This would return "REGISTER here"

Getting char from string at specified index

Getting one char from string at specified index

Dim pos As Integer
Dim outStr As String
pos = 2 
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)

outStr="b"

How do I suspend painting for a control and its children?

I usually use a little modified version of ngLink's answer.

public class MyControl : Control
{
    private int suspendCounter = 0;

    private void SuspendDrawing()
    {
        if(suspendCounter == 0) 
            SendMessage(this.Handle, WM_SETREDRAW, false, 0);
        suspendCounter++;
    }

    private void ResumeDrawing()
    {
        suspendCounter--; 
        if(suspendCounter == 0) 
        {
            SendMessage(this.Handle, WM_SETREDRAW, true, 0);
            this.Refresh();
        }
    }
}

This allows suspend/resume calls to be nested. You must make sure to match each SuspendDrawing with a ResumeDrawing. Hence, it wouldn't probably be a good idea to make them public.

How to install Jdk in centos

Try the following to see if you have the proper repository installed:

# yum search java | grep 'java-'

This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:

http://dag.wieers.com/rpm/FAQ.php#B

After you've got it installed try yum search again... This time you'll have a bunch of java stuff.

# yum search java | grep 'java-'

This will return the list of the available java packages. You can install one like this:

# yum install java-1.7.0-openjdk.x86_64

How do I copy items from list to list without foreach?

For a list of elements

List<string> lstTest = new List<string>();

lstTest.Add("test1");
lstTest.Add("test2");
lstTest.Add("test3");
lstTest.Add("test4");
lstTest.Add("test5");
lstTest.Add("test6");

If you want to copy all the elements

List<string> lstNew = new List<string>();
lstNew.AddRange(lstTest);

If you want to copy the first 3 elements

List<string> lstNew = lstTest.GetRange(0, 3);

Error: 0xC0202009 at Data Flow Task, OLE DB Destination [43]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E21

In my case the underlying system account through which the package was running was locked out. Once we got the system account unlocked and reran the package, it executed successfully. The developer said that he got to know of this while debugging wherein he directly tried to connect to the server and check the status of the connection.

Bash script and /bin/bash^M: bad interpreter: No such file or directory

Your file has Windows line endings, which is confusing Linux.

Remove the spurious CR characters. You can do it with the following command:

 $ sed -i -e 's/\r$//' setup.sh

Faking an RS232 Serial Port

If you are developing for Windows, the com0com project might be, what you are looking for.

It provides pairs of virtual COM ports that are linked via a nullmodem connetion. You can then use your favorite terminal application or whatever you like to send data to one COM port and recieve from the other one.

EDIT:

As Thomas pointed out the project lacks of a signed driver, which is especially problematic on certain Windows version (e.g. Windows 7 x64).

There are a couple of unofficial com0com versions around that do contain a signed driver. One recent verion (3.0.0.0) can be downloaded e.g. from here.

Improve SQL Server query performance on large tables

The question specifically states the performance needs to be improved for ad-hoc queries, and that indexes can't be added. So taking that at face value, what can be done to improve performance on any table?

Since we're considering ad-hoc queries, the WHERE clause and the ORDER BY clause can contain any combination of columns. This means that almost regardless of what indexes are placed on the table there will be some queries that require a table scan, as seen above in query plan of a poorly performing query.

Taking this into account, let's assume there are no indexes at all on the table apart from a clustered index on the primary key. Now let's consider what options we have to maximize performance.

  • Defragment the table

    As long as we have a clustered index then we can defragment the table using DBCC INDEXDEFRAG (deprecated) or preferably ALTER INDEX. This will minimize the number of disk reads required to scan the table and will improve speed.

  • Use the fastest disks possible. You don't say what disks you're using but if you can use SSDs.

  • Optimize tempdb. Put tempdb on the fastest disks possible, again SSDs. See this SO Article and this RedGate article.

  • As stated in other answers, using a more selective query will return less data, and should be therefore be faster.

Now let's consider what we can do if we are allowed to add indexes.

If we weren't talking about ad-hoc queries, then we would add indexes specifically for the limited set of queries being run against the table. Since we are discussing ad-hoc queries, what can be done to improve speed most of the time?

  • Add a single column index to each column. This should give SQL Server at least something to work with to improve the speed for the majority of queries, but won't be optimal.
  • Add specific indexes for the most common queries so they are optimized.
  • Add additional specific indexes as required by monitoring for poorly performing queries.

Edit

I've run some tests on a 'large' table of 22 million rows. My table only has six columns but does contain 4GB of data. My machine is a respectable desktop with 8Gb RAM and a quad core CPU and has a single Agility 3 SSD.

I removed all indexes apart from the primary key on the Id column.

A similar query to the problem one given in the question takes 5 seconds if SQL server is restarted first and 3 seconds subsequently. The database tuning advisor obviously recommends adding an index to improve this query, with an estimated improvement of > 99%. Adding an index results in a query time of effectively zero.

What's also interesting is that my query plan is identical to yours (with the clustered index scan), but the index scan accounts for 9% of the query cost and the sort the remaining 91%. I can only assume your table contains an enormous amount of data and/or your disks are very slow or located over a very slow network connection.

Is JavaScript's "new" keyword considered harmful?

Another case for new is what I call Pooh Coding. Winnie the Pooh follows his tummy. I say go with the language you are using, not against it.

Chances are that the maintainers of the language will optimize the language for the idioms they try to encourage. If they put a new keyword into the language they probably think it makes sense to be clear when creating a new instance.

Code written following the language's intentions will increase in efficiency with each release. And code avoiding the key constructs of the language will suffer with time.

EDIT: And this goes well beyond performance. I can't count the times I've heard (or said) "why the hell did they do that?" when finding strange looking code. It often turns out that at the time when the code was written there was some "good" reason for it. Following the Tao of the language is your best insurance for not having your code ridiculed some years from now.

Conversion from Long to Double in Java

Long i = 1000000;
String s = i + "";
Double d = Double.parseDouble(s);
Float f = Float.parseFloat(s);

This way we can convert Long type to Double or Float or Int without any problem because it's easy to convert string value to Double or Float or Int.

Validate SSL certificates with Python

M2Crypto can do the validation. You can also use M2Crypto with Twisted if you like. The Chandler desktop client uses Twisted for networking and M2Crypto for SSL, including certificate validation.

Based on Glyphs comment it seems like M2Crypto does better certificate verification by default than what you can do with pyOpenSSL currently, because M2Crypto checks subjectAltName field too.

I've also blogged on how to get the certificates Mozilla Firefox ships with in Python and usable with Python SSL solutions.

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

I don't think maven supports this. If you're on Unix, and don't want to leave your current directory, you could use a small shell script, a shell function, or just a sub-shell:

user@host ~/project$ (cd ~/some/location; mvn install)
[ ... mvn build ... ]
user@host ~/project$

As a bash function (which you could add to your ~/.bashrc):

function mvn-there() {
  DIR="$1"
  shift
  (cd $DIR; mvn "$@")     
} 

user@host ~/project$ mvn-there ~/some/location install)
[ ... mvn build ... ]
user@host ~/project$

I realize this doesn't answer the specific question, but may provide you with what you're after. I'm not familiar with the Windows shell, though you should be able to reach a similar solution there as well.

Regards

Excel VBA to Export Selected Sheets to PDF

I'm pretty mixed up on this. I am also running Excel 2010. I tried saving two sheets as a single PDF using:

    ThisWorkbook.Sheets(Array(1,2)).Select
    **Selection**.ExportAsFixedFormat xlTypePDF, FileName & ".pdf", , , False

but I got nothing but blank pages. It saved both sheets, but nothing on them. It wasn't until I used:

    ThisWorkbook.Sheets(Array(1,2)).Select
    **ActiveSheet**.ExportAsFixedFormat xlTypePDF, FileName & ".pdf", , , False

that I got a single PDF file with both sheets.

I tried manually saving these two pages using Selection in the Options dialog to save the two sheets I had selected, but got blank pages. When I tried the Active Sheet(s) option, I got what I wanted. When I recorded this as a macro, Excel used ActiveSheet when it successfully published the PDF. What gives?

Difference between a View's Padding and Margin

Margin refers to the extra space outside of an element. Padding refers to the extra space within an element. The margin is the extra space around the control. The padding is extra space inside the control.

It's hard to see the difference with margin and padding with a white fill, but with a colored fill you can see it fine.

CSS selector for disabled input type="submit"

Does that work in IE6?

No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.

You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.


EDIT
If you are to ignore IE6, you could do (CSS2.1):

input[type=submit][disabled=disabled],
button[disabled=disabled] {
    ...
}

CSS3 (IE9+):

input[type=submit]:disabled,
button:disabled {
    ...
}

You can substitute [disabled=disabled] (attribute value) with [disabled] (attribute presence).

Set android shape color programmatically

May be I am too late.But if you are using Kotlin. There is way like this

var gd = layoutMain.background as GradientDrawable

 //gd.setCornerRadius(10)
  gd.setColor(ContextCompat.getColor(ctx , R.color.lightblue))
  gd.setStroke(1, ContextCompat.getColor(ctx , R.color.colorPrimary)) // (Strokewidth,colorId)

Enjoy....

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

Here is an example where I use a different list to add the objects for removal, then afterwards I use stream.foreach to remove elements from original list :

private ObservableList<CustomerTableEntry> customersTableViewItems = FXCollections.observableArrayList();
...
private void removeOutdatedRowsElementsFromCustomerView()
{
    ObjectProperty<TimeStamp> currentTimestamp = new SimpleObjectProperty<>(TimeStamp.getCurrentTime());
    long diff;
    long diffSeconds;
    List<Object> objectsToRemove = new ArrayList<>();
    for(CustomerTableEntry item: customersTableViewItems) {
        diff = currentTimestamp.getValue().getTime() - item.timestamp.getValue().getTime();
        diffSeconds = diff / 1000 % 60;
        if(diffSeconds > 10) {
            // Element has been idle for too long, meaning no communication, hence remove it
            System.out.printf("- Idle element [%s] - will be removed\n", item.getUserName());
            objectsToRemove.add(item);
        }
    }
    objectsToRemove.stream().forEach(o -> customersTableViewItems.remove(o));
}

Difference between Role and GrantedAuthority in Spring Security

Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.

Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.

Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.

On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)

The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.

Jake

Private vs Protected - Visibility Good-Practice Concern

Stop abusing private fields!!!

The comments here seem to be overwhelmingly supportive towards using private fields. Well, then I have something different to say.

Are private fields good in principle? Yes. But saying that a golden rule is make everything private when you're not sure is definitely wrong! You won't see the problem until you run into one. In my opinion, you should mark fields as protected if you're not sure.

There are two cases you want to extend a class:

  • You want to add extra functionality to a base class
  • You want to modify existing class that's outside the current package (in some libraries perhaps)

There's nothing wrong with private fields in the first case. The fact that people are abusing private fields makes it so frustrating when you find out you can't modify shit.

Consider a simple library that models cars:

class Car {
    private screw;
    public assembleCar() {
       screw.install();
    };
    private putScrewsTogether() {
       ...
    };
}

The library author thought: there's no reason the users of my library need to access the implementation detail of assembleCar() right? Let's mark screw as private.

Well, the author is wrong. If you want to modify only the assembleCar() method without copying the whole class into your package, you're out of luck. You have to rewrite your own screw field. Let's say this car uses a dozen of screws, and each of them involves some untrivial initialization code in different private methods, and these screws are all marked private. At this point, it starts to suck.

Yes, you can argue with me that well the library author could have written better code so there's nothing wrong with private fields. I'm not arguing that private field is a problem with OOP. It is a problem when people are using them.

The moral of the story is, if you're writing a library, you never know if your users want to access a particular field. If you're unsure, mark it protected so everyone would be happier later. At least don't abuse private field.

I very much support Nick's answer.

Standard Android Button with a different color

You can set theme of your button to this

<style name="AppTheme.ButtonBlue" parent="Widget.AppCompat.Button.Colored">
 <item name="colorButtonNormal">@color/HEXColor</item>
 <item name="android:textColor">@color/HEXColor</item>
</style>

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

You need to use an Angular form directive on the select. You can do that with ngModel. For example

@Component({
  selector: 'my-app',
  template: `
    <h2>Select demo</h2>
    <select [(ngModel)]="selectedCity" (ngModelChange)="onChange($event)" >
      <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option>
    </select>
  `
})
class App {
  cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}];
  selectedCity = this.cities[1];

  onChange(city) {
    alert(city.name);
  }
}

The (ngModelChange) event listener emits events when the selected value changes. This is where you can hookup your callback.

Note you will need to make sure you have imported the FormsModule into the application.

Here is a Plunker

How to create a sticky left sidebar menu using bootstrap 3?

You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix component is no longer included:

Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.

How to list all the roles existing in Oracle database?

all_roles.sql

SELECT SUBSTR(TRIM(rtp.role),1,12)          AS ROLE
     , SUBSTR(rp.grantee,1,16)              AS GRANTEE
     , SUBSTR(TRIM(rtp.privilege),1,12)     AS PRIVILEGE
     , SUBSTR(TRIM(rtp.owner),1,12)         AS OWNER
     , SUBSTR(TRIM(rtp.table_name),1,28)    AS TABLE_NAME
     , SUBSTR(TRIM(rtp.column_name),1,20)   AS COLUMN_NAME
     , SUBSTR(rtp.common,1,4)               AS COMMON
     , SUBSTR(rtp.grantable,1,4)            AS GRANTABLE
     , SUBSTR(rp.default_role,1,16)         AS DEFAULT_ROLE
     , SUBSTR(rp.admin_option,1,4)          AS ADMIN_OPTION
  FROM role_tab_privs rtp
  LEFT JOIN dba_role_privs rp
    ON (rtp.role = rp.granted_role)
 WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
   AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
   AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
   AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
 ORDER BY 1
        , 2
        , 3
        , 4
;

Usage

SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.

AngularJS view not updating on model change

Do not use $scope.$apply() angular already uses it and it can result in this error

$rootScope:inprog Action Already In Progress

if you use twice, use $timeout or interval

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

The normal way of doing it is:

  • You get the users from the database in controller.
  • You send a collection of users to the View
  • In the view to loop the list of users building the list.

You don't need a JsonResult or jQuery for this.

Spring Boot - How to log all requests and responses with exceptions in single place?

If you are seeing only part of your request payload, you need to call the setMaxPayloadLength function as it defaults to showing only 50 characters in your request body. Also, setting setIncludeHeaders to false is a good idea if you don't want to log your auth headers!

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(false);
    loggingFilter.setIncludeQueryString(false);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setIncludeHeaders(false);
    loggingFilter.setMaxPayloadLength(500);
    return loggingFilter;
}

How to capitalize the first letter of a String in Java?

public void capitalizeFirstLetter(JTextField textField) {

    try {

        if (!textField.getText().isEmpty()) {
            StringBuilder b = new StringBuilder(textField.getText());
            int i = 0;
            do {
                b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase());
                i = b.indexOf(" ", i) + 1;
            } while (i > 0 && i < b.length());
            textField.setText(b.toString());
        }

    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
    }
}

What is __pycache__?

__pycache__ is a folder containing Python 3 bytecode compiled and ready to be executed.

I don't recommend routinely deleting these files or suppressing creation during development as it may hurt performance. Just have a recursive command ready (see below) to clean up when needed as bytecode can become stale in edge cases (see comments).

Python programmers usually ignore bytecode. Indeed __pycache__ and *.pyc are common lines to see in .gitignore files. Bytecode is not meant for distribution and can be disassembled using dis module.


If you are using OS X you can easily hide all of these folders in your project by running following command from the root folder of your project.

find . -name '__pycache__' -exec chflags hidden {} \;

Replace __pycache__ with *.pyc for Python 2.

This sets a flag on all those directories (.pyc files) telling Finder/Textmate 2 to exclude them from listings. Importantly the bytecode is there, it's just hidden.

Rerun the command if you create new modules and wish to hide new bytecode or if you delete the hidden bytecode files.


On Windows the equivalent command might be (not tested, batch script welcome):

dir * /s/b | findstr __pycache__ | attrib +h +s +r

Which is same as going through the project hiding folders using right-click > hide...


Running unit tests is one scenario (more in comments) where deleting the *.pyc files and __pycache__ folders is indeed useful. I use the following lines in my ~/.bash_profile and just run cl to clean up when needed.

alias cpy='find . -name "__pycache__" -delete'
alias cpc='find . -name "*.pyc"       -delete'
...
alias cl='cpy && cpc && ...'

and more lately

# pip install pyclean
pyclean .

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

UIView bottom border?

The most complete answer. https://github.com/oney/UIView-Border

let rectangle = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 60))
rectangle.backgroundColor = UIColor.grayColor()
view.addSubview(rectangle)
rectangle.borderTop = Border(size: 3, color: UIColor.orangeColor(), offset: UIEdgeInsets(top: 0, left: -10, bottom: 0, right: -5))
rectangle.borderBottom = Border(size: 6, color: UIColor.redColor(), offset: UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 0))
rectangle.borderLeft = Border(size: 2, color: UIColor.blueColor(), offset: UIEdgeInsets(top: 10, left: -10, bottom: 0, right: 0))
rectangle.borderRight = Border(size: 2, color: UIColor.greenColor(), offset: UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 0))

enter image description here

What is the difference between visibility:hidden and display:none?

display:none will hide the element and collapse the space is was taking up, whereas visibility:hidden will hide the element and preserve the elements space. display:none also effects some of the properties available from javascript in older versions of IE and Safari.

First Heroku deploy failed `error code=H10`

The H10 error code could mean many different things. In my case, the first time was because I didn't know that Heroku isn't compatible with Sqlite3, the second time was because I accidentally pushed an update with Google analytics working in development as well as production.

pip installs packages successfully, but executables not found from command line

In addition to adding python's bin directory to $PATH variable, I also had to change the owner of that directory, to make it work. No idea why I wasn't the owner already.

chown -R ~/Library/Python/

Pandas: Subtracting two date columns and the result being an integer

You can use datetime module to help here. Also, as a side note, a simple date subtraction should work as below:

import datetime as dt
import numpy as np
import pandas as pd

#Assume we have df_test:
In [222]: df_test
Out[222]: 
   first_date second_date
0  2016-01-31  2015-11-19
1  2016-02-29  2015-11-20
2  2016-03-31  2015-11-21
3  2016-04-30  2015-11-22
4  2016-05-31  2015-11-23
5  2016-06-30  2015-11-24
6         NaT  2015-11-25
7         NaT  2015-11-26
8  2016-01-31  2015-11-27
9         NaT  2015-11-28
10        NaT  2015-11-29
11        NaT  2015-11-30
12 2016-04-30  2015-12-01
13        NaT  2015-12-02
14        NaT  2015-12-03
15 2016-04-30  2015-12-04
16        NaT  2015-12-05
17        NaT  2015-12-06

In [223]: df_test['Difference'] = df_test['first_date'] - df_test['second_date'] 

In [224]: df_test
Out[224]: 
   first_date second_date  Difference
0  2016-01-31  2015-11-19     73 days
1  2016-02-29  2015-11-20    101 days
2  2016-03-31  2015-11-21    131 days
3  2016-04-30  2015-11-22    160 days
4  2016-05-31  2015-11-23    190 days
5  2016-06-30  2015-11-24    219 days
6         NaT  2015-11-25         NaT
7         NaT  2015-11-26         NaT
8  2016-01-31  2015-11-27     65 days
9         NaT  2015-11-28         NaT
10        NaT  2015-11-29         NaT
11        NaT  2015-11-30         NaT
12 2016-04-30  2015-12-01    151 days
13        NaT  2015-12-02         NaT
14        NaT  2015-12-03         NaT
15 2016-04-30  2015-12-04    148 days
16        NaT  2015-12-05         NaT
17        NaT  2015-12-06         NaT

Now, change type to datetime.timedelta, and then use the .days method on valid timedelta objects.

In [226]: df_test['Diffference'] = df_test['Difference'].astype(dt.timedelta).map(lambda x: np.nan if pd.isnull(x) else x.days)

In [227]: df_test
Out[227]: 
   first_date second_date  Difference  Diffference
0  2016-01-31  2015-11-19     73 days           73
1  2016-02-29  2015-11-20    101 days          101
2  2016-03-31  2015-11-21    131 days          131
3  2016-04-30  2015-11-22    160 days          160
4  2016-05-31  2015-11-23    190 days          190
5  2016-06-30  2015-11-24    219 days          219
6         NaT  2015-11-25         NaT          NaN
7         NaT  2015-11-26         NaT          NaN
8  2016-01-31  2015-11-27     65 days           65
9         NaT  2015-11-28         NaT          NaN
10        NaT  2015-11-29         NaT          NaN
11        NaT  2015-11-30         NaT          NaN
12 2016-04-30  2015-12-01    151 days          151
13        NaT  2015-12-02         NaT          NaN
14        NaT  2015-12-03         NaT          NaN
15 2016-04-30  2015-12-04    148 days          148
16        NaT  2015-12-05         NaT          NaN
17        NaT  2015-12-06         NaT          NaN

Hope that helps.

Javascript-Setting background image of a DIV via a function and function parameter

From what I know, the correct syntax is:

function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
    document.getElementById(tabName).style.backgroundImage = "url('buttons/" + imagePrefix + ".png')";
}

So basically, getElementById(tabName).backgroundImage and split the string like:

"cssInHere('and" + javascriptOutHere + "/cssAgain')";

Remove Elements from a HashSet while Iterating

Java 8 Collection has a nice method called removeIf that makes things easier and safer. From the API docs:

default boolean removeIf(Predicate<? super E> filter)
Removes all of the elements of this collection that satisfy the given predicate. 
Errors or runtime exceptions thrown during iteration or by the predicate 
are relayed to the caller.

Interesting note:

The default implementation traverses all elements of the collection using its iterator(). 
Each matching element is removed using Iterator.remove().

From: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

For GMT, here is the easiest way:

Select dateadd(s, @UnixTime+DATEDIFF (S, GETUTCDATE(), GETDATE()), '1970-01-01')

Do I use <img>, <object>, or <embed> for SVG files?

I can recommend the SVG Primer (published by the W3C), which covers this topic: http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#SVG_in_HTML

If you use <object> then you get raster fallback for free*:

<object data="your.svg" type="image/svg+xml">
  <img src="yourfallback.jpg" />
</object>

*) Well, not quite for free, because some browsers download both resources, see Larry's suggestion below for how to get around that.

2014 update:

  • If you want a non-interactive svg, use <img> with script fallbacks to png version (for older IE and android < 3). One clean and simple way to do that:

    <img src="your.svg" onerror="this.src='your.png'">.

    This will behave much like a GIF image, and if your browser supports declarative animations (SMIL) then those will play.

  • If you want an interactive svg, use either <iframe> or <object>.

  • If you need to provide older browsers the ability to use an svg plugin, then use <embed>.

  • For svg in css background-image and similar properties, modernizr is one choice for switching to fallback images, another is depending on multiple backgrounds to do it automatically:

    div {
        background-image: url(fallback.png);
        background-image: url(your.svg), none;
    }
    

    Note: the multiple backgrounds strategy doesn't work on Android 2.3 because it supports multiple backgrounds but not svg.

An additional good read is this blogpost on svg fallbacks.

jQuery check if it is clicked or not

Using jQuery, I would suggest a shorter solution.

var elementClicked;
$("element").click(function(){
   elementClicked = true;
});
if( elementClicked != true ) {
    alert("element not clicked");
}else{
    alert("element clicked");
}

("element" here is to be replaced with the actual name tag)

Showing line numbers in IPython/Jupyter Notebooks

For me, ctrl + m is used to save the webpage as png, so it does not work properly. But I find another way.

On the toolbar, there is a bottom named open the command paletee, you can click it and type in the line, and you can see the toggle cell line number here.

Calculate RSA key fingerprint

Reproducing content from AWS forums here, because I found it useful to my use case - I wanted to check which of my keys matched ones I had imported into AWS

openssl pkey -in ~/.ssh/ec2/primary.pem -pubout -outform DER | openssl md5 -c

Where:

  • primary.pem is the private key to check

Note that this gives a different fingerprint from the one computed by ssh-keygen.

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

How to display tables on mobile using Bootstrap?

Bootstrap 3 introduces responsive tables:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

Bootstrap 4 is similar, but with more control via some new classes:

...responsive across all viewports ... with .table-responsive. Or, pick a maximum breakpoint with which to have a responsive table up to by using .table-responsive{-sm|-md|-lg|-xl}.

Credit to Jason Bradley for providing an example:

Responsive Tables

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

You can use PHP to add a stylesheet for IE 10

Like:

if (stripos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10')) {
    <link rel="stylesheet" type="text/css" href="../ie10.css" />
}

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

You are correct, @RequestBody annotated parameter is expected to hold the entire body of the request and bind to one object, so you essentially will have to go with your options.

If you absolutely want your approach, there is a custom implementation that you can do though:

Say this is your json:

{
    "str1": "test one",
    "str2": "two test"
}

and you want to bind it to the two params here:

@RequestMapping(value = "/Test", method = RequestMethod.POST)
public boolean getTest(String str1, String str2)

First define a custom annotation, say @JsonArg, with the JSON path like path to the information that you want:

public boolean getTest(@JsonArg("/str1") String str1, @JsonArg("/str2") String str2)

Now write a Custom HandlerMethodArgumentResolver which uses the JsonPath defined above to resolve the actual argument:

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.jayway.jsonpath.JsonPath;

public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{

    private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonArg.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String body = getRequestBody(webRequest);
        String val = JsonPath.read(body, parameter.getMethodAnnotation(JsonArg.class).value());
        return val;
    }

    private String getRequestBody(NativeWebRequest webRequest){
        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        String jsonBody = (String) servletRequest.getAttribute(JSONBODYATTRIBUTE);
        if (jsonBody==null){
            try {
                String body = IOUtils.toString(servletRequest.getInputStream());
                servletRequest.setAttribute(JSONBODYATTRIBUTE, body);
                return body;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "";

    }
}

Now just register this with Spring MVC. A bit involved, but this should work cleanly.

Use of #pragma in C

#pragma is for compiler directives that are machine-specific or operating-system-specific, i.e. it tells the compiler to do something, set some option, take some action, override some default, etc. that may or may not apply to all machines and operating systems.

See msdn for more info.

Easy way to get a test file into JUnit

If you need to actually get a File object, you could do the following:

URL url = this.getClass().getResource("/test.wsdl");
File testWsdl = new File(url.getFile());

Which has the benefit of working cross platform, as described in this blog post.

Babel command not found

Worked for me e.g.

./node_modules/.bin/babel --version
./node_modules/.bin/babel src/main.js

Find length (size) of an array in jquery

var array=[];

array.push(array);  //insert the array value using push methods.

for (var i = 0; i < array.length; i++) {    
    nameList += "" + array[i] + "";          //display the array value.                                                             
}

$("id/class").html(array.length);   //find the array length.

Can I use Homebrew on Ubuntu?

October 2019 - Ubuntu 18.04 on WSL with oh-my-zsh; the instructions here worked perfectly -

(first, install pre-requisites using sudo apt-get install build-essential curl file git)

finally create a ~/.zprofile with the following contents: emulate sh -c '. ~/.profile'

Easy login script without database

if you dont have a database, you will have to hardcode the login details in your code, or read it from a flat file on disk.

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Reading a string with spaces with sscanf

Since you want the trailing string from the input, you can use %n (number of characters consumed thus far) to get the position at which the trailing string starts. This avoids memory copies and buffer sizing issues, but comes at the cost that you may need to do them explicitly if you wanted a copy.

const char *input = "19  cool kid";
int age;
int nameStart = 0;
sscanf(input, "%d %n", &age, &nameStart);
printf("%s is %d years old\n", input + nameStart, age);

outputs:

cool kid is 19 years old

Excel: Searching for multiple terms in a cell

Try using COUNT function like this

=IF(COUNT(SEARCH({"Romney","Obama","Gingrich"},C1)),1,"")

Note that you don't need the wildcards (as teylyn says) and unless there's a specific reason "1" doesn't need quotes (in fact that makes it a text value)

Counting the number of True Booleans in a Python List

If you are only concerned with the constant True, a simple sum is fine. However, keep in mind that in Python other values evaluate as True as well. A more robust solution would be to use the bool builtin:

>>> l = [1, 2, True, False]
>>> sum(bool(x) for x in l)
3

UPDATE: Here's another similarly robust solution that has the advantage of being more transparent:

>>> sum(1 for x in l if x)
3

P.S. Python trivia: True could be true without being 1. Warning: do not try this at work!

>>> True = 2
>>> if True: print('true')
... 
true
>>> l = [True, True, False, True]
>>> sum(l)
6
>>> sum(bool(x) for x in l)
3
>>> sum(1 for x in l if x)
3

Much more evil:

True = False

How to get the name of the current Windows user in JavaScript

JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.

JavaScript will not be able to determine your Windows user name.

Setting default values to null fields when mapping with Jackson

There is no annotation to set default value.
You can set default value only on java class level:

public class JavaObject 
{
    public String notNullMember;

    public String optionalMember = "Value";
}

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

It's a table-valued function, but you're using it as a scalar function.

Try:

where Emp_Id IN (SELECT i.items FROM dbo.Splitfn(@Id,',') AS i)

But... also consider changing your function into an inline TVF, as it'll perform better.

All combinations of a list of lists

Nothing wrong with straight up recursion for this task, and if you need a version that works with strings, this might fit your needs:

combinations = []

def combine(terms, accum):
    last = (len(terms) == 1)
    n = len(terms[0])
    for i in range(n):
        item = accum + terms[0][i]
        if last:
            combinations.append(item)
        else:
            combine(terms[1:], item)


>>> a = [['ab','cd','ef'],['12','34','56']]
>>> combine(a, '')
>>> print(combinations)
['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']

Moment.js transform to date object

Since momentjs has no control over javascript date object I found a work around to this.

_x000D_
_x000D_
const currentTime = new Date();    _x000D_
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");_x000D_
const convertTimeObject = new Date(convertTime);
_x000D_
_x000D_
_x000D_

This will give you a javascript date object with the converted time

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

I wrapped @Tieme s answer with a helper function.

In TypeScript:

export const mapN = <T = any[]>(count: number, fn: (...args: any[]) => T): T[] => [...Array(count)].map((_, i) => fn())

Now you can run:

const arr: string[] = mapN(3, () => 'something')
// returns ['something', 'something', 'something']

Count characters in textarea

A more generic version so you can use the function for more than one field.

<script src="../site/jquery/jquery.min.js" ></script>
<script type="text/javascript">

function countChar(inobj, maxl, outobj) {
    var len = inobj.value.length;
    var msg = ' chr left';
    if (len >= maxl) {
        inobj.value = inobj.value.substring(0, maxl);
        $(outobj).text(0 + msg);
    } else {
        $(outobj).text(maxl - len + msg);
    }
}


$(document).ready(function(){

    //set up summary field character count
    countChar($('#summary').get(0),500, '#summarychrs'); //show inital value on page load
    $('#summary').keyup(function() {
        countChar(this, 500, '#summarychrs'); //set up on keyup event function
    });

});
</script>

<textarea name="summary" id="summary" cols="60" rows="3" ><?php echo $summary ?></textarea> 
<span id="summarychrs">0</span>

How do I restore a dump file from mysqldump?

You cannot use the Restore menu in MySQL Admin if the backup / dump wasn't created from there. It's worth a shot though. If you choose to "ignore errors" with the checkbox for that, it will say it completed successfully, although it clearly exits with only a fraction of rows imported...this is with a dump, mind you.

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

In the case where the problem is that System.loadLibrary cannot find the DLL in question, one common misconception (reinforced by Java's error message) is that the system property java.library.path is the answer. If you set the system property java.library.path to the directory where your DLL is located, then System.loadLibrary will indeed find your DLL. However, if your DLL in turn depends on other DLLs, as is often the case, then java.library.path cannot help, because the loading of the dependent DLLs is managed entirely by the operating system, which knows nothing of java.library.path. Thus, it is almost always better to bypass java.library.path and simply add your DLL's directory to LD_LIBRARY_PATH (Linux), DYLD_LIBRARY_PATH (MacOS), or Path (Windows) prior to starting the JVM.

(Note: I am using the term "DLL" in the generic sense of DLL or shared library.)

Fix CSS hover on iPhone/iPad/iPod

Some people don't know about this. You can apply it on div:hover and working on iPhone .

Add the following css to the element with :hover effect

.mm {
    cursor: pointer;
}

Generic Property in C#

You cannot 'alter' the property syntax this way. What you can do is this:

class Foo
{
    string MyProperty { get; set; }  // auto-property with inaccessible backing field
}

and a generic version would look like this:

class Foo<T>
{
    T MyProperty { get; set; }
}

How to clear all <div>s’ contents inside a parent <div>?

You can use .empty() function to clear all the child elements

 $(document).ready(function () {
  $("#button").click(function () {
   //only the content inside of the element will be deleted
   $("#masterdiv").empty();
  });
 });

To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/

How do you enable auto-complete functionality in Visual Studio C++ express edition?

Include the class that you are using Within your text file, then intelliSense will know where to look when you type within your text file. This works for me.

So it’s important to check the Unreal API to see where the included class is so that you have the path to type on the include line. Hope that makes sense.

How do I use modulus for float/double?

You probably had a typo when you first ran it.

evaluating 0.5 % 0.3 returns '0.2' (A double) as expected.

Mindprod has a good overview of how modulus works in Java.

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

Here is the solution steps:

  1. backup your database (structure with drop option and data)
  2. stop mysql engine service
  3. remove the database directory manually from inside mysql/data
  4. start mysql engine
  5. create new database with any name different from your corrupted database
  6. create single table with the name of the corrupted table inside the new database (this is the secret). and it is better to create the table with exactly the same structure.
  7. rename the database to the old corrupted database
  8. restore your backup and your table will be working fine.

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

Downloading a file from spring controllers

something like below

@RequestMapping(value = "/download", method = RequestMethod.GET)
public void getFile(HttpServletResponse response) {
    try {
        DefaultResourceLoader loader = new DefaultResourceLoader();
        InputStream is = loader.getResource("classpath:META-INF/resources/Accepted.pdf").getInputStream();
        IOUtils.copy(is, response.getOutputStream());
        response.setHeader("Content-Disposition", "attachment; filename=Accepted.pdf");
        response.flushBuffer();
    } catch (IOException ex) {
        throw new RuntimeException("IOError writing file to output stream");
    }
}

You can display PDF or download it examples here

Image inside div has extra space below the image

I found it works great using display:block; on the image and vertical-align:top; on the text.

_x000D_
_x000D_
.imagebox {_x000D_
    width:200px;_x000D_
    float:left;_x000D_
    height:88px;_x000D_
    position:relative;_x000D_
    background-color: #999;_x000D_
}_x000D_
.container {_x000D_
    width:600px;_x000D_
    height:176px;_x000D_
    background-color: #666;_x000D_
    position:relative;_x000D_
    overflow:hidden;_x000D_
}_x000D_
.text {_x000D_
    color: #000;_x000D_
    font-size: 11px;_x000D_
    font-family: robotomeduim, sans-serif;_x000D_
    vertical-align:top;_x000D_
    _x000D_
}_x000D_
_x000D_
.imagebox img{ display:block;}
_x000D_
<div class="container">_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
    <div class="imagebox">_x000D_
        <img src="http://machdiamonds.com/n69xvs.jpg" /> <span class="text">Image title</span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

or you can edit the code a JS FIDDLE

How can I create a simple index.html file which lists all files/directories?

There are enough valid reasons to explicitly disable automatic directory indexes in apache or other web servers. Or, for example, you might only want to include certain file types in the index. In such cases you might still want to have a statically generated index.html file for specific folders.

tree

tree is a minimalistic utility that is available on most unix-like systems (ubuntu/debian: sudo apt install tree, mac: brew install tree, windows: zip) and which can generate plain text, XML, JSON or HTML output.

Generate an HTML directory index one level deep:

tree -H '.' -L 1 --noreport --charset utf-8 > index.html

Only include specific file types that match a glob pattern, e.g. *.zip files:

tree -H '.' -L 1 --noreport --charset utf-8 -P "*.zip" > index.html

The argument to -H is what will be used as a base href, so you can pass either a relative path such as . or an absolute path from the web root, such as /files. -L 1 limits the listing to the current directory only.

Generator script with recursive traversal

I needed an index generator which I could style the way I want, and which would also include the file sizes, so ended up using this script — in addition to having customizable styling, the script can also recursively generate an index.html file in all the nested subdirectories.

Update: an updated version (python 3) of the index generation script that uses cleaner styling (inspired by caddyserver's file-server module), includes last modified times and is more responsive in mobile viewports.

ERROR 1049 (42000): Unknown database

Its a common error which happens when we try to access a database which doesn't exist. So create the database using

CREATE DATABASE blog_development;

The error commonly occours when we have dropped the database using

DROP DATABASE blog_development;

and then try to access the database.

JavaFX FXML controller - constructor vs initialize method

In a few words: The constructor is called first, then any @FXML annotated fields are populated, then initialize() is called.

This means the constructor does not have access to @FXML fields referring to components defined in the .fxml file, while initialize() does have access to them.

Quoting from the Introduction to FXML:

[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.

bash "if [ false ];" returns true instead of false -- why?

A Quick Boolean Primer for Bash

The if statement takes a command as an argument (as do &&, ||, etc.). The integer result code of the command is interpreted as a boolean (0/null=true, 1/else=false).

The test statement takes operators and operands as arguments and returns a result code in the same format as if. An alias of the test statement is [, which is often used with if to perform more complex comparisons.

The true and false statements do nothing and return a result code (0 and 1, respectively). So they can be used as boolean literals in Bash. But if you put the statements in a place where they're interpreted as strings, you'll run into issues. In your case:

if [ foo ]; then ... # "if the string 'foo' is non-empty, return true"
if foo; then ...     # "if the command foo succeeds, return true"

So:

if [ true  ] ; then echo "This text will always appear." ; fi;
if [ false ] ; then echo "This text will always appear." ; fi;
if true      ; then echo "This text will always appear." ; fi;
if false     ; then echo "This text will never appear."  ; fi;

This is similar to doing something like echo '$foo' vs. echo "$foo".

When using the test statement, the result depends on the operators used.

if [ "$foo" = "$bar" ]   # true if the string values of $foo and $bar are equal
if [ "$foo" -eq "$bar" ] # true if the integer values of $foo and $bar are equal
if [ -f "$foo" ]         # true if $foo is a file that exists (by path)
if [ "$foo" ]            # true if $foo evaluates to a non-empty string
if foo                   # true if foo, as a command/subroutine,
                         # evaluates to true/success (returns 0 or null)

In short, if you just want to test something as pass/fail (aka "true"/"false"), then pass a command to your if or && etc. statement, without brackets. For complex comparisons, use brackets with the proper operators.

And yes, I'm aware there's no such thing as a native boolean type in Bash, and that if and [ and true are technically "commands" and not "statements"; this is just a very basic, functional explanation.

Android ImageView Zoom-in and Zoom-Out

It's old, but this may help someone else.

Below TouchImageView class supports both zooming in/out on either pinch or double tap

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;

public class TouchImageView extends ImageView implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {

    Matrix matrix;

    // We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // Remember some things for zooming
    PointF last = new PointF();
    PointF start = new PointF();
    float minScale = 1f;
    float maxScale = 3f;
    float[] m;

    int viewWidth, viewHeight;
    static final int CLICK = 3;
    float saveScale = 1f;
    protected float origWidth, origHeight;
    int oldMeasuredWidth, oldMeasuredHeight;

    ScaleGestureDetector mScaleDetector;

    Context context;

    public TouchImageView(Context context) {
        super(context);
        sharedConstructing(context);
    }

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

    GestureDetector mGestureDetector;

    private void sharedConstructing(Context context) {
        super.setClickable(true);
        this.context = context;
        mGestureDetector = new GestureDetector(context, this);
        mGestureDetector.setOnDoubleTapListener(this);

        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        matrix = new Matrix();
        m = new float[9];
        setImageMatrix(matrix);
        setScaleType(ScaleType.MATRIX);

        setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mScaleDetector.onTouchEvent(event);
                mGestureDetector.onTouchEvent(event);

                PointF curr = new PointF(event.getX(), event.getY());

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        last.set(curr);
                        start.set(last);
                        mode = DRAG;
                        break;

                    case MotionEvent.ACTION_MOVE:
                        if (mode == DRAG) {
                            float deltaX = curr.x - last.x;
                            float deltaY = curr.y - last.y;
                            float fixTransX = getFixDragTrans(deltaX, viewWidth,
                                    origWidth * saveScale);
                            float fixTransY = getFixDragTrans(deltaY, viewHeight,
                                    origHeight * saveScale);
                            matrix.postTranslate(fixTransX, fixTransY);
                            fixTrans();
                            last.set(curr.x, curr.y);
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                        mode = NONE;
                        int xDiff = (int) Math.abs(curr.x - start.x);
                        int yDiff = (int) Math.abs(curr.y - start.y);
                        if (xDiff < CLICK && yDiff < CLICK)
                            performClick();
                        break;

                    case MotionEvent.ACTION_POINTER_UP:
                        mode = NONE;
                        break;
                }

                setImageMatrix(matrix);
                invalidate();
                return true; // indicate event was handled
            }

        });
    }

    public void setMaxZoom(float x) {
        maxScale = x;
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        // Double tap is detected
        Log.i("MAIN_TAG", "Double tap detected");
        float origScale = saveScale;
        float mScaleFactor;

        if (saveScale == maxScale) {
            saveScale = minScale;
            mScaleFactor = minScale / origScale;
        } else {
            saveScale = maxScale;
            mScaleFactor = maxScale / origScale;
        }

        matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
                viewHeight / 2);

        fixTrans();
        return false;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    private class ScaleListener extends
            ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            mode = ZOOM;
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            float mScaleFactor = detector.getScaleFactor();
            float origScale = saveScale;
            saveScale *= mScaleFactor;
            if (saveScale > maxScale) {
                saveScale = maxScale;
                mScaleFactor = maxScale / origScale;
            } else if (saveScale < minScale) {
                saveScale = minScale;
                mScaleFactor = minScale / origScale;
            }

            if (origWidth * saveScale <= viewWidth
                    || origHeight * saveScale <= viewHeight)
                matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
                        viewHeight / 2);
            else
                matrix.postScale(mScaleFactor, mScaleFactor,
                        detector.getFocusX(), detector.getFocusY());

            fixTrans();
            return true;
        }
    }

    void fixTrans() {
        matrix.getValues(m);
        float transX = m[Matrix.MTRANS_X];
        float transY = m[Matrix.MTRANS_Y];

        float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
        float fixTransY = getFixTrans(transY, viewHeight, origHeight
                * saveScale);

        if (fixTransX != 0 || fixTransY != 0)
            matrix.postTranslate(fixTransX, fixTransY);
    }

    float getFixTrans(float trans, float viewSize, float contentSize) {
        float minTrans, maxTrans;

        if (contentSize <= viewSize) {
            minTrans = 0;
            maxTrans = viewSize - contentSize;
        } else {
            minTrans = viewSize - contentSize;
            maxTrans = 0;
        }

        if (trans < minTrans)
            return -trans + minTrans;
        if (trans > maxTrans)
            return -trans + maxTrans;
        return 0;
    }

    float getFixDragTrans(float delta, float viewSize, float contentSize) {
        if (contentSize <= viewSize) {
            return 0;
        }
        return delta;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        viewWidth = MeasureSpec.getSize(widthMeasureSpec);
        viewHeight = MeasureSpec.getSize(heightMeasureSpec);

        //
        // Rescales image on rotation
        //
        if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight
                || viewWidth == 0 || viewHeight == 0)
            return;
        oldMeasuredHeight = viewHeight;
        oldMeasuredWidth = viewWidth;

        if (saveScale == 1) {
            // Fit to screen.
            float scale;

            Drawable drawable = getDrawable();
            if (drawable == null || drawable.getIntrinsicWidth() == 0
                    || drawable.getIntrinsicHeight() == 0)
                return;
            int bmWidth = drawable.getIntrinsicWidth();
            int bmHeight = drawable.getIntrinsicHeight();

            Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight);

            float scaleX = (float) viewWidth / (float) bmWidth;
            float scaleY = (float) viewHeight / (float) bmHeight;
            scale = Math.min(scaleX, scaleY);
            matrix.setScale(scale, scale);

            // Center the image
            float redundantYSpace = (float) viewHeight
                    - (scale * (float) bmHeight);
            float redundantXSpace = (float) viewWidth
                    - (scale * (float) bmWidth);
            redundantYSpace /= (float) 2;
            redundantXSpace /= (float) 2;

            matrix.postTranslate(redundantXSpace, redundantYSpace);

            origWidth = viewWidth - 2 * redundantXSpace;
            origHeight = viewHeight - 2 * redundantYSpace;
            setImageMatrix(matrix);
        }
        fixTrans();
    }
}

Usage: You can replace your ImageView with TouchImageView in both XML & java

1. For XML

<?xml version="1.0" encoding="utf-8"?>
<com.example.android.myapp.TouchImageView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/imViewedImage"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:focusable="true" />

2. For Java

TouchImageView imViewedImage = findViewById(R.id.imViewedImage);

Checking network connection

Taking unutbu's answer as a starting point, and having been burned in the past by a "static" IP address changing, I've made a simple class that checks once using a DNS lookup (i.e., using the URL "https://www.google.com"), and then stores the IP address of the responding server for use on subsequent checks. That way, the IP address is always up to date (assuming the class is re-initialized at least once every few years or so). I also give credit to gawry for this answer, which showed me how to get the server's IP address (after any redirection, etc.). Please disregard the apparent hackiness of this solution, I'm going for a minimal working example here. :)

Here is what I have:

import socket

try:
    from urllib2 import urlopen, URLError
    from urlparse import urlparse
except ImportError:  # Python 3
    from urllib.parse import urlparse
    from urllib.request import urlopen, URLError

class InternetChecker(object):
    conn_url = 'https://www.google.com/'

    def __init__(self):
        pass

    def test_internet(self):
        try:
            data = urlopen(self.conn_url, timeout=5)
        except URLError:
            return False

        try:
            host = data.fp._sock.fp._sock.getpeername()
        except AttributeError:  # Python 3
            host = data.fp.raw._sock.getpeername()

        # Ensure conn_url is an IPv4 address otherwise future queries will fail
        self.conn_url = 'http://' + (host[0] if len(host) == 2 else
                                     socket.gethostbyname(urlparse(data.geturl()).hostname))

        return True

# Usage example
checker = InternetChecker()
checker.test_internet()

How do I pretty-print existing JSON data with Java?

I think for pretty-printing something, it's very helpful to know its structure.

To get the structure you have to parse it. Because of this, I don't think it gets much easier than first parsing the JSON string you have and then using the pretty-printing method toString mentioned in the comments above.

Of course you can do similar with any JSON library you like.

How to remove single character from a String

To modify Strings, read about StringBuilder because it is mutable except for immutable String. Different operations can be found here https://docs.oracle.com/javase/tutorial/java/data/buffers.html. The code snippet below creates a StringBuilder and then append the given String and then delete the first character from the String and then convert it back from StringBuilder to a String.

StringBuilder sb = new StringBuilder();

sb.append(str);
sb.deleteCharAt(0);
str = sb.toString();

Allow a div to cover the whole page instead of the area within the container

Try this

#dimScreen {
    width: 100%;
    height: 100%;
    background:rgba(255,255,255,0.5);
    position: fixed;
    top: 0;
    left: 0;
}

How good is Java's UUID.randomUUID?

At a former employer we had a unique column that contained a random uuid. We got a collision the first week after it was deployed. Sure, the odds are low but they aren't zero. That is why Log4j 2 contains UuidUtil.getTimeBasedUuid. It will generate a UUID that is unique for 8,925 years so long as you don't generate more than 10,000 UUIDs/millisecond on a single server.

How to get the second column from command output?

Or use sed & regex.

<some_command> | sed 's/^.* \(".*"$\)/\1/'

C++ Get name of type in template

The solution is

typeid(T).name()

which returns std::type_info.

Load dimension value from res/values/dimension.xml from source code

The Resource class also has a method getDimensionPixelSize() which I think will fit your needs.

How to add local .jar file dependency to build.gradle file?

Goto File -> Project Structure -> Modules -> app -> Dependencies Tab -> Click on +(button) -> Select File Dependency - > Select jar file in the lib folder

This steps will automatically add your dependency to gralde

Very Simple

Update ViewPager dynamically?

For some reason none of the answers worked for me so I had to override the restoreState method without calling super in my fragmentStatePagerAdapter. Code:

private class MyAdapter extends FragmentStatePagerAdapter {

    // [Rest of implementation]

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {}

}

Git checkout: updating paths is incompatible with switching branches

I suspect there is no remote branch named remote-name, but that you've inadvertently created a local branch named origin/remote-name.

Is it possible you at some point typed:

git branch origin/remote-name

Thus creating a local branch named origin/remote-name? Type this command:

git checkout origin/remote-name

You'll either see:

Switched to branch "origin/remote-name"

which means it's really a mis-named local branch, or

Note: moving to "origin/rework-isscoring" which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
  git checkout -b 

which means it really is a remote branch.

Subset and ggplot2

Here 2 options for subsetting:

Using subset from base R:

library(ggplot2)
ggplot(subset(dat,ID %in% c("P1" , "P3"))) + 
         geom_line(aes(Value1, Value2, group=ID, colour=ID))

Using subset the argument of geom_line(Note I am using plyr package to use the special . function).

library(plyr)
ggplot(data=dat)+ 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
                ,subset = .(ID %in% c("P1" , "P3")))

You can also use the complementary subsetting:

subset(dat,ID != "P2")

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

You can use following commands to extract public/private key from a PKCS#12 container:

  • PKCS#1 Private key

    openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem
    
  • Certificates:

    openssl pkcs12 -in yourP12File.pfx -clcerts -nokeys -out publicCert.pem
    

How to delete all instances of a character in a string in python?

# s1 == source string
# char == find this character
# repl == replace with this character
def findreplace(s1, char, repl):
    s1 = s1.replace(char, repl)
    return s1

# find each 'i' in the string and replace with a 'u'
print findreplace('it is icy', 'i', 'u')
# output
''' ut us ucy '''

How to create string with multiple spaces in JavaScript

You can use the <pre> tag with innerHTML. The HTML <pre> element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional ("monospace") font. Whitespace inside this element is displayed as written. If you don't want a different font, simply add pre as a selector in your CSS file and style it as desired.

Ex:

var a = '<pre>something        something</pre>';
document.body.innerHTML = a;

TLS 1.2 in .NET Framework 4.0

I code in VB and was able to add the following line to my Global.asax.vb file inside of Application_Start

ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)    'TLS 1.2

HTML checkbox onclick called in Javascript

How about putting the checkbox into the label, making the label automatically "click sensitive" for the check box, and giving the checkbox a onchange event?

<label ..... ><input type="checkbox" onchange="toggleCheckbox(this)" .....> 

function toggleCheckbox(element)
 {
   element.checked = !element.checked;
 }

This will additionally catch users using a keyboard to toggle the check box, something onclick would not.

How to hide UINavigationBar 1px bottom line

In Swift 3 we do this way

For any view controller:

navigationBar.shadowImage = UIImage()
setBackgroundImage(UIImage(), for: .default)

For an entire app:

UINavigationBar.appearance().setBackgroundImage(UIImage(),barMetrics: .Default)
UINavigationBar.appearance().shadowImage = UIImage()

Proper way to set response status and JSON content in a REST API made with nodejs and express

try {
  var data = {foo: "bar"};
  res.json(JSON.stringify(data));
}
catch (e) {
  res.status(500).json(JSON.stringify(e));
}

Check if a file exists with wildcard in shell script

Found a couple of neat solutions worth sharing. The first still suffers from "this will break if there's too many matches" problem:

pat="yourpattern*" matches=($pat) ; [[ "$matches" != "$pat" ]] && echo "found"

(Recall that if you use an array without the [ ] syntax, you get the first element of the array.)

If you have "shopt -s nullglob" in your script, you could simply do:

matches=(yourpattern*) ; [[ "$matches" ]] && echo "found"

Now, if it's possible to have a ton of files in a directory, you're pretty well much stuck with using find:

find /path/to/dir -maxdepth 1 -type f -name 'yourpattern*' | grep -q '.' && echo 'found'

Authentication issue when debugging in VS2013 - iis express

As I was researching this I found my answer, but can't find the answer on the internet, so I thought I'd share this:

I fixed my issue by modifying my applicationhost.config file. My file was saved in the "\My Documents\IISExpress\config" folder.

It seems that VS2013 was ignoring my web.config file and applying different authentication methods.

I had to modify this portion of the file to look like the below. In truth, I only modified the anonymousAuthentication to be false and the windowsAuthentication mode to true.

<authentication>

  <anonymousAuthentication enabled="false" userName="" />

  <basicAuthentication enabled="false" />

  <clientCertificateMappingAuthentication enabled="false" />

  <digestAuthentication enabled="false" />

  <iisClientCertificateMappingAuthentication enabled="false">
  </iisClientCertificateMappingAuthentication>

  <windowsAuthentication enabled="true">
    <providers>
      <add value="Negotiate" />
      <add value="NTLM" />
    </providers>
  </windowsAuthentication>

</authentication>

Trigger change() event when setting <select>'s value with val() function

The straight answer is already in a duplicate question: Why does the jquery change event not trigger when I set the value of a select using val()?

As you probably know setting the value of the select doesn't trigger the change() event, if you're looking for an event that is fired when an element's value has been changed through JS there isn't one.

If you really want to do this I guess the only way is to write a function that checks the DOM on an interval and tracks changed values, but definitely don't do this unless you must (not sure why you ever would need to)

Added this solution:
Another possible solution would be to create your own .val() wrapper function and have it trigger a custom event after setting the value through .val(), then when you use your .val() wrapper to set the value of a <select> it will trigger your custom event which you can trap and handle.

Be sure to return this, so it is chainable in jQuery fashion

How to have a drop down <select> field in a rails form?

Rails drop down using has_many association for article and category:

has_many :articles

belongs_to :category

<%= form.select :category_id,Category.all.pluck(:name,:id),{prompt:'select'},{class: "form-control"}%>

CSS3 Transition - Fade out effect

You forgot to add a position property to the .dummy-wrap class, and the top/left/bottom/right values don't apply to statically positioned elements (the default)

http://jsfiddle.net/dYBD2/2/

Error: Cannot pull with rebase: You have unstaged changes

This works for me:

git fetch
git rebase --autostash FETCH_HEAD

How to directly execute SQL query in C#?

Something like this should suffice, to do what your batch file was doing (dumping the result set as semi-colon delimited text to the console):

// sqlcmd.exe
// -S .\PDATA_SQLEXPRESS
// -U sa
// -P 2BeChanged!
// -d PDATA_SQLEXPRESS
// -s ; -W -w 100
// -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "

DataTable dt            = new DataTable() ;
int       rows_returned ;

const string credentials = @"Server=(localdb)\.\PDATA_SQLEXPRESS;Database=PDATA_SQLEXPRESS;User ID=sa;Password=2BeChanged!;" ;
const string sqlQuery = @"
  select tPatCulIntPatIDPk ,
         tPatSFirstname    ,
         tPatSName         ,
         tPatDBirthday
  from dbo.TPatientRaw
  where tPatSName = @patientSurname
  " ;

using ( SqlConnection connection = new SqlConnection(credentials) )
using ( SqlCommand    cmd        = connection.CreateCommand() )
using ( SqlDataAdapter sda       = new SqlDataAdapter( cmd ) )
{
  cmd.CommandText = sqlQuery ;
  cmd.CommandType = CommandType.Text ;
  connection.Open() ;
  rows_returned = sda.Fill(dt) ;
  connection.Close() ;
}

if ( dt.Rows.Count == 0 )
{
  // query returned no rows
}
else
{

  //write semicolon-delimited header
  string[] columnNames = dt.Columns
                           .Cast<DataColumn>()
                           .Select( c => c.ColumnName )
                           .ToArray()
                           ;
  string   header      = string.Join("," , columnNames) ;
  Console.WriteLine(header) ;

  // write each row
  foreach ( DataRow dr in dt.Rows )
  {

    // get each rows columns as a string (casting null into the nil (empty) string
    string[] values = new string[dt.Columns.Count];
    for ( int i = 0 ; i < dt.Columns.Count ; ++i )
    {
      values[i] = ((string) dr[i]) ?? "" ; // we'll treat nulls as the nil string for the nonce
    }

    // construct the string to be dumped, quoting each value and doubling any embedded quotes.
    string data = string.Join( ";" , values.Select( s => "\""+s.Replace("\"","\"\"")+"\"") ) ;
    Console.WriteLine(values);

  }

}

How to get all groups that a user is a member of?

Get-Member is a cmdlet for listing the members of a .NET object. This has nothing to do with user/group membership. You can get the current user's group membership like so:

PS> [System.Security.Principal.WindowsIdentity]::GetCurrent().Groups | 
         Format-Table -auto

BinaryLength AccountDomainSid    Value
------------ ----------------    -----
          28 S-1-5-21-...        S-1-5-21-2229937839-1383249143-3977914998-513
          12                     S-1-1-0
          28 S-1-5-21-...        S-1-5-21-2229937839-1383249143-3977914998-1010
          28 S-1-5-21-...        S-1-5-21-2229937839-1383249143-3977914998-1003
          16                     S-1-5-32-545
...

If you need access to arbitrary users' group info then @tiagoinu suggestion of using the Quest AD cmdlets is a better way to go.

Visual studio code terminal, how to run a command with administrator rights?

Running as admin didn't help me. (also got errors with syscall: rename)

Turns out this error can also occur if files are locked by Windows.

This can occur if :

  • You are actually running the project
  • You have files open in both Visual Studio and VSCode.

Running as admin doesn't get around windows file locking.

I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error

Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.

Python reading from a file and saving to utf-8

Process text to and from Unicode at the I/O boundaries of your program using open with the encoding parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False) is the encoding used), so I recommend always explicitly using the encoding parameter for portability and clarity (Python 3 syntax below):

with open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with open(filename, 'w', encoding='utf8') as f:
    f.write(text)

If still using Python 2 or for Python 2/3 compatibility, the io module implements open with the same semantics as Python 3's open and exists in both versions:

import io
with io.open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with io.open(filename, 'w', encoding='utf8') as f:
    f.write(text)

Problems installing the devtools package

I'm on windows and had the same issue.

I used the below code :

install.packages("devtools", type = "win.binary")

Then library(devtools) worked for me.

Bootstrap Alert Auto Close

one more solution for this Automatically close or fade away the bootstrap alert message after 5 seconds:

This is the HTML code used to display the message:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert alert-danger">_x000D_
This is an example message..._x000D_
</div>_x000D_
_x000D_
_x000D_
<script type="text/javascript">_x000D_
_x000D_
$(document).ready(function () {_x000D_
 _x000D_
window.setTimeout(function() {_x000D_
    $(".alert").fadeTo(1000, 0).slideUp(1000, function(){_x000D_
        $(this).remove(); _x000D_
    });_x000D_
}, 5000);_x000D_
 _x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

2D cross-platform game engine for Android and iOS?

V-Play (v-play.net) is a cross-platform game engine based on Qt/QML with many useful V-Play QML game components for handling multiple display resolutions & aspect ratios, animations, particles, physics, multi-touch, gestures, path finding and more. API reference The engine core is written in native C++, combined with the custom renderer, the games reach a solid performance of 60fps across all devices.

V-Play also comes with ready-to-use game templates for the most successful game genres like tower defense, platform games or puzzle games.

If you are curious about games made with V-Play, here is a quick selection of them:

(Disclaimer: I'm one of the guys behind V-Play)

WCF Service Returning "Method Not Allowed"

you need to add in web.config

<endpoint address="customBinding" binding="customBinding" bindingConfiguration="basicConfig" contract="WcfRest.IService1"/>  

<bindings>  
    <customBinding>  
        <binding name="basicConfig">  
            <binaryMessageEncoding/>  
            <httpTransport transferMode="Streamed" maxReceivedMessageSize="67108864"/>  
        </binding>  
    </customBinding> 

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

change your code to this

$start_date = new DateTime( "@" . $dbResult->db_timestamp );

and it will work fine

How to close an iframe within iframe itself

"Closing" the current iFrame is not possible but you can tell the parent to manipulate the dom and make it invisible.

In IFrame:

parent.closeIFrame();

In parent:

function closeIFrame(){
     $('#youriframeid').remove();
}

How do you configure HttpOnly cookies in tomcat / java webapps?

I Found in OWASP

<session-config>
  <cookie-config>
    <http-only>true</http-only>
  </cookie-config>
</session-config>

this is also fix for "httponlycookies in config" security issue

C# event with custom arguments

You need to declare a custom eventhandler.

public class MyEventArgs: EventArgs
{
  ...
}

public delegate void MyEventHandler(object sender, MyEventArgs e);

public class MyControl: UserControl
{
  public event MyEventHandler MyEvent;
   ...
}

Regular expression to search multiple strings (Textpad)

To get the lines that contain the texts 8768, 9875 or 2353, use:

^.*(8768|9875|2353).*$

What it means:

^                      from the beginning of the line
.*                     get any character except \n (0 or more times)
(8768|9875|2353)       if the line contains the string '8768' OR '9875' OR '2353'
.*                     and get any character except \n (0 or more times)
$                      until the end of the line

If you do want the literal * char, you'd have to escape it:

^.*(\*8768|\*9875|\*2353).*$

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Use component scanning as given below, if com.project.action.PasswordHintAction is annotated with stereotype annotations

<context:component-scan base-package="com.project.action"/>

EDIT

I see your problem, in PasswordHintActionTest you are autowiring PasswordHintAction. But you did not create bean configuration for PasswordHintAction to autowire. Add one of stereotype annotation(@Component, @Service, @Controller) to PasswordHintAction like

@Component
public class PasswordHintAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;

or create xml configuration in applicationcontext.xml like

<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />

Checking if an object is null in C#

No, you should be using !=. If data is actually null then your program will just crash with a NullReferenceException as a result of attempting to call the Equals method on null. Also realize that, if you specifically want to check for reference equality, you should use the Object.ReferenceEquals method as you never know how Equals has been implemented.

Your program is crashing because dataList is null as you never initialize it.

How to configure log4j.properties for SpringJUnit4ClassRunner?

I know this is old, but I was having trouble too. For Spring 3 using Maven and Eclipse, I needed to put the log4j.xml in src/test/resources for the Unit test to log properly. Placing in in the root of the test did not work for me. Hopefully this helps others.

How to style the parent element when hovering a child element?

As mentioned previously "there is no CSS selector for selecting a parent of a selected child".

So you either:


Here is the example for the javascript/jQuery solution

On the javascript side:

$('#my-id-selector-00').on('mouseover', function(){
  $(this).parent().addClass('is-hover');
}).on('mouseout', function(){
  $(this).parent().removeClass('is-hover');
})

And on the CSS side, you'd have something like this:

.is-hover {
  background-color: red;
}

How to get a matplotlib Axes instance to plot to?

You can either

fig, ax = plt.subplots()  #create figure and axes
candlestick(ax, quotes, ...)

or

candlestick(plt.gca(), quotes) #get the axis when calling the function

The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot

Implement a simple factory pattern with Spring 3 annotations

Try this:

public interface MyService {
 //Code
}

@Component("One")
public class MyServiceOne implements MyService {
 //Code
}

@Component("Two")
public class MyServiceTwo implements MyService {
 //Code
}

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I also had this issue while developping on HTML5 in local. I had issues with images and getImageData function. Finally, I discovered one can launch chrome with the --allow-file-access-from-file command switch, that get rid of this protection security. The only thing is that it makes your browser less safe, and you can't have one chrome instance with the flag on and another without the flag.

SQL Query to add a new column after an existing column in SQL Server 2005

ALTER won't do it because column order does not matter for storage or querying

If SQL Server, you'd have to use the SSMS Table Designer to arrange your columns, which can then generate a script which drops and recreates the table

Edit Jun 2013

Cross link to my answer here: Performance / Space implications when ordering SQL Server columns?

Dealing with commas in a CSV file

I used Csvreader library but by using that I got data by exploding from comma(,) in column value.

So If you want to insert CSV file data which contains comma(,) in most of the columns values, you can use below function. Author link => https://gist.github.com/jaywilliams/385876

function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

Any way to select without causing locking in MySQL?

Found an article titled "MYSQL WITH NOLOCK"

https://web.archive.org/web/20100814144042/http://sqldba.org/articles/22-mysql-with-nolock.aspx

in MS SQL Server you would do the following:

SELECT * FROM TABLE_NAME WITH (nolock)

and the MYSQL equivalent is

SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT * FROM TABLE_NAME ;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;

EDIT

Michael Mior suggested the following (from the comments)

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT * FROM TABLE_NAME ;
COMMIT ;

The input is not a valid Base-64 string as it contains a non-base 64 character

I get this error because a field was varbinary in sqlserver table instead of varchar.

Where can I read the Console output in Visual Studio 2015

You can run your program by: Debug -> Start Without Debugging. It will keep a console opened after the program will be finished.

enter image description here

Easy way to concatenate two byte arrays

Here's a nice solution using Guava's com.google.common.primitives.Bytes:

byte[] c = Bytes.concat(a, b);

The great thing about this method is that it has a varargs signature:

public static byte[] concat(byte[]... arrays)

which means that you can concatenate an arbitrary number of arrays in a single method call.

Resize a large bitmap file to scaled output file on Android

Taking into account that you want to resize to exact size and want to keep as much quality as needed I think you should try this.

  1. Find out the size of the resized image with call of BitmapFactory.decodeFile and providing the checkSizeOptions.inJustDecodeBounds
  2. Calculate the maximum possible inSampleSize you can use on your device to not exceed the memory. bitmapSizeInBytes = 2*width*height; Generally for your picture inSampleSize=2 would be fine since you will need only 2*1944x1296)=4.8Mb? which should feet in memory
  3. Use BitmapFactory.decodeFile with inSampleSize to load the Bitmap
  4. Scale the bitmap to exact size.

Motivation: multiple-steps scaling could give you higher quality picture, however there is no guarantee that it will work better than using high inSampleSize. Actually, I think that you also can use inSampleSize like 5 (not pow of 2) to have direct scaling in one operation. Or just use 4 and then you can just use that image in UI. if you send it to server - than you can do scaling to exact size on server side which allow you to use advanced scaling techniques.

Notes: if the Bitmap loaded in step-3 is at least 4 times larger (so the 4*targetWidth < width) you probably can use several resizing to achieve better quality. at least that works in generic java, in android you don't have the option to specify the interpolation used for scaling http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html

How to remove all white space from the beginning or end of a string?

string a = "   Hello   ";
string trimmed = a.Trim();

trimmed is now "Hello"

git is not installed or not in the PATH

If you installed GitHubDesktop then the path for git.exe will be ,

C:\Users\<'Username'>\AppData\Local\GitHubDesktop\app-1.1.1\resources\app\git\cmd

Add this path to the environment variables by following,

** (Note: \cmd at the end, not \cmd\git.exe).**

Navigate to the Environmental Variables Editor and find the Path variable in the “System Variables” section. Click Edit… and paste the URL of Git to the end. Save!

Now open a new cmd and type command git. If you are able to see the git usage then it's done.

Now you can execute your command to install your package.

ex: npm install native-base --save

What is the difference between int, Int16, Int32 and Int64?

They both are indeed synonymous, However i found the small difference between them,

1)You cannot use Int32 while creatingenum

enum Test : Int32
{ XXX = 1   // gives you compilation error
}

enum Test : int
{ XXX = 1   // Works fine
}

2) Int32 comes under System declaration. if you remove using.System you will get compilation error but not in case for int

how to run mysql in ubuntu through terminal

If you want to run your scripts, then

mysql -u root -p < yourscript.sql

JavaScript: Passing parameters to a callback function

When you have a callback that will be called by something other than your code with a specific number of params and you want to pass in additional params you can pass a wrapper function as the callback and inside the wrapper pass the additional param(s).

function login(accessedViaPopup) {
    //pass FB.login a call back function wrapper that will accept the
    //response param and then call my "real" callback with the additional param
    FB.login(function(response){
        fb_login_callback(response,accessedViaPopup);
    });
}

//handles respone from fb login call
function fb_login_callback(response, accessedViaPopup) {
    //do stuff
}

How to format dateTime in django template?

I suspect wpis.entry.lastChangeDate has been somehow transformed into a string in the view, before arriving to the template.

In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper, and then see if the template crashes.

You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.

On an unrelated notice, why don't you use models.DateTimeField(auto_now_add=True) to set the datetime on creation?

How can I search for a multiline pattern in a file?

perl -ne 'print if (/begin pattern/../end pattern/)' filename

Array inside a JavaScript Object?

_x000D_
_x000D_
var defaults = {_x000D_
_x000D_
  "background-color": "#000",_x000D_
  color: "#fff",_x000D_
  weekdays: [_x000D_
    {0: 'sun'},_x000D_
    {1: 'mon'},_x000D_
    {2: 'tue'},_x000D_
    {3: 'wed'},_x000D_
    {4: 'thu'},_x000D_
    {5: 'fri'},_x000D_
    {6: 'sat'}_x000D_
  ]_x000D_
_x000D_
};_x000D_
               _x000D_
console.log(defaults.weekdays[3]);
_x000D_
_x000D_
_x000D_

mysql data directory location

If the software is Sequel pro the default install mysql on Mac OSX has data located here:

/usr/local/var/mysql

Hibernate Group by Criteria Object

You can use the approach @Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:

    session.createCriteria(SomeTable.class)       
                    .add(Restrictions.ge("someColumn", xxxxx))      
                    .setProjection(Projections.projectionList()
                            .add(Projections.groupProperty("someColumn"))
                            .add(Projections.max("someColumn"))
                            .add(Projections.min("someColumn"))
                            .add(Projections.count("someColumn"))           
                    ).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));

List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

I recently just ran into this issue as well. I had a very large table in the dialog div. It was >15,000 rows. When the .empty() was called on the dialog div, I was getting the error above.

I found a round-about solution where before I call cleaning the dialog box, I would remove every other row from the very large table, then call the .empty(). It seemed to have worked though. It seems that my old version of JQuery can't handle such large elements.

Get first letter of a string from column

.str.get

This is the simplest to specify string methods

# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df

        A    B
0     xyz  123
1     abc  456
2  foobar  789

df.dtypes

A    object
B     int64
dtype: object

For string (read:object) type columns, use

df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)

.str handles NaNs by returning NaN as the output.

For non-numeric columns, an .astype conversion is required beforehand, as shown in @Ed Chum's answer.

# Note that this won't work well if the data has NaNs. 
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

List Comprehension and Indexing

There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.

# For string columns
df['C'] = [x[0] for x in df['A']]

# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

If your data has NaNs, then you will need to handle this appropriately with an if/else in the list comprehension,

df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2

        A      B
0     xyz  123.0
1     NaN  456.0
2  foobar    NaN

# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]

# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]

        A      B    C    D
0     xyz  123.0    x    1
1     NaN  456.0  NaN    4
2  foobar    NaN    f  NaN

Let's do some timeit tests on some larger data.

df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True) 

%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])

%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])

12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

List comprehensions are 4x faster.

How to concatenate two layers in keras?

Adding to the above-accepted answer so that it helps those who are using tensorflow 2.0


import tensorflow as tf

# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)

# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)

# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])

# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])

# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)

Result:

------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------

How can I initialize an ArrayList with all zeroes in Java?

The 60 you're passing is just the initial capacity for internal storage. It's a hint on how big you think it might be, yet of course it's not limited by that. If you need to preset values you'll have to set them yourself, e.g.:

for (int i = 0; i < 60; i++) {
    list.add(0);
}

Java 8 stream's .min() and .max(): why does this compile?

Comparator is a functional interface, and Integer::max complies with that interface (after autoboxing/unboxing is taken into consideration). It takes two int values and returns an int - just as you'd expect a Comparator<Integer> to (again, squinting to ignore the Integer/int difference).

However, I wouldn't expect it to do the right thing, given that Integer.max doesn't comply with the semantics of Comparator.compare. And indeed it doesn't really work in general. For example, make one small change:

for (int i = 1; i <= 20; i++)
    list.add(-i);

... and now the max value is -20 and the min value is -1.

Instead, both calls should use Integer::compare:

System.out.println(list.stream().max(Integer::compare).get());
System.out.println(list.stream().min(Integer::compare).get());

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

How to force uninstallation of windows service

well, you can use SC.EXE to delete any windows Service forcefully if un-install doesnt removes by any chance.

sc delete <Service_Name>

Read more on "MS Techno Blogging" Deleting Services Forcefully from Services MMC

How do I kill the process currently using a port on localhost in Windows?

Step 1 (same is in accepted answer written by KavinduWije):

netstat -ano | findstr :yourPortNumber

Change in Step 2 to:

tskill typeyourPIDhere 

Note: taskkill is not working in some git bash terminal

Oracle Error ORA-06512

I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

Might be worthwhile using the CultureInfo to apply DateTime formatting throughout the website. Insteado f running around formatting whever you have to.

CultureInfo.CurrentUICulture.DateTimeFormat.SetAllDateTimePatterns( ...

or

CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"; 

Code should go somewhere in your Global.asax file

protected void Application_Start(){ ...

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We faced the same problem:

ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log

In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.

Formatting Phone Numbers in PHP

Phone numbers are hard. For a more robust, international solution, I would recommend this well-maintained PHP port of Google's libphonenumber library.

Using it like this,

use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;

$phoneUtil = PhoneNumberUtil::getInstance();

$numberString = "+12123456789";

try {
    $numberPrototype = $phoneUtil->parse($numberString, "US");

    echo "Input: " .          $numberString . "\n";
    echo "isValid: " .       ($phoneUtil->isValidNumber($numberPrototype) ? "true" : "false") . "\n";
    echo "E164: " .           $phoneUtil->format($numberPrototype, PhoneNumberFormat::E164) . "\n";
    echo "National: " .       $phoneUtil->format($numberPrototype, PhoneNumberFormat::NATIONAL) . "\n";
    echo "International: " .  $phoneUtil->format($numberPrototype, PhoneNumberFormat::INTERNATIONAL) . "\n";
} catch (NumberParseException $e) {
    // handle any errors
}

you will get the following output:

Input: +12123456789
isValid: true
E164: +12123456789
National: (212) 345-6789
International: +1 212-345-6789

I'd recommend using the E164 format for duplicate checks. You could also check whether the number is a actually mobile number or not (using PhoneNumberUtil::getNumberType()), or whether it's even a US number (using PhoneNumberUtil::getRegionCodeForNumber()).

As a bonus, the library can handle pretty much any input. If you, for instance, choose to run 1-800-JETBLUE through the code above, you will get

Input: 1-800-JETBLUE
isValid: true
E164: +18005382583
National: (800) 538-2583
International: +1 800-538-2583

Neato.

It works just as nicely for countries other than the US. Just use another ISO country code in the parse() argument.

Giving UIView rounded corners

In Swift 4.2 and Xcode 10.1

let myView = UIView()
myView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
myView.myViewCorners()
//myView.myViewCorners(width: myView.frame.width)//Pass View width
view.addSubview(myView)

extension UIView {
    //If you want only round corners
    func myViewCorners() {
        layer.cornerRadius = 10
        layer.borderWidth = 1.0
        layer.borderColor = UIColor.red.cgColor
        layer.masksToBounds = true
    }
    //If you want complete round shape, enable above comment line
    func myViewCorners(width:CGFloat) {
        layer.cornerRadius = width/2
        layer.borderWidth = 1.0
        layer.borderColor = UIColor.red.cgColor
        layer.masksToBounds = true
    }
}

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

You can use Delorean to travel in space and time!

import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch

http://delorean.readthedocs.org/en/latest/quickstart.html  

`React/RCTBridgeModule.h` file not found

QUICK FIX (not the best)

Change the import react-native header lines:

 #import <React/RCTBridgeModule.h>
 #import <React/RCTLog.h>

To:

 #import "RCTBridgeModule.h"
 #import "RCTLog.h"

Here is an example of changes I had to make for the library I was trying to use: Closes #46 - 'RCTBridgeModule.h' file not found.

How can I group data with an Angular filter?

In addition to the accepted answers above I created a generic 'groupBy' filter using the underscore.js library.

JSFiddle (updated): http://jsfiddle.net/TD7t3/

The filter

app.filter('groupBy', function() {
    return _.memoize(function(items, field) {
            return _.groupBy(items, field);
        }
    );
});

Note the 'memoize' call. This underscore method caches the result of the function and stops angular from evaluating the filter expression every time, thus preventing angular from reaching the digest iterations limit.

The html

<ul>
    <li ng-repeat="(team, players) in teamPlayers | groupBy:'team'">
        {{team}}
        <ul>
            <li ng-repeat="player in players">
                {{player.name}}
            </li>
        </ul>
    </li>
</ul>

We apply our 'groupBy' filter on the teamPlayers scope variable, on the 'team' property. Our ng-repeat receives a combination of (key, values[]) that we can use in our following iterations.

Update June 11th 2014 I expanded the group by filter to account for the use of expressions as the key (eg nested variables). The angular parse service comes in quite handy for this:

The filter (with expression support)

app.filter('groupBy', function($parse) {
    return _.memoize(function(items, field) {
        var getter = $parse(field);
        return _.groupBy(items, function(item) {
            return getter(item);
        });
    });
});

The controller (with nested objects)

app.controller('homeCtrl', function($scope) {
    var teamAlpha = {name: 'team alpha'};
    var teamBeta = {name: 'team beta'};
    var teamGamma = {name: 'team gamma'};

    $scope.teamPlayers = [{name: 'Gene', team: teamAlpha},
                      {name: 'George', team: teamBeta},
                      {name: 'Steve', team: teamGamma},
                      {name: 'Paula', team: teamBeta},
                      {name: 'Scruath of the 5th sector', team: teamGamma}];
});

The html (with sortBy expression)

<li ng-repeat="(team, players) in teamPlayers | groupBy:'team.name'">
    {{team}}
    <ul>
        <li ng-repeat="player in players">
            {{player.name}}
        </li>
    </ul>
</li>

JSFiddle: http://jsfiddle.net/k7fgB/2/

How to change font in ipython notebook

In addition to the suggestion by Konrad here, I'd like to suggest jupyter themes, which seems to have more options, such as line-height, font size, cell width etc.

Command line usage:

jt  [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT]
[-nfs NBFONTSIZE] [-tf TCFONT] [-tfs TCFONTSIZE] [-dfs DFFONTSIZE]
[-m MARGINS] [-cursw CURSORWIDTH] [-cursc CURSORCOLOR] [-vim]
[-cellw CELLWIDTH] [-lineh LINEHEIGHT] [-altp] [-P] [-T] [-N]
[-r] [-dfonts]

How to copy JavaScript object to new variable NOT by reference?

Your only option is to somehow clone the object.

See this stackoverflow question on how you can achieve this.

For simple JSON objects, the simplest way would be:

var newObject = JSON.parse(JSON.stringify(oldObject));

if you use jQuery, you can use:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:

In ES6 or TypeScript (2.1+):

var shallowCopy = { ...oldObject };

var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };

Note that if extraProp is also a property on oldObject, its value will not be used because the extraProp : "abc" is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.

Send email with PHP from html form on submit with the same script

EDIT (#1)

If I understand correctly, you wish to have everything in one page and execute it from the same page.

You can use the following code to send mail from a single page, for example index.php or contact.php

The only difference between this one and my original answer is the <form action="" method="post"> where the action has been left blank.

It is better to use header('Location: thank_you.php'); instead of echo in the PHP handler to redirect the user to another page afterwards.

Copy the entire code below into one file.

<?php 
if(isset($_POST['submit'])){
    $to = "[email protected]"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html> 

Original answer


I wasn't quite sure as to what the question was, but am under the impression that a copy of the message is to be sent to the person who filled in the form.

Here is a tested/working copy of an HTML form and PHP handler. This uses the PHP mail() function.

The PHP handler will also send a copy of the message to the person who filled in the form.

You can use two forward slashes // in front of a line of code if you're not going to use it.

For example: // $subject2 = "Copy of your form submission"; will not execute.

HTML FORM:

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

PHP handler (mail_handler.php)

(Uses info from HTML form and sends the Email)

<?php 
if(isset($_POST['submit'])){
    $to = "[email protected]"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    // You cannot use header and echo together. It's one or the other.
    }
?>

To send as HTML:

If you wish to send mail as HTML and for both instances, then you will need to create two separate sets of HTML headers with different variable names.

Read the manual on mail() to learn how to send emails as HTML:


Footnotes:

  • In regards to HTML5

You have to specify the URL of the service that will handle the submitted data, using the action attribute.

As outlined at https://www.w3.org/TR/html5/forms.html under 4.10.1.3 Configuring a form to communicate with a server. For complete information, consult the page.

Therefore, action="" will not work in HTML5.

The proper syntax would be:

  • action="handler.xxx" or
  • action="http://www.example.com/handler.xxx".

Note that xxx will be the extension of the type of file used to handle the process. This could be a .php, .cgi, .pl, .jsp file extension etc.


Consult the following Q&A on Stack if sending mail fails:

Mean Squared Error in Numpy?

You can use:

mse = ((A - B)**2).mean(axis=ax)

Or

mse = (np.square(A - B)).mean(axis=ax)
  • with ax=0 the average is performed along the row, for each column, returning an array
  • with ax=1 the average is performed along the column, for each row, returning an array
  • with ax=None the average is performed element-wise along the array, returning a scalar value

Why is an OPTIONS request sent and can I disable it?

It can be solved in case of use of a proxy that intercept the request and write the appropriate headers. In the particular case of Varnish these would be the rules:

if (req.http.host == "CUSTOM_URL" ) {
set resp.http.Access-Control-Allow-Origin = "*";
if (req.method == "OPTIONS") {
   set resp.http.Access-Control-Max-Age = "1728000";
   set resp.http.Access-Control-Allow-Methods = "GET, POST, PUT, DELETE, PATCH, OPTIONS";
   set resp.http.Access-Control-Allow-Headers = "Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since";
   set resp.http.Content-Length = "0";
   set resp.http.Content-Type = "text/plain charset=UTF-8";
   set resp.status = 204;
}

}

"PKIX path building failed" and "unable to find valid certification path to requested target"

When you have above error with atlassian software ex. jira

2018-08-18 11:35:00,312 Caesium-1-4 WARN anonymous    Default Mail Handler [c.a.mail.incoming.mailfetcherservice] Default Mail Handler[10001]: javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target while connecting to host 'imap.xyz.pl' as user '[email protected]' via protocol 'imaps, caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

you can add certs to it's trusted keystore (change missing_ca to proper cert name):

keytool -importcert -file missing_ca.crt -alias missing_ca -keystore /opt/atlassian/jira/jre/lib/security/cacerts

If asked for password put changeit and confirm y

After that simply restart jira.

AngularJS- Login and Authentication in each route and controller

You should check user authentication in two main sites.

  • When users change state, checking it using '$routeChangeStart' callback
  • When a $http request is sent from angular, using an interceptor.

How to clear radio button in Javascript?

In my case this got the job done:

const chbx = document.getElementsByName("input_name");

for(let i=0; i < chbx.length; i++) {
    chbx[i].checked = false;
}

How can I hide/show a div when a button is clicked?

This works:

_x000D_
_x000D_
     function showhide(id) {_x000D_
        var e = document.getElementById(id);_x000D_
        e.style.display = (e.style.display == 'block') ? 'none' : 'block';_x000D_
     }
_x000D_
    <!DOCTYPE html>_x000D_
    <html>   _x000D_
    <body>_x000D_
    _x000D_
     <a href="javascript:showhide('uniquename')">_x000D_
      Click to show/hide._x000D_
     </a>_x000D_
    _x000D_
     <div id="uniquename" style="display:none;">_x000D_
      <p>Content goes here.</p>_x000D_
     </div>_x000D_
    _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Pass arguments to Constructor in VBA

Here's a little trick I'm using lately and brings good results. I would like to share with those who have to fight often with VBA.

1.- Implement a public initiation subroutine in each of your custom classes. I call it InitiateProperties throughout all my classes. This method has to accept the arguments you would like to send to the constructor.

2.- Create a module called factory, and create a public function with the word "Create" plus the same name as the class, and the same incoming arguments as the constructor needs. This function has to instantiate your class, and call the initiation subroutine explained in point (1), passing the received arguments. Finally returned the instantiated and initiated method.

Example:

Let's say we have the custom class Employee. As the previous example, is has to be instantiated with name and age.

This is the InitiateProperties method. m_name and m_age are our private properties to be set.

Public Sub InitiateProperties(name as String, age as Integer)

    m_name = name
    m_age = age

End Sub

And now in the factory module:

Public Function CreateEmployee(name as String, age as Integer) as Employee

    Dim employee_obj As Employee
    Set employee_obj = new Employee

    employee_obj.InitiateProperties name:=name, age:=age
    set CreateEmployee = employee_obj

End Function

And finally when you want to instantiate an employee

Dim this_employee as Employee
Set this_employee = factory.CreateEmployee(name:="Johnny", age:=89)

Especially useful when you have several classes. Just place a function for each in the module factory and instantiate just by calling factory.CreateClassA(arguments), factory.CreateClassB(other_arguments), etc.

EDIT

As stenci pointed out, you can do the same thing with a terser syntax by avoiding to create a local variable in the constructor functions. For instance the CreateEmployee function could be written like this:

Public Function CreateEmployee(name as String, age as Integer) as Employee

    Set CreateEmployee = new Employee
    CreateEmployee.InitiateProperties name:=name, age:=age

End Function

Which is nicer.

Creating C formatted strings (not printing them)

http://www.gnu.org/software/hello/manual/libc/Variable-Arguments-Output.html gives the following example to print to stderr. You can modify it to use your log function instead:

 #include <stdio.h>
 #include <stdarg.h>

 void
 eprintf (const char *template, ...)
 {
   va_list ap;
   extern char *program_invocation_short_name;

   fprintf (stderr, "%s: ", program_invocation_short_name);
   va_start (ap, template);
   vfprintf (stderr, template, ap);
   va_end (ap);
 }

Instead of vfprintf you will need to use vsprintf where you need to provide an adequate buffer to print into.

Change value in a cell based on value in another cell

If you want to do something like the following example, you'd have to use nested ifs.

If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.

Here's how you'd do it:

=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))

Datetime in where clause

Use a convert function to get all entries for a particular day.

Select * from tblErrorLog where convert(date,errorDate,101) = '12/20/2008'

See CAST and CONVERT for more info

Read a zipped file as a pandas DataFrame

If you want to read a zipped or a tar.gz file into pandas dataframe, the read_csv methods includes this particular implementation.

df = pd.read_csv('filename.zip')

Or the long form:

df = pd.read_csv('filename.zip', compression='zip', header=0, sep=',', quotechar='"')

Description of the compression argument from the docs:

compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’ For on-the-fly decompression of on-disk data. If ‘infer’ and filepath_or_buffer is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’ (otherwise no decompression). If using ‘zip’, the ZIP file must contain only one data file to be read in. Set to None for no decompression.

New in version 0.18.1: support for ‘zip’ and ‘xz’ compression.

Auto populate columns in one sheet from another sheet

In Google Sheets you can use =ArrayFormula(Sheet1!B2:B)on the first cell and it will populate all column contents not sure if that will work in excel

Is it possible to program iPhone in C++

I'm not sure about C++, but you can definitely code iPhone applications in C#, using a product called MonoTouch.

You can see this post for detailed discussion on MonoTouch Vs Obj-C: How to decide between MonoTouch and Objective-C?

Converting strings to floats in a DataFrame

df['MyColumnName'] = df['MyColumnName'].astype('float64') 

Provide schema while reading csv file as a dataframe

schema definition as simple string

Just in case if some one is interested in schema definition as simple string with date and time stamp

data file creation from Terminal or shell

echo " 
2019-07-02 22:11:11.000999, 01/01/2019, Suresh, abc  
2019-01-02 22:11:11.000001, 01/01/2020, Aadi, xyz 
" > data.csv

Defining the schema as String

    user_schema = 'timesta TIMESTAMP,date DATE,first_name STRING , last_name STRING'

reading the data

    df = spark.read.csv(path='data.csv', schema = user_schema, sep=',', dateFormat='MM/dd/yyyy',timestampFormat='yyyy-MM-dd HH:mm:ss.SSSSSS')

    df.show(10, False)

    +-----------------------+----------+----------+---------+
    |timesta                |date      |first_name|last_name|
    +-----------------------+----------+----------+---------+
    |2019-07-02 22:11:11.999|2019-01-01| Suresh   | abc     |
    |2019-01-02 22:11:11.001|2020-01-01| Aadi     | xyz     |
    +-----------------------+----------+----------+---------+

Please note defining the schema explicitly instead of letting spark infer the schema also improves the spark read performance.

Editing specific line in text file in Python

You want to do something like this:

# with is like your try .. finally block in this case
with open('stats.txt', 'r') as file:
    # read a list of lines into data
    data = file.readlines()

print data
print "Your name: " + data[0]

# now change the 2nd line, note that you have to add a newline
data[1] = 'Mage\n'

# and write everything back
with open('stats.txt', 'w') as file:
    file.writelines( data )

The reason for this is that you can't do something like "change line 2" directly in a file. You can only overwrite (not delete) parts of a file - that means that the new content just covers the old content. So, if you wrote 'Mage' over line 2, the resulting line would be 'Mageior'.

OS X Terminal Colors

If you are using tcsh, then edit your ~/.cshrc file to include the lines:

setenv CLICOLOR 1
setenv LSCOLORS dxfxcxdxbxegedabagacad

Where, like Martin says, LSCOLORS specifies the color scheme you want to use.

To generate the LSCOLORS you want to use, checkout this site

How to exit from ForEach-Object in PowerShell

Item #1. Putting a break within the foreach loop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:

$todo=$project.PropertyGroup 
foreach ($thing in $todo){
    if ($thing -eq 'some_condition'){
        break
    }
}

Item #2. PowerShell lets you modify an array within a foreach loop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.

$a=1,2,3
foreach ($value in $a){
  Write-Host $value
}
Write-Host $a

I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.

using favicon with css

There is no explicit way to change the favicon globally using CSS that I know of. But you can use a simple trick to change it on the fly.

First just name, or rename, the favicon to "favicon.ico" or something similar that will be easy to remember, or is relevant for the site you're working on. Then add the link to the favicon in the head as you usually would. Then when you drop in a new favicon just make sure it's in the same directory as the old one, and that it has the same name, and there you go!

It's not a very elegant solution, and it requires some effort. But dropping in a new favicon in one place is far easier than doing a find and replace of all the links, or worse, changing them manually. At least this way doesn't involve messing with the code.

Of course dropping in a new favicon with the same name will delete the old one, so make sure to backup the old favicon in case of disaster, or if you ever want to go back to the old design.

When to use AtomicReference in Java?

Here is a use case for AtomicReference:

Consider this class that acts as a number range, and uses individual AtmomicInteger variables to maintain lower and upper number bounds.

public class NumberRange {
    // INVARIANT: lower <= upper
    private final AtomicInteger lower = new AtomicInteger(0);
    private final AtomicInteger upper = new AtomicInteger(0);

    public void setLower(int i) {
        // Warning -- unsafe check-then-act
        if (i > upper.get())
            throw new IllegalArgumentException(
                    "can't set lower to " + i + " > upper");
        lower.set(i);
    }

    public void setUpper(int i) {
        // Warning -- unsafe check-then-act
        if (i < lower.get())
            throw new IllegalArgumentException(
                    "can't set upper to " + i + " < lower");
        upper.set(i);
    }

    public boolean isInRange(int i) {
        return (i >= lower.get() && i <= upper.get());
    }
}

Both setLower and setUpper are check-then-act sequences, but they do not use sufficient locking to make them atomic. If the number range holds (0, 10), and one thread calls setLower(5) while another thread calls setUpper(4), with some unlucky timing both will pass the checks in the setters and both modifications will be applied. The result is that the range now holds (5, 4)an invalid state. So while the underlying AtomicIntegers are thread-safe, the composite class is not. This can be fixed by using a AtomicReference instead of using individual AtomicIntegers for upper and lower bounds.

public class CasNumberRange {
    // Immutable
    private static class IntPair {
        final int lower;  // Invariant: lower <= upper
        final int upper;

        private IntPair(int lower, int upper) {
            this.lower = lower;
            this.upper = upper;
        }
    }

    private final AtomicReference<IntPair> values = 
            new AtomicReference<IntPair>(new IntPair(0, 0));

    public int getLower() {
        return values.get().lower;
    }

    public void setLower(int lower) {
        while (true) {
            IntPair oldv = values.get();
            if (lower > oldv.upper)
                throw new IllegalArgumentException(
                    "Can't set lower to " + lower + " > upper");
            IntPair newv = new IntPair(lower, oldv.upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }

    public int getUpper() {
        return values.get().upper;
    }

    public void setUpper(int upper) {
        while (true) {
            IntPair oldv = values.get();
            if (upper < oldv.lower)
                throw new IllegalArgumentException(
                    "Can't set upper to " + upper + " < lower");
            IntPair newv = new IntPair(oldv.lower, upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }
}

How to import .py file from another directory?

You can add to the system-path at runtime:

import sys
sys.path.insert(0, 'path/to/your/py_file')

import py_file

This is by far the easiest way to do it.

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

I've tried both these and still get failure due to conflicts. At the end of my patience, I cloned master in another location, copied everything into the other branch and committed it. which let me continue. The "-X theirs" option should have done this for me, but it did not.

git merge -s recursive -X theirs master

error: 'merge' is not possible because you have unmerged files. hint: Fix them up in the work tree, hint: and then use 'git add/rm ' as hint: appropriate to mark resolution and make a commit, hint: or use 'git commit -a'. fatal: Exiting because of an unresolved conflict.

java.lang.NoClassDefFoundError: org/json/JSONObject

No.. It is not proper way. Refer the steps,

For Classpath reference: Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.

For Deployment Assembly: Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.

This is the proper way! Don't forget to remove environment variable. It is not required now.

Try this. Surely it will work. Try to use Maven, it will simplify you task.

Append a dictionary to a dictionary

Assuming that you do not want to change orig, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:

from itertools import chain
dest = dict(chain(orig.items(), extra.items()))

Or without itertools:

dest = dict(list(orig.items()) + list(extra.items()))

Note that you only need to pass the result of items() into list() on Python 3, on 2.x dict.items() already returns a list so you can just do dict(orig.items() + extra.items()).

As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:

from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))

Failed to resolve: com.android.support:appcompat-v7:28.0

some guys who still might have the problem like me (FOR IRANIAN and all the coutries who have sanctions) , this is error can be fixed with proxy i used this free proxy for android studio 3.2 https://github.com/freedomofdevelopers/fod just to to Settings (Ctrl + Alt + S) and search HTTP proxy then check Manual proxy configuration then add fodev.org for host name and 8118 for Port number

Screenshot of proxy settings in android studio

React JS Error: is not defined react/jsx-no-undef

you should do import Map from './Map' React is just telling you it doesn't know where variable you are importing is.

Insert into a MySQL table or update if exists

Use INSERT ... ON DUPLICATE KEY UPDATE

QUERY:

INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
name="A", age=19

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

After a sequence of attempts I came into a facile solution. You can try Reinstalling ActiveX plugin for Adobe flashplayer.

Get client IP address via third party web service

Well, if in the HTML you import a script...

<script type="text/javascript" src="//stier.linuxfaq.org/ip.php"></script>

You can then use the variable userIP (which would be the visitor's IP address) anywhere on the page.

To redirect: <script>if (userIP == "555.555.555.55") {window.location.replace("http://192.168.1.3/flex-start/examples/navbar-fixed-top/");}</script>

Or to show it on the page: document.write (userIP);

DISCLAIMER: I am the author of the script I said to import. The script comes up with the IP by using PHP. The source code of the script is below.

<?php //Gets the IP address $ip = getenv("REMOTE_ADDR") ; Echo "var userIP = '" . $ip . "';"; ?>