Programs & Examples On #Sql data services

Set title background color

Try with the following code

View titleView = getWindow().findViewById(android.R.id.title);
    if (titleView != null) {
      ViewParent parent = titleView.getParent();
      if (parent != null && (parent instanceof View)) {
        View parentView = (View)parent;
        parentView.setBackgroundColor(Color.RED);
      }
    }

also use this link its very useful : http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/

Having both a Created and Last Updated timestamp columns in MySQL 4.0

For mysql 5.7.21 I use the following and works fine:

CREATE TABLE Posts ( modified_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP )

Java using enum with switch statement

This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.

tsconfig.json: Build:No inputs were found in config file

If you don't want TypeScript compilation, disable it in your .csproj file, according to this post.

Just add the following line to your .csproj file:

<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>

Edit and replay XHR chrome/firefox etc?

My two suggestions:

  1. Chrome's Postman plugin + the Postman Interceptor Plugin. More Info: Postman Capturing Requests Docs

  2. If you're on Windows then Telerik's Fiddler is an option. It has a composer option to replay http requests, and it's free.

Should IBOutlets be strong or weak under ARC?

WARNING, OUTDATED ANSWER: this answer is not up to date as per WWDC 2015, for the correct answer refer to the accepted answer (Daniel Hall) above. This answer will stay for record.


Summarized from the developer library:

From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create will therefore typically be weak by default, because:

  • Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.

  • The strong outlets are frequently specified by framework classes (for example, UIViewController’s view outlet, or NSWindowController’s window outlet).

    @property (weak) IBOutlet MyView *viewContainerSubview;
    @property (strong) IBOutlet MyOtherClass *topLevelObject;
    

Entity Framework The underlying provider failed on Open

I faced the same issue. Though in my case I was trying to connect my desktop application to a remote db. So for me, all the above didn't work. I solve this problem by just adding the port (as 128.02.39.29:3315) and it magically works! The reason why I didn't bother to add the port in the first place is because I used same approach (without the port) in another desktop app and it worked. So I hope this might help someone as well.

How to write a simple Java program that finds the greatest common divisor between two numbers?

public static int GCD(int x, int y) {   
    int r;
    while (y!=0) {
        r = x%y;
        x = y;
        y = r;
    }
    return x;
}

Could not autowire field:RestTemplate in Spring boot application

It's exactly what the error says. You didn't create any RestTemplate bean, so it can't autowire any. If you need a RestTemplate you'll have to provide one. For example, add the following to TestMicroServiceApplication.java:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Note, in earlier versions of the Spring cloud starter for Eureka, a RestTemplate bean was created for you, but this is no longer true.

How do we control web page caching, across all browsers?

The headers in the answer provided by BalusC does not prevent Safari 5 (and possibly older versions as well) from displaying content from the browser cache when using the browser's back button. A way to prevent this is to add an empty onunload event handler attribute to the body tag:

<body onunload=""> 

This hack apparently breaks the back-forward cache in Safari: Is there a cross-browser onload event when clicking the back button?

CSS: Truncate table cells, but fit as much as possible

Don't know if this will help anyone, but I solved a similar problem by specifying specific width sizes in percentage for each column. Obviously, this would work best if each column has content with width that doesn't vary too widely.

Difference between Git and GitHub

What is Git:

"Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency"

Git is a distributed peer-peer version control system. Each node in the network is a peer, storing entire repositories which can also act as a multi-node distributed back-ups. There is no specific concept of a central server although nodes can be head-less or 'bare', taking on a role similar to the central server in centralised version control systems.

What is GitHub:

"GitHub is a web-based Git repository hosting service, which offers all of the distributed revision control and source code management (SCM) functionality of Git as well as adding its own features."

Github provides access control and several collaboration features such as wikis, task management, and bug tracking and feature requests for every project.

You do not need GitHub to use Git.

GitHub (and any other local, remote or hosted system) can all be peers in the same distributed versioned repositories within a single project.

Github allows you to:

  • Share your repositories with others.
  • Access other user's repositories.
  • Store remote copies of your repositories (github servers) as backup of your local copies.

Make div stay at bottom of page's content all the time even when there are scrollbars

This is an intuitive solution using the viewport command that just sets the minimum height to the viewport height minus the footer height.

html,body{
height: 100%
}
#nonFooter{
min-height: calc(100vh - 30px)
}

#footer {
height:30px;
margin: 0;
clear: both;
width:100%;
}

Can regular JavaScript be mixed with jQuery?

You can, but be aware of the return types with jQuery functions. jQuery won't always use the exact same JavaScript object type, although generally they will return subclasses of what you would expect to be returned from a similar JavaScript function.

What are file descriptors, explained in simple terms?

In simple words, when you open a file, the operating system creates an entry to represent that file and store the information about that opened file. So if there are 100 files opened in your OS then there will be 100 entries in OS (somewhere in kernel). These entries are represented by integers like (...100, 101, 102....). This entry number is the file descriptor. So it is just an integer number that uniquely represents an opened file in operating system. If your process opens 10 files then your Process table will have 10 entries for file descriptors.

Similarly when you open a network socket, it is also represented by an integer and it is called Socket Descriptor. I hope you understand.

Is String.Contains() faster than String.IndexOf()?

Use a benchmark library, like this recent foray from Jon Skeet to measure it.

Caveat Emptor

As all (micro-)performance questions, this depends on the versions of software you are using, the details of the data inspected and the code surrounding the call.

As all (micro-)performance questions, the first step has to be to get a running version which is easily maintainable. Then benchmarking, profiling and tuning can be applied to the measured bottlenecks instead of guessing.

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

For this, I use FLAG_ACTIVITY_CLEAR_TOP flag for starting Intent
(without FLAG_ACTIVITY_NEW_TASK)

and launchMode = "singleTask" in manifest for launched activity.

Seems like it works as I need - activity does not restart and all other activities are closed.

Uncaught TypeError: data.push is not a function

I think you set it as

var data = []; 

but after some time you made it like:

data = 'some thing which is not an array'; 

then data.push('') will not work as it is not an array anymore.

How to append rows in a pandas dataframe in a for loop?

First, create a empty DataFrame with column names, after that, inside the for loop, you must define a dictionary (a row) with the data to append:

df = pd.DataFrame(columns=['A'])
for i in range(5):
    df = df.append({'A': i}, ignore_index=True)
df
   A
0  0
1  1
2  2
3  3
4  4

If you want to add a row with more columns, the code will looks like this:

df = pd.DataFrame(columns=['A','B','C'])
for i in range(5):
    df = df.append({'A': i,
                    'B': i * 2,
                    'C': i * 3,
                   }
                   ,ignore_index=True
                  )
df
    A   B   C
0   0   0   0
1   1   2   3
2   2   4   6
3   3   6   9
4   4   8   12

Source

Is there a command to list all Unix group names?

To list all local groups which have users assigned to them, use this command:

cut -d: -f1 /etc/group | sort

For more info- > Unix groups, Cut command, sort command

How to encrypt and decrypt file in Android?

You could use java-aes-crypto or Facebook's Conceal

java-aes-crypto

Quoting from the repo

A simple Android class for encrypting & decrypting strings, aiming to avoid the classic mistakes that most such classes suffer from.

Facebook's conceal

Quoting from the repo

Conceal provides easy Android APIs for performing fast encryption and authentication of data

Add an image in a WPF button

Please try the below XAML snippet:

<Button Width="300" Height="50">
  <StackPanel Orientation="Horizontal">
    <Image Source="Pictures/img.jpg" Width="20" Height="20"/>
    <TextBlock Text="Blablabla" VerticalAlignment="Center" />
  </StackPanel>
</Button>

In XAML elements are in a tree structure. So you have to add the child control to its parent control. The below code snippet also works fine. Give a name for your XAML root grid as 'MainGrid'.

Image img = new Image();
img.Source = new BitmapImage(new Uri(@"foo.png"));

StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);

Button btn = new Button();
btn.Content = stackPnl;
MainGrid.Children.Add(btn);

How to set up googleTest as a shared library on Linux

Update for Debian/Ubuntu

Google Mock (package: google-mock) and Google Test (package: libgtest-dev) have been merged. The new package is called googletest. Both old names are still available for backwards compatibility and now depend on the new package googletest.

So, to get your libraries from the package repository, you can do the following:

sudo apt-get install googletest -y
cd /usr/src/googletest
sudo mkdir build
cd build
sudo cmake ..
sudo make
sudo cp googlemock/*.a googlemock/gtest/*.a /usr/lib

After that, you can link against -lgmock (or against -lgmock_main if you do not use a custom main method) and -lpthread. This was sufficient for using Google Test in my cases at least.

If you want the most current version of Google Test, download it from github. After that, the steps are similar:

git clone https://github.com/google/googletest
cd googletest
sudo mkdir build
cd build
sudo cmake ..
sudo make
sudo cp lib/*.a /usr/lib

As you can see, the path where the libraries are created has changed. Keep in mind that the new path might be valid for the package repositories soon, too.

Instead of copying the libraries manually, you could use sudo make install. It "currently" works, but be aware that it did not always work in the past. Also, you don't have control over the target location when using this command and you might not want to pollute /usr/lib.

Build error: You must add a reference to System.Runtime

install https://www.microsoft.com/en-us/download/details.aspx?id=49978 Microsoft .NET Framework 4.6.1 Developer Pack and add this line of code in Web.config file

<compilation debug="true" targetFramework="4.5">
          <assemblies>
            <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
          </assemblies>
        </compilation>

What version of javac built my jar?

Developers and administrators running Bash may find these convenience functions helpful:

jar_jdk_version() {
  [[ -n "$1" && -x "`command -v javap`" ]] && javap -classpath "$1" -verbose $(jar -tf "$1" | grep '.class' | head -n1 | sed -e 's/\.class$//') | grep 'major version' | sed -e 's/[^0-9]\{1,\}//'
}

print_jar_jdk_version() {
  local version
  version=$(jar_jdk_version "$1")
  case $version in 49) version=1.5;; 50) version=1.6;; 51) version=1.7;; 52) version=1.8;; esac
  [[ -n "$version" ]] && echo "`basename "$1"` contains classes compiled with JDK version $version."
}

You can paste them in for one-time usage or add them to ~/.bash_aliases or ~/.bashrc. The results look something like:

$ jar_jdk_version poi-ooxml-3.5-FINAL.jar
49

and

$ print_jar_jdk_version poi-ooxml-3.5-FINAL.jar
poi-ooxml-3.5-FINAL.jar contains classes compiled with JDK version 1.5.

EDIT As jackrabbit points out, you can't 100% rely on the manifest to tell you anything useful. If it was, then you could pull it out in your favorite UNIX shell with unzip:

$ unzip -pa poi-ooxml-3.5-FINAL.jar META-INF/MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 11.3-b02 (Sun Microsystems Inc.)
Built-By: yegor
Specification-Title: Apache POI
Specification-Version: 3.5-FINAL-20090928
Specification-Vendor: Apache
Implementation-Title: Apache POI
Implementation-Version: 3.5-FINAL-20090928
Implementation-Vendor: Apache

This .jar doesn't have anything useful in the manifest about the contained classes.

Best way to get identity of inserted row?

When you use Entity Framework, it internally uses the OUTPUT technique to return the newly inserted ID value

DECLARE @generated_keys table([Id] uniqueidentifier)

INSERT INTO TurboEncabulators(StatorSlots)
OUTPUT inserted.TurboEncabulatorID INTO @generated_keys
VALUES('Malleable logarithmic casing');

SELECT t.[TurboEncabulatorID ]
FROM @generated_keys AS g 
   JOIN dbo.TurboEncabulators AS t 
   ON g.Id = t.TurboEncabulatorID 
WHERE @@ROWCOUNT > 0

The output results are stored in a temporary table variable, joined back to the table, and return the row value out of the table.

Note: I have no idea why EF would inner join the ephemeral table back to the real table (under what circumstances would the two not match).

But that's what EF does.

This technique (OUTPUT) is only available on SQL Server 2008 or newer.

Edit - The reason for the join

The reason that Entity Framework joins back to the original table, rather than simply use the OUTPUT values is because EF also uses this technique to get the rowversion of a newly inserted row.

You can use optimistic concurrency in your entity framework models by using the Timestamp attribute:

public class TurboEncabulator
{
   public String StatorSlots)

   [Timestamp]
   public byte[] RowVersion { get; set; }
}

When you do this, Entity Framework will need the rowversion of the newly inserted row:

DECLARE @generated_keys table([Id] uniqueidentifier)

INSERT INTO TurboEncabulators(StatorSlots)
OUTPUT inserted.TurboEncabulatorID INTO @generated_keys
VALUES('Malleable logarithmic casing');

SELECT t.[TurboEncabulatorID], t.[RowVersion]
FROM @generated_keys AS g 
   JOIN dbo.TurboEncabulators AS t 
   ON g.Id = t.TurboEncabulatorID 
WHERE @@ROWCOUNT > 0

And in order to retrieve this Timetsamp you cannot use an OUTPUT clause.

That's because if there's a trigger on the table, any Timestamp you OUTPUT will be wrong:

  • Initial insert. Timestamp: 1
  • OUTPUT clause outputs timestamp: 1
  • trigger modifies row. Timestamp: 2

The returned timestamp will never be correct if you have a trigger on the table. So you must use a separate SELECT.

And even if you were willing to suffer the incorrect rowversion, the other reason to perform a separate SELECT is that you cannot OUTPUT a rowversion into a table variable:

DECLARE @generated_keys table([Id] uniqueidentifier, [Rowversion] timestamp)

INSERT INTO TurboEncabulators(StatorSlots)
OUTPUT inserted.TurboEncabulatorID, inserted.Rowversion INTO @generated_keys
VALUES('Malleable logarithmic casing');

The third reason to do it is for symmetry. When performing an UPDATE on a table with a trigger, you cannot use an OUTPUT clause. Trying do UPDATE with an OUTPUT is not supported, and will give an error:

The only way to do it is with a follow-up SELECT statement:

UPDATE TurboEncabulators
SET StatorSlots = 'Lotus-O deltoid type'
WHERE ((TurboEncabulatorID = 1) AND (RowVersion = 792))

SELECT RowVersion
FROM TurboEncabulators
WHERE @@ROWCOUNT > 0 AND TurboEncabulatorID = 1

Make outer div be automatically the same height as its floating content

You can set the outerdiv's CSS to this

#outerdiv {
    overflow: hidden; /* make sure this doesn't cause unexpected behaviour */
}

You can also do this by adding an element at the end with clear: both. This can be added normally, with JS (not a good solution) or with :after CSS pseudo element (not widely supported in older IEs).

The problem is that containers won't naturally expand to include floated children. Be warned with using the first example, if you have any children elements outside the parent element, they will be hidden. You can also use 'auto' as the property value, but this will invoke scrollbars if any element appears outside.

You can also try floating the parent container, but depending on your design, this may be impossible/difficult.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

multipart/form-data encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded encoding. When using a different encoding, the request.getParameter() calls will all return null. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts() instead. Also see this blog for extended examples.

Prior to Servlet 3.0, a de facto standard to parse multipart/form-data requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).

HTML text input field with currency symbol

For bootstrap its works

<span class="form-control">$ <input type="text"/></span>

Don't use class="form-control" in input field.

How can I pop-up a print dialog box using Javascript?

I do this to make sure they remember to print landscape, which is necessary for a lot of pages on a lot of printers.

<a href="javascript:alert('Please be sure to set your printer to Landscape.');window.print();">Print Me...</a>

or

<body onload="alert('Please be sure to set your printer to Landscape.');window.print();">
etc.
</body>

How to access array elements in a Django template?

You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.

Python string prints as [u'String']

[u'String'] is a text representation of a list that contains a Unicode string on Python 2.

If you run print(some_list) then it is equivalent to
print'[%s]' % ', '.join(map(repr, some_list)) i.e., to create a text representation of a Python object with the type list, repr() function is called for each item.

Don't confuse a Python object and its text representationrepr('a') != 'a' and even the text representation of the text representation differs: repr(repr('a')) != repr('a').

repr(obj) returns a string that contains a printable representation of an object. Its purpose is to be an unambiguous representation of an object that can be useful for debugging, in a REPL. Often eval(repr(obj)) == obj.

To avoid calling repr(), you could print list items directly (if they are all Unicode strings) e.g.: print ",".join(some_list)—it prints a comma separated list of the strings: String

Do not encode a Unicode string to bytes using a hardcoded character encoding, print Unicode directly instead. Otherwise, the code may fail because the encoding can't represent all the characters e.g., if you try to use 'ascii' encoding with non-ascii characters. Or the code silently produces mojibake (corrupted data is passed further in a pipeline) if the environment uses an encoding that is incompatible with the hardcoded encoding.

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

There's no "simple command" to do that. You can write a function, or take your choice of several that are available online in various code repositories. I use this:

function get-loggedonuser ($computername){

#mjolinor 3/17/10

$regexa = '.+Domain="(.+)",Name="(.+)"$'
$regexd = '.+LogonId="(\d+)"$'

$logontype = @{
"0"="Local System"
"2"="Interactive" #(Local logon)
"3"="Network" # (Remote logon)
"4"="Batch" # (Scheduled task)
"5"="Service" # (Service account logon)
"7"="Unlock" #(Screen saver)
"8"="NetworkCleartext" # (Cleartext network logon)
"9"="NewCredentials" #(RunAs using alternate credentials)
"10"="RemoteInteractive" #(RDP\TS\RemoteAssistance)
"11"="CachedInteractive" #(Local w\cached credentials)
}

$logon_sessions = @(gwmi win32_logonsession -ComputerName $computername)
$logon_users = @(gwmi win32_loggedonuser -ComputerName $computername)

$session_user = @{}

$logon_users |% {
$_.antecedent -match $regexa > $nul
$username = $matches[1] + "\" + $matches[2]
$_.dependent -match $regexd > $nul
$session = $matches[1]
$session_user[$session] += $username
}


$logon_sessions |%{
$starttime = [management.managementdatetimeconverter]::todatetime($_.starttime)

$loggedonuser = New-Object -TypeName psobject
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Session" -Value $_.logonid
$loggedonuser | Add-Member -MemberType NoteProperty -Name "User" -Value $session_user[$_.logonid]
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Type" -Value $logontype[$_.logontype.tostring()]
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Auth" -Value $_.authenticationpackage
$loggedonuser | Add-Member -MemberType NoteProperty -Name "StartTime" -Value $starttime

$loggedonuser
}

}

How to display activity indicator in middle of the iphone screen?

If you want to try to do it by using interface, you can view my video for this. This way, you no need to write any code to show Activity Indicator in the middle of the iPhone screen.

How to update and order by using ms sql

You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:

UPDATE  messages 
SET status=10 
WHERE ID in (SELECT TOP (10) Id 
             FROM Table 
             WHERE status=0 
             ORDER BY priority DESC);

Mask output of `The following objects are masked from....:` after calling attach() function

You actually don't need to use the attach at all. I had the same problem and it was resolved by removing the attach statement.

Managing jQuery plugin dependency in webpack

Add this to your plugins array in webpack.config.js

new webpack.ProvidePlugin({
    'window.jQuery': 'jquery',
    'window.$': 'jquery',
})

then require jquery normally

require('jquery');

If pain persists getting other scripts to see it, try explicitly placing it in the global context via (in the entry js)

window.$ = jQuery;

How to generate a HTML page dynamically using PHP?

You dont need to generate any dynamic html page, just use .htaccess file and rewrite the URL.

How to resolve Value cannot be null. Parameter name: source in linq?

System.ArgumentNullException: Value cannot be null. Parameter name: value

This error message is not very helpful!

You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.

As a generic way to solve this, look at the stack trace or call stack:

Test method GetApiModel threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: value
    at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

You can see that the parameter name value is the first parameter for DeserializeObject. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.

You can change the code to check for null.

Javascript: how to validate dates in format MM-DD-YYYY?

what isn't working about it? here's a tested version:

String.prototype.isValidDate = function()   {

    const match = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
    if (!match || match.length !== 4) {
        return false
    }

    const test = new Date(match[3], match[1] - 1, match[2]);

    return (
        (test.getMonth() == match[1] - 1) &&
        (test.getDate() == match[2]) &&
        (test.getFullYear() == match[3])
    );
}

var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
alert(date.isValidDate() ); // true

Remove all items from RecyclerView

Help yourself:

public void clearAdapter() {
    arrayNull.clear();
    notifyDataSetChanged();
}

How to combine multiple inline style objects?

You can also combine classes with inline styling like this:

<View style={[className, {paddingTop: 25}]}>
  <Text>Some Text</Text>
</View>

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Hi recently looked into this and had issues referencing the named table (list object) within excel

if you place a suffix '$' on the table name all is well in the world

Sub testSQL()

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset

    ' Declare variables
    strFile = ThisWorkbook.FullName

    ' construct connection string
    strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"

    ' create connection and recordset objects
    Set cn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    ' open connection
    cn.Open strCon

    ' construct SQL query
    strSQL = "SELECT * FROM [TableName$] where [ColumnHeader] = 'wibble';"

    ' execute SQL query
    rs.Open strSQL, cn

    Debug.Print rs.GetString

    ' close connection
    rs.Close
    cn.Close
    Set rs = Nothing
    Set cn = Nothing
End Sub

How do you create a read-only user in PostgreSQL?

I’ve created a convenient script for that; pg_grant_read_to_db.sh. This script grants read-only privileges to a specified role on all tables, views and sequences in a database schema and sets them as default.

Get the POST request body from HttpServletRequest

This works for both GET and POST:

@Context
private HttpServletRequest httpRequest;


private void printRequest(HttpServletRequest httpRequest) {
    System.out.println(" \n\n Headers");

    Enumeration headerNames = httpRequest.getHeaderNames();
    while(headerNames.hasMoreElements()) {
        String headerName = (String)headerNames.nextElement();
        System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
    }

    System.out.println("\n\nParameters");

    Enumeration params = httpRequest.getParameterNames();
    while(params.hasMoreElements()){
        String paramName = (String)params.nextElement();
        System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
    }

    System.out.println("\n\n Row data");
    System.out.println(extractPostRequestBody(httpRequest));
}

static String extractPostRequestBody(HttpServletRequest request) {
    if ("POST".equalsIgnoreCase(request.getMethod())) {
        Scanner s = null;
        try {
            s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s.hasNext() ? s.next() : "";
    }
    return "";
}

Import PEM into Java Key Store

Although this question is pretty old and it has already a-lot answers, I think it is worth to provide an alternative. Using native java classes makes it very verbose to just use pem files and almost forces you wanting to convert the pem files into p12 or jks files as using p12 or jks files are much easier. I want to give anyone who wants an alternative for the already provided answers.

GitHub - SSLContext Kickstart

var keyManager = PemUtils.loadIdentityMaterial("certificate-chain.pem", "private-key.pem");
var trustManager = PemUtils.loadTrustMaterial("some-trusted-certificate.pem");

var sslFactory = SSLFactory.builder()
          .withIdentityMaterial(keyManager)
          .withTrustMaterial(trustManager)
          .build();

var sslContext = sslFactory.getSslContext();

I need to provide some disclaimer here, I am the library maintainer

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

Is your application running as a 64 or 32bit process? You can check this in the task manager.

It could be, it is running as 32bit, even though the entire system is running on 64bit.

If 32bit, a third party library could be causing this. But first make sure your application is compiling for "Any CPU", as stated in the comments.

String.format() to format double in java

code extracted from this link ;

Double amount = new Double(345987.246);
NumberFormat numberFormatter;
String amountOut;

numberFormatter = NumberFormat.getNumberInstance(currentLocale);
amountOut = numberFormatter.format(amount);
System.out.println(amountOut + " " + 
                   currentLocale.toString());

The output from this example shows how the format of the same number varies with Locale:

345 987,246  fr_FR
345.987,246  de_DE
345,987.246  en_US

How to deal with the URISyntaxException

A general solution requires parsing the URL into a RFC 2396 compliant URI (note that this is an old version of the URI standard, which java.net.URI uses).

I have written a Java URL parsing library that makes this possible: galimatias. With this library, you can achieve your desired behaviour with this code:

String urlString = //...
URLParsingSettings settings = URLParsingSettings.create()
  .withStandard(URLParsingSettings.Standard.RFC_2396);
URL url = URL.parse(settings, urlString);

Note that galimatias is in a very early stage and some features are experimental, but it is already quite solid for this use case.

typesafe select onChange event using reactjs and typescript

As far as I can tell, this is currently not possible - a cast is always needed.

To make it possible, the .d.ts of react would need to be modified so that the signature of the onChange of a SELECT element used a new SelectFormEvent. The new event type would expose target, which exposes value. Then the code could be typesafe.

Otherwise there will always be the need for a cast to any.

I could encapsulate all that in a MYSELECT tag.

Passing Parameters JavaFX FXML

Here is an example for passing parameters to a fxml document through namespace.

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1">
    <BorderPane>
        <center>
            <Label text="$labelText"/>
        </center>
    </BorderPane>
</VBox>

Define value External Text for namespace variable labelText:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class NamespaceParameterExampleApplication extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws IOException {
        final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("namespace-parameter-example.fxml"));

        fxmlLoader.getNamespace()
                  .put("labelText", "External Text");

        final Parent root = fxmlLoader.load();

        primaryStage.setTitle("Namespace Parameter Example");
        primaryStage.setScene(new Scene(root, 400, 400));
        primaryStage.show();
    }
}

How do I find out if the GPS of an Android device is enabled

Here is the snippet worked in my case

final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
    buildAlertMessageNoGps();
}

`

How to write a std::string to a UTF-8 text file

There is nice tiny library to work with utf8 from c++: utfcpp

How can I analyze a heap dump in IntelliJ? (memory leak)

You can just run "Java VisualVM" which is located at jdk/bin/jvisualvm.exe

This will open a GUI, use the "File" menu -> "Load..." then choose your *.hprof file

That's it, you're done!

Failed to run sdkmanager --list with Java 9

Short addition to the above for openJDK 11 with android sdk tools before upgrading to the latest version.

The above solutions didn't work for me

set DEFAULT_JVM_OPTS="-Dcom.android.sdklib.toolsdir=%~dp0\.."

To get this working I have installed the jaxb-ri (reference implementation) from the maven repo.

The information was given https://github.com/javaee/jaxb-v2 and links to the https://repo1.maven.org/maven2/com/sun/xml/bind/jaxb-ri/2.3.2/jaxb-ri-2.3.2.zip
This download includes a standalone runtime implementation in the mod-Folder.

I copied the mod-Folder to $android_sdk\tools\lib\ and added the following to classpath variable:

;%APP_HOME%\lib\mod\jakarta.xml.bind-api.jar;%APP_HOME%\lib\mod\jakarta.activation-api.jar;%APP_HOME%\lib\mod\jaxb-runtime.jar;%APP_HOME%\lib\mod\istack-commons-runtime.jar;

So finally it looks like:

set CLASSPATH=%APP_HOME%\lib\dvlib-26.0.0-dev.jar;%APP_HOME%\lib\jimfs-1.1.jar;%APP_HOME%\lib\jsr305-1.3.9.jar;%APP_HOME%\lib\repository-26.0.0-dev.jar;%APP_HOME%\lib\j2objc-annotations-1.1.jar;%APP_HOME%\lib\layoutlib-api-26.0.0-dev.jar;%APP_HOME%\lib\gson-2.3.jar;%APP_HOME%\lib\httpcore-4.2.5.jar;%APP_HOME%\lib\commons-logging-1.1.1.jar;%APP_HOME%\lib\commons-compress-1.12.jar;%APP_HOME%\lib\annotations-26.0.0-dev.jar;%APP_HOME%\lib\error_prone_annotations-2.0.18.jar;%APP_HOME%\lib\animal-sniffer-annotations-1.14.jar;%APP_HOME%\lib\httpclient-4.2.6.jar;%APP_HOME%\lib\commons-codec-1.6.jar;%APP_HOME%\lib\common-26.0.0-dev.jar;%APP_HOME%\lib\kxml2-2.3.0.jar;%APP_HOME%\lib\httpmime-4.1.jar;%APP_HOME%\lib\annotations-12.0.jar;%APP_HOME%\lib\sdklib-26.0.0-dev.jar;%APP_HOME%\lib\guava-22.0.jar;%APP_HOME%\lib\mod\jakarta.xml.bind-api.jar;%APP_HOME%\lib\mod\jakarta.activation-api.jar;%APP_HOME%\lib\mod\jaxb-runtime.jar;%APP_HOME%\lib\mod\istack-commons-runtime.jar;

Maybe I missed a lib due to some minor errors showing up. But sdkmanager.bat --update or --list is running now.

Import SQL file by command line in Windows 7

If you don't have password you can use the command without

-u

Like this

C:\wamp>bin\mysql\mysql5.7.11\bin\mysql.exe -u {User Name} {Database Name} < C:\File.sql

Or on the SQL console

mysql -u {User Name} -p {Database Name} < C:/File.sql

Passing an array/list into a Python function

def sumlist(items=[]):
    sum = 0
    for i in items:
        sum += i

    return sum

t=sumlist([2,4,8,1])
print(t)

PHP page redirect

As metioned by nixxx adding ob_start() before adding any php code will prevent the headers already sent error.

It worked for me

The code below also works. But it first loads the page and then redirects when I use it.

echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$redirect_url.'">';

whitespaces in the path of windows filepath

path = r"C:\Users\mememe\Google Drive\Programs\Python\file.csv"

Closing the path in r"string" also solved this problem very well.

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

I run it like this -

created > startOfDay(-0d)

It gives me all issues created today. When you change -0d to -1d, it will give you all issues created yesterday and today.

How to install npm peer dependencies automatically?

Install yarn an then run

yarn global add install-peerdeps

Changing font size and direction of axes text in ggplot2

Adding to previous solutions, you can also specify the font size relative to the base_size included in themes such as theme_bw() (where base_size is 11) using the rel() function.

For example:

ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  theme_bw() +
  theme(axis.text.x=element_text(size=rel(0.5), angle=90))

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

Count number of matches of a regex in Javascript

('my string'.match(/\s/g) || []).length;

Custom date format with jQuery validation plugin

You can create your own custom validation method using the addMethod function. Say you wanted to validate "dd/mm/yyyy":

$.validator.addMethod(
    "australianDate",
    function(value, element) {
        // put your own logic here, this is just a (crappy) example
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
    },
    "Please enter a date in the format dd/mm/yyyy."
);

And then on your form add:

$('#myForm')
    .validate({
        rules : {
            myDate : {
                australianDate : true
            }
        }
    })
;

How to add a file to the last commit in git?

Yes, there's a command git commit --amend which is used to "fix" last commit.

In your case it would be called as:

git add the_left_out_file
git commit --amend --no-edit

The --no-edit flag allow to make amendment to commit without changing commit message.

EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.

javascript get child by id

document.getElementById('child') should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.

edit : see this page - ids MUST be unique.

edit edit : alternate way to solve the problem :

<div onclick="test('child1')">
    Test
    <div id="child1">child</div>
</div>

then you just need the test() function to look up the element by id that you passed in.

SQL Server Management Studio, how to get execution time down to milliseconds

Turn on Client Statistics by doing one of the following:

  • Menu: Query > Include client Statistics
  • Toolbar: Click the button (next to Include Actual Execution Time)
  • Keyboard: Shift-Alt-S

Then you get a new tab which records the timings, IO data and rowcounts etc for (up to) the last 10 exections (plus averages!):

enter image description here

How to move up a directory with Terminal in OS X

cd .. will back the directory up by one. If you want to reach a folder in the parent directory, you can do something like cd ../foldername. You can use the ".." trick as many times as you want to back up through multiple parent directories. For example, cd ../../Applications would take you to Macintosh HD/Applications

What's the difference between "Solutions Architect" and "Applications Architect"?

Sounds like the same to me! Though I don't totally disagree with Oli. I'd give a selected few people the Software Architect title if they want it but experience tells me the people who would actually deserve the title of Software Architect usually aint that in to titles.

How to attach a file using mail command on Linux?

My answer needs base64 in addition to mail, but some uuencode versions can also do base64 with -m, or you can forget about mime and use the plain uuencode output...

   [email protected]
   [email protected]
   SUBJECT="Auto emailed"
   MIME="application/x-gzip"  # Adjust this to the proper mime-type of file
   FILE=somefile.tar.gz
   ENCODING=base64  
   boundary="---my-unlikely-text-for-mime-boundary---$$--" 

   (cat <<EOF
    From: $FROM
    To: $REPORT_DEST
    Subject: $SUBJECT
    Date: $(date +"%a, %b %e %Y %T %z")
    Mime-Version: 1.0
    Content-Type: multipart/mixed; boundary="$boundary"
    Content-Disposition: inline

    --$boundary
    Content-Type: text/plain; charset=us-ascii
    Content-Disposition: inline

    This email has attached the file

    --$boundary
    Content-Type: $MIME;name="$FILE"
    Content-Disposition: attachment;filename="$FILE"
    Content-Transfer-Encoding: $ENCODING

    EOF
    base64 $FILE
    echo ""
    echo "--$boundary" ) | mail

Where does Oracle SQL Developer store connections?

On linux systems:

~/.sqldeveloper/system<sqldeveloper_version>/o.jdeveloper.db.connection/connections.xml

compareTo() vs. equals()

String s1 = "a";
String s2 = "c";

System.out.println(s1.compareTo(s2));
System.out.println(s1.equals(s2));

This prints -2 and false

String s1 = "c";
String s2 = "a";
System.out.println(s1.compareTo(s2));
System.out.println(s1.equals(s2));

This prints 2 and false

String s1 = "c";
String s2 = "c";
System.out.println(s1.compareTo(s2));
System.out.println(s1.equals(s2));

This prints 0 and true

equals returns boolean if and only if both strings match.

compareTo is meant to not just tell if they match but also to tell which String is lesser than the other, and also by how much, lexicographically. This is mostly used while sorting in collection.

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

HTML:

<div  ng-repeat="scannedDevice in ScanResult">
        <!--GridStarts-->
          <div >
              <img ng-src={{'./assets/img/PlaceHolder/Test.png'}} 
                   <!--Pass Param-->
                   ng-click="connectDevice(scannedDevice.id)"
                   altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}" 
                   onerror="this.src = $(this).attr('altSrc')">
           </div>    
 </div>

Java Script:

   //Global Variables
    var  ANGULAR_APP = angular.module('TestApp',[]);

    ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {

      //Variables
      $scope.ScanResult = [];

      //Pass Parameter
      $scope.connectDevice = function(deviceID) {
            alert("Connecting : "+deviceID );
        };
     }]);

How do I parse a HTML page with Node.js

You can use the npm modules jsdom and htmlparser to create and parse a DOM in Node.JS.

Other options include:

  • BeautifulSoup for python
  • you can convert you html to xhtml and use XSLT
  • HTMLAgilityPack for .NET
  • CsQuery for .NET (my new favorite)
  • The spidermonkey and rhino JS engines have native E4X support. This may be useful, only if you convert your html to xhtml.

Out of all these options, I prefer using the Node.js option, because it uses the standard W3C DOM accessor methods and I can reuse code on both the client and server. I wish BeautifulSoup's methods were more similar to the W3C dom, and I think converting your HTML to XHTML to write XSLT is just plain sadistic.

msvcr110.dll is missing from computer error while installing PHP

To identify which x86/x64 version of VC is needed:

Go to IIS Manager > Handler Mappings > right click then Edit *.php path. In the "Executable (optional)" field note in which version of Program Files is the php-cgi.exe installed.

Expansion of variables inside single quotes in a command in Bash

Inside single quotes everything is preserved literally, without exception.

That means you have to close the quotes, insert something, and then re-enter again.

'before'"$variable"'after'
'before'"'"'after'
'before'\''after'

Word concatenation is simply done by juxtaposition. As you can verify, each of the above lines is a single word to the shell. Quotes (single or double quotes, depending on the situation) don't isolate words. They are only used to disable interpretation of various special characters, like whitespace, $, ;... For a good tutorial on quoting see Mark Reed's answer. Also relevant: Which characters need to be escaped in bash?

Do not concatenate strings interpreted by a shell

You should absolutely avoid building shell commands by concatenating variables. This is a bad idea similar to concatenation of SQL fragments (SQL injection!).

Usually it is possible to have placeholders in the command, and to supply the command together with variables so that the callee can receive them from the invocation arguments list.

For example, the following is very unsafe. DON'T DO THIS

script="echo \"Argument 1 is: $myvar\""
/bin/sh -c "$script"

If the contents of $myvar is untrusted, here is an exploit:

myvar='foo"; echo "you were hacked'

Instead of the above invocation, use positional arguments. The following invocation is better -- it's not exploitable:

script='echo "arg 1 is: $1"'
/bin/sh -c "$script" -- "$myvar"

Note the use of single ticks in the assignment to script, which means that it's taken literally, without variable expansion or any other form of interpretation.

How to make VS Code to treat other file extensions as certain language?

The easiest way I've found for a global association is simply to ctrl+k m (or ctrl+shift+p and type "change language mode") with a file of the type you're associating open.

In the first selections will be "Configure File Association for 'x' " (whatever file type - see image attached) Selecting this makes the filetype association permanent

enter image description here

This may have changed (probably did) since the original question and accepted answer (and I don't know when it changed) but it's so much easier than the manual editing steps in the accepted and some of the other answers, and totaly avoids having to muss with IDs that may not be obvious.

How to convert JSON to string?

Try to Use JSON.stringify

Regards

SQL: IF clause within WHERE clause

Use a CASE statement
UPDATE: The previous syntax (as pointed out by a few people) doesn't work. You can use CASE as follows:

WHERE OrderNumber LIKE
  CASE WHEN IsNumeric(@OrderNumber) = 1 THEN 
    @OrderNumber 
  ELSE
    '%' + @OrderNumber
  END

Or you can use an IF statement like @N. J. Reed points out.

Why is MySQL InnoDB insert so slow?

This is an old topic but frequently searched. So long as you are aware of risks (as stated by @philip Koshy above) of losing committed transactions in the last one second or so, before massive updates, you may set these global parameters

innodb_flush_log_at_trx_commit=0
sync_binlog=0

then turn then back on (if so desired) after update is complete.

innodb_flush_log_at_trx_commit=1
sync_binlog=1

for full ACID compliance.

There is a huge difference in write/update performance when both of these are turned off and on. In my experience, other stuff discussed above makes some difference but only marginal.

One other thing that impacts update/insert greatly is full text index. In one case, a table with two text fields having full text index, inserting 2mil rows took 6 hours and the same took only 10 min after full text index was removed. More indexes, more time. So search indexes other than unique and primary key may be removed prior to massive inserts/updates.

How to change MySQL timezone in a database connection using Java?

Is there a way we can get the list of supported timeZone from MySQL ? ex - serverTimezone=America/New_York. That can solve many such issue. I believe every time you need to specify the correct time zone from the Application irrespective of the DB TimeZone.

Way to create multiline comments in Bash?

Multiline comment in bash

: <<'END_COMMENT'
This is a heredoc (<<) redirected to a NOP command (:).
The single quotes around END_COMMENT are important,
because it disables variable resolving and command resolving
within these lines.  Without the single-quotes around END_COMMENT,
the following two $() `` commands would get executed:
$(gibberish command)
`rm -fr mydir`
comment1
comment2 
comment3
END_COMMENT

CSS: Hover one element, effect for multiple elements?

OR

.section:hover > div {
  background-color: #0CF;
}

NOTE Parent element state can only affect a child's element state so you can use:

.image:hover + .layer {
  background-color: #0CF;
}
.image:hover {
  background-color: #0CF;
}

but you can not use

.layer:hover + .image {
  background-color: #0CF;
}

jQuery Data vs Attr?

The main difference between the two is where it is stored and how it is accessed.

$.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

$.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

Data set with attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects

Data set with .data()

  • accessible only from .data(name)
  • not accessible from .attr() or anywhere else
  • not publicly visible on the element upon inspection
  • can be objects

How to get the real and total length of char * (char array)?

You can find the length of a char* string like this:

char* mystring = "Hello World";
int length = sprintf(mystring, "%s", mystring);

sprintf() prints mystring onto itself, and returns the number of characters printed.

TypeError: $(...).on is not a function

I tried the solution of Oskar (and many others) but for me it finaly only worked with:

jQuery(function($){
   // Your jQuery code here, using the $
});

See: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

How to append in a json file in Python?

json_obj=json.dumps(a_dict, ensure_ascii=False)

How to exit an application properly

Application.Exit() does the trick too: any forms you have can still cancel this for instance if you want to present a save changes dialog.

java.lang.RuntimeException: Unable to start activity ComponentInfo

Your Manifest Must Change like this Activity name must Specified like ".YourActivityname"

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
     android:minSdkVersion="8" android:targetSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".MainTabPanel"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MyBookActivity"  >            
    </activity>
</application>

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

As I faced this error, somewhere in your code your funcs or libraries that used run on different threads, so try to call all code on the same thread , it fixed my problem.

If you call methods on WebView from any thread other than your app's UI thread, it can cause unexpected results. For example, if your app uses multiple threads, you can use the runOnUiThread() method to ensure your code executes on the UI thread:

Google reference link

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

To check if a Path exists to a directory, use this one:

$pathToDirectory = "c:\program files\blahblah\"
if (![System.IO.Directory]::Exists($pathToDirectory))
{
 mkdir $path1
}

To check if a Path to a file exists use what @Mathias suggested:

[System.IO.File]::Exists($pathToAFile)

Removing viewcontrollers from navigation stack

I wrote an extension with method which removes all controllers between root and top, unless specified otherwise.

extension UINavigationController {
func removeControllers(between start: UIViewController?, end: UIViewController?) {
    guard viewControllers.count > 1 else { return }
    let startIndex: Int
    if let start = start {
        guard let index = viewControllers.index(of: start) else {
            return
        }
        startIndex = index
    } else {
        startIndex = 0
    }

    let endIndex: Int
    if let end = end {
        guard let index = viewControllers.index(of: end) else {
            return
        }
        endIndex = index
    } else {
        endIndex = viewControllers.count - 1
    }
    let range = startIndex + 1 ..< endIndex
    viewControllers.removeSubrange(range)
}

}

If you want to use range (for example: 2 to 5) you can just use

    let range = 2 ..< 5
    viewControllers.removeSubrange(range)

Tested on iOS 12.2, Swift 5

How do you execute an arbitrary native command from a string?

Invoke-Expression, also aliased as iex. The following will work on your examples #2 and #3:

iex $command

Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:

$command = 'C:\somepath\someexe.exe somearg'
iex $command

However, if the exe is in quotes, you need the help of & to get it running, as in this example, as run from the commandline:

>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"

And then in the script:

$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"

Likely, you could handle nearly all cases by detecting if the first character of the command string is ", like in this naive implementation:

function myeval($command) {
    if ($command[0] -eq '"') { iex "& $command" }
    else { iex $command }
}

But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}, perhaps for specific exception types/messages, or examine the command string.

If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

Well if you have given

@ManyToOne ()
   @JoinColumn (name = "countryId")
   private Country country;

then object of that class i mean Country need to be save first.

because it will only allow User to get saved into the database if there is key available for the Country of that user for the same. means it will allow user to be saved if and only if that country is exist into the Country table.

So for that you need to save that Country first into the table.

Does Java SE 8 have Pairs or Tuples?

UPDATE: This answer is in response to the original question, Does Java SE 8 have Pairs or Tuples? (And implicitly, if not, why not?) The OP has updated the question with a more complete example, but it seems like it can be solved without using any kind of Pair structure. [Note from OP: here is the other correct answer.]


The short answer is no. You either have to roll your own or bring in one of the several libraries that implements it.

Having a Pair class in Java SE was proposed and rejected at least once. See this discussion thread on one of the OpenJDK mailing lists. The tradeoffs are not obvious. On the one hand, there are many Pair implementations in other libraries and in application code. That demonstrates a need, and adding such a class to Java SE will increase reuse and sharing. On the other hand, having a Pair class adds to the temptation of creating complicated data structures out of Pairs and collections without creating the necessary types and abstractions. (That's a paraphrase of Kevin Bourillion's message from that thread.)

I recommend everybody read that entire email thread. It's remarkably insightful and has no flamage. It's quite convincing. When it started I thought, "Yeah, there should be a Pair class in Java SE" but by the time the thread reached its end I had changed my mind.

Note however that JavaFX has the javafx.util.Pair class. JavaFX's APIs evolved separately from the Java SE APIs.

As one can see from the linked question What is the equivalent of the C++ Pair in Java? there is quite a large design space surrounding what is apparently such a simple API. Should the objects be immutable? Should they be serializable? Should they be comparable? Should the class be final or not? Should the two elements be ordered? Should it be an interface or a class? Why stop at pairs? Why not triples, quads, or N-tuples?

And of course there is the inevitable naming bikeshed for the elements:

  • (a, b)
  • (first, second)
  • (left, right)
  • (car, cdr)
  • (foo, bar)
  • etc.

One big issue that has hardly been mentioned is the relationship of Pairs to primitives. If you have an (int x, int y) datum that represents a point in 2D space, representing this as Pair<Integer, Integer> consumes three objects instead of two 32-bit words. Furthermore, these objects must reside on the heap and will incur GC overhead.

It would seem clear that, like Streams, it would be essential for there to be primitive specializations for Pairs. Do we want to see:

Pair
ObjIntPair
ObjLongPair
ObjDoublePair
IntObjPair
IntIntPair
IntLongPair
IntDoublePair
LongObjPair
LongIntPair
LongLongPair
LongDoublePair
DoubleObjPair
DoubleIntPair
DoubleLongPair
DoubleDoublePair

Even an IntIntPair would still require one object on the heap.

These are, of course, reminiscent of the proliferation of functional interfaces in the java.util.function package in Java SE 8. If you don't want a bloated API, which ones would you leave out? You could also argue that this isn't enough, and that specializations for, say, Boolean should be added as well.

My feeling is that if Java had added a Pair class long ago, it would have been simple, or even simplistic, and it wouldn't have satisfied many of the use cases we are envisioning now. Consider that if Pair had been added in the JDK 1.0 time frame, it probably would have been mutable! (Look at java.util.Date.) Would people have been happy with that? My guess is that if there were a Pair class in Java, it would be kinda-sort-not-really-useful and everybody will still be rolling their own to satisfy their needs, there would be various Pair and Tuple implementations in external libraries, and people would still be arguing/discussing about how to fix Java's Pair class. In other words, kind of in the same place we're at today.

Meanwhile, some work is going on to address the fundamental issue, which is better support in the JVM (and eventually the Java language) for value types. See this State of the Values document. This is preliminary, speculative work, and it covers only issues from the JVM perspective, but it already has a fair amount of thought behind it. Of course there are no guarantees that this will get into Java 9, or ever get in anywhere, but it does show the current direction of thinking on this topic.

jquery function val() is not equivalent to "$(this).value="?

Note that :

typeof $(this) is JQuery object.

and

typeof $(this)[0] is HTMLElement object

then : if you want to apply .val() on HTMLElement , you can add this extension .

HTMLElement.prototype.val=function(v){
   if(typeof v!=='undefined'){this.value=v;return this;}
   else{return this.value}
}

Then :

document.getElementById('myDiv').val() ==== $('#myDiv').val()

And

 document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')

????? INVERSE :

Conversely? if you want to add value property to jQuery object , follow those steps :

  1. Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .

  2. Insert Line after L96 , add this code value:"" to init this new prop enter image description here

  3. Search on jQuery.fn.init , it will be almost Line 2747

enter image description here

  1. Now , assign a value to value prop : (Before return statment add this.value=jQuery(selector).val()) enter image description here

Enjoy now : $('#myDiv').value

How to replace all double quotes to single quotes using jquery?

Use double quote to enclose the quote or escape it.

newTemp = mystring.replace(/"/g, "'");

or

newTemp = mystring.replace(/"/g, '\'');

How do I calculate the date six months from the current date using the datetime Python module?

Modified the AddMonths() for use in Zope and handling invalid day numbers:

def AddMonths(d,x):
    days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    newmonth = ((( d.month() - 1) + x ) % 12 ) + 1
    newyear  = d.year() + ((( d.month() - 1) + x ) // 12 ) 
    if d.day() > days_of_month[newmonth-1]:
      newday = days_of_month[newmonth-1]
    else:
      newday = d.day() 
    return DateTime( newyear, newmonth, newday)

Cannot connect to the Docker daemon on macOS

You should execute script for install docker and launch it from command line:

brew install --cask docker
sudo -H pip3 install --upgrade pip3
open -a Docker
docker-compose ... 

after that docker-compose should work

How to ignore files/directories in TFS for avoiding them to go to central source repository?

For VS2015 and VS2017

Works with TFS (on-prem) or VSO (Visual Studio Online - the Azure-hosted offering)

The NuGet documentation provides instructions on how to accomplish this and I just followed them successfully for Visual Studio 2015 & Visual Studio 2017 against VSTS (Azure-hosted TFS). Everything is fully updated as of Nov 2016 Aug 2018.

I recommend you follow NuGet's instructions but just to recap what I did:

  1. Make sure your packages folder is not committed to TFS. If it is, get it out of there.
  2. Everything else we create below goes into the same folder that your .sln file exists in unless otherwise specified (NuGet's instructions aren't completely clear on this).
  3. Create a .nuget folder. You can use Windows Explorer to name it .nuget. for it to successfully save as .nuget (it automatically removes the last period) but directly trying to name it .nuget may not work (you may get an error or it may change the name, depending on your version of Windows). Or name the directory nuget, and open the parent directory in command line prompt. type. ren nuget .nuget
  4. Inside of that folder, create a NuGet.config file and add the following contents and save it:

NuGet.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <solution>
        <add key="disableSourceControlIntegration" value="true" />
    </solution>
</configuration>
  1. Go back in your .sln's folder and create a new text file and name it .tfignore (if using Windows Explorer, use the same trick as above and name it .tfignore.)
  2. Put the following content into that file:

.tfignore:

# Ignore the NuGet packages folder in the root of the repository.
# If needed, prefix 'packages' with additional folder names if it's 
# not in the same folder as .tfignore.
packages

# include package target files which may be required for msbuild,
# again prefixing the folder name as needed.
!packages/*.targets
  1. Save all of this, commit it to TFS, then close & re-open Visual Studio and the Team Explorer should no longer identify the packages folder as a pending check-in.
  2. Copy/pasted via Windows Explorer the .tfignore file and .nuget folder to all of my various solutions and committed them and I no longer have the packages folder trying to sneak into my source control repo!

Further Customization

While not mine, I have found this .tfignore template by sirkirby to be handy. The example in my answer covers the Nuget packages folder but this template includes some other things as well as provides additional examples that can be useful if you wish to customize this further.

How to get Selected Text from select2 when using <input>

In Select2 version 4 each option has the same properties of the objects in the list;

if you have the object

Obj = {
  name: "Alberas",
  description: "developer",
  birthDate: "01/01/1990"
}

then you retrieve the selected data

var data = $('#id-selected-input').select2('data');
console.log(data[0].name);
console.log(data[0].description);
console.log(data[0].birthDate);
 

Redirect form to different URL based on select option element

you can use this simple way

<select onchange="location = this.value;">
                <option value="/finished">Finished</option>
                <option value="/break">Break</option>
                <option value="/issue">Issues</option>
                <option value="/downtime">Downtime</option>
</select>

will redirect to route url you can direct to .html page or direct to some link just change value in option.

IE and Edge fix for object-fit: cover;

I just used the @misir-jafarov and is working now with :

  • IE 8,9,10,11 and EDGE detection
  • used in Bootrap 4
  • take the height of its parent div
  • cliped vertically at 20% of top and horizontally 50% (better for portraits)

here is my code :

if (document.documentMode || /Edge/.test(navigator.userAgent)) {
    jQuery('.art-img img').each(function(){
        var t = jQuery(this),
            s = 'url(' + t.attr('src') + ')',
            p = t.parent(),
            d = jQuery('<div></div>');

        p.append(d);
        d.css({
            'height'                : t.parent().css('height'),
            'background-size'       : 'cover',
            'background-repeat'     : 'no-repeat',
            'background-position'   : '50% 20%',
            'background-image'      : s
        });
        t.hide();
    });
}

Hope it helps.

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

Quick fix for CGRectMake , CGPointMake, CGSizeMake in Swift3 & iOS10

Add these extensions :

extension CGRect{
    init(_ x:CGFloat,_ y:CGFloat,_ width:CGFloat,_ height:CGFloat) {
        self.init(x:x,y:y,width:width,height:height)
    }

}
extension CGSize{
    init(_ width:CGFloat,_ height:CGFloat) {
        self.init(width:width,height:height)
    }
}
extension CGPoint{
    init(_ x:CGFloat,_ y:CGFloat) {
        self.init(x:x,y:y)
    }
}

Then go to "Find and Replace in Workspace" Find CGRectMake , CGPointMake, CGSizeMake and Replace them with CGRect , CGPoint, CGSize

These steps might save all the time as Xcode right now doesn't give us quick conversion from Swift 2+ to Swift 3

How to draw a checkmark / tick using CSS?

i like this way because you don't need to create two components just one.

.checkmark:after {
    opacity: 1;
    height: 4em;
    width: 2em;
    -webkit-transform-origin: left top;
    transform-origin: left top;
    border-right: 2px solid #5cb85c;
    border-top: 2px solid #5cb85c;
    content: '';
    left: 2em;
    top: 4em;
    position: absolute;
}

Animation from Scott Galloway Pen

Slide div left/right using jQuery

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
            $('#right').show("slide", { direction: "right" }, 500);_x000D_
        });_x000D_
    });_x000D_
    $("#right").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
            $('#left').show("slide", { direction: "left" }, 500);_x000D_
        });_x000D_
    });_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
        $('#fsEditWindow').show("slide", { direction: "left" }, 500);
    });
});

It will work like charm take a look at the demo.

Identify if a string is a number

int n;
bool isNumeric = int.TryParse("123", out n);

Update As of C# 7:

var isNumeric = int.TryParse("123", out int n);

or if you don't need the number you can discard the out parameter

var isNumeric = int.TryParse("123", out _);

The var s can be replaced by their respective types!

Specifying onClick event type with Typescript and React.Konva

You should be using event.currentTarget. React is mirroring the difference between currentTarget (element the event is attached to) and target (the element the event is currently happening on). Since this is a mouse event, type-wise the two could be different, even if it doesn't make sense for a click.

https://github.com/facebook/react/issues/5733 https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

How do I read text from the clipboard?

If you don't want to install extra packages, ctypes can get the job done as well.

import ctypes

CF_TEXT = 1

kernel32 = ctypes.windll.kernel32
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
kernel32.GlobalLock.restype = ctypes.c_void_p
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
user32 = ctypes.windll.user32
user32.GetClipboardData.restype = ctypes.c_void_p

def get_clipboard_text():
    user32.OpenClipboard(0)
    try:
        if user32.IsClipboardFormatAvailable(CF_TEXT):
            data = user32.GetClipboardData(CF_TEXT)
            data_locked = kernel32.GlobalLock(data)
            text = ctypes.c_char_p(data_locked)
            value = text.value
            kernel32.GlobalUnlock(data_locked)
            return value
    finally:
        user32.CloseClipboard()

print(get_clipboard_text())

Are email addresses case sensitive?

I know this is an old question but I just want to comment here: To any extent email addresses ARE case sensitive, most users would be "very unwise" to actively use an email address that requires capitals. They would soon stop using the address because they'd be missing a lot of their mail. (Unless they have a specific reason to make things difficult, and they expect mail only from specific senders they know.)

That's because imperfect humans as well as imperfect software exist, (Surprise!) which will assume all email is lowercase, and for this reason these humans and software will send messages using a "lower cased version" of the address regardless of how it was provided to them. If the recipient is unable to receive such messages, it won't be long before they notice they're missing a lot, and switch to a lowercase-only email address, or get their server set up to be case-insensitive.

OSError [Errno 22] invalid argument when use open() in Python

for folder, subs, files in os.walk(unicode(docs_dir, 'utf-8')):
    for filename in files:
        if not filename.startswith('.'):
            file_path = os.path.join(folder, filename)

HTTP post XML data in C#

In General:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

In your specific situation:

Instead of:

request.ContentType = "application/x-www-form-urlencoded";

use:

request.ContentType = "text/xml; encoding='utf-8'";

Also, remove:

string postData = "XMLData=" + Sendingxml;

And replace:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

with:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());

Converting String Array to an Integer Array

Converting String array into stream and mapping to int is the best option available in java 8.

    String[] stringArray = new String[] { "0", "1", "2" };
    int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
    System.out.println(Arrays.toString(intArray));

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

For me, when i wanted to clone from my repository, i had the same message noticed before "Permission denied (publickey) fatal: Could not read from remote repository". The solution for my case is to not use sudo before clone That's it.

How to conditional format based on multiple specific text in Excel

You can use MATCH for instance.

  1. Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.

  2. In the entry box, put:

    =MATCH(A2, 'Sheet2'!A:A, 0)
    
  3. Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.

MATCH takes the value A2 from your data table, looks into 'Sheet2'!A:A and if there's an exact match (that's why there's a 0 at the end), then it'll return the row number.

Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.

EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:

=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))

How to search file text for a pattern and replace it with a given value

If you need to do substitutions across line boundaries, then using ruby -pi -e won't work because the p processes one line at a time. Instead, I recommend the following, although it could fail with a multi-GB file:

ruby -e "file='translation.ja.yml'; IO.write(file, (IO.read(file).gsub(/\s+'$/, %q('))))"

The is looking for white space (potentially including new lines) following by a quote, in which case it gets rid of the whitespace. The %q(')is just a fancy way of quoting the quote character.

Python string class like StringBuilder in C#?

I have used the code of Oliver Crow (link given by Andrew Hare) and adapted it a bit to tailor Python 2.7.3. (by using timeit package). I ran on my personal computer, Lenovo T61, 6GB RAM, Debian GNU/Linux 6.0.6 (squeeze).

Here is the result for 10,000 iterations:

method1:  0.0538418292999 secs
process size 4800 kb
method2:  0.22602891922 secs
process size 4960 kb
method3:  0.0605459213257 secs
process size 4980 kb
method4:  0.0544030666351 secs
process size 5536 kb
method5:  0.0551080703735 secs
process size 5272 kb
method6:  0.0542731285095 secs
process size 5512 kb

and for 5,000,000 iterations (method 2 was ignored because it ran tooo slowly, like forever):

method1:  5.88603997231 secs
process size 37976 kb
method3:  8.40748500824 secs
process size 38024 kb
method4:  7.96380496025 secs
process size 321968 kb
method5:  8.03666186333 secs
process size 71720 kb
method6:  6.68192911148 secs
process size 38240 kb

It is quite obvious that Python guys have done pretty great job to optimize string concatenation, and as Hoare said: "premature optimization is the root of all evil" :-)

How to increase Bootstrap Modal Width?

n your code, for the modal-dialog div, add another class, modal-lg:

use modal-xl

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

Turning off eslint rule for a specific line

You can use the following

/*eslint-disable */

//suppress all warnings between comments
alert('foo');

/*eslint-enable */

Which is slightly buried the "configuring rules" section of the docs;

To disable a warning for an entire file, you can include a comment at the top of the file e.g.

/*eslint eqeqeq:0*/

Update

ESlint has now been updated with a better way disable a single line, see @goofballLogic's excellent answer.

Android XXHDPI resources

xxhdpi was not specified before but now new devices S4, HTC one are surely comes inside xxhdpi .These device dpi are around 440. I do not know exact limit for xxhdpi See how to develop android application for xxhdpi device Samsung S4 I know this is late answer but as thing had change since the question asked

Note Google Nexus 10 need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.

Parsing a JSON array using Json.Net

Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage

And you can convert the entire object to a string, filename.json is expected to be located in documents folder.

        var text = File.ReadAllText("filename.json");
        var json = JsonValue.Parse(text);

        while (JsonValue.Null != null)
        {
            Console.WriteLine(json.ToString());

        }
        Console.ReadLine();

AngularJS Error: $injector:unpr Unknown Provider

Your angular module needs to be initialized properly. The global object app needs to be defined and initialized correctly to inject the service.

Please see below sample code for reference:

app.js

var app = angular.module('SampleApp',['ngRoute']); //You can inject the dependencies within the square bracket    

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $routeProvider
    .when('/', {
      templateUrl:"partials/login.html",
      controller:"login"
    });

  $locationProvider
    .html5Mode(true);
}]);

app.factory('getSettings', ['$http', '$q', function($http, $q) {
  return {
    //Code edited to create a function as when you require service it returns object by default so you can't return function directly. That's what understand...
    getSetting: function (type) { 
      var q = $q.defer();
      $http.get('models/settings.json').success(function (data) {
        q.resolve(function() {
          var settings = jQuery.parseJSON(data);
          return settings[type];
        });
      });
      return q.promise;
    }
  }
}]);

app.controller("globalControl", ['$scope','getSettings', function ($scope,getSettings) {
  //Modified the function call for updated service
  var loadSettings = getSettings.getSetting('global');
  loadSettings.then(function(val) {
    $scope.settings = val;
  });
}]);

Sample HTML code should be like this:

<!DOCTYPE html>
<html>
    <head lang="en">
        <title>Sample Application</title>
    </head>
    <body ng-app="SampleApp" ng-controller="globalControl">
        <div>
            Your UI elements go here
        </div>
        <script src="app.js"></script>
    </body>
</html>

Please note that the controller is not binding to an HTML tag but to the body tag. Also, please try to include your custom scripts at end of the HTML page as this is a standard practice to follow for performance reasons.

I hope this will solve your basic injection issue.

How can I force component to re-render with hooks in React?

Simple code

const forceUpdate = React.useReducer(bool => !bool)[1];

Use:

forceUpdate();

What is the default root pasword for MySQL 5.7

MySQL server 5.7 was already installed by default on my new Linux Mint 19.

But, what's the MySQL root password? It turns out that:

The default installation uses auth_socket for authentication, in lieu of passwords!

It allows a password-free login, provided that one is logged into the Linux system with the same user name. To login as the MySQL root user, one can use sudo:

sudo mysql --user=root

But how to then change the root password? To illustrate what's going on, I created a new user "me", with full privileges, with:

mysql> CREATE USER 'me'@'localhost' IDENTIFIED BY 'my_new_password';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'me'@'localhost' WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES;

Comparing "me" with "root":

mysql> SELECT user, plugin, HEX(authentication_string)  FROM mysql.user WHERE user = 'me' or user = 'root';
+------+-----------------------+----------------------------------------------------------------------------+
| user | plugin                | HEX(authentication_string)                                                 |
+------+-----------------------+----------------------------------------------------------------------------+
| root | auth_socket           |                                                                            |
| me   | mysql_native_password | 2A393846353030304545453239394634323734333139354241344642413245373537313... |
+------+-----------------------+----------------------------------------------------------------------------+

Because it's using auth_socket, the root password cannot be changed: the SET PASSWORD command fails, and mysql_secure_installation desn't attain anything...

==> To zap this alternate authentication mode and return the MySQL root user to using passwords:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'SOME_NEW_ROOT_PASSWORD';

A good explanation.

More details from the MySQL manual.

Uncaught ReferenceError: $ is not defined error in jQuery

Change the order you're including your scripts (jQuery first):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
    src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>

JSON to PHP Array using file_get_contents

Check some typo ','

<?php
 //file_get_content(url);
$jsonD = '{
    "bpath":"http://www.sampledomain.com/",
    "clist":[{
            "cid":"11",
            "display_type":"grid",
            "ctitle":"abc",
            "acount":"71",
            "alist":[{
                    "aid":"6865",
                    "adate":"2 Hours ago",
                    "atitle":"test",
                    "adesc":"test desc",
                    "aimg":"",
                    "aurl":"?nid=6865",
                    "weburl":"news.php?nid=6865",
                    "cmtcount":"0"
                },
                {
                    "aid":"6857",
                    "adate":"20 Hours ago",
                    "atitle":"test1",
                    "adesc":"test desc1",
                    "aimg":"",
                    "aurl":"?nid=6857",
                    "weburl":"news.php?nid=6857",
                    "cmtcount":"0"
                }
            ]
        },
        {
            "cid":"1",
            "display_type":"grid",
            "ctitle":"test1",
            "acount":"2354",
            "alist":[{
                    "aid":"6851",
                    "adate":"1 Days ago",
                    "atitle":"test123",
                    "adesc":"test123 desc",
                    "aimg":"",
                    "aurl":"?nid=6851",
                    "weburl":"news.php?nid=6851",
                    "cmtcount":"7"
                },
                {
                    "aid":"6847",
                    "adate":"2 Days ago",
                    "atitle":"test12345",
                    "adesc":"test12345 desc",
                    "aimg":"",
                    "aurl":"?nid=6847",
                    "weburl":"news.php?nid=6847",
                    "cmtcount":"7"
                }
            ]
        }
    ]
}
';

$parseJ = json_decode($jsonD,true);

print_r($parseJ);
?>

How to detect if a stored procedure already exists

In addition to what has already been said I also like to add a different approach and advocate the use of differential script deployment strategy. Instead of making a stateful script that always checks the current state and acts based on that state, deploy via a series of stateless scripts that upgrade from well known versions. I have used this strategy and it pays off big time as my deployment scripts are now all 'IF' free.

How to obtain the last path segment of a URI

You can use getPathSegments() function. (Android Documentation)

Consider your example URI:

String uri = "http://base_path/some_segment/id"

You can get the last segment using:

List<String> pathSegments = uri.getPathSegments();
String lastSegment = pathSegments.get(pathSegments.size - 1);

lastSegment will be id.

How do I display images from Google Drive on a website?

i supposed you uploaded your photo in your drive all what you need to do is while you are opening your google drive just open your dev tools in chrome and head to your img tag and copy the link beside the src attribute and use it

Get host domain from URL?

Use Uri class and use Host property

Uri url = new Uri(@"http://support.domain.com/default.aspx?id=12345");
Console.WriteLine(url.Host);

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

This is a more common error now as many projects are moving their master branch to another name like main, primary, default, root, reference, latest, etc, as discussed at Github plans to replace racially insensitive terms like ‘master’ and ‘whitelist’.

To fix it, first find out what the project is now using, which you can find via their github, gitlab or other git server.

Then do this to capture the current configuration:

$ git branch -vv
...
* master  968695b [origin/master] Track which contest a ballot was sampled for (#629)
...

Find the line describing the master branch, and note whether the remote repo is called origin, upstream or whatever.

Then using that information, change the branch name to the new one, e.g. if it says you're currently tracking origin/master, substitute main:

git branch master --set-upstream-to origin/main

You can also rename your own branch to avoid future confusion:

git branch -m main

Reading/writing an INI file

Preface

Firstly, read this MSDN blog post on the limitations of INI files. If it suits your needs, read on.

This is a concise implementation I wrote, utilising the original Windows P/Invoke, so it is supported by all versions of Windows with .NET installed, (i.e. Windows 98 - Windows 10). I hereby release it into the public domain - you're free to use it commercially without attribution.

The tiny class

Add a new class called IniFile.cs to your project:

using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

// Change this to match your program's normal namespace
namespace MyProg
{
    class IniFile   // revision 11
    {
        string Path;
        string EXE = Assembly.GetExecutingAssembly().GetName().Name;

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);

        public IniFile(string IniPath = null)
        {
            Path = new FileInfo(IniPath ?? EXE + ".ini").FullName;
        }

        public string Read(string Key, string Section = null)
        {
            var RetVal = new StringBuilder(255);
            GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
            return RetVal.ToString();
        }

        public void Write(string Key, string Value, string Section = null)
        {
            WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
        }

        public void DeleteKey(string Key, string Section = null)
        {
            Write(Key, null, Section ?? EXE);
        }

        public void DeleteSection(string Section = null)
        {
            Write(null, null, Section ?? EXE);
        }

        public bool KeyExists(string Key, string Section = null)
        {
            return Read(Key, Section).Length > 0;
        }
    }
}

How to use it

Open the INI file in one of the 3 following ways:

// Creates or loads an INI file in the same directory as your executable
// named EXE.ini (where EXE is the name of your executable)
var MyIni = new IniFile();

// Or specify a specific name in the current dir
var MyIni = new IniFile("Settings.ini");

// Or specify a specific name in a specific dir
var MyIni = new IniFile(@"C:\Settings.ini");

You can write some values like so:

MyIni.Write("DefaultVolume", "100");
MyIni.Write("HomePage", "http://www.google.com");

To create a file like this:

[MyProg]
DefaultVolume=100
HomePage=http://www.google.com

To read the values out of the INI file:

var DefaultVolume = MyIni.Read("DefaultVolume");
var HomePage = MyIni.Read("HomePage");

Optionally, you can set [Section]'s:

MyIni.Write("DefaultVolume", "100", "Audio");
MyIni.Write("HomePage", "http://www.google.com", "Web");

To create a file like this:

[Audio]
DefaultVolume=100

[Web]
HomePage=http://www.google.com

You can also check for the existence of a key like so:

if(!MyIni.KeyExists("DefaultVolume", "Audio"))
{
    MyIni.Write("DefaultVolume", "100", "Audio");
}

You can delete a key like so:

MyIni.DeleteKey("DefaultVolume", "Audio");

You can also delete a whole section (including all keys) like so:

MyIni.DeleteSection("Web");

Please feel free to comment with any improvements!

Making a POST call instead of GET using urllib2

Try this instead:

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe',
                         'age'  : '10'})
req = urllib2.Request(url=url,data=data)
content = urllib2.urlopen(req).read()
print content

LINQ Joining in C# with multiple conditions

Your and should be a && in the where clause.

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
and epl.ArriveAirportBy > sd.UTCArrivalTime

should be

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
&& epl.ArriveAirportBy > sd.UTCArrivalTime

ReactJS - Does render get called any time "setState" is called?

Even though it's stated in many of the other answers here, the component should either:

  • implement shouldComponentUpdate to render only when state or properties change

  • switch to extending a PureComponent, which already implements a shouldComponentUpdate method internally for shallow comparisons.

Here's an example that uses shouldComponentUpdate, which works only for this simple use case and demonstration purposes. When this is used, the component no longer re-renders itself on each click, and is rendered when first displayed, and after it's been clicked once.

_x000D_
_x000D_
var TimeInChild = React.createClass({_x000D_
    render: function() {_x000D_
        var t = new Date().getTime();_x000D_
_x000D_
        return (_x000D_
            <p>Time in child:{t}</p>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
var Main = React.createClass({_x000D_
    onTest: function() {_x000D_
        this.setState({'test':'me'});_x000D_
    },_x000D_
_x000D_
    shouldComponentUpdate: function(nextProps, nextState) {_x000D_
      if (this.state == null)_x000D_
        return true;_x000D_
  _x000D_
      if (this.state.test == nextState.test)_x000D_
        return false;_x000D_
        _x000D_
      return true;_x000D_
  },_x000D_
_x000D_
    render: function() {_x000D_
        var currentTime = new Date().getTime();_x000D_
_x000D_
        return (_x000D_
            <div onClick={this.onTest}>_x000D_
            <p>Time in main:{currentTime}</p>_x000D_
            <p>Click me to update time</p>_x000D_
            <TimeInChild/>_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render(<Main/>, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
_x000D_
_x000D_
_x000D_

How do I remove the horizontal scrollbar in a div?

If you don't have anything overflowing horizontally, you can also just use

overflow: auto;

and it will only show scrollbars when needed.

See The CSS Overflow Property

What is the difference between Tomcat, JBoss and Glassfish?

Both JBoss and Tomcat are Java servlet application servers, but JBoss is a whole lot more. The substantial difference between the two is that JBoss provides a full Java Enterprise Edition (Java EE) stack, including Enterprise JavaBeans and many other technologies that are useful for developers working on enterprise Java applications.

Tomcat is much more limited. One way to think of it is that JBoss is a Java EE stack that includes a servlet container and web server, whereas Tomcat, for the most part, is a servlet container and web server.

Hide element by class in pure Javascript

<script type="text/javascript">
        $(document).ready(function(){

                $('.appBanner').fadeOut('slow');

        });
    </script>

or

<script type="text/javascript">
        $(document).ready(function(){

                $('.appBanner').hide();

        });
    </script>

ios simulator: how to close an app

You can use this command to quit an app in iOS Simulator

xcrun simctl terminate booted com.apple.mobilesafari

You will need to know the bundle id of the app you have installed in the simulator. You can refer to this link

Sending simple message body + file attachment using Linux Mailx

On RHEL Linux, I had trouble getting my message in the body of the email instead of as an attachment . Using od -cx, I found that the body of my email contained several /r. I used a perl script to strip the /r, and the message was correctly inserted into the body of the email.

mailx -s "subject text" [email protected] < 'body.txt'

The text file body.txt contained the char \r, so I used perl to strip \r.

cat body.txt | perl success.pl > body2.txt
mailx -s "subject text" [email protected] < 'body2.txt'

This is success.pl

    while (<STDIN>) {
        my $currLine = $_;
        s?\r??g;
        print
    }
;

rotating axis labels in R

You need to use theme() function as follows rotating x-axis labels by 90 degrees:

ggplot(...)+...+ theme(axis.text.x = element_text(angle=90, hjust=1))

What's the difference between text/xml vs application/xml for webservice response

application/xml is seen by svn as binary type whereas text/xml as text file for which a diff can be displayed.

Android - Dynamically Add Views into View

Use the LayoutInflater to create a view based on your layout template, and then inject it into the view where you need it.

LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);

// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");

// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

You may have to adjust the index where you want to insert the view.

Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT, or MATCH_PARENT, etc.

Android Facebook style slide

Recently I have worked on my sliding menu implementation version. It uses popular J.Feinstein Android library SlidingMenu.

Please check the source code at GitHub:

https://github.com/baruckis/Android-SlidingMenuImplementation

Download app directly to the device to try:

https://play.google.com/store/apps/details?id=com.baruckis.SlidingMenuImplementation

Code should be self-explanatory because of comments. I hope it will be helpful! ;)

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

If you want to make it fast, you could use a lookup table like in Bit Twiddling Hacks (integer log2 only).

uint32_t v; // find the log base 2 of 32-bit v
int r;      // result goes here

static const int MultiplyDeBruijnBitPosition[32] = 
{
  0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
  8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};

v |= v >> 1; // first round down to one less than a power of 2 
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;

r = MultiplyDeBruijnBitPosition[(uint32_t)(v * 0x07C4ACDDU) >> 27];

In addition you should take a look at your compilers builtin methods like _BitScanReverse which could be faster because it may entirely computed in hardware.

Take also a look at possible duplicate How to do an integer log2() in C++?

Call child method from parent

you can use ref to call the function of the child component from the parent

Functional Component Solution

in functional component, you have to use useImperativeHandle for getting ref into a child like below

import React, { forwardRef, useRef, useImperativeHandle } from 'react';
export default function ParentFunction() {
    const childRef = useRef();
    return (
        <div className="container">
            <div>
                Parent Component
            </div>
            <button
                onClick={() => { childRef.current.showAlert() }}
            >
            Call Function
            </button>
            <Child ref={childRef}/>
        </div>
    )
}
const Child = forwardRef((props, ref) => {
    useImperativeHandle(
        ref,
        () => ({
            showAlert() {
                alert("Child Function Called")
            }
        }),
    )
    return (
       <div>Child Component</div>
    )
})

Class Component Solution

Child.js

import s from './Child.css';

class Child extends Component {
 getAlert() {
    alert('clicked');
 }
 render() {
  return (
    <h1>Hello</h1>
  );
 }
}

export default Child;

Parent.js

class Parent extends Component {
 render() {
  onClick() {
    this.refs.child.getAlert();
  }
  return (
    <div>
      <Child ref="child" />
      <button onClick={this.onClick}>Click</button>
    </div>
  );
 }
}

How to place Text and an Image next to each other in HTML?

You want to use css float for this, you can put it directly in your code.

<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>

But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).

HTML:

<body>
  <img src="website_art.png" class="myImage"/>
  <h3 class="heading">The Art of Gaming</h3>
</body>

CSS:

.myImage {
  float: left;
  height: 75px;
  width: 235px;
  font-family: Veranda;
}
.heading {
  float:right;
}

Unable to open debugger port in IntelliJ

  1. In glassfish\domains\domain1\config\domain.xml set before start server:

_x000D_
_x000D_
      <java-config classpath-suffix="" debug-options="-agentlib:jdwp=transport=dt_socket,address=9009,server=y,suspend=n" java-home="C:\Program Files\Java\jdk1.8.0_162" debug-enabled="true" system-classpath="">
_x000D_
_x000D_
_x000D_

or set debug-enabled="true" server=y,suspend=n in http://localhost:4848/common/index.jsf Glassfish 4 address=9009,server=y,suspend=n

  1. In current Idea 2018 - Server Run Configuration - Debug - Port - address Server Run Configuration - Debug - Port - address

Install NuGet via PowerShell script

None of the above solutions worked for me, I found an article that explained the issue. The security protocols on the system were deprecated and therefore displayed an error message that no match was found for the ProviderPackage.

Here is a the basic steps for upgrading your security protocols:

Run both cmdlets to set .NET Framework strong cryptography registry keys. After that, restart PowerShell and check if the security protocol TLS 1.2 is added. As of last, install the PowerShellGet module.

The first cmdlet is to set strong cryptography on 64 bit .Net Framework (version 4 and above).

[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
1
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
The second cmdlet is to set strong cryptography on 32 bit .Net Framework (version 4 and above).

[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
1
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Restart Powershell and check for supported security protocols.

[PS] C:\>[Net.ServicePointManager]::SecurityProtocol
Tls, Tls11, Tls12
1
2
[PS] C:\>[Net.ServicePointManager]::SecurityProtocol
Tls, Tls11, Tls12
Run the command Install-Module PowershellGet -Force and press Y to install NuGet provider, follow with Enter.

[PS] C:\>Install-Module PowershellGet -Force
 
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\administrator.EXOIP\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install
and import the NuGet provider now?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

[PS] C:\>Install-Module PowershellGet -Force
 
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\administrator.EXOIP\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install
and import the NuGet provider now?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

Laravel 5.4 Specific Table Migration

php artisan help migrate

You will see the option:

--path[=PATH] The path to the migrations files to be executed

By the way, you can probably indicate the root folder of the file that you want to migrate:

php artisan migrate --path=/database/migrations/sample.php

Or, You can create a new folder in migrations, then migrate all the migration files you want inside it:

php artisan migrate --path=/database/migrations/new_folder

How do I check if there are duplicates in a flat list?

If you are fond of functional programming style, here is a useful function, self-documented and tested code using doctest.

def decompose(a_list):
    """Turns a list into a set of all elements and a set of duplicated elements.

    Returns a pair of sets. The first one contains elements
    that are found at least once in the list. The second one
    contains elements that appear more than once.

    >>> decompose([1,2,3,5,3,2,6])
    (set([1, 2, 3, 5, 6]), set([2, 3]))
    """
    return reduce(
        lambda (u, d), o : (u.union([o]), d.union(u.intersection([o]))),
        a_list,
        (set(), set()))

if __name__ == "__main__":
    import doctest
    doctest.testmod()

From there you can test unicity by checking whether the second element of the returned pair is empty:

def is_set(l):
    """Test if there is no duplicate element in l.

    >>> is_set([1,2,3])
    True
    >>> is_set([1,2,1])
    False
    >>> is_set([])
    True
    """
    return not decompose(l)[1]

Note that this is not efficient since you are explicitly constructing the decomposition. But along the line of using reduce, you can come up to something equivalent (but slightly less efficient) to answer 5:

def is_set(l):
    try:
        def func(s, o):
            if o in s:
                raise Exception
            return s.union([o])
        reduce(func, l, set())
        return True
    except:
        return False

How to use PHP to connect to sql server

<?php  
$serverName = "ServerName"; 
$uid = "sqlusername";   
$pwd = "sqlpassword";  
$databaseName = "DBName"; 

$connectionInfo = array( "UID"=>$uid,                            
                         "PWD"=>$pwd,                            
                         "Database"=>$databaseName); 

/* Connect using SQL Server Authentication. */  
$conn = sqlsrv_connect( $serverName, $connectionInfo);  

$tsql = "SELECT id, FirstName, LastName, Email FROM tblContact";  

/* Execute the query. */  

$stmt = sqlsrv_query( $conn, $tsql);  

if ( $stmt )  
{  
     echo "Statement executed.<br>\n";  
}   
else   
{  
     echo "Error in statement execution.\n";  
     die( print_r( sqlsrv_errors(), true));  
}  

/* Iterate through the result set printing a row of data upon each iteration.*/  

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))  
{  
     echo "Col1: ".$row[0]."\n";  
     echo "Col2: ".$row[1]."\n";  
     echo "Col3: ".$row[2]."<br>\n";  
     echo "-----------------<br>\n";  
}  

/* Free statement and connection resources. */  
sqlsrv_free_stmt( $stmt);  
sqlsrv_close( $conn);  
?>  

http://robsphp.blogspot.ae/2012/09/how-to-install-microsofts-sql-server.html

Concatenate string with field value in MySQL

MySQL uses CONCAT() to concatenate strings

SELECT * FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)

How do I convert seconds to hours, minutes and seconds?

If you need to get datetime.time value, you can use this trick:

my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()

You cannot add timedelta to time, but can add it to datetime.

UPD: Yet another variation of the same technique:

my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()

Instead of 1 you can use any number greater than 0. Here we use the fact that datetime.fromordinal will always return datetime object with time component being zero.

List of all unique characters in a string?

Use an OrderedDict. This will ensure that the order is preserved

>>> ''.join(OrderedDict.fromkeys( "aaabcabccd").keys())
'abcd'

PS: I just timed both the OrderedDict and Set solution, and the later is faster. If order does not matter, set should be the natural solution, if Order Matter;s this is how you should do.

>>> from timeit import Timer
>>> t1 = Timer(stmt=stmt1, setup="from __main__ import data, OrderedDict")
>>> t2 = Timer(stmt=stmt2, setup="from __main__ import data")
>>> t1.timeit(number=1000)
1.2893918431815337
>>> t2.timeit(number=1000)
0.0632140599081196

Confused about __str__ on list in Python

__str__ is only called when a string representation is required of an object.

For example str(uno), print "%s" % uno or print uno

However, there is another magic method called __repr__ this is the representation of an object. When you don't explicitly convert the object to a string, then the representation is used.

If you do this uno.neighbors.append([[str(due),4],[str(tri),5]]) it will do what you expect.

Syntax error "syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)"

It seems that you have a bunch of describes that never have ends keywords, starting with describe "when email format is invalid" do until describe "when email address is already taken" do

Put an end on those guys and you're probably done =)

How to set a variable to be "Today's" date in Python/Pandas

pd.datetime.now().strftime("%d/%m/%Y")

this will give output as '11/02/2019'

you can use add time if you want

pd.datetime.now().strftime("%d/%m/%Y %I:%M:%S")

this will give output as '11/02/2019 11:08:26'

strftime formats

Python one-line "for" expression

for item in array: array2.append (item)

Or, in this case:

array2 += array

How do I change Eclipse to use spaces instead of tabs?

As an augmentation to the other answers, on Mac OS X, the "Preferences" menu is under Eclipse, not Window (unlike Windows/Linux Eclipse distributions). Everything else is still the same as pointed out by other answers past this point.

IE: Java Formatter available under:

Eclipse >      | # Not Window!
Preferences >  |
Java >         |
Code Style >   |
Formatter      |

From here, edit the formatter and the tab policy can be set under "Indentation".

How to show changed file name only with git log?

If you need just file names like:

dir/subdir/file1.txt
dir/subdir2/file2.sql
dir2/subdir3/file6.php

(which I use as a source for tar command) you will also need to filter out commit messages.

In order to do this I use following command:

git log --name-only --oneline | grep -v '.{7} '

Grep command excludes (-v param) every line which starts with seven symbols (which is the length of my git hash for git log command) followed by space. So it filters out every git hash message line and leave only lines with file names.

One useful improvement is to append uniq to remove duplicate lines so it will looks as follow:

git log --name-only --oneline | grep -v '.{7} ' | uniq

How do I use brew installed Python as the default Python?

python now points to python3, if you need python 2 then do: brew install python@2 and then in your .zshrc or .bashrc file export PATH="/usr/local/opt/python@2/libexec/bin:$PATH" Now, pyhon --version = Python 2.7.14 and python3 --version = Python 3.6.4. That's the behavior I'm used to seeing in my terminal.

setHintTextColor() in EditText

Inside Layout Xml File We can Change Color of Hint.....

android:textColorHint="@android:color/*****"

you can replace * with color or color code.

How to make circular background using css?

Check with following css. Demo

.circle { 
   width: 140px;
   height: 140px;
   background: red; 
   -moz-border-radius: 70px; 
   -webkit-border-radius: 70px; 
   border-radius: 70px;
}

For more shapes you can follow following urls:

http://davidwalsh.name/css-triangles

How can I combine multiple nested Substitute functions in Excel?

=SUBSTITUTE(text, old_text, new_text)

if: a=!, b=@, c=#,... x=>, y=?, z=~, " "="     "
then: abcdefghijklmnopqrstuvwxyz ... try this out
equals: !@#$%^&*()-=+[]\{}|;:/<>?~     ...     ;}?     ;*(|     ]:;

RULES:

(1) text to substitute is in cell A1
(2) max 64 substitution levels (the formula below only has 27 levels [alphabet + space])
(2) "old_text" cannot also be a "new_text" (ie: if a=z .: z cannot be "old text")

---so if a=z,b=y,...y=b,z=a, then the result is 
---abcdefghijklmnopqrstuvwxyz = zyxwvutsrqponnopqrstuvwxyz (and z changes to a then changes back to z) ... (pattern starts to fail after m=n, n=m... and n becomes n)

The formula is:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"a","!"),"b","@"),"c","#"),"d","$"),"e","%"),"f","^"),"g","&"),"h","*"),"i","("),"j",")"),"k","-"),"l","="),"m","+"),"n","["),"o","]"),"p","\"),"q","{"),"r","}"),"s","|"),"t",";"),"u",":"),"v","/"),"w","<"),"x",">"),"y","?"),"z","~")," ","     ")

Can overridden methods differ in return type?

Yes, if they return a subtype. Here's an example:

package com.sandbox;

public class Sandbox {

    private static class Parent {
        public ParentReturnType run() {
            return new ParentReturnType();
        }
    }

    private static class ParentReturnType {

    }

    private static class Child extends Parent {
        @Override
        public ChildReturnType run() {
            return new ChildReturnType();
        }
    }

    private static class ChildReturnType extends ParentReturnType {
    }
}

This code compiles and runs.

Java Reflection Performance

Interestingly enough, settting setAccessible(true), which skips the security checks, has a 20% reduction in cost.

Without setAccessible(true)

new A(), 70 ns
A.class.newInstance(), 214 ns
new A(), 84 ns
A.class.newInstance(), 229 ns

With setAccessible(true)

new A(), 69 ns
A.class.newInstance(), 159 ns
new A(), 85 ns
A.class.newInstance(), 171 ns

How can I format a nullable DateTime with ToString()?

What about something as easy as this:

String.Format("{0:dd/MM/yyyy}", d2)

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

I used this and it worked out well for me. If your directory is

"repo" and your project is "hello" copy the project there

cd /path/to/my/repo

Initialize your directory

git init

Stage the project

git add hello

commit the project

git commit

Add configurations using the email and username you are using in Bitbucket

git config --global user.email
git config --global user.name

Add comment to the project

git commit -m 'comment'

push the project now

git push origin master

Check out of the master

git checkout master

Change directory in Node.js command prompt

To switch to the another directory process.chdir("../");

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Try to open Services Window, by writing services.msc into Start->Run and hit Enter.

When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.

How do I get git to default to ssh and not https for new repositories

The response provided by Trevor is correct.

But here is what you can directly add in your .gitconfig:

# Enforce SSH
[url "ssh://[email protected]/"]
  insteadOf = https://github.com/
[url "ssh://[email protected]/"]
  insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
  insteadOf = https://bitbucket.org/

How can I change the color of AlertDialog title and the color of the line under it

In the class onCreateView, I put this:

Dialog d = getDialog();
    d.setTitle(Html.fromHtml("<font color='#EC407A'>About</font>"));
    int dividerId = d.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
    View divider = d.findViewById(dividerId);
    divider.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

colorPrimary links to our colors.xml file that stores all the colors. Also d.setTitle provides a hacky way to set the title colour.

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

I forgot to add the "Password=xxx;" in the connection string in my case.

Make more than one chart in same IPython Notebook cell

Another way, for variety. Although this is somewhat less flexible than the others. Unfortunately, the graphs appear one above the other, rather than side-by-side, which you did request in your original question. But it is very concise.

df.plot(subplots=True)

If the dataframe has more than the two series, and you only want to plot those two, you'll need to replace df with df[['korisnika','osiguranika']].

How to use std::sort to sort an array in C++

If you don't know the size, you can use:

std::sort(v, v + sizeof v / sizeof v[0]);

Even if you do know the size, it's a good idea to code it this way as it will reduce the possibility of a bug if the array size is changed later.

Rails: call another controller action from a controller

Composition to the rescue!

Given the reason, rather than invoking actions across controllers one should design controllers to seperate shared and custom parts of the code. This will help to avoid both - code duplication and breaking MVC pattern.

Although that can be done in a number of ways, using concerns (composition) is a good practice.

# controllers/a_controller.rb
class AController < ApplicationController
  include Createable

  private def redirect_url
    'one/url'
  end
end

# controllers/b_controller.rb
class BController < ApplicationController
  include Createable

  private def redirect_url
    'another/url'
  end
end

# controllers/concerns/createable.rb
module Createable
  def create
    do_usefull_things
    redirect_to redirect_url
  end
end

Hope that helps.

How to perform element-wise multiplication of two lists?

For large lists, we can do it the iter-way:

product_iter_object = itertools.imap(operator.mul, [1,2,3,4], [2,3,4,5])

product_iter_object.next() gives each of the element in the output list.

The output would be the length of the shorter of the two input lists.

What is the meaning of the prefix N in T-SQL statements and when should I use it?

It's declaring the string as nvarchar data type, rather than varchar

You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.

To quote from Microsoft:

Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.


If you want to know the difference between these two data types, see this SO post:

What is the difference between varchar and nvarchar?

What represents a double in sql server?

float

Or if you want to go old-school:

real

You can also use float(53), but it means the same thing as float.

("real" is equivalent to float(24), not float/float(53).)

The decimal(x,y) SQL Server type is for when you want exact decimal numbers rather than floating point (which can be approximations). This is in contrast to the C# "decimal" data type, which is more like a 128-bit floating point number.

MSSQL's float type is equivalent to the 64-bit double type in .NET. (My original answer from 2011 said there could be a slight difference in mantissa, but I've tested this in 2020 and they appear to be 100% compatible in their binary representation of both very small and very large numbers -- see https://dotnetfiddle.net/wLX5Ox for my test).

To make things more confusing, a "float" in C# is only 32-bit, so it would be more equivalent in SQL to the real/float(24) type in MSSQL than float/float(53).

In your specific use case... All you need is 5 places after the decimal point to represent latitude and longitude within about one-meter precision, and you only need up to three digits before the decimal point for the degrees. Float(24) or decimal(8,5) will best fit your needs in MSSQL, and using float in C# is good enough, you don't need double. In fact, your users will probably thank you for rounding to 5 decimal places rather than having a bunch of insignificant digits coming along for the ride.

Could not load NIB in bundle

Be careful: Xcode is caseSensitive with file names. It's not the same "Fun" than "fun".

java.net.SocketTimeoutException: Read timed out under Tomcat

Here are the basic instructions:-

  1. Locate the "server.xml" file in the "conf" folder beneath Tomcat's base directory (i.e. %CATALINA_HOME%/conf/server.xml).
  2. Open the file in an editor and search for <Connector.
  3. Locate the relevant connector that is timing out - this will typically be the HTTP connector, i.e. the one with protocol="HTTP/1.1".
  4. If a connectionTimeout value is set on the connector, it may need to be increased - e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout property value is set on the connector, the default is 60 seconds - if this is insufficient, the property may need to be added.
  5. Restart Tomcat

How to set a DateTime variable in SQL Server 2008?

First of all - use single quotes around your date literals!

Second of all, I would strongly recommend always using the ISO-8601 date format - this works regardless of what your locale, regional or language settings are on your SQL Server.

The ISO-8601 format is either:

  • YYYYMMDD for dates only (e.g. 20110825 for the 25th of August, 2011)
  • YYYY-MM-DDTHH:MM:SS for dates and time (e.g. 2011-08-25T14:15:00 for 25th of AUgust, 14:15/2:15pm in the afternoon)

Make TextBox uneditable

Use the ReadOnly property on the TextBox.

myTextBox.ReadOnly = true;

But Remember: TextBoxBase.ReadOnly Property

When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

Command to get time in milliseconds

date command didnt provide milli seconds on OS X, so used an alias from python

millis(){  python -c "import time; print(int(time.time()*1000))"; }

OR

alias millis='python -c "import time; print(int(time.time()*1000))"'

EDIT: following the comment from @CharlesDuffy. Forking any child process takes extra time.

$ time date +%s%N
1597103627N
date +%s%N  0.00s user 0.00s system 63% cpu 0.006 total

Python is still improving it's VM start time, and it is not as fast as ahead-of-time compiled code (such as date).

On my machine, it took about 30ms - 60ms (that is 5x-10x of 6ms taken by date)

$ time python -c "import time; print(int(time.time()*1000))"
1597103899460
python -c "import time; print(int(time.time()*1000))"  0.03s user 0.01s system 83% cpu 0.053 total

I figured awk is lightweight than python, so awk takes in the range of 6ms to 12ms (i.e. 1x to 2x of date):

$ time awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'
1597103729525
awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'  0.00s user 0.00s system 74% cpu 0.010 total

ORA-00979 not a group by expression

Too bad Oracle has limitations like these. Sure, the result for a column not in the GROUP BY would be random, but sometimes you want that. Silly Oracle, you can do this in MySQL/MSSQL.

BUT there is a work around for Oracle:

While the following line does not work

SELECT unique_id_col, COUNT(1) AS cnt FROM yourTable GROUP BY col_A;

You can trick Oracle with some 0's like the following, to keep your column in scope, but not group by it (assuming these are numbers, otherwise use CONCAT)

SELECT MAX(unique_id_col) AS unique_id_col, COUNT(1) AS cnt 
FROM yourTable GROUP BY col_A, (unique_id_col*0 + col_A);

When is layoutSubviews called?

When migrating an OpenGL app from SDK 3 to 4, layoutSubviews was not called anymore. After a lot of trial and error I finally opened MainWindow.xib, selected the Window object, in the inspector chose Window Attributes tab (leftmost) and checked "Visible at launch". It seems that in SDK 3 it still used to cause a layoutSubViews call, but not in 4.

6 hours of frustration put to an end.

increase font size of hyperlink text html

increase the padding size of font and then try to increase font size:-

style="padding-bottom:40px; font-size: 50px;"

How to check if type of a variable is string?

since basestring isn't defined in Python3, this little trick might help to make the code compatible:

try: # check whether python knows about 'basestring'
   basestring
except NameError: # no, it doesn't (it's Python3); use 'str' instead
   basestring=str

after that you can run the following test on both Python2 and Python3

isinstance(myvar, basestring)

What is the meaning of "int(a[::-1])" in Python?

Assuming a is a string. The Slice notation in python has the syntax -

list[<start>:<stop>:<step>]

So, when you do a[::-1], it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.

Example -

>>> a = '1234'
>>> a[::-1]
'4321'

Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.

Git checkout: updating paths is incompatible with switching branches

Alternate syntax,

git fetch origin remote_branch_name:local_branch_name

Replace whitespace with a comma in a text file in Linux

sed can do this:

sed 's/[\t ]/,/g' input.file

That will send to the console,

sed -i 's/[\t ]/,/g' input.file

will edit the file in-place

Reversing a String with Recursion in Java

The call to the reverce(substring(1)) wil be performed before adding the charAt(0). since the call are nested, the reverse on the substring will then be called before adding the ex-second character (the new first character since this is the substring)

reverse ("ello") + "H" = "olleH"
--------^-------
reverse ("llo") + "e" = "olle"
---------^-----
reverse ("lo") + "l" = "oll"
--------^-----
reverse ("o") + "l" = "ol"
---------^----
"o" = "o"

Printing Mongo query output to a file while in the mongo shell

If you invoke the shell with script-file, db address, and --quiet arguments, you can redirect the output (made with print() for example) to a file:

mongo localhost/mydatabase --quiet myScriptFile.js > output 

C# How to determine if a number is a multiple of another?

Try

public bool IsDivisible(int x, int n)
{
   return (x % n) == 0;
}

The modulus operator % returns the remainder after dividing x by n which will always be 0 if x is divisible by n.

For more information, see the % operator on MSDN.