Programs & Examples On #Messagedialog

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How to POST using HTTPclient content type = application/x-www-form-urlencoded

I was using a .Net Core 2.1 API with the [FromBody] attribute and I had to use the following solution to successfully Post to it:

_apiClient =  new HttpClient();
_apiClient.BaseAddress = new Uri(<YOUR API>);
var MyObject myObject = new MyObject(){
    FirstName = "Me",
    LastName = "Myself"
};

var stringified = JsonConvert.SerializeObject(myObject);
var result = await _apiClient.PostAsync("api/appusers", new StringContent(stringified, Encoding.UTF8, "application/json"));

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

I have found that adding these lines of code to the pom.xml file of the maven project solves similar issues for me:-

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>com.packagename.MainClassName</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Return string Input with parse.string

If you're really bent upon converting Integer to String value, I suggest use String.valueOf(YourIntegerVariable). More details can be found at: http://www.tutorialspoint.com/java/java_string_valueof.htm

Java ArrayList - Check if list is empty

Source: CodeSpeedy Click to know more Check if an ArrayList is empty or not

import java.util.ArrayList;
public class arraycheck {
public static void main(String args[]){
ArrayList<Integer> list=new ArrayList<Integer>();

    if(list.size()==0){
        System.out.println("Its Empty");

    }
    else
        System.out.println("Not Empty");

   }

}

Output:

run:
Its Empty
BUILD SUCCESSFUL (total time: 0 seconds)

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

In the ActionListener Class you can simply add

public void actionPerformed(ActionEvent event) {
    if (event.getSource()==textField){
        textButton.doClick();
    }
    else if (event.getSource()==textButton) {
        //do something
    }
}

Compiler error: "class, interface, or enum expected"

class, interface, or enum expected

The above error is even possible when import statement is miss spelled. A proper statement is "import com.company.HelloWorld;"

If by mistake while code writing/editing it is miss written like "t com.company.HelloWorld;"

compiler will show "class, interface, or enum expected"

how to use math.pi in java

Replace

volume = (4 / 3) Math.PI * Math.pow(radius, 3);

With:

volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

Change this dialog.cancel(); to dialog.dismiss();

The solution is to call dismiss() on the Dialog you created in NetErrorPage.java:114 before exiting the Activity, e.g. in onPause().

Views have a reference to their parent Context (taken from constructor argument). If you leave an Activity without destroying Dialogs and other dynamically created Views, they still hold this reference to your Activity (if you created with this as Context: like new ProgressDialog(this)), so it cannot be collected by the GC, causing a memory leak.

How to cancel a Task in await?

Read up on Cancellation (which was introduced in .NET 4.0 and is largely unchanged since then) and the Task-Based Asynchronous Pattern, which provides guidelines on how to use CancellationToken with async methods.

To summarize, you pass a CancellationToken into each method that supports cancellation, and that method must check it periodically.

private async Task TryTask()
{
  CancellationTokenSource source = new CancellationTokenSource();
  source.CancelAfter(TimeSpan.FromSeconds(1));
  Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token);

  // (A canceled task will raise an exception when awaited).
  await task;
}

private int slowFunc(int a, int b, CancellationToken cancellationToken)
{
  string someString = string.Empty;
  for (int i = 0; i < 200000; i++)
  {
    someString += "a";
    if (i % 1000 == 0)
      cancellationToken.ThrowIfCancellationRequested();
  }

  return a + b;
}

exception.getMessage() output with class name

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

public static void main(String[] args) {
    try {
        throw new RuntimeException("Cannot move file");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
    }
}

...you will see a popup that says exactly what you want.


However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:

public static void main(String[] args) {
    try {
        throw new Exception(new RuntimeException("Cannot move file"));
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                                      "Error: " + getRootCause(ex).getMessage());
    }
}

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

Raising a number to a power in Java

Too late for the OP of course, but still... Rearranging the expression as:

int bmi = (10000 * weight) / (height * height)

Eliminates all the floating point, and converts a division by a constant to a multiplication, which should execute faster. Integer precision is probably adequate for this application, but if it is not then:

double bmi = (10000.0 * weight) / (height * height)

would still be an improvement.

JOptionPane Yes or No window

Code for Yes and No Message

      int n = JOptionPane.showConfirmDialog(  
                null,
                "sample question?!" ,
                "",
                JOptionPane.YES_NO_OPTION);

      if(n == JOptionPane.YES_OPTION)
      {
          JOptionPane.showMessageDialog(null, "Opening...");
      }
      else
      {
          JOptionPane.showMessageDialog(null, "Goodbye");
          System.exit(0);

How can I express that two values are not equal to eachother?

"Not equals" can be expressed with the "not" operator ! and the standard .equals.

if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b

Popup Message boxes

A couple of "enhancements" I use for debugging, especially when running projects (ie not in debug mode).

  1. Default the message-box title to the name of the calling method. This is handy for stopping a thread at a given point, but must be cleaned-up before release.
  2. Automatically copy the caller-name and message to the clipboard, because you can't search an image!

    package forumposts;
    
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;
    import javax.swing.JOptionPane;
    
    public final class MsgBox
    {
        public static void info(String message) {
            info(message, theNameOfTheMethodThatCalledMe());
        }
        public static void info(String message, String caller) {
            show(message, caller, JOptionPane.INFORMATION_MESSAGE);
        }
    
        static void error(String message) {
            error(message, theNameOfTheMethodThatCalledMe());
        }
        public static void error(String message, String caller) {
            show(message, caller, JOptionPane.ERROR_MESSAGE);
        }
    
        public static void show(String message, String title, int iconId) {
            setClipboard(title+":"+NEW_LINE+message);
            JOptionPane.showMessageDialog(null, message, title, iconId);
        }
        private static final String NEW_LINE = System.lineSeparator();
    
        public static String theNameOfTheMethodThatCalledMe() {
            return Thread.currentThread().getStackTrace()[3].getMethodName();
        }
    
        public static void setClipboard(String message) {
            CLIPBOARD.setContents(new StringSelection(message), null);
            // nb: we don't respond to the "your content was splattered"
            //     event, so it's OK to pass a null owner.
        }
        private static final Toolkit AWT_TOOLKIT = Toolkit.getDefaultToolkit();
        private static final Clipboard CLIPBOARD = AWT_TOOLKIT.getSystemClipboard();
    
    }
    

The full class also has debug and warning methods, but I cut them for brevity and you get the main points anyway. You can use a public static boolean isDebugEnabled to suppress debug messages. If done properly the optimizer will (almost) remove these method calls from your production code. See: http://c2.com/cgi/wiki?ConditionalCompilationInJava

Cheers. Keith.

How to open warning/information/error dialog in Swing?

Just complementing: It's kind of obvious, but you can use static imports to give you a hand, like this:

import static javax.swing.JOptionPane.*;

public class SimpleDialog(){
    public static void main(String argv[]) {
        showMessageDialog(null, "Message", "Title", ERROR_MESSAGE);
    }
}

Value Change Listener to JTextField

Add a listener to the underlying Document, which is automatically created for you.

// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
    warn();
  }
  public void removeUpdate(DocumentEvent e) {
    warn();
  }
  public void insertUpdate(DocumentEvent e) {
    warn();
  }

  public void warn() {
     if (Integer.parseInt(textField.getText())<=0){
       JOptionPane.showMessageDialog(null,
          "Error: Please enter number bigger than 0", "Error Message",
          JOptionPane.ERROR_MESSAGE);
     }
  }
});

How can I tell if a Java integer is null?

There is no exists for a SCALAR in Perl, anyway. The Perl way is

defined( $x ) 

and the equivalent Java is

anInteger != null

Those are the equivalents.

exists $hash{key}

Is like the Java

map.containsKey( "key" )

From your example, I think you're looking for

if ( startIn != null ) { ...

Disable beep of Linux Bash on Windows 10

Uncommenting set bell-style none in /etc/inputrc and creating a .bash_profile with setterm -blength 0 didn't stop vim from beeping.

What worked for me was creating a .vimrc file in my home directory with set visualbell.

Source: https://linuxconfig.org/turn-off-beep-bell-on-linux-terminal

How to hide axes and gridlines in Matplotlib (python)

# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

Note, you need matplotlib>=1.2 for set_zticks() to work.

$ is not a function - jQuery error

It's really hard to tell, but one of the 9001 ads on the page may be clobbering the $ object.

jQuery provides the global jQuery object (which is present on your page). You can do the following to "get" $ back:

jQuery(document).ready(function ($) {
    // Your code here
});

If you think you're having jQuery problems, please use the debug (non-production) versions of the library.

Also, it's probably not best to be editing a live site like that ...

SOAP or REST for Web Services?

SOAP is useful from a tooling perspective because the WSDL is so easily consumed by tools. So, you can get Web Service clients generated for you in your favorite language.

REST plays well with AJAX'y web pages. If you keep your requests simple, you can make service calls directly from your JavaScript, and that comes in very handy. Try to stay away from having any namespaces in your response XML, I've seen browsers choke on those. So, xsi:type is probably not going to work for you, no overly complex XML Schemas.

REST tends to have better performance as well. CPU requirements of the code generating REST responses tend to be lower than what SOAP frameworks exhibit. And, if you have your XML generation ducks lined up on the server side, you can effectively stream XML out to the client. So, imagine you're reading rows of database cursor. As you read a row, you format it as an XML element, and you write that directly out to the service consumer. This way, you don't have to collect all of the database rows in memory before starting to write your XML output - you read and write at the same time. Look into novel templating engines or XSLT to get the streaming to work for REST.

SOAP on the other hand tends to get generated by tool-generated services as a big blob and only then written. This is not an absolute truth, mind you, there are ways to get streaming characteristics out of SOAP, like by using attachments.

My decision making process is as follows: if I want my service to be easily tooled by consumers, and the messages I write will be medium-to-small-ish (10MB or less), and I don't mind burning some extra CPU cycles on the server, I go with SOAP. If I need to serve to AJAX on web browsers, or I need the thing to stream, or my responses are gigantic, I go REST.

Finally, there are lots of great standards built up around SOAP, like WS-Security and getting stateful Web Services, that you can plug in to if you're using the right tools. That kind of stuff really makes a difference, and can help you satisfy some hairy requirements.

Installing packages in Sublime Text 2

Try using Sublime Package Control to install your packages.

Also take a look at these tips

Mailto links do nothing in Chrome but work in Firefox?

Fix that worked for me since my Protocol handlers was empty

https://productforums.google.com/forum/#!topic/gmail/CQMCGRvyhCM

See redfish43 reply , to sum up

For mailto: - Make sure you are logged in to Gmail and the active window is your main Gmail page (or nothing will happen). - Copy/paste this into the address bar:

javascript:navigator.registerProtocolHandler("mailto","https://mail.google.com/mail/?extsrc=mailto&url=%s","Gmail")

Add the javascript: to the front again if needed, because when you pasted it, Chrome probably trimmed everything before and including the colon. Then hit enter.

When popup window opens click on "Allow"

How do I fix the npm UNMET PEER DEPENDENCY warning?

UNMET PEER DEPENDENCY error is thrown when the dependencies of one or more modules specified in the package.json file is not met. Check the warnings carefully and update the package.json file with correct versions of dependencies.

Then run

rm -rf node_modules/
npm cache clean
npm install

This will install all the required dependencies correctly.

How to convert a ruby hash object to JSON?

require 'json/ext' # to use the C based extension instead of json/pure

puts {hash: 123}.to_json

C# DropDownList with a Dictionary as DataSource

When a dictionary is enumerated, it will yield KeyValuePair<TKey,TValue> objects... so you just need to specify "Value" and "Key" for DataTextField and DataValueField respectively, to select the Value/Key properties.

Thanks to Joe's comment, I reread the question to get these the right way round. Normally I'd expect the "key" in the dictionary to be the text that's displayed, and the "value" to be the value fetched. Your sample code uses them the other way round though. Unless you really need them to be this way, you might want to consider writing your code as:

list.Add(cul.DisplayName, cod);

(And then changing the binding to use "Key" for DataTextField and "Value" for DataValueField, of course.)

In fact, I'd suggest that as it seems you really do want a list rather than a dictionary, you might want to reconsider using a dictionary in the first place. You could just use a List<KeyValuePair<string, string>>:

string[] languageCodsList = service.LanguagesAvailable();
var list = new List<KeyValuePair<string, string>>();

foreach (string cod in languageCodsList)
{
    CultureInfo cul = new CultureInfo(cod);
    list.Add(new KeyValuePair<string, string>(cul.DisplayName, cod));
}

Alternatively, use a list of plain CultureInfo values. LINQ makes this really easy:

var cultures = service.LanguagesAvailable()
                      .Select(language => new CultureInfo(language));
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

If you're not using LINQ, you can still use a normal foreach loop:

List<CultureInfo> cultures = new List<CultureInfo>();
foreach (string cod in service.LanguagesAvailable())
{
    cultures.Add(new CultureInfo(cod));
}
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

Cannot install packages inside docker Ubuntu image

You need to update the package list in your Ubuntu:

$ sudo apt-get update
$ sudo apt-get install <package_name>

DataTable, How to conditionally delete rows

Extension method based on Linq

public static void DeleteRows(this DataTable dt, Func<DataRow, bool> predicate)
{
    foreach (var row in dt.Rows.Cast<DataRow>().Where(predicate).ToList())
        row.Delete();
}

Then use:

DataTable dt = GetSomeData();
dt.DeleteRows(r => r.Field<double>("Amount") > 123.12 && r.Field<string>("ABC") == "XYZ");

How to create a zip archive with PowerShell?

I use this snippet to check my database backups folder for backup files not compressed yet, compress them using 7-Zip, and finally deleting the *.bak files to save some disk space. Notice files are ordered by length (smallest to biggest) before compression to avoid some files not being compressed.

$bkdir = "E:\BackupsPWS"
$7Zip = 'C:\"Program Files"\7-Zip\7z.exe'

get-childitem -path $bkdir | Sort-Object length |
where
{
    $_.extension -match ".(bak)" -and
    -not (test-path ($_.fullname -replace "(bak)", "7z"))
} |
foreach
{
    $zipfilename = ($_.fullname -replace "bak", "7z")
    Invoke-Expression "$7Zip a $zipfilename $($_.FullName)"
}
get-childitem -path $bkdir |
where {
    $_.extension -match ".(bak)" -and
   (test-path ($_.fullname -replace "(bak)", "7z"))
} |
foreach { del $_.fullname }

Here you can check a PowerShell script to backup, compress and transfer those files over FTP.

How to replace NA values in a table for selected columns

This is now trivial in tidyr with replace_na(). The function appears to work for data.tables as well as data.frames:

tidyr::replace_na(x, list(a=0, b=0))

Update one MySQL table with values from another

UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id

That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read

As for running slow, how large are the tables? You should have indexes on tobeupdated.value and original.value

EDIT: we can also simplify the query

UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id

USING is shorthand when both tables of a join have an identical named key such as id. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Broadcast receiver for checking internet connection in android app

manifest:

<receiver android:name=".your.namepackage.here.ConnectivityReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    </intent-filter>
</receiver>

class for receiver:

public class ConnectivityReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        switch (action) {
            case ConnectivityManager.CONNECTIVITY_ACTION:
                DebugUtils.logDebug("BROADCAST", "network change");
                if(NetworkUtils.isConnect()){
                    //do action here
                }
            break;
        }
    }
}

and classs utils like example:

public class NetworkUtils {

    public static boolean isConnect() {
        ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Network[] netArray = connectivityManager.getAllNetworks();
            NetworkInfo netInfo;
            for (Network net : netArray) {
                netInfo = connectivityManager.getNetworkInfo(net);
                if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                    //if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                    Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                    return true;
                }
            }
        } else {
            if (connectivityManager != null) {
                @SuppressWarnings("deprecation")
                NetworkInfo[] netInfoArray = connectivityManager.getAllNetworkInfo();
                if (netInfoArray != null) {
                    for (NetworkInfo netInfo : netInfoArray) {
                        if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                            //if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
                            Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
}

How to validate an email address in PHP

If you're just looking for an actual regex that allows for various dots, underscores and dashes, it as follows: [a-zA-z0-9.-]+\@[a-zA-z0-9.-]+.[a-zA-Z]+. That will allow a fairly stupid looking email like tom_anderson.1-neo@my-mail_matrix.com to be validated.

How do I view / replay a chrome network debugger har file saved with content?

Open chrome browser. right click anywhere on a page > inspect elements > go to network tab > drag and drop the .har file You should see the logs.

When using a Settings.settings file in .NET, where is the config actually stored?

If your settings file is in a web app, they will be in teh web.config file (right below your project. If they are in any other type of project, they will be in the app.config file (also below your project).

Edit

As is pointed out in the comments: your design time application settings are in an app.config file for applications other than web applications. When you build, the app.config file is copied to the output directory, and will be named yourexename.exe.config. At runtime, only the file named yourexename.exe.config will be read.

What is the best way to left align and right align two div tags?

<div style="float: left;">Left Div</div>
<div style="float: right;">Right Div</div>

Change the icon of the exe file generated from Visual Studio 2010

I found it easier to edit the project file directly e.g. YourApp.csproj.

You can do this by modifying ApplicationIcon property element:

<ApplicationIcon>..\Path\To\Application.ico</ApplicationIcon>

Also, if you create an MSI installer for your application e.g. using WiX, you can use the same icon again for display in Add/Remove Programs. See tip 5 here.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

I came here with the same Error, though one with a different origin.

It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.

An int type is expected, not a np.float64

Solution: Try to install numpy 1.11.0

sudo pip install -U numpy==1.11.0.

Oracle SQL update based on subquery between two tables

There are two ways to do what you are trying

One is a Multi-column Correlated Update

UPDATE PRODUCTION a
SET (name, count) = (
  SELECT name, count
  FROM STAGING b
  WHERE a.ID = b.ID);

DEMO

You can use merge

MERGE INTO PRODUCTION a
USING ( select id, name, count 
          from STAGING ) b
ON ( a.id = b.id )
WHEN MATCHED THEN 
UPDATE SET  a.name = b.name,
            a.count = b.count

DEMO

SQL Server 2008: TOP 10 and distinct together

This is the right answer and you can find 3 heights value from table

SELECT TOP(1)  T.id FROM (SELECT DISTINCT TOP(3) st.id  FROM Table1 AS t1 , Table2 AS t2 WHERE t1.id=t2.id ORDER BY (t2.id) DESC ) T ORDER BY(T.id) ASC

How can I use a JavaScript variable as a PHP variable?

PHP runs on the server. It outputs some text (usually). This is then parsed by the client.

During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.

If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).

You can do this by:

  • Setting location (GET only)
  • Submitting a form (with the FormElement.submit() method)
  • Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.

Which ever option you choose, the PHP is essentially the same. Read from $_GET or $_POST, run your database code, then return some data to the client.

Failed linking file resources

Sometimes it happen what you copy paste code from another project fro example you copy

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="256dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemTextColor="@color/colorDrawerItems"
        app:menu="@menu/activity_main_drawer" />

Unfortunately Android studio not always show dependency error, but what happen is that class NavigationView is missing because implementation 'com.android.support:design not added to the project

How to create a shared library with cmake?

Always specify the minimum required version of cmake

cmake_minimum_required(VERSION 3.9)

You should declare a project. cmake says it is mandatory and it will define convenient variables PROJECT_NAME, PROJECT_VERSION and PROJECT_DESCRIPTION (this latter variable necessitate cmake 3.9):

project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")

Declare a new library target. Please avoid the use of file(GLOB ...). This feature does not provide attended mastery of the compilation process. If you are lazy, copy-paste output of ls -1 sources/*.cpp :

add_library(mylib SHARED
    sources/animation.cpp
    sources/buffers.cpp
    [...]
)

Set VERSION property (optional but it is a good practice):

set_target_properties(mylib PROPERTIES VERSION ${PROJECT_VERSION})

You can also set SOVERSION to a major number of VERSION. So libmylib.so.1 will be a symlink to libmylib.so.1.0.0.

set_target_properties(mylib PROPERTIES SOVERSION 1)

Declare public API of your library. This API will be installed for the third-party application. It is a good practice to isolate it in your project tree (like placing it include/ directory). Notice that, private headers should not be installed and I strongly suggest to place them with the source files.

set_target_properties(mylib PROPERTIES PUBLIC_HEADER include/mylib.h)

If you work with subdirectories, it is not very convenient to include relative paths like "../include/mylib.h". So, pass a top directory in included directories:

target_include_directories(mylib PRIVATE .)

or

target_include_directories(mylib PRIVATE include)
target_include_directories(mylib PRIVATE src)

Create an install rule for your library. I suggest to use variables CMAKE_INSTALL_*DIR defined in GNUInstallDirs:

include(GNUInstallDirs)

And declare files to install:

install(TARGETS mylib
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})

You may also export a pkg-config file. This file allows a third-party application to easily import your library:

Create a template file named mylib.pc.in (see pc(5) manpage for more information):

prefix=@CMAKE_INSTALL_PREFIX@
exec_prefix=@CMAKE_INSTALL_PREFIX@
libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@

Name: @PROJECT_NAME@
Description: @PROJECT_DESCRIPTION@
Version: @PROJECT_VERSION@

Requires:
Libs: -L${libdir} -lmylib
Cflags: -I${includedir}

In your CMakeLists.txt, add a rule to expand @ macros (@ONLY ask to cmake to not expand variables of the form ${VAR}):

configure_file(mylib.pc.in mylib.pc @ONLY)

And finally, install generated file:

install(FILES ${CMAKE_BINARY_DIR}/mylib.pc DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)

You may also use cmake EXPORT feature. However, this feature is only compatible with cmake and I find it difficult to use.

Finally the entire CMakeLists.txt should looks like:

cmake_minimum_required(VERSION 3.9)
project(mylib VERSION 1.0.1 DESCRIPTION "mylib description")
include(GNUInstallDirs)
add_library(mylib SHARED src/mylib.c)
set_target_properties(mylib PROPERTIES
    VERSION ${PROJECT_VERSION}
    SOVERSION 1
    PUBLIC_HEADER api/mylib.h)
configure_file(mylib.pc.in mylib.pc @ONLY)
target_include_directories(mylib PRIVATE .)
install(TARGETS mylib
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES ${CMAKE_BINARY_DIR}/mylib.pc
    DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)

Getting mouse position in c#

To get the position look at the OnMouseMove event. The MouseEventArgs will give you the x an y positions...

protected override void OnMouseMove(MouseEventArgs mouseEv) 

To set the mouse position use the Cursor.Position property.

http://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.position.aspx

How do I get the parent directory in Python?

import os

def parent_filedir(n):
    return parent_filedir_iter(n, os.path.dirname(__file__))

def parent_filedir_iter(n, path):
    n = int(n)
    if n <= 1:
        return path
    return parent_filedir_iter(n - 1, os.path.dirname(path))

test_dir = os.path.abspath(parent_filedir(2))

Byte Array and Int conversion in Java

I found a simple way in com.google.common.primitives which is in the [Maven:com.google.guava:guava:12.0.1]

long newLong = Longs.fromByteArray(oldLongByteArray);
int newInt = Ints.fromByteArray(oldIntByteArray);

Have a nice try :)

Select multiple images from android gallery

https://github.com/Sarjeetsinghbabu/Gallery create intent for reqouest image list

          int LAUNCH_SECOND_ACTIVITY = 101;

           Intent i = new Intent(CallMainActivity2.this, 
            GalleryFoldersActivity.class);
            startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);

https://github.com/Sarjeetsinghbabu/Gallery

After selected image get list of model

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == LAUNCH_SECOND_ACTIVITY) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
            Log.d(TAG, "onActivityResult: "+result);
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}

https://github.com/Sarjeetsinghbabu/Gallery enter image description here

enter image description here

How to capture no file for fs.readFileSync()?

I prefer this way of handling this. You can check if the file exists synchronously:

var file = 'info.json';
var content = '';

// Check that the file exists locally
if(!fs.existsSync(file)) {
  console.log("File not found");
}

// The file *does* exist
else {
  // Read the file and do anything you want
  content = fs.readFileSync(file, 'utf-8');
}

Note: if your program also deletes files, this has a race condition as noted in the comments. If however you only write or overwrite files, without deleting them, then this is totally fine.

Why is C so fast, and why aren't other languages as fast or faster?

With modern optimizing compilers, it's highly unlikely that a pure C program is going to be all that much faster than compiled .net code, if at all. With the productivity enhancement that frameworks like .net provide the developer, you can do things in a day that used to take weeks or months in regular C. Coupled with the cheap cost of hardware compared to a developer's salary, it's just WAY cheaper to write the stuff in a high-level language and throw hardware at any slowness.

The reason Jeff and Joel talk about C being the "real programmer" language is because there is no hand-holding in C. You must allocate your own memory, deallocate that memory, do your own bounds-checking, etc. There's no such thing as new object(); There's no garbage collection, classes, OOP, entity frameworks, LINQ, properties, attributes, fields, or anything like that. You have to know things like pointer arithmetic and how to dereference a pointer. And, for that matter, know and understand what a pointer is. You have to know what a stack frame is and what the instruction pointer is. You have to know the memory model of the CPU architecture you're working on. There is a lot of implicit understanding of the architecture of a microcomputer (usually the microcomputer you're working on) when programming in C that simply is not present nor necessary when programming in something like C# or Java. All of that information has been off-loaded to the compiler (or VM) programmer.

How to copy a file from remote server to local machine?

I would recommend to use sftp, use this command sftp -oPort=7777 user@host where -oPort is custom port number of ssh , in case if u changed it to 7777, then u can use -oPort, else if use only port 22 then plain sftp user@host which asks for the password , then u can log in, and u can navigate to required location using cd /home/user then a simple command get table u can download it, If u want to download a directory/folder get -r someDirectory will do it. If u want the file permissions also to exist then get -Pr someDirectory. For uploading on to remote change get to put in above commands.

Cant get text of a DropDownList in code - can get value but not text

had the same problem and just solved it, i used string [variable_Name] =dropdownlist1.SelectedItem.Text;

Finding duplicate values in a SQL table

The exact code would differ depending on whether you want to find duplicate rows as well or only different ids with the same email and name. If id is a primary key or otherwise has a unique constraint this distinction does not exist, but the question does not specify this. In the former case you can use code given in several other answers:

SELECT name, email, COUNT(*)
FROM users
GROUP BY name, email
HAVING COUNT(*) > 1

In the latter case you would use:

SELECT name, email, COUNT(DISTINCT id)
FROM users
GROUP BY name, email
HAVING COUNT(DISTINCT id) > 1
ORDER BY COUNT(DISTINCT id) DESC

How to calculate number of days between two dates

Try this Using moment.js (Its quite easy to compute date operations in javascript)

firstDate.diff(secondDate, 'days', false);// true|false for fraction value

Result will give you number of days in integer.

How do I 'svn add' all unversioned files to SVN?

svn add --force .

This will add any unversioned file in the current directory and all versioned child directories.

How can I install packages using pip according to the requirements.txt file from a local directory?

This works for everyone:

pip install -r /path/to/requirements.txt

Cross field validation with Hibernate Validator (JSR 303)

I'm surprised this isn't available out of the box. Anyway, here is a possible solution.

I've created a class level validator, not the field level as described in the original question.

Here is the annotation code:

package com.moa.podium.util.constraints;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = MatchesValidator.class)
@Documented
public @interface Matches {

  String message() default "{com.moa.podium.util.constraints.matches}";

  Class<?>[] groups() default {};

  Class<? extends Payload>[] payload() default {};

  String field();

  String verifyField();
}

And the validator itself:

package com.moa.podium.util.constraints;

import org.mvel2.MVEL;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class MatchesValidator implements ConstraintValidator<Matches, Object> {

  private String field;
  private String verifyField;


  public void initialize(Matches constraintAnnotation) {
    this.field = constraintAnnotation.field();
    this.verifyField = constraintAnnotation.verifyField();
  }

  public boolean isValid(Object value, ConstraintValidatorContext context) {
    Object fieldObj = MVEL.getProperty(field, value);
    Object verifyFieldObj = MVEL.getProperty(verifyField, value);

    boolean neitherSet = (fieldObj == null) && (verifyFieldObj == null);

    if (neitherSet) {
      return true;
    }

    boolean matches = (fieldObj != null) && fieldObj.equals(verifyFieldObj);

    if (!matches) {
      context.disableDefaultConstraintViolation();
      context.buildConstraintViolationWithTemplate("message")
          .addNode(verifyField)
          .addConstraintViolation();
    }

    return matches;
  }
}

Note that I've used MVEL to inspect the properties of the object being validated. This could be replaced with the standard reflection APIs or if it is a specific class you are validating, the accessor methods themselves.

The @Matches annotation can then be used used on a bean as follows:

@Matches(field="pass", verifyField="passRepeat")
public class AccountCreateForm {

  @Size(min=6, max=50)
  private String pass;
  private String passRepeat;

  ...
}

As a disclaimer, I wrote this in the last 5 minutes, so I probably haven't ironed out all the bugs yet. I'll update the answer if anything goes wrong.

Is it possible to modify a string of char in C?

It seems like your question has been answered but now you might wonder why char *a = "String" is stored in read-only memory. Well, it is actually left undefined by the c99 standard but most compilers choose to it this way for instances like:

printf("Hello, World\n");

c99 standard(pdf) [page 130, section 6.7.8]:

The declaration:

char s[] = "abc", t[3] = "abc";

defines "plain" char array objects s and t whose elements are initialized with character string literals. This declaration is identical to char

s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

char *p = "abc";

defines p with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

Detect network connection type on Android

The answer from Emil Davtyan is good, but network types have been added that are not accounted for in his answer. So, isConnectionFast(int type, int subType) may return false when it should be true.

Here is a modified class which uses reflection to account for added network types in later APIs:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * <p>Utility methods to check the current network connection status.</p>
 *
 * <p>This requires the caller to hold the permission
 * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.</p>
 */
public class NetworkUtils {

  /** The absence of a connection type. */
  public static final int TYPE_NONE = -1;

  /** Unknown network class. */
  public static final int NETWORK_CLASS_UNKNOWN = 0;
  /** Class of broadly defined "2G" networks. */
  public static final int NETWORK_CLASS_2_G = 1;
  /** Class of broadly defined "3G" networks. */
  public static final int NETWORK_CLASS_3_G = 2;
  /** Class of broadly defined "4G" networks. */
  public static final int NETWORK_CLASS_4_G = 3;

  /**
   * Returns details about the currently active default data network. When connected, this network
   * is the default route for outgoing connections. You should always check {@link
   * NetworkInfo#isConnected()} before initiating network traffic. This may return {@code null}
   * when there is no default network.
   *
   * @return a {@link NetworkInfo} object for the current default network or {@code null} if no
   * network default network is currently active
   *
   * This method requires the call to hold the permission
   * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
   * @see ConnectivityManager#getActiveNetworkInfo()
   */
  public static NetworkInfo getInfo(Context context) {
    return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
        .getActiveNetworkInfo();
  }

  /**
   * Reports the current network type.
   *
   * @return {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI} ,
   * {@link ConnectivityManager#TYPE_WIMAX}, {@link ConnectivityManager#TYPE_ETHERNET}, {@link
   * ConnectivityManager#TYPE_BLUETOOTH}, or other types defined by {@link ConnectivityManager}.
   * If there is no network connection then -1 is returned.
   * @see NetworkInfo#getType()
   */
  public static int getType(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return TYPE_NONE;
    }
    return info.getType();
  }

  /**
   * Return a network-type-specific integer describing the subtype of the network.
   *
   * @return the network subtype
   * @see NetworkInfo#getSubtype()
   */
  public static int getSubType(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return TYPE_NONE;
    }
    return info.getSubtype();
  }

  /** Returns the NETWORK_TYPE_xxxx for current data connection. */
  public static int getNetworkType(Context context) {
    return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
        .getNetworkType();
  }

  /** Check if there is any connectivity */
  public static boolean isConnected(Context context) {
    return getType(context) != TYPE_NONE;
  }

  /** Check if there is any connectivity to a Wifi network */
  public static boolean isWifiConnection(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return false;
    }
    switch (info.getType()) {
      case ConnectivityManager.TYPE_WIFI:
        return true;
      default:
        return false;
    }
  }

  /** Check if there is any connectivity to a mobile network */
  public static boolean isMobileConnection(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return false;
    }
    switch (info.getType()) {
      case ConnectivityManager.TYPE_MOBILE:
        return true;
      default:
        return false;
    }
  }

  /** Check if the current connection is fast. */
  public static boolean isConnectionFast(Context context) {
    NetworkInfo info = getInfo(context);
    if (info == null || !info.isConnected()) {
      return false;
    }
    switch (info.getType()) {
      case ConnectivityManager.TYPE_WIFI:
      case ConnectivityManager.TYPE_ETHERNET:
        return true;
      case ConnectivityManager.TYPE_MOBILE:
        int networkClass = getNetworkClass(getNetworkType(context));
        switch (networkClass) {
          case NETWORK_CLASS_UNKNOWN:
          case NETWORK_CLASS_2_G:
            return false;
          case NETWORK_CLASS_3_G:
          case NETWORK_CLASS_4_G:
            return true;
        }
      default:
        return false;
    }
  }

  private static int getNetworkClassReflect(int networkType)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Method getNetworkClass = TelephonyManager.class.getDeclaredMethod("getNetworkClass", int.class);
    if (!getNetworkClass.isAccessible()) {
      getNetworkClass.setAccessible(true);
    }
    return (int) getNetworkClass.invoke(null, networkType);
  }

  /**
   * Return general class of network type, such as "3G" or "4G". In cases where classification is
   * contentious, this method is conservative.
   */
  public static int getNetworkClass(int networkType) {
    try {
      return getNetworkClassReflect(networkType);
    } catch (Exception ignored) {
    }

    switch (networkType) {
      case TelephonyManager.NETWORK_TYPE_GPRS:
      case 16: // TelephonyManager.NETWORK_TYPE_GSM:
      case TelephonyManager.NETWORK_TYPE_EDGE:
      case TelephonyManager.NETWORK_TYPE_CDMA:
      case TelephonyManager.NETWORK_TYPE_1xRTT:
      case TelephonyManager.NETWORK_TYPE_IDEN:
        return NETWORK_CLASS_2_G;
      case TelephonyManager.NETWORK_TYPE_UMTS:
      case TelephonyManager.NETWORK_TYPE_EVDO_0:
      case TelephonyManager.NETWORK_TYPE_EVDO_A:
      case TelephonyManager.NETWORK_TYPE_HSDPA:
      case TelephonyManager.NETWORK_TYPE_HSUPA:
      case TelephonyManager.NETWORK_TYPE_HSPA:
      case TelephonyManager.NETWORK_TYPE_EVDO_B:
      case TelephonyManager.NETWORK_TYPE_EHRPD:
      case TelephonyManager.NETWORK_TYPE_HSPAP:
      case 17: // TelephonyManager.NETWORK_TYPE_TD_SCDMA:
        return NETWORK_CLASS_3_G;
      case TelephonyManager.NETWORK_TYPE_LTE:
      case 18: // TelephonyManager.NETWORK_TYPE_IWLAN:
        return NETWORK_CLASS_4_G;
      default:
        return NETWORK_CLASS_UNKNOWN;
    }
  }

  private NetworkUtils() {
    throw new AssertionError();
  }

}

How to create an Array with AngularJS's ng-model

First thing is first. You need to define $scope.telephone as an array in your controller before you can start using it in your view.

$scope.telephone = [];

To address the issue of ng-model not being recognised when you append a new input - for that to work you have to use the $compile Angular service.

From the Angular.js API reference on $compile:

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

// I'm using Angular syntax. Using jQuery will have the same effect
// Create input element
var input = angular.element('<div><input type="text" ng-model="telephone[' + $scope.inputCounter + ']"></div>');
// Compile the HTML and assign to scope
var compile = $compile(input)($scope);

Have a look on JSFiddle

How can I switch my signed in user in Visual Studio 2013?

I was also able to fix this by signing in putting my product key in and then signing out and then logging in under my new login.

Plain Old CLR Object vs Data Transfer Object

TL;DR:

A DTO describes the pattern of state transfer. A POCO doesn't describe anything. It's another way of saying "object" in OOP. It comes from POJO (Java), coined by Martin Fowler who literally just describes it as a fancier name for 'object' because 'object' isn't very sexy.

A DTO is an object pattern used to transfer state between layers of concern. They can have behavior (i.e. can technically be a poco) so long as that behavior doesn't mutate the state. For example, it may have a method that serializes itself.

A POCO is a plain object, but what is meant by 'plain' is that it is not special. It just means it's a CLR object with no implied pattern to it. A generic term. It isn't made to work with some other framework. So if your POCO has [JsonProperty] or EF decorations all over it's properties, for example, then it I'd argue that it isn't a POCO.

Here some examples of different kinds of object patterns to compare:

  • View Model: used to model data for a view. Usually has data annotations to assist binding and validation. In MVVM, it also acts as a controller. It's more than a DTO
  • Value Object: used to represent values
  • Aggregate Root: used to manage state and invariants
  • Handlers: used to respond to an event/message
  • Attributes: used as decorations to deal with cross-cutting concerns
  • Service: used to perform complex tasks
  • Controller: used to control flow of requests and responses
  • Factory: used to configure and/or assemble complex objects for use when a constructor isn't good enough. Also used to make decisions on which objects need to be created at runtime.
  • Repository/DAO: used to access data

These are all just objects, but notice that most of them are generally tied to a pattern. So you could call them "objects" or you could be more specific about its intent and call it by what it is. This is also why we have design patterns; to describe complex concepts in a few works. DTO is a pattern. Aggregate root is a pattern, View Model is a pattern (e.g. MVC & MVVM). POCO is not a pattern.

A POCO doesn't describe a pattern. It is just a different way of referring to classes/objects in OOP. Think of it as an abstract concept; they can be referring to anything. IMO, there's a one-way relationship though because once an object reaches the point where it can only serve one purpose cleanly, it is no longer a POCO. For example, once you mark up your class with decorations to make it work with some framework, it is no longer a POCO. Therefore:

  • A DTO is a POCO
  • A POCO is not a DTO
  • A View Model is a POCO
  • A POCO is not a View Model

The point in making a distinction between the two is about keeping patterns clear and consistent in effort to not cross concerns and lead to tight coupling. For example if you have a business object that has methods to mutate state, but is also decorated to hell with EF decorations for saving to SQL Server AND JsonProperty so that it can be sent back over an API endpoint. That object would be intolerant to change, and would likely be littered with variants of properties (e.g. UserId, UserPk, UserKey, UserGuid, where some of them are marked up to not be saved to the DB and others marked up to not be serialized to JSON at the API endpoint).

So if you were to tell me something was a DTO, then I'd probably make sure it was never used for anything other than moving state around. If you told me something was a view model, then I'd probably make sure it wasn't getting saved to a database. If you told me something was a Domain Model, then I'd probably make sure it had no dependencies on anything outside of the domain. But if you told me something was a POCO, you wouldn't really be telling me much at all.

Finding row index containing maximum value using R

See ?order. You just need the last index (or first, in decreasing order), so this should do the trick:

order(matrix[,2],decreasing=T)[1]

How to deal with persistent storage (e.g. databases) in Docker

I'm just using a predefined directory on the host to persist data for PostgreSQL. Also, this way it is possible to easily migrate existing PostgreSQL installations to Docker containers: https://crondev.com/persistent-postgresql-inside-docker/

Name does not exist in the current context

"The project works on the laptop, but now having copied the updated source code onto the desktop ..."

I did something similar, creating two versions of a project and copying files between them. It gave me the same error.

My solution was to go into the project file, where I discovered that what had looked like this:

<Compile Include="App_Code\Common\Pair.cs" />
<Compile Include="App_Code\Common\QueryCommand.cs" />

Now looked like this:

<Content Include="App_Code\Common\Pair.cs">
  <SubType>Code</SubType>
</Content>
<Content Include="App_Code\Common\QueryCommand.cs">
  <SubType>Code</SubType>
</Content>

When I changed them back, Visual Studio was happy again.

Confirm password validation in Angular 6

You can use this way to fulfill this requirement. I use the below method to validate the Password and Confirm Password.

To use this method you have to import FormGroup from @angular/forms library.

import { FormBuilder, Validators, FormGroup } from '@angular/forms';

FormBuilder Group:

this.myForm= this.formBuilder.group({
  password    : ['', Validators.compose([Validators.required])],
  confirmPassword    : ['',  Validators.compose([Validators.required])],
},
{validator: this.checkPassword('password', 'confirmPassword') }
);

Method to Validate two fields:

 checkPassword(controlName: string, matchingControlName: string) {
    return (formGroup: FormGroup) => {
        const control = formGroup.controls[controlName];
        const matchingControl = formGroup.controls[matchingControlName];
        if (matchingControl.errors && !matchingControl.errors.mustMatch) {
            // return if another validator has already found an error on the matchingControl
            return;
        }
        // set error on matchingControl if validation fails
        if (control.value !== matchingControl.value) {
            matchingControl.setErrors({ mustMatch: true });
            this.isPasswordSame = (matchingControl.status == 'VALID') ? true : false;
        } else {
            matchingControl.setErrors(null);
            this.isPasswordSame = (matchingControl.status == 'VALID') ? true : false;
        }
    }
  }

HTML: Here I am use personalized isPasswordSame variable you can use the inbuilt hasError or any other.

<form [formGroup]="myForm">
  <ion-item>
    <ion-label position="floating">Password</ion-label>
    <ion-input required type="text" formControlName="password" placeholder="Enter Password"></ion-input>
  </ion-item>
  <ion-label *ngIf="myForm.controls.password.valid">
      <p class="error">Please enter password!!</p>
  </ion-label>
  <ion-item>
    <ion-label position="floating">Confirm Password</ion-label>
    <ion-input required type="text" formControlName="confirmPassword" placeholder="Enter Confirm Password"></ion-input>
  </ion-item>
  <ion-label *ngIf="isPasswordSame">
      <p class="error">Password and Confrim Password must be same!!</p>
  </ion-label>
</form>

Should I use <i> tag for icons instead of <span>?

Why are they using <i> tag to display icons ?

Because it is:

  • Short
  • i stands for icon (although not in HTML)

Is it not a bad practice ?

Awful practice. It is a triumph of performance over semantics.

How to work on UAC when installing XAMPP

To disable UAC go to Start>Control Panel>User Accounts there you will find an option Turn User Account Control on or off just click on it and uncheck User Account Control to help protect your computer click OK.

Please refer to this link : https://community.apachefriends.org/f/viewtopic.php?f=16&t=45364

Youtube - downloading a playlist - youtube-dl

Removing the v=...& part from the url, and only keep the list=... part. The main problem being the special character &, interpreted by the shell.

You can also quote your 'url' in your command.

More information here (for instance) :

https://askubuntu.com/questions/564567/how-to-download-playlist-from-youtube-dl

throwing exceptions out of a destructor

So my question is this - if throwing from a destructor results in undefined behavior, how do you handle errors that occur during a destructor?

The main problem is this: you can't fail to fail. What does it mean to fail to fail, after all? If committing a transaction to a database fails, and it fails to fail (fails to rollback), what happens to the integrity of our data?

Since destructors are invoked for both normal and exceptional (fail) paths, they themselves cannot fail or else we're "failing to fail".

This is a conceptually difficult problem but often the solution is to just find a way to make sure that failing cannot fail. For example, a database might write changes prior to committing to an external data structure or file. If the transaction fails, then the file/data structure can be tossed away. All it has to then ensure is that committing the changes from that external structure/file an atomic transaction that can't fail.

The pragmatic solution is perhaps just make sure that the chances of failing on failure are astronomically improbable, since making things impossible to fail to fail can be almost impossible in some cases.

The most proper solution to me is to write your non-cleanup logic in a way such that the cleanup logic can't fail. For example, if you're tempted to create a new data structure in order to clean up an existing data structure, then perhaps you might seek to create that auxiliary structure in advance so that we no longer have to create it inside a destructor.

This is all much easier said than done, admittedly, but it's the only really proper way I see to go about it. Sometimes I think there should be an ability to write separate destructor logic for normal execution paths away from exceptional ones, since sometimes destructors feel a little bit like they have double the responsibilities by trying to handle both (an example is scope guards which require explicit dismissal; they wouldn't require this if they could differentiate exceptional destruction paths from non-exceptional ones).

Still the ultimate problem is that we can't fail to fail, and it's a hard conceptual design problem to solve perfectly in all cases. It does get easier if you don't get too wrapped up in complex control structures with tons of teeny objects interacting with each other, and instead model your designs in a slightly bulkier fashion (example: particle system with a destructor to destroy the entire particle system, not a separate non-trivial destructor per particle). When you model your designs at this kind of coarser level, you have less non-trivial destructors to deal with, and can also often afford whatever memory/processing overhead is required to make sure your destructors cannot fail.

And that's one of the easiest solutions naturally is to use destructors less often. In the particle example above, perhaps upon destroying/removing a particle, some things should be done that could fail for whatever reason. In that case, instead of invoking such logic through the particle's dtor which could be executed in an exceptional path, you could instead have it all done by the particle system when it removes a particle. Removing a particle might always be done during a non-exceptional path. If the system is destroyed, maybe it can just purge all particles and not bother with that individual particle removal logic which can fail, while the logic that can fail is only executed during the particle system's normal execution when it's removing one or more particles.

There are often solutions like that which crop up if you avoid dealing with lots of teeny objects with non-trivial destructors. Where you can get tangled up in a mess where it seems almost impossible to be exception-safety is when you do get tangled up in lots of teeny objects that all have non-trivial dtors.

It would help a lot if nothrow/noexcept actually translated into a compiler error if anything which specifies it (including virtual functions which should inherit the noexcept specification of its base class) attempted to invoke anything that could throw. This way we'd be able to catch all this stuff at compile-time if we actually write a destructor inadvertently which could throw.

Sublime Text 2: How to delete blank/empty lines

Sublime Text 2 & 3

The Comments of @crates work for me,

Step 1: Simply press on ctrl+H

Step 2: press on RegEX key

Step 3: write this in the Find: ^[\s]*?[\n\r]+

Step 4: replace all

Check Whether a User Exists

Using sed:

username="alice"
if [ `sed -n "/^$username/p" /etc/passwd` ]
then
    echo "User [$username] already exists"
else
    echo "User [$username] doesn't exist"
fi

limit text length in php and provide 'Read more' link

Another method: insert the following in your theme's function.php file.

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_trim_excerpt');

function custom_trim_excerpt($text) { // Fakes an excerpt if needed
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = x;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
array_push($words, '...');
$text = implode(' ', $words);
}
}
return $text;
}

You can use this.

How to show google.com in an iframe?

This used to work because I used it to create custom Google searches with my own options. Google made changes on their end and broke my private customized search page :( No longer working sample below. It was very useful for complex search patterns.

<form method="get" action="http://www.google.com/search" target="main"><input name="q" value="" type="hidden"> <input name="q" size="40" maxlength="2000" value="" type="text">

web

I guess the better option is to just use Curl or similar.

How can I override the OnBeforeUnload dialog and replace it with my own?

What about to use the specialized version of the "bind" command "one". Once the event handler executes the first time, it’s automatically removed as an event handler.

$(window).one("beforeunload", BeforeUnload);

How can I check if the array of objects have duplicate property values?

//checking duplicate elements in an array
var arr=[1,3,4,6,8,9,1,3,4,7];
var hp=new Map();
console.log(arr.sort());
var freq=0;
for(var i=1;i<arr.length;i++){
// console.log(arr[i-1]+" "+arr[i]);
if(arr[i]==arr[i-1]){
freq++;

}
else{
hp.set(arr[i-1],freq+1);
freq=0;
}
}
console.log(hp);

Reading a plain text file in Java

import java.util.stream.Stream;
import java.nio.file.*;
import java.io.*;

class ReadFile {

 public static void main(String[] args) {

    String filename = "Test.txt";

    try(Stream<String> stream = Files.lines(Paths.get(filename))) {

          stream.forEach(System.out:: println);

    } catch (IOException e) {

        e.printStackTrace();
    }

 }

 }

Just use java 8 Stream.

Detecting a redirect in ajax request?

You can now use fetch API/ It returns redirected: *boolean*

How to run stored procedures in Entity Framework Core?

Nothing have to do... when you are creating dbcontext for code first approach initialize namespace below the fluent API area make list of sp and use it another place where you want.

public partial class JobScheduleSmsEntities : DbContext
{
    public JobScheduleSmsEntities()
        : base("name=JobScheduleSmsEntities")
    {
        Database.SetInitializer<JobScheduleSmsEntities>(new CreateDatabaseIfNotExists<JobScheduleSmsEntities>());
    }

    public virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<ReachargeDetail> ReachargeDetails { get; set; }
    public virtual DbSet<RoleMaster> RoleMasters { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //modelBuilder.Types().Configure(t => t.MapToStoredProcedures());

        //modelBuilder.Entity<RoleMaster>()
        //     .HasMany(e => e.Customers)
        //     .WithRequired(e => e.RoleMaster)
        //     .HasForeignKey(e => e.RoleID)
        //     .WillCascadeOnDelete(false);
    }
    public virtual List<Sp_CustomerDetails02> Sp_CustomerDetails()
    {
        //return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Sp_CustomerDetails02>("Sp_CustomerDetails");
        //  this.Database.SqlQuery<Sp_CustomerDetails02>("Sp_CustomerDetails");
        using (JobScheduleSmsEntities db = new JobScheduleSmsEntities())
        {
           return db.Database.SqlQuery<Sp_CustomerDetails02>("Sp_CustomerDetails").ToList();

        }

    }

}

}

public partial class Sp_CustomerDetails02
{
    public long? ID { get; set; }
    public string Name { get; set; }
    public string CustomerID { get; set; }
    public long? CustID { get; set; }
    public long? Customer_ID { get; set; }
    public decimal? Amount { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public int? CountDay { get; set; }
    public int? EndDateCountDay { get; set; }
    public DateTime? RenewDate { get; set; }
    public bool? IsSMS { get; set; }
    public bool? IsActive { get; set; }
    public string Contact { get; set; }
}

Why would I use dirname(__FILE__) in an include or include_once statement?

I might have even a simpler explanation to this question compared to the accepted answer so I'm going to give it a go: Assume this is the structure of the files and directories of a project:

Project root directory:
                       file1.php
                       file3.php
                       dir1/
                            file2.php

(dir1 is a directory and file2.php is inside it)

And this is the content of each of the three files above:

//file1.php:
<?php include "dir1/file2.php"

//file2.php:
<?php include "../file3.php"

//file3.php:
<?php echo "Hello, Test!";

Now run file1.php and try to guess what should happen. You might expect to see "Hello, Test!", however, it won't be shown! What you'll get instead will be an error indicating that the file you have requested(file3.php) does not exist!

The reason is that, inside file1.php when you include file2.php, the content of it is getting copied and then pasted back directly into file1.php which is inside the root directory, thus this part "../file3.php" runs from the root directory and thus goes one directory up the root! (and obviously it won't find the file3.php).

Now, what should we do ?!

Relative paths of course have the problem above, so we have to use absolute paths. However, absolute paths have also one problem. If you (for example) copy the root folder (containing your whole project) and paste it in anywhere else on your computer, the paths will be invalid from that point on! And that'll be a REAL MESS!

So we kind of need paths that are both absolute and dynamic(Each file dynamically finds the absolute path of itself wherever we place it)!

The way we do that is by getting help from PHP, and dirname() is the function to go for, which gives the absolute path to the directory in which a file exists in. And each file name could also be easily accessed using the __FILE__ constant. So dirname(__FILE__) would easily give you the absolute (while dynamic!) path to the file we're typing in the above code. Now move your whole project to a new place, or even a new system, and tada! it works!

So now if we turn the project above to this:

//file1.php:
<?php include(dirname(__FILE__)."/dir1/file2.php");

//file2.php:
<?php include(dirname(__FILE__)."/../file3.php");

//file3.php:
<?php echo "Hello, Test!";

if you run it, you'll see the almighty Hello, Test!! (hopefully, if you've not done anything else wrong).

It's also worth mentioning that from PHP5, a nicer way(with regards to readability and preventing eye boilage!) has been provided by PHP as well which is the constant __DIR__ which does exactly the same thing as dirname(__FILE__)!

Hope that helps.

jQuery looping .each() JSON key/value not working

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

Adding an .env file to React Project

4 steps

  1. npm install dotenv --save

  2. Next add the following line to your app.

    require('dotenv').config()

  3. Then create a .env file at the root directory of your application and add the variables to it.

// contents of .env 

REACT_APP_API_KEY = 'my-secret-api-key'
  1. Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.

If you are using create-react-app then you only need step 3 and 4 but keep in mind variable needs to start with REACT_APP_ for it to work.

Reference: https://create-react-app.dev/docs/adding-custom-environment-variables/

NOTE - Need to restart application after adding variable in .env file.

Reference - https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f

How to add a browser tab icon (favicon) for a website?

There are a number of different icons and even splash screens that you can set for various devices. This answer goes through how to support them all.

Here are some snippets I have used with relevant links to where I gathered the information. See my blog for more information and more information about the ASP.NET MVC Boilerplate project template with all this built in right out of the box (Including sample image files).

Add the following mark-up to your html head. The commented out sections are entirely optional. While the uncommented sections are recommended to cover all icon usages. Don't be scared, most if it is comments to help you.

<!-- Icons & Platform Specific Settings - Favicon generator used to generate the icons below http://realfavicongenerator.net/ -->
<!-- shortcut icon - It is best to add this icon to the root of your site and only use this link element if you move it somewhere else. This file contains the following sizes 16x16, 32x32 and 48x48. -->
<!--<link rel="shortcut icon" href="favicon.ico">-->
<!-- favicon-96x96.png - For Google TV. -->
<link rel="icon" type="image/png" href="/content/images/favicon-96x96.png" sizes="96x96">
<!-- favicon-16x16.png - The classic favicon, displayed in the tabs. -->
<link rel="icon" type="image/png" href="/content/images/favicon-16x16.png" sizes="16x16">
<!-- favicon-32x32.png - For Safari on Mac OS. -->
<link rel="icon" type="image/png" href="/content/images/favicon-32x32.png" sizes="32x32">

<!-- Android/Chrome -->
<!-- manifest-json - The location of the browser configuration file. It contains locations of icon files, name of the application and default device screen orientation. Note that the name field is mandatory.
    https://developer.chrome.com/multidevice/android/installtohomescreen. -->
<link rel="manifest" href="/content/icons/manifest.json">
<!-- theme-color - The colour of the toolbar in Chrome M39+
    http://updates.html5rocks.com/2014/11/Support-for-theme-color-in-Chrome-39-for-Android -->
<meta name="theme-color" content="#1E1E1E">
<!-- favicon-192x192.png - For Android Chrome M36 to M38 this HTML is used. M39+ uses the manifest.json file. -->
<link rel="icon" type="image/png" href="/content/icons/favicon-192x192.png" sizes="192x192">
<!-- mobile-web-app-capable - Run Android/Chrome version M31 to M38 in standalone mode, hiding the browser chrome. -->
<!-- <meta name="mobile-web-app-capable" content="yes"> -->

<!-- Apple Icons - You can move all these icons to the root of the site and remove these link elements, if you don't mind the clutter.
    https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Introduction.html#//apple_ref/doc/uid/30001261-SW1 -->
<!-- apple-mobile-web-app-title - The name of the application if pinned to the IOS start screen. -->
<!--<meta name="apple-mobile-web-app-title" content="">-->
<!-- apple-mobile-web-app-capable - Hide the browsers user interface on IOS, when the app is run in 'standalone' mode. Any links to other pages that are clicked whilst your app is in standalone mode will launch the full Safari browser. -->
<!--<meta name="apple-mobile-web-app-capable" content="yes">-->
<!-- apple-mobile-web-app-status-bar-style - default/black/black-translucent Styles the IOS status bar. Using black-translucent makes it transparent and overlays it on top of your site, so make sure you have enough margin. -->
<!--<meta name="apple-mobile-web-app-status-bar-style" content="black">-->
<!-- apple-touch-icon-57x57.png - Android Stock Browser and non-Retina iPhone and iPod Touch -->
<link rel="apple-touch-icon" sizes="57x57" href="/content/images/apple-touch-icon-57x57.png">
<!-- apple-touch-icon-114x114.png - iPhone (with 2× display) iOS = 6 -->
<link rel="apple-touch-icon" sizes="114x114" href="/content/images/apple-touch-icon-114x114.png">
<!-- apple-touch-icon-72x72.png - iPad mini and the first- and second-generation iPad (1× display) on iOS = 6 -->
<link rel="apple-touch-icon" sizes="72x72" href="/content/images/apple-touch-icon-72x72.png">
<!-- apple-touch-icon-144x144.png - iPad (with 2× display) iOS = 6 -->
<link rel="apple-touch-icon" sizes="144x144" href="/content/images/apple-touch-icon-144x144.png">
<!-- apple-touch-icon-60x60.png - Same as apple-touch-icon-57x57.png, for non-retina iPhone with iOS7. -->
<link rel="apple-touch-icon" sizes="60x60" href="/content/images/apple-touch-icon-60x60.png">
<!-- apple-touch-icon-120x120.png - iPhone (with 2× and 3 display) iOS = 7 -->
<link rel="apple-touch-icon" sizes="120x120" href="/content/images/apple-touch-icon-120x120.png">
<!-- apple-touch-icon-76x76.png - iPad mini and the first- and second-generation iPad (1× display) on iOS = 7 -->
<link rel="apple-touch-icon" sizes="76x76" href="/content/images/apple-touch-icon-76x76.png">
<!-- apple-touch-icon-152x152.png - iPad 3+ (with 2× display) iOS = 7 -->
<link rel="apple-touch-icon" sizes="152x152" href="/content/images/apple-touch-icon-152x152.png">
<!-- apple-touch-icon-180x180.png - iPad and iPad mini (with 2× display) iOS = 8 -->
<link rel="apple-touch-icon" sizes="180x180" href="/content/images/apple-touch-icon-180x180.png">

<!-- Apple Startup Images - These are shown when the page is loading if the site is pinned https://gist.github.com/tfausak/2222823 -->
<!-- apple-touch-startup-image-1536x2008.png - iOS 6 & 7 iPad (retina, portrait) -->
<link rel="apple-touch-startup-image"
      href="/content/images/apple-touch-startup-image-1536x2008.png"
      media="(device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2)">
<!-- apple-touch-startup-image-1496x2048.png - iOS 6 & 7 iPad (retina, landscape) -->
<link rel="apple-touch-startup-image"
      href="/content/images/apple-touch-startup-image-1496x2048.png"
      media="(device-width: 768px) and (device-height: 1024px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2)">
<!-- apple-touch-startup-image-768x1004.png - iOS 6 iPad (portrait) -->
<link rel="apple-touch-startup-image"
      href="/content/images/apple-touch-startup-image-768x1004.png"
      media="(device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 1)">
<!-- apple-touch-startup-image-748x1024.png - iOS 6 iPad (landscape) -->
<link rel="apple-touch-startup-image"
      href="/content/images/apple-touch-startup-image-748x1024.png"
      media="(device-width: 768px) and (device-height: 1024px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 1)">
<!-- apple-touch-startup-image-640x1096.png - iOS 6 & 7 iPhone 5 -->
<link rel="apple-touch-startup-image"
      href="/content/images/apple-touch-startup-image-640x1096.png"
      media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)">
<!-- apple-touch-startup-image-640x920.png - iOS 6 & 7 iPhone (retina) -->
<link rel="apple-touch-startup-image"
      href="/content/images/apple-touch-startup-image-640x920.png"
      media="(device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 2)">
<!-- apple-touch-startup-image-320x460.png - iOS 6 iPhone -->
<link rel="apple-touch-startup-image"
      href="/content/images/apple-touch-startup-image-320x460.png"
      media="(device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 1)">

<!-- Windows 8 Icons - If you add an RSS feed, revisit this page and regenerate the browserconfig.xml file. You will then have a cool live tile!
     browserconfig.xml - Windows 8.1 - Has been added to the root of the site. This points to the tile images and tile background colour. It contains the following images:
     mstile-70x70.png - For Windows 8.1 / IE11.
     mstile-144x144.png - For Windows 8 / IE10.
     mstile-150x150.png - For Windows 8.1 / IE11.
     mstile-310x310.png - For Windows 8.1 / IE11.
     mstile-310x150.png - For Windows 8.1 / IE11.
     See http://www.buildmypinnedsite.com/en and http://msdn.microsoft.com/en-gb/library/ie/dn255024%28v=vs.85%29.aspx. -->
<!-- application-name - Windows 8+ - The name of the application if pinned to the start screen. -->
<!--<meta name="application-name" content="">-->
<!-- msapplication-TileColor - Windows 8 - The tile colour which shows around your tile image (msapplication-TileImage). -->
<meta name="msapplication-TileColor" content="#5cb95c">
<!-- msapplication-TileImage - Windows 8 - The tile image. -->
<meta name="msapplication-TileImage" content="/content/images/mstile-144x144.png">

My browserconfig.xml file. Full explanation above.

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="/Content/Images/mstile-70x70.png"/>
      <square150x150logo src="/Content/Images/mstile-150x150.png"/>
      <square310x310logo src="/Content/Images/mstile-310x310.png"/>
      <wide310x150logo src="/Content/Images/mstile-310x150.png"/>
      <TileColor>#5cb95c</TileColor>
    </tile>
  </msapplication>
</browserconfig>

My manifest.json file. Full explanation above.

{
    "name": "ASP.NET MVC Boilerplate (Required! Update This)",
    "icons": [
        {
            "src": "\/Content\/icons\/android-chrome-36x36.png",
            "sizes": "36x36",
            "type": "image\/png",
            "density": "0.75"
        },
        {
            "src": "\/Content\/icons\/android-chrome-48x48.png",
            "sizes": "48x48",
            "type": "image\/png",
            "density": "1.0"
        },
        {
            "src": "\/Content\/icons\/android-chrome-72x72.png",
            "sizes": "72x72",
            "type": "image\/png",
            "density": "1.5"
        },
        {
            "src": "\/Content\/icons\/android-chrome-96x96.png",
            "sizes": "96x96",
            "type": "image\/png",
            "density": "2.0"
        },
        {
            "src": "\/Content\/icons\/android-chrome-144x144.png",
            "sizes": "144x144",
            "type": "image\/png",
            "density": "3.0"
        },
        {
            "src": "\/Content\/icons\/android-chrome-192x192.png",
            "sizes": "192x192",
            "type": "image\/png",
            "density": "4.0"
        }
    ]
}

A list of the files in the project (Note that the names of these files are important if you decide to put some of them at the root of your project to avoid using the above meta tags):

favicon.ico
browserconfig.xml
Content/Images/
    android-chrome-144x144.png
    android-chrome-192x192.png
    android-chrome-36x36.png
    android-chrome-48x48.png
    android-chrome-72x72.png
    android-chrome-96x96.png
    apple-touch-icon.png
    apple-touch-icon-57x57.png
    apple-touch-icon-60x60.png
    apple-touch-icon-72x72.png
    apple-touch-icon-76x76.png
    apple-touch-icon-114x114.png
    apple-touch-icon-120x120.png
    apple-touch-icon-144x144.png
    apple-touch-icon-152x152.png
    apple-touch-icon-180x180.png
    apple-touch-icon-precomposed.png (180x180)
    favicon-16x16.png
    favicon-32x32.png
    favicon-96x96.png
    favicon-192x192.png
    manifest.json
    mstile-70x70.png
    mstile-144x144.png
    mstile-150x150.png
    mstile-310x150.png
    mstile-310x310.png
    apple-touch-startup-image-1536x2008.png
    apple-touch-startup-image-1496x2048.png
    apple-touch-startup-image-768x1004.png
    apple-touch-startup-image-748x1024.png
    apple-touch-startup-image-640x1096.png
    apple-touch-startup-image-640x920.png
    apple-touch-startup-image-320x460.png

Total Overhead

If you take out the comments that's 3KB of extra HTML, if you don't support splash screens that's 1.5KB. If you are using GZIP compression on your HTML content, which everyone should be doing these days, that leaves you with about 634 Bytes of overhead per request to support all platforms or 446 Bytes without splash screens. I personally think its worth it to support IOS, Android and Windows devices but its your choice, I'm just giving the options!

Side Note About The Current Web Icon/Splash Screen/Settings Situation

This situation with vendor specific icons, splash screens and special tags to control the web browser or pinned icons is ridiculous. In a perfect world we would all use a favicon.svg file which could look good at any size and could be placed at the root of the page. Only FireFox supports this at the time of writing (See CanIUse.com).

However, icons are not the only setting these days, there are several other vendor specific settings (shown above) but a favicon.svg file would cover most use cases.

Update

Updated to include the new Android/Chrome version M39+ favicon/theming options. Interestingly, they have gone with a similar approach to Microsoft but are using a JSON file instead of XML.

ReactJS Two components communicating

The following code helps me to setup communication between two siblings. The setup is done in their parent during render() and componentDidMount() calls. It is based on https://reactjs.org/docs/refs-and-the-dom.html Hope it helps.

class App extends React.Component<IAppProps, IAppState> {
    private _navigationPanel: NavigationPanel;
    private _mapPanel: MapPanel;

    constructor() {
        super();
        this.state = {};
    }

    // `componentDidMount()` is called by ReactJS after `render()`
    componentDidMount() {
        // Pass _mapPanel to _navigationPanel
        // It will allow _navigationPanel to call _mapPanel directly
        this._navigationPanel.setMapPanel(this._mapPanel);
    }

    render() {
        return (
            <div id="appDiv" style={divStyle}>
                // `ref=` helps to get reference to a child during rendering
                <NavigationPanel ref={(child) => { this._navigationPanel = child; }} />
                <MapPanel ref={(child) => { this._mapPanel = child; }} />
            </div>
        );
    }
}

Is there a way to make a DIV unselectable?

Not sure of your use case, but you could make it draggable.

Get single listView SelectedItem

foreach (ListViewItem itemRow in taskShowListView.Items)
{
    if (itemRow.Items[0].Checked == true)
    {
        int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);

        string taskDate = itemRow.SubItems[1].ToString();
        string taskDescription = itemRow.SubItems[2].ToString();            
    }
}

Text Progress Bar in the Console

Code for python terminal progress bar

import sys
import time

max_length = 5
at_length = max_length
empty = "-"
used = "%"

bar = empty * max_length

for i in range(0, max_length):
    at_length -= 1

    #setting empty and full spots
    bar = used * i
    bar = bar+empty * at_length

    #\r is carriage return(sets cursor position in terminal to start of line)
    #\0 character escape

    sys.stdout.write("[{}]\0\r".format(bar))
    sys.stdout.flush()

    #do your stuff here instead of time.sleep
    time.sleep(1)

sys.stdout.write("\n")
sys.stdout.flush()

Functional style of Java 8's Optional.ifPresent and if-not-Present?

Another solution would be to use higher-order functions as follows

opt.<Runnable>map(value -> () -> System.out.println("Found " + value))
   .orElse(() -> System.out.println("Not Found"))
   .run();

Override browser form-filling and input highlighting with HTML/CSS

I've seen Google toolbar's autocomplete feature disabled with javascript. It might work with some other autofill tools; I don't know if it'll help with browsers built in autocomplete.

<script type="text/javascript"><!--
  if(window.attachEvent)
    window.attachEvent("onload",setListeners);

  function setListeners(){
    inputList = document.getElementsByTagName("INPUT");
    for(i=0;i<inputList.length;i++){
      inputList[i].attachEvent("onpropertychange",restoreStyles);
      inputList[i].style.backgroundColor = "";
    }
    selectList = document.getElementsByTagName("SELECT");
    for(i=0;i<selectList.length;i++){
      selectList[i].attachEvent("onpropertychange",restoreStyles);
      selectList[i].style.backgroundColor = "";
    }
  }

  function restoreStyles(){
    if(event.srcElement.style.backgroundColor != "")
      event.srcElement.style.backgroundColor = "";
  }//-->
</script>

How to avoid the "divide by zero" error in SQL?

You can at least stop the query from breaking with an error and return NULL if there is a division by zero:

SELECT a / NULLIF(b, 0) FROM t 

However, I would NEVER convert this to Zero with coalesce like it is shown in that other answer which got many upvotes. This is completely wrong in a mathematical sense, and it is even dangerous as your application will likely return wrong and misleading results.

Include an SVG (hosted on GitHub) in MarkDown

I contacted GitHub to say that github.io-hosted SVGs are no longer displayed in GitHub READMEs. I received this reply:

We have had to disable svg image rendering on GitHub.com due to potential cross site scripting vulnerabilities.

How to iterate over a string in C?

sizeof(source) returns the number of bytes required by the pointer char*. You should replace it with strlen(source) which will be the length of the string you're trying to display.

Also, you should probably replace printf("%s",source[i]) with printf("%c",source[i]) since you're displaying a character.

Getting list of files in documents folder

A shorter syntax for SWIFT 3

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

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

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

Usage example:

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

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

How do I align a label and a textarea?

Align the text area box to the label, not the label to the text area,

label {
    width: 180px;
    display: inline-block;
}

textarea{
    vertical-align: middle;
}

<label for="myfield">Label text</label><textarea id="myfield" rows="5" cols="30"></textarea>

Difference between id and name attributes in HTML

name is deprecated for link targets, and invalid in HTML5. It no longer works at least in latest Firefox (v13). Change <a name="hello"> to<a id="hello">

The target does not need to be an <a> tag, it can be <p id="hello"> or <h2 id="hello"> etc. which is often cleaner code.

As other posts say clearly, name is still used (needed) in forms. It is also still used in META tags.

SQL to generate a list of numbers from 1 to 100

Your question is difficult to understand, but if you want to select the numbers from 1 to 100, then this should do the trick:

Select Rownum r
From dual
Connect By Rownum <= 100

How to merge a specific commit in Git

I used to cherry pick, but found I had some mysterious issues from time to time. I came across a blog by Raymond Chen, a 25 year veteran at Microsoft, that describes some scenarios where cherry picking can cause issues in certain cases.

One of the rules of thumb is, if you cherry pick from one branch into another, then later merge between those branches, you're likely sooner or later going to experience issues.

Here's a reference to Raymond Chen's blogs on this topic: https://devblogs.microsoft.com/oldnewthing/20180312-00/?p=98215

The only issue I had with Raymond's blog is he did not provide a full working example. So I will attempt to provide one here.

The question above asks how to merge only the commit pointed to by the HEAD in the a-good-feature branch over to master.

Here is how that would be done:

  1. Find the common ancestor between the master and a-good-feature branches.
  2. Create a new branch from that ancestor, we'll call this new branch patch.
  3. Cherry pick one or more commits into this new patch branch.
  4. Merge the patch branch into both the master and a-good-feature branches.
  5. The master branch will now contain the commits, and both master and a-good-feature branches will also have a new common ancestor, which will resolve any future issues if further merging is performed later on.

Here is an example of those commands:

git checkout master...a-good-feature  [checkout the common ancestor]
git checkout -b patch
git cherry-pick a-good-feature  [this is not only the branch name, but also the commit we want]
git checkout master
git merge patch
git checkout a-good-feature
git merge -s ours patch

It might be worth noting that the last line that merged into the a-good-feature branch used the "-s ours" merge strategy. The reason for this is because we simply need to create a commit in the a-good-feature branch that points to a new common ancestor, and since the code is already in that branch, we want to make sure there isn't any chance of a merge conflict. This becomes more important if the commit(s) you are merging are not the most recent.

The scenarios and details surrounding partial merges can get pretty deep, so I recommend reading through all 10 parts of Raymond Chen's blog to gain a full understanding of what can go wrong, how to avoid it, and why this works.

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

This problem can be caused by requests for certain files that don't exist. For example, requests for files in wp-content/uploads/ where the file does not exist.

If this is the situation you're seeing, you can solve the problem by going to .htaccess and changing this line:

RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

to:

RewriteRule ^(wp-(content|admin|includes).*) - [L]

The underlying issue is that the rule above triggers a rewrite to the exact same url with a slash in front and because there was a rewrite, the newly rewritten request goes back through the rules again and the same rule is triggered. By changing that line's "$1" to "-", no rewrite happens and so the rewriting process does not start over again with the same URL.

It's possible that there's a difference in how apache 2.2 and 2.4 handle this situation of only-difference-is-a-slash-in-front and that's why the default rules provided by WordPress aren't working perfectly.

ImportError: DLL load failed: %1 is not a valid Win32 application

I just hit this and the problem was that the package had at one point been installed in the per-user packages directory. (On Windows.) aka %AppData%\Python. So Python was looking there first, finding an old 32-bit version of the .pyd file, and failing with the listed error. Unfortunately pip uninstall by itself wasn't enough to clean this, and at this time pip 10.0.1 doesn't seem to have a --user parameter for uninstall, only for install.

tl;dr Deleting the old .pyd from %AppData%\python\python27\site-packages resolved this problem for me.

What is the (function() { } )() construct in JavaScript?

Usually, we don't invoke a function immediately after we write it in the program. In extremely simple terms, when you call a function right after its creation, it is called IIFE - a fancy name.

Create a date from day month and year with T-SQL

For SQL Server versions below 12 i can recommend use of CAST in combination with SET DATEFORMAT

-- 26 February 2015
SET DATEFORMAT dmy
SELECT CAST('26-2-2015' AS DATE)

SET DATEFORMAT ymd
SELECT CAST('2015-2-26' AS DATE)

how you create those strings is up to you

Deep copy of a dict in python

dict.copy() is a shallow copy function for dictionary
id is built-in function that gives you the address of variable

First you need to understand "why is this particular problem is happening?"

In [1]: my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}

In [2]: my_copy = my_dict.copy()

In [3]: id(my_dict)
Out[3]: 140190444167808

In [4]: id(my_copy)
Out[4]: 140190444170328

In [5]: id(my_copy['a'])
Out[5]: 140190444024104

In [6]: id(my_dict['a'])
Out[6]: 140190444024104

The address of the list present in both the dicts for key 'a' is pointing to same location.
Therefore when you change value of the list in my_dict, the list in my_copy changes as well.


Solution for data structure mentioned in the question:

In [7]: my_copy = {key: value[:] for key, value in my_dict.items()}

In [8]: id(my_copy['a'])
Out[8]: 140190444024176

Or you can use deepcopy as mentioned above.

How do you share code between projects/solutions in Visual Studio?

Two main steps involved are

1- Creating a C++ dll

In visual studio

New->Project->Class Library in c++ template. Name of project here is first_dll in 
visual studio 2010. Now declare your function as public in first_dll.h file and 
write the code in first_dll.cpp file as shown below.

Header File code

// first_dll.h

using namespace System;

namespace first_dll 
{

public ref class Class1
{
public:
    static double sum(int ,int );
    // TODO: Add your methods for this class here.
};
}

Cpp File

//first_dll.cpp
#include "stdafx.h"

#include "first_dll.h"

namespace first_dll
{

    double Class1:: sum(int x,int y)
    {
        return x+y;
    }

 }

Check This

**Project-> Properties -> Configuration/General -> Configuration Type** 

this option should be Dynamic Library(.dll) and build the solution/project now.

first_dll.dll file is created in Debug folder

2- Linking it in C# project

Open C# project

Rightclick on project name in solution explorer -> Add -> References -> Browse to path 
where first_dll.dll is created and add the file.

Add this line at top in C# project

Using first_dll; 

Now function from dll can be accessed using below statement in some function

double var = Class1.sum(4,5);

I created dll in c++ project in VS2010 and used it in VS2013 C# project.It works well.

Laravel 5 Application Key

You can generate a key by the following command:

php artisan key:generate 

The key will be written automatically in your .env file.

APP_KEY=YOUR_GENERATED_KEY

If you want to see your key after generation use --show option

php artisan key:generate --show

Note: The .env is a hidden file in your project folder.

enter image description here

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

When an array is passed to a method or function in PHP, it is passed by value unless you explicitly pass it by reference, like so:

function test(&$array) {
    $array['new'] = 'hey';
}

$a = $array(1,2,3);
// prints [0=>1,1=>2,2=>3]
var_dump($a);
test($a);
// prints [0=>1,1=>2,2=>3,'new'=>'hey']
var_dump($a);

In your second question, $b is not a reference to $a, but a copy of $a.

Much like the first example, you can reference $a by doing the following:

$a = array(1,2,3);
$b = &$a;
// prints [0=>1,1=>2,2=>3]
var_dump($b);
$b['new'] = 'hey';
// prints [0=>1,1=>2,2=>3,'new'=>'hey']
var_dump($a);

javascript - pass selected value from popup window to parent window input box

My approach: use a div instead of a pop-up window.

See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/

Or save the code below as test.html and try it locally.

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(window).load(function(){
            $('.btnChoice').on('click', function(){
                $('#divChoices').show()
                thefield = $(this).prev()
                $('.btnselect').on('click', function(){
                    theselected = $(this).prev()
                    thefield.val( theselected.val() )
                    $('#divChoices').hide()
                })
            })

            $('#divChoices').css({
                'border':'2px solid red',
                'position':'fixed',
                'top':'100',
                'left':'200',
                'display':'none'
            })
        });
    </script>
</head>

<body>

<div class="divform">
    <input type="checkbox" name="kvi1" id="kvi1" value="1">
    <label>Field 1: </label>
    <input size="10" type="number" id="sku1" name="sku1">
    <button id="choice1" class="btnChoice">?</button>
    <br>
    <input type="checkbox" name="kvi2" id="kvi2" value="2">
    <label>Field 2: </label>
    <input size="10"  type="number" id="sku2" name="sku2">
    <button id="choice2" class="btnChoice">?</button>
</div>

<div id="divChoices">
    Select something: 
    <br>
    <input size="10" type="number" id="ch1" name="ch1" value="11">
    <button id="btnsel1" class="btnselect">Select</button>
    <label for="ch1">bla bla bla</label>
    <br>
    <input size="10" type="number" id="ch2" name="ch2" value="22">
    <button id="btnsel2" class="btnselect">Select</button>
    <label for="ch2">ble ble ble</label>
</div>

</body>

</html>

clean and simple.

Using scanner.nextLine()

Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.

Generating a WSDL from an XSD file

Personally (and given what I know, i.e., Java and axis), I'd generate a Java data model from the .xsd files (Axis 2 can do this), and then add an interface to describe my web service that uses that model, and then generate a WSDL from that interface.

Because .NET has all these features as well, it must be possible to do all this in that ecosystem as well.

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

ProductionWorker extends Employee, thus it is said that it has all the capabilities of an Employee. In order to accomplish that, Java automatically puts a super(); call in each constructor's first line, you can put it manually but usually it is not necessary. In your case, it is necessary because the call to super(); cannot be placed automatically due to the fact that Employee's constructor has parameters.

You either need to define a default constructor in your Employee class, or call super('Erkan', 21, new Date()); in the first line of the constructor in ProductionWorker.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

You need not specify the classes folder. Intellij should be able to load it. You will get this error if "Project Compiler output" is blank.

Just make sure that below value is set: Project Settings -> Project -> Project Compiler output to your projectDir/out folder

What exactly is Apache Camel?

101 Word Intro

Camel is a framework with a consistent API and programming model for integrating applications together. The API is based on theories in Enterprise Integration Patterns - i.e., bunch of design patterns that tend to use messaging. It provides out of the box implementations of most of these patterns, and additionally ships with over 200 different components you can use to easily talk to all kinds of other systems. To use Camel, first write your business logic in POJOs and implement simple interfaces centered around messages. Then use Camel’s DSL to create "Routes" which are sets of rules for gluing your application together.

Extended Intro

On the surface, Camel's functionality rivals traditional Enterprise Service Bus products. We typically think of a Camel Route being a "mediation" (aka orchestration) component that lives on the server side, but because it's a Java library it’s easy to embed and it can live on a client side app just as well and help you integrate it with point to point services (aka choreography). You can even take your POJOs that process the messages inside the Camel route and easily spin them off into their own remote consumer processes, e.g. if you needed to scale just one piece independently. You can use Camel to connect routes or processors through any number of different remote transport/protocols depending on your needs. Do you need an extremely efficient and fast binary protocol, or one that is more human readable and easy to debug? What if you wanted to switch? With Camel this is usually as easy as changing a line or two in your route and not changing any business logic at all. Or you could support both - you’re free to run many Routes at once in a Camel Context.

You don't really need to use Camel for simple applications that are going to live in a single process or JVM - it would be overkill. But it's not conceptually any more difficult than code you may write yourself. And if your requirements change, the separation of business logic and glue code makes it easier to maintain over time. Once you learn the Camel API, it is easy to use it like a Swiss-Army knife and apply it quickly in many different contexts to cut down on the amount of custom code you’d otherwise have to write. You can learn one flavor - the Java DSL, for example, a fluent API that's easy to chain together - and pick up the other flavors easily.

Overall Camel is a great fit if you are trying to do microservices. I have found it invaluable for evolutionary architecture, because you can put off a lot of the difficult, "easy-to-get-wrong" decisions about protocols, transports and other system integration problems until you know more about your problem domain. Just focus on your EIPs and core business logic and switch to new Routes with the "right" components as you learn more.

Filter data.frame rows by a logical condition

To select rows according to one 'cell_type' (e.g. 'hesc'), use ==:

expr[expr$cell_type == "hesc", ]

To select rows according to two or more different 'cell_type', (e.g. either 'hesc' or 'bj fibroblast'), use %in%:

expr[expr$cell_type %in% c("hesc", "bj fibroblast"), ]

NumPy array is not JSON serializable

Here is an implementation that work for me and removed all nans (assuming these are simple object (list or dict)):

from numpy import isnan

def remove_nans(my_obj, val=None):
    if isinstance(my_obj, list):
        for i, item in enumerate(my_obj):
            if isinstance(item, list) or isinstance(item, dict):
                my_obj[i] = remove_nans(my_obj[i], val=val)

            else:
                try:
                    if isnan(item):
                        my_obj[i] = val
                except Exception:
                    pass

    elif isinstance(my_obj, dict):
        for key, item in my_obj.iteritems():
            if isinstance(item, list) or isinstance(item, dict):
                my_obj[key] = remove_nans(my_obj[key], val=val)

            else:
                try:
                    if isnan(item):
                        my_obj[key] = val
                except Exception:
                    pass

    return my_obj

How to make div appear in front of another?

Use the CSS z-index property. Elements with a greater z-index value are positioned in front of elements with smaller z-index values.

Note that for this to work, you also need to set a position style (position:absolute, position:relative, or position:fixed) on both/all of the elements you want to order.

Set iframe content height to auto resize dynamically

In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:

<body onload="parent.alertsize(document.body.scrollHeight);">

In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:

<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>

What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.

To that JavaScript function it sends how many pixels its (iframe) height is.

The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.

That's it, nothing else is needed.


But if you like to know some more small tricks keep on reading...

DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
}
</script>

to that script just add:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>

How you use the above script is easy:

<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>

For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)

Complete holding page code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>

<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>

Complete iframe code: (this iframe named "theiframe.htm")

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight);
}
</script>
</head>

<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END

</body>
</html>

Demo

How to get the exact local time of client?

The most reliable way I've found to display the local time of a city or location is by tapping into a Time Zone API such as Google Time Zone API. It returns the correct time zone, and more importantly, Day Light Savings Time offset of any location, which just using JavaScript's Date() object cannot be done as far as I'm aware. There's a good tutorial on using the API to get and display the local time here:

var loc = '35.731252, 139.730291' // Tokyo expressed as lat,lng tuple
var targetDate = new Date() // Current date/time of user computer
var timestamp = targetDate.getTime() / 1000 + targetDate.getTimezoneOffset() * 60 // Current UTC date/time expressed as seconds since midnight, January 1, 1970 UTC
var apikey = 'YOUR_TIMEZONE_API_KEY_HERE'
var apicall = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + loc + '&timestamp=' + timestamp + '&key=' + apikey

var xhr = new XMLHttpRequest() // create new XMLHttpRequest2 object
xhr.open('GET', apicall) // open GET request
xhr.onload = function() {
  if (xhr.status === 200) { // if Ajax request successful
    var output = JSON.parse(xhr.responseText) // convert returned JSON string to JSON object
    console.log(output.status) // log API return status for debugging purposes
    if (output.status == 'OK') { // if API reports everything was returned successfully
      var offsets = output.dstOffset * 1000 + output.rawOffset * 1000 // get DST and time zone offsets in milliseconds
      var localdate = new Date(timestamp * 1000 + offsets) // Date object containing current time of Tokyo (timestamp + dstOffset + rawOffset)
      console.log(localdate.toLocaleString()) // Display current Tokyo date and time
    }
  } else {
    alert('Request failed.  Returned status of ' + xhr.status)
  }
}
xhr.send() // send request

From: Displaying the Local Time of Any City using JavaScript and Google Time Zone API

How to know which is running in Jupyter notebook?

Assuming you have the wrong backend system you can change the backend kernel by creating a new or editing the existing kernel.json in the kernels folder of your jupyter data path jupyter --paths. You can have multiple kernels (R, Python2, Python3 (+virtualenvs), Haskell), e.g. you can create an Anaconda specific kernel:

$ <anaconda-path>/bin/python3 -m ipykernel install --user --name anaconda --display-name "Anaconda"

Should create a new kernel:

<jupyter-data-dir>/kernels/anaconda/kernel.json

{
    "argv": [ "<anaconda-path>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
    "display_name": "Anaconda",
    "language": "python"
}

You need to ensure ipykernel package is installed in the anaconda distribution.

This way you can just switch between kernels and have different notebooks using different kernels.

How do I set multipart in axios with react?

If you are sending alphanumeric data try changing

'Content-Type': 'multipart/form-data'

to

'Content-Type': 'application/x-www-form-urlencoded'

If you are sending non-alphanumeric data try to remove 'Content-Type' at all.

If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)

SSL: CERTIFICATE_VERIFY_FAILED with Python3

I have a lib what use https://requests.readthedocs.io/en/master/ what use https://pypi.org/project/certifi/ but I have a custom CA included in my /etc/ssl/certs.

So I solved my problem like this:

# Your TLS certificates directory (Debian like)
export SSL_CERT_DIR=/etc/ssl/certs
# CA bundle PATH (Debian like again)
export CA_BUNDLE_PATH="${SSL_CERT_DIR}/ca-certificates.crt"
# If you have a virtualenv:
. ./.venv/bin/activate
# Get the current certifi CA bundle
CERTFI_PATH=`python -c 'import certifi; print(certifi.where())'`

test -L $CERTFI_PATH || rm $CERTFI_PATH
test -L $CERTFI_PATH || ln -s $CA_BUNDLE_PATH $CERTFI_PATH

Et voilà !

warning about too many open figures

Here's a bit more detail to expand on Hooked's answer. When I first read that answer, I missed the instruction to call clf() instead of creating a new figure. clf() on its own doesn't help if you then go and create another figure.

Here's a trivial example that causes the warning:

from matplotlib import pyplot as plt, patches
import os


def main():
    path = 'figures'
    for i in range(21):
        _fig, ax = plt.subplots()
        x = range(3*i)
        y = [n*n for n in x]
        ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
        plt.step(x, y, linewidth=2, where='mid')
        figname = 'fig_{}.png'.format(i)
        dest = os.path.join(path, figname)
        plt.savefig(dest)  # write image to file
        plt.clf()
    print('Done.')

main()

To avoid the warning, I have to pull the call to subplots() outside the loop. In order to keep seeing the rectangles, I need to switch clf() to cla(). That clears the axis without removing the axis itself.

from matplotlib import pyplot as plt, patches
import os


def main():
    path = 'figures'
    _fig, ax = plt.subplots()
    for i in range(21):
        x = range(3*i)
        y = [n*n for n in x]
        ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
        plt.step(x, y, linewidth=2, where='mid')
        figname = 'fig_{}.png'.format(i)
        dest = os.path.join(path, figname)
        plt.savefig(dest)  # write image to file
        plt.cla()
    print('Done.')

main()

If you're generating plots in batches, you might have to use both cla() and close(). I ran into a problem where a batch could have more than 20 plots without complaining, but it would complain after 20 batches. I fixed that by using cla() after each plot, and close() after each batch.

from matplotlib import pyplot as plt, patches
import os


def main():
    for i in range(21):
        print('Batch {}'.format(i))
        make_plots('figures')
    print('Done.')


def make_plots(path):
    fig, ax = plt.subplots()
    for i in range(21):
        x = range(3 * i)
        y = [n * n for n in x]
        ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
        plt.step(x, y, linewidth=2, where='mid')
        figname = 'fig_{}.png'.format(i)
        dest = os.path.join(path, figname)
        plt.savefig(dest)  # write image to file
        plt.cla()
    plt.close(fig)


main()

I measured the performance to see if it was worth reusing the figure within a batch, and this little sample program slowed from 41s to 49s (20% slower) when I just called close() after every plot.

node.js http 'get' request with query string parameters

No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:

const requestUrl = url.parse(url.format({
    protocol: 'https',
    hostname: 'yoursite.com',
    pathname: '/the/path',
    query: {
        key: value
    }
}));

Then make the request with the formatted url. requestUrl.path will include the query parameters.

const req = https.get({
    hostname: requestUrl.hostname,
    path: requestUrl.path,
}, (res) => {
   // ...
})

clear form values after submission ajax

use this:

$('form.contactForm input[type="text"],texatrea, select').val('');

or if you have a reference to the form with this:

$('input[type="text"],texatrea, select', this).val('');

:input === <input> + <select>s + <textarea>s

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

Unknown column in 'field list' error on MySQL Update query

In my case, it was caused by an unseen trailing space at the end of the column name. Just check if you really use "y" or "y " instead.

What is the difference between a hash join and a merge join (Oracle RDBMS )?

A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.

A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.

(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).

The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:

  1. The size of each hash table is reduced, hence reducing the maximum amount of memory required and potentially removing the need for the operation to require temporary disk space.
  2. For parallel query operations the amount of inter-process messaging is vastly reduced, reducing CPU usage and improving performance, as each hash join can be performed by one pair of PQ processes.
  3. For non-parallel query operations the memory requirement is reduced by a factor of n, and the first rows are projected from the query earlier.

You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.

In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.

This topic is very well covered in the documentation.

http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523

12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm

lvalue required as left operand of assignment error when using C++

if you use an assignment operator but use it in wrong way or in wrong place, then you'll get this types of errors!

suppose if you type:
p+1=p; you will get the error!!

you will get the same error for this:
if(ch>='a' && ch='z')
as you see can see that I i tried to assign in if() statement!!!
how silly I am!!! right??
ha ha
actually i forgot to give less then(<) sign
if(ch>='a' && ch<='z')
and got the error!!

WCF on IIS8; *.svc handler mapping doesn't work

More specifically:

  1. Run Server Manager (on task bar and start menu)
  2. Choose the server to administer (probably local server)
  3. Scroll down to "Roles and Features" section.
  4. Choose "Add Role or Feature" from Tasks drop down
  5. On "Add Role or Feature Wizard" dialog, click down to "Features" in list of pages on the left.
  6. Expand ".Net 3.5" or ".Net 4.5", depending on what you have installed. (you can go back up to "roles" screen to add if you don't have.
  7. Under "WCF Services", check the box for "HTTP-Activation". You can also add non-http types if you know you need them (tcp, named pipes, etc).
  8. Click "Install" Button.

TNS Protocol adapter error while starting Oracle SQL*Plus

You might have set oracle not to start automatically. Goto Start and search for Services. Scroll down and look for OracleServiceORCL (or OracleServiceSID). Double click and change startup type to automatic if it is set as manual.

Variable name as a string in Javascript

This works for basic expressions

const nameof = exp => exp.toString().match(/[.](\w+)/)[1];

Example

nameof(() => options.displaySize);

Snippet:

_x000D_
_x000D_
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };_x000D_
var myFirstName = 'Chuck';_x000D_
var varname = nameof(function () { return window.myFirstName; });_x000D_
console.log(varname);
_x000D_
_x000D_
_x000D_

React.createElement: type is invalid -- expected a string

I got the exactly same error, Do this instead:

npm install react-router@next 
react-router-dom@next
npm install --save history

How can one change the timestamp of an old commit in Git?

After reading all the answers I came up with a more succinct and convenient way of editing the date of multiple commits at once without the need of rebasing interactively:

git rebase HEAD~4 --exec "git commit --amend --no-edit --date 'now'"

It changes both the committer and author dates.

How do I add multiple conditions to "ng-disabled"?

Wanny is correct. The && operator doesn't work in HTML. With Angular, you must use the double pipes (||)for multiple conditions.

Directory.GetFiles: how to get only filename, not full path?

Use this to obtain only the filename.

Path.GetFileName(files[0]);

Is it possible to add an HTML link in the body of a MAILTO link

Section 2 of RFC 2368 says that the body field is supposed to be in text/plain format, so you can't do HTML.

However even if you use plain text it's possible that some modern mail clients would render a URL as a clickable link anyway, though.

Entity Framework change connection at runtime

DbContext has a constructor overload that accepts the name of a connection string or a connection string itself. Implement your own version and pass it to the base constructor:

public class MyDbContext : DbContext
{
    public MyDbContext( string nameOrConnectionString ) 
        : base( nameOrConnectionString )
    {
    }
}

Then simply pass the name of a configured connection string or a connection string itself when you instantiate your DbContext

var context = new MyDbContext( "..." );

T-SQL CASE Clause: How to specify WHEN NULL

Found a solution to this. Just ISNULL the CASE statement:

ISNULL(CASE x WHEN x THEN x ELSE x END, '') AS 'BLAH'

Using Server.MapPath in external C# Classes in ASP.NET

class test
{
public static void useServerPath(string path)
{
   if (File.Exists(path)
{
 \\...... do whatever you wabt
}
else
{
\\.....
}
}

Now when you call the method from the codebehind

for example :

protected void BtAtualizacao_Click(object sender, EventArgs e)
        {
             string path = Server.MapPath("Folder") + "\\anifile.txt";

            test.useServerPath(path);
}

in this way your code is to simple and with one method u can use multiple path for each call :)

Counting the number of elements with the values of x in a vector

The most direct way is sum(numbers == x).

numbers == x creates a logical vector which is TRUE at every location that x occurs, and when suming, the logical vector is coerced to numeric which converts TRUE to 1 and FALSE to 0.

However, note that for floating point numbers it's better to use something like: sum(abs(numbers - x) < 1e-6).

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

Maybe you are not allowed to start the service "MySQL 55". Set the login information of Service "MySQL 55" as local!

enter image description here

To see the list of aviable services in Windows 7:

  1. Open a run box enter image description here
  2. Type services.msc and press return.
  3. Find the service MySQL55
  4. A right click of the MySQL55 Local Service shows Properties -> Log On enter image description hereenter image description here

Android: How to open a specific folder via Intent and show its content in a file browser?

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

intent.setType("text/csv");

intent.addCategory(Intent.CATEGORY_OPENABLE);

try {
      startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 0);

} catch (android.content.ActivityNotFoundException ex) {
  ex.printStackTrace();
}

then you just need to add the response

public void  onActivityResult(int requestCode, int resultCode, Intent data){

switch (requestCode) {
  case 0: {
     //what you want to do
    //file = new File(uri.getPath());
  }
}
}

SSRS Field Expression to change the background color of the Cell

=IIF(fields!column.value =Condition,"Red","Black")

Bootstrap Modal before form Submit

It is easy to solve, only create an hidden submit:

<button id="submitCadastro" type="button">ENVIAR</button>
<input type="submit" id="submitCadastroHidden" style="display: none;" >

with jQuery you click the submit:

$("#submitCadastro").click(function(){
    if($("#checkDocumentos").prop("checked") == false){
        //alert("Aceite os termos e condições primeiro!.");
        $("#modalERROR").modal("show");
    }else{
        //$("#formCadastro").submit();
        $("#submitCadastroHidden").click();                     
    }
});

"Invalid form control" only in Google Chrome

No validate will do the job.

<form action="whatever" method="post" novalidate>

How to create a GUID in Excel?

for me it is correct, in Excel spanish

=CONCATENAR(
DEC.A.HEX(ALEATORIO.ENTRE(0,4294967295),8),"-",
DEC.A.HEX(ALEATORIO.ENTRE(0,65535),4),"-",
DEC.A.HEX(ALEATORIO.ENTRE(16384,20479),4),"-",
DEC.A.HEX(ALEATORIO.ENTRE(32768,49151),4),"-",
DEC.A.HEX(ALEATORIO.ENTRE(0,65535),4),
DEC.A.HEX(ALEATORIO.ENTRE(0,4294967295),8)
)

How to make a <svg> element expand or contract to its parent container?

What's worked for me recently is to remove all height="" and width="" attributes from the <svg> tag and all child tags. Then you can use scaling using a percentage of the parent container's height or width.

Before:

<svg width="3212" height="3212" viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
   circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>

After:

<svg viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
   circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>

Testing two JSON objects for equality ignoring child order in Java

You can use zjsonpatch library, which presents the diff information in accordance with RFC 6902 (JSON Patch). Its very easy to use. Please visit its description page for its usage

The right way of setting <a href=""> when it's a local file

By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)

So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).

If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,

How is a tag different from a branch in Git? Which should I use, here?

What you need to realize, coming from CVS, is that you no longer create directories when setting up a branch.
No more "sticky tag" (which can be applied to just one file), or "branch tag".
Branch and tags are two different objects in Git, and they always apply to the all repo.

You would no longer (with SVN this time) have to explicitly structure your repository with:

branches
   myFirstBranch
     myProject
       mySubDirs
   mySecondBranch
     ...
tags
   myFirstTag
     myProject
       mySubDirs
   mySecondTag
   ...

That structure comes from the fact CVS is a revision system and not a version system (see Source control vs. Revision Control?).
That means branches are emulated through tags for CVS, directory copies for SVN.

Your question makes senses if you are used to checkout a tag, and start working in it.
Which you shouldn't ;)
A tag is supposed to represent an immutable content, used only to access it with the guarantee to get the same content every time.

In Git, the history of revisions is a series of commits, forming a graph.
A branch is one path of that graph

x--x--x--x--x # one branch
    \ 
     --y----y # another branch
       1.1
        ^
        |
        # a tag pointing to a commit
  • If you checkout a tag, you will need to create a branch to start working from it.
  • If you checkout a branch, you will directly see the latest commit it('HEAD') of that branch.

See Jakub Narebski's answer for all the technicalities, but frankly, at this point, you do not need (yet) all the details ;)

The main point is: a tag being a simple pointer to a commit, you will never be able to modify its content. You need a branch.


In your case, each developer working on a specific feature:

  • should create their own branch in their respective repository
  • track branches from their colleague's repositories (the one working on the same feature)
  • pulling/pushing in order to share your work with your peers.

Instead of tracking directly the branches of your colleagues, you could track only the branch of one "official" central repository to which everyone pushes his/her work in order to integrate and share everyone's work for this particular feature.

Adding placeholder attribute using Jquery

You just need this:

$(".hidden").attr("placeholder", "Type here to search");

classList is used for manipulating classes and not attributes.

Is there a quick change tabs function in Visual Studio Code?

macOS - revised 2017

IN 2017, the VS CODE keyboard shortcuts have changed to CTRL+1, CTRL+2,CTRL+3 etc..to switch between tabs.

CMD+1, CMD+2, and CMD+3 switch between and create tab groups

Lazy Method for Reading Big File in Python?

f = ... # file-like object, i.e. supporting read(size) function and 
        # returning empty string '' when there is nothing to read

def chunked(file, chunk_size):
    return iter(lambda: file.read(chunk_size), '')

for data in chunked(f, 65536):
    # process the data

UPDATE: The approach is best explained in https://stackoverflow.com/a/4566523/38592

JQuery: detect change in input field

You can bind the 'input' event to the textbox. This would fire every time the input changes, so when you paste something (even with right click), delete and type anything.

$('#myTextbox').on('input', function() {
    // do something
});

If you use the change handler, this will only fire after the user deselects the input box, which may not be what you want.

There is an example of both here: http://jsfiddle.net/6bSX6/

How can I import Swift code to Objective-C?

Be careful with dashes and underscores, they can be mixed up and your Project Name and Target name won't be the same as SWIFT_MODULE_NAME.

Dashes and underscores

concatenate two strings

You can use concatenation operator and instead of declaring two variables only use one variable

String finalString =  cursor.getString(numcol) + cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));

socket.error: [Errno 48] Address already in use

Just in case above solutions didn't work:

  1. Get the port your process is listening to:

    $ ps ax | grep python

  2. Kill the Process

    $ kill PROCESS_NAME

How can I specify a [DllImport] path at runtime?

DllImport will work fine without the complete path specified as long as the dll is located somewhere on the system path. You may be able to temporarily add the user's folder to the path.

What is the Angular equivalent to an AngularJS $watch?

Try this when your application still demands $parse, $eval, $watch like behavior in Angular

https://github.com/vinayk406/angular-expression-parser

How to implement class constants?

All of the replies with readonly are only suitable when this is a pure TS environment - if it's ever being made into a library then this doesn't actually prevent anything, it just provides warnings for the TS compiler itself.

Static is also not correct - that's adding a method to the Class, not to an instance of the class - so you need to address it directly.

There are several ways to manage this, but the pure TS way is to use a getter - exactly as you have done already.

The alternative way is to put it in as readonly, but then use Object.defineProperty to lock it - this is almost the same thing that is being done via the getter, but you can lock it to have a value, rather than a method to use to get it -

class MyClass {
    MY_CONSTANT = 10;

    constructor() {
        Object.defineProperty(this, "MY_CONSTANT", {value: this.MY_CONSTANT});
    }
}

The defaults make it read-only, but check out the docs for more details.

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

I had the same problem and the error was due to a rename of the dll. It could happen that the library name is also written somewhere inside the dll. When I put back its original name I was able to load using System.loadLibrary

/usr/bin/codesign failed with exit code 1

In My Case, after a fews days of research,

All I did to revolve is listed below:

  1. delete all the certificate on your keychain.
  2. goto your apple account. a) download the specify certificate your want to install on your keychain. b)(Optional) Also create and download the require profile.
  3. in Xcode, clean your project. This may take some time.
  4. Build your project.

This should work for similar codesign issues.

Note, during this process the OS would ask for your credential validation.

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

How to do the equivalent of pass by reference for primitives in Java

Java is not call by reference it is call by value only

But all variables of object type are actually pointers.

So if you use a Mutable Object you will see the behavior you want

public class XYZ {

    public static void main(String[] arg) {
        StringBuilder toyNumber = new StringBuilder("5");
        play(toyNumber);
        System.out.println("Toy number in main " + toyNumber);
    }

    private static void play(StringBuilder toyNumber) {
        System.out.println("Toy number in play " + toyNumber);
        toyNumber.append(" + 1");
        System.out.println("Toy number in play after increement " + toyNumber);
    }
}

Output of this code:

run:
Toy number in play 5
Toy number in play after increement 5 + 1
Toy number in main 5 + 1
BUILD SUCCESSFUL (total time: 0 seconds)

You can see this behavior in Standard libraries too. For example Collections.sort(); Collections.shuffle(); These methods does not return a new list but modifies it's argument object.

    List<Integer> mutableList = new ArrayList<Integer>();

    mutableList.add(1);
    mutableList.add(2);
    mutableList.add(3);
    mutableList.add(4);
    mutableList.add(5);

    System.out.println(mutableList);

    Collections.shuffle(mutableList);

    System.out.println(mutableList);

    Collections.sort(mutableList);

    System.out.println(mutableList);

Output of this code:

run:
[1, 2, 3, 4, 5]
[3, 4, 1, 5, 2]
[1, 2, 3, 4, 5]
BUILD SUCCESSFUL (total time: 0 seconds)

Eclipse CDT project built but "Launch Failed. Binary Not Found"

I've got the same problem on Eclipse 3.8.1. For me it worked to set the artifact type to executable:

Right click on the project -> C/C++ Build -> Settings -> Build Artifact -> Artifact Type: Executable

Finally rebuilding the project produced the Binaries entry in the Project Explorer.

angular 2 how to return data from subscribe

I have used this way lots time ...

_x000D_
_x000D_
@Component({_x000D_
   selector: "data",_x000D_
   template: "<h1>{{ getData() }}</h1>"_x000D_
})_x000D_
_x000D_
export class DataComponent{_x000D_
    this.http.get(path).subscribe({_x000D_
       DataComponent.setSubscribeData(res);_x000D_
    })_x000D_
}_x000D_
_x000D_
_x000D_
static subscribeData:any;_x000D_
static setSubscribeData(data):any{_x000D_
    DataComponent.subscribeData=data;_x000D_
    return data;_x000D_
}
_x000D_
_x000D_
_x000D_

use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...

What Content-Type value should I send for my XML sitemap?

Other answers here address the general question of what the proper Content-Type for an XML response is, and conclude (as with What's the difference between text/xml vs application/xml for webservice response) that both text/xml and application/xml are permissible. However, none address whether there are any rules specific to sitemaps.

Answer: there aren't. The sitemap spec is https://www.sitemaps.org, and using Google site: searches you can confirm that it does not contain the words or phrases mime, mimetype, content-type, application/xml, or text/xml anywhere. In other words, it is entirely silent on the topic of what Content-Type should be used for serving sitemaps.

In the absence of any commentary in the sitemap spec directly addressing this question, we can safely assume that the same rules apply as when choosing the Content-Type of any other XML document - i.e. that it may be either text/xml or application/xml.

Stripping everything but alphanumeric chars from a string in Python

As a spin off from some other answers here, I offer a really simple and flexible way to define a set of characters that you want to limit a string's content to. In this case, I'm allowing alphanumerics PLUS dash and underscore. Just add or remove characters from my PERMITTED_CHARS as suits your use case.

PERMITTED_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-" 
someString = "".join(c for c in someString if c in PERMITTED_CHARS)

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

This work around will fix the issue found by @Cletus.

function submitForm(form) {
    //get the form element's document to create the input control with
    //(this way will work across windows in IE8)
    var button = form.ownerDocument.createElement('input');
    //make sure it can't be seen/disrupts layout (even momentarily)
    button.style.display = 'none';
    //make it such that it will invoke submit if clicked
    button.type = 'submit';
    //append it and click it
    form.appendChild(button).click();
    //if it was prevented, make sure we don't get a build up of buttons
    form.removeChild(button);
}

Will work on all modern browsers.
Will work across tabs/spawned child windows (yes, even in IE<9).
And is in vanilla!

Just pass it a DOM reference to a form element and it'll make sure all the attached listeners, the onsubmit, and (if its not prevented by then) finally, submit the form.

a href link for entire div in HTML/CSS

This can be done in many ways. a. Using nested inside a tag.

<a href="link1.html">
   <div> Something in the div </div>
 </a>

b. Using the Inline JavaScript Method

<div onclick="javascript:window.location.href='link1.html' "> 
  Some Text 
</div>

c. Using jQuery inside tag

HTML:

<div class="demo" > Some text here </div>

jQuery:

$(".demo").click( function() {
  window.location.href="link1.html";
 });

TypeError: 'float' object is not subscriptable

PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))      
for i,price in enumerate(PriceList):
  PriceList[i] = PizzaChange + 3*int(i>=7)

Brew doctor says: "Warning: /usr/local/include isn't writable."

For some it's going to be:

sudo chown -R JonJames:admin /usr/local/lib

where "lib" is used as opposed to "bin" or "include" or "whatever else"

The Homebrew Warning "should" explain what specifically is not writable and then give you a command syntax for follow, however you will need to use the ":" as opposed to what the Warning mentions which is actually not correct syntax??

Where do I find the Instagram media ID of a image

You can actually derive the MediaId from the last segment of the link algorithmically using a method I wrote about here: http://carrot.is/coding/instagram-ids. It works by mapping the URL segment by character codes & converting the id into a base 64 number.

For example, given the link you mentioned (http://instagram.com/p/Y7GF-5vftL), we get the last segment (Y7GF-5vftL) then we map it into character codes using the base64 url-safe alphabet (24:59:6:5:62:57:47:31:45:11_64). Next, we convert this base64 number into base10 (448979387270691659).

If you append your userId after an _ you get the full id in the form you specified, but since the MediaId is unique without the userId you can actually omit the userId from most requests.

Finally, I made a Node.js module called instagram-id-to-url-segment to automate this conversion:

convert = require('instagram-id-to-url-segment');
instagramIdToUrlSegment = convert.instagramIdToUrlSegment;
urlSegmentToInstagramId = convert.urlSegmentToInstagramId;

instagramIdToUrlSegment('448979387270691659'); // Y7GF-5vftL
urlSegmentToInstagramId('Y7GF-5vftL'); // 448979387270691659

Any way to declare an array in-line?

m(new String[]{"blah", "hey", "yo"});

Restarting cron after changing crontab file?

On CentOS with cPanel sudo /etc/init.d/crond reload does the trick.

On CentOS7: sudo systemctl start crond.service

Using String Format to show decimal up to 2 places or simple integer

Try:

String.Format("{0:0.00}", Convert.ToDecimal(totalPrice));

Twitter Bootstrap - add top space between rows

You can use the following class for bootstrap 4:

mt-0 mt-1 mt-2 mt-3 mt-4 ...

Ref: https://v4-alpha.getbootstrap.com/utilities/spacing/

How to access component methods from “outside” in ReactJS?

Alternatively, if the method on Child is truly static (not a product of current props, state) you can define it on statics and then access it as you would a static class method. For example:

var Child = React.createClass({
  statics: {
    someMethod: function() {
      return 'bar';
    }
  },
  // ...
});

console.log(Child.someMethod()) // bar

How to use *ngIf else?

In Angular 4.0 if..else syntax is quite similar to conditional operators in Java.

In Java you use to "condition?stmnt1:stmnt2".

In Angular 4.0 you use *ngIf="condition;then stmnt1 else stmnt2".

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

somearray = ["some", "thing"]

anotherarray = ["another", "thing"]

somearray + anotherarray

Simple linked list in C++

I think that, to make sure the indeep linkage of each node in the list, the addNode method must be like this:

void addNode(struct node *head, int n) {
  if (head->Next == NULL) {
    struct node *NewNode = new node;
    NewNode->value = n;
    NewNode->Next = NULL;
    head->Next = NewNode;
  }
  else 
    addNode(head->Next, n);
}

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app. in API constructor add the following:

public class TargetClassController : ControllerBase
{
    private readonly IConfiguration _config;

    public TargetClassController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<DTOResponse>> Get(int id)
    {
        var config = _config["YourKeySection:key"];
    }
}

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

How to set host_key_checking=false in ansible inventory file?

You set these configs either in the /etc/ansible/ansible.cfg or ~/.ansible.cfg or ansible.cfg(in your current directory) file

[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no

tested with ansible 2.9.6 in ubuntu 20.04

Android: show soft keyboard automatically when focus is on an EditText

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

I call this in onCreate() to show keyboard automatically, when I came in the Activity.

How to implement the --verbose or -v option into a script?

@kindall's solution does not work with my Python version 3.5. @styles correctly states in his comment that the reason is the additional optional keywords argument. Hence my slightly refined version for Python 3 looks like this:

if VERBOSE:
    def verboseprint(*args, **kwargs):
        print(*args, **kwargs)
else:
    verboseprint = lambda *a, **k: None # do-nothing function

Appending output of a Batch file To log file

Instead of using ">" to redirect like this:

java Foo > log

use ">>" to append normal "stdout" output to a new or existing file:

java Foo >> log

However, if you also want to capture "stderr" errors (such as why the Java program couldn't be started), you should also use the "2>&1" tag which redirects "stderr" (the "2") to "stdout" (the "1"). For example:

java Foo >> log 2>&1 

Count all duplicates of each value

SELECT   col,
         COUNT(dupe_col) AS dupe_cnt
FROM     TABLE
GROUP BY col
HAVING   COUNT(dupe_col) > 1
ORDER BY COUNT(dupe_col) DESC

Laravel Eloquent inner join with multiple conditions

This is not politically correct but works

   ->leftJoin("players as p","n.item_id", "=", DB::raw("p.id_player and n.type='player'"))

How to wrap text around an image using HTML/CSS

If the image size is variable or the design is responsive, in addition to wrapping the text, you can set a min width for the paragraph to avoid it to become too narrow.
Give an invisible CSS pseudo-element with the desired minimum paragraph width. If there isn't enough space to fit this pseudo-element, then it will be pushed down underneath the image, taking the paragraph with it.

#container:before {
  content: ' ';
  display: table;
  width: 10em;    /* Min width required */
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

Sum rows in data.frame or matrix

The rowSums function (as Greg mentions) will do what you want, but you are mixing subsetting techniques in your answer, do not use "$" when using "[]", your code should look something more like:

data$new <- rowSums( data[,43:167] )

If you want to use a function other than sum, then look at ?apply for applying general functions accross rows or columns.

Test process.env with Jest

Expanding a bit on Serhan C.'s answer...

According to the blog post How to Setup dotenv with Jest Testing - In-depth Explanation, you can include "dotenv/config" directly in setupFiles, without having to create and reference an external script that calls require("dotenv").config().

I.e., simply do

module.exports = {
    setupFiles: ["dotenv/config"]
}

How to insert values in table with foreign key using MySQL?

Case 1

INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('dan red', 
           (SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')

it is advisable to store your values in lowercase to make retrieval easier and less error prone

Case 2

mysql docs

INSERT INTO tab_teacher (name_teacher) 
    VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('rich man', LAST_INSERT_ID())

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

All the solutions given in this thread don't mention an existing - and native - way to solve this problem without reordering DOM and/or using event preventing tricks. But there's a good reason: this way is proprietary - and available on MS web platform only. Quoting MSDN:

-ms-scroll-chaining property - specifies the scrolling behavior that occurs when a user hits the scroll limit during a manipulation. Property values:

chained - Initial value. The nearest scrollable parent element begins scrolling when the user hits a scroll limit during a manipulation. No bounce effect is shown.

none - A bounce effect is shown when the user hits a scroll limit during a manipulation.

Granted, this property is supported on IE10+/Edge only. Still, here's a telling quote:

To give you a sense of how popular preventing scroll chaining may be, according to my quick http-archive search "-ms-scroll-chaining: none" is used in 0.4% of top 300K pages despite being limited in functionality and only supported on IE/Edge.

And now good news, everyone! Starting from Chrome 63, we finally have a native cure for Blink-based platforms too - and that's both Chrome (obviously) and Android WebView (soon).

Quoting the introducing article:

The overscroll-behavior property is a new CSS feature that controls the behavior of what happens when you over-scroll a container (including the page itself). You can use it to cancel scroll chaining, disable/customize the pull-to-refresh action, disable rubberbanding effects on iOS (when Safari implements overscroll-behavior), and more.[...]

The property takes three possible values:

auto - Default. Scrolls that originate on the element may propagate to ancestor elements.

contain - prevents scroll chaining. Scrolls do not propagate to ancestors but local effects within the node are shown. For example, the overscroll glow effect on Android or the rubberbanding effect on iOS which notifies the user when they've hit a scroll boundary. Note: using overscroll-behavior: contain on the html element prevents overscroll navigation actions.

none - same as contain but it also prevents overscroll effects within the node itself (e.g. Android overscroll glow or iOS rubberbanding).

[...] The best part is that using overscroll-behavior does not adversely affect page performance like the hacks mentioned in the intro!

Here's this feature in action. And here's corresponding CSS Module document.

UPDATE: Firefox, since version 59, has joined the club, and MS Edge is expected to implement this feature in version 18. Here's the corresponding caniusage.

Remove Backslashes from Json Data in JavaScript

You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:

JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

  • The first danger lies in reload(sys).

    When you reload a module, you actually get two copies of the module in your runtime. The old module is a Python object like everything else, and stays alive as long as there are references to it. So, half of the objects will be pointing to the old module, and half to the new one. When you make some change, you will never see it coming when some random object doesn't see the change:

    (This is IPython shell)
    
    In [1]: import sys
    
    In [2]: sys.stdout
    Out[2]: <colorama.ansitowin32.StreamWrapper at 0x3a2aac8>
    
    In [3]: reload(sys)
    <module 'sys' (built-in)>
    
    In [4]: sys.stdout
    Out[4]: <open file '<stdout>', mode 'w' at 0x00000000022E20C0>
    
    In [11]: import IPython.terminal
    
    In [14]: IPython.terminal.interactiveshell.sys.stdout
    Out[14]: <colorama.ansitowin32.StreamWrapper at 0x3a9aac8>
    
  • Now, sys.setdefaultencoding() proper

    All that it affects is implicit conversion str<->unicode. Now, utf-8 is the sanest encoding on the planet (backward-compatible with ASCII and all), the conversion now "just works", what could possibly go wrong?

    Well, anything. And that is the danger.

    • There may be some code that relies on the UnicodeError being thrown for non-ASCII input, or does the transcoding with an error handler, which now produces an unexpected result. And since all code is tested with the default setting, you're strictly on "unsupported" territory here, and no-one gives you guarantees about how their code will behave.
    • The transcoding may produce unexpected or unusable results if not everything on the system uses UTF-8 because Python 2 actually has multiple independent "default string encodings". (Remember, a program must work for the customer, on the customer's equipment.)
      • Again, the worst thing is you will never know that because the conversion is implicit -- you don't really know when and where it happens. (Python Zen, koan 2 ahoy!) You will never know why (and if) your code works on one system and breaks on another. (Or better yet, works in IDE and breaks in console.)

Logical Operators, || or OR?

There is nothing bad or better, It just depends on the precedence of operators. Since || has higher precedence than or, so || is mostly used.

What does axis in pandas mean?

Many answers here helped me a lot!

In case you get confused by the different behaviours of axis in Python and MARGIN in R (like in the apply function), you may find a blog post that I wrote of interest: https://accio.github.io/programming/2020/05/19/numpy-pandas-axis.html.

In essence:

  • Their behaviours are, intriguingly, easier to understand with three-dimensional array than with two-dimensional arrays.
  • In Python packages numpy and pandas, the axis parameter in sum actually specifies numpy to calculate the mean of all values that can be fetched in the form of array[0, 0, ..., i, ..., 0] where i iterates through all possible values. The process is repeated with the position of i fixed and the indices of other dimensions vary one after the other (from the most far-right element). The result is a n-1-dimensional array.
  • In R, the MARGINS parameter let the apply function calculate the mean of all values that can be fetched in the form of array[, ... , i, ... ,] where i iterates through all possible values. The process is not repeated when all i values have been iterated. Therefore, the result is a simple vector.

Very simple C# CSV reader

This fixed version of code above remember the last element of CVS row ;-)

(tested with a CSV file with 5400 rows and 26 elements by row)

   public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')  {
            bool bolQuote = false;
            StringBuilder bld = new StringBuilder();
            List<string> retAry = new List<string>();

            foreach (char c in r.ToCharArray())
                if ((c == fieldSep && !bolQuote))
                {
                    retAry.Add(bld.ToString());
                    bld.Clear();
                }
                else
                    if (c == stringSep)
                        bolQuote = !bolQuote;
                    else
                        bld.Append(c);

            /* to solve the last element problem */
            retAry.Add(bld.ToString()); /* added this line */
            return retAry.ToArray();
        }

Is there a way to take a screenshot using Java and save it to some sort of image?

Believe it or not, you can actually use java.awt.Robot to "create an image containing pixels read from the screen." You can then write that image to a file on disk.

I just tried it, and the whole thing ends up like:

Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(args[0]));

NOTE: This will only capture the primary monitor. See GraphicsConfiguration for multi-monitor support.

Identify duplicate values in a list in Python

Here's a list comprehension that does what you want. As @Codemonkey says, the list starts at index 0, so the indices of the duplicates are 0 and 3.

>>> [i for i, x in enumerate(mylist) if mylist.count(x) > 1]
[0, 3]

How can I display a list view in an Android Alert Dialog?

You can use a custom dialog.

Custom dialog layout. list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ListView
        android:id="@+id/lv"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"/>
</LinearLayout>

In your activity

Dialog dialog = new Dialog(Activity.this);
       dialog.setContentView(R.layout.list)

ListView lv = (ListView ) dialog.findViewById(R.id.lv);
dialog.setCancelable(true);
dialog.setTitle("ListView");
dialog.show();

Edit:

Using alertdialog

String names[] ={"A","B","C","D"};
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom, null);
alertDialog.setView(convertView);
alertDialog.setTitle("List");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names);
lv.setAdapter(adapter);
alertDialog.show();

custom.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

</ListView>

Snap

enter image description here

PowerShell: Comparing dates

I wanted to show how powerful it can be aside from just checking "-lt".

Example: I used it to calculate time differences take from Windows event view Application log:

Get the difference between the two date times:

PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))

Object created:

PS> $Obj


Days              : 0
Hours             : 0
Minutes           : 31
Seconds           : 0
Milliseconds      : 0
Ticks             : 18600000000
TotalDays         : 0.0215277777777778
TotalHours        : 0.516666666666667
TotalMinutes      : 31
TotalSeconds      : 1860
TotalMilliseconds : 1860000

Access an item directly:

PS> $Obj.Minutes
31

Permission is only granted to system app

In Eclipse:

Window -> Preferences -> Android -> Lint Error Checking.

In the list find an entry with ID = ProtectedPermission. Set the Severity to something lower than Error. This way you can still compile the project using Eclipse.

In Android Studio:

File -> Settings -> Editor -> Inspections

Under Android Lint, locate Using system app permission. Either uncheck the checkbox or choose a Severity lower than Error.

How do you get the footer to stay at the bottom of a Web page?

Flexbox solution

Flex layout is preferred for natural header and footer heights. This flex solution is tested in modern browsers and actually works :) in IE11.

See JS Fiddle.

HTML

<body>
  <header>
    ...
  </header>
  <main>
    ...
  </main>
  <footer>
    ...
  </footer>
</body>  

CSS

html {
  height: 100%;
}

body {
  height: 100%;
  min-height: 100vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  margin: 0;
  display: flex;
  flex-direction: column;
}

main {
  flex-grow: 1;
  flex-shrink: 0;
}

header,
footer {
  flex: none;
}

Converting list to *args when calling function

You can use the * operator before an iterable to expand it within the function call. For example:

timeseries_list = [timeseries1 timeseries2 ...]
r = scikits.timeseries.lib.reportlib.Report(*timeseries_list)

(notice the * before timeseries_list)

From the python documentation:

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

This is also covered in the python tutorial, in a section titled Unpacking argument lists, where it also shows how to do a similar thing with dictionaries for keyword arguments with the ** operator.

Equivalent of varchar(max) in MySQL?

The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):

VARCHAR(65535)

However, note that the limit is lower if you use a multi-byte character set:

VARCHAR(21844) CHARACTER SET utf8

Here are some examples:

The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table.

mysql> CREATE TABLE foo ( v VARCHAR(65534) );
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

But if we try decreasing lengths, we find the greatest length that works:

mysql> CREATE TABLE foo ( v VARCHAR(65532) );
Query OK, 0 rows affected (0.01 sec)

Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't necessarily use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters.

mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8;
ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead

In spite of what the last error told us, InnoDB still doesn't like a length of 21845.

mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.

mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;
Query OK, 0 rows affected (0.32 sec)

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

Besides the solution using the FileProvider, there is another way to work around this. Simply put

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

in Application.onCreate(). In this way the VM ignores the file URI exposure.

Method

builder.detectFileUriExposure()

enables the file exposure check, which is also the default behavior if we don't setup a VmPolicy.

I encountered a problem that if I use a content:// URI to send something, some apps just can't understand it. And downgrading the target SDK version is not allowed. In this case my solution is useful.

Update:

As mentioned in the comment, StrictMode is diagnostic tool, and is not supposed to be used for this problem. When I posted this answer a year ago, many apps can only receive File uris. They just crash when I tried to send a FileProvider uri to them. This is fixed in most apps now, so we should go with the FileProvider solution.

Force add despite the .gitignore file

Despite Daniel Böhmer's working solution, Ohad Schneider offered a better solution in a comment:

If the file is usually ignored, and you force adding it - it can be accidentally ignored again in the future (like when the file is deleted, then a commit is made and the file is re-created.

You should just un-ignore it in the .gitignore file like that: Unignore subdirectories of ignored directories in Git

Field 'id' doesn't have a default value?

Since mysql 5.6, there is a new default that makes sure you are explicitly inserting every field that doesn't have a default value set in the table definition.

to disable and test this: see this answer here: mysql error 1364 Field doesn't have a default values

I would recommend you test without it, then reenable it and make sure all your tables have default values for fields you are not explicitly passing in every INSERT query.

If a third party mysql viewer is giving this error, you are probably limited to the fix in that link.

C# - Simplest way to remove first occurrence of a substring from another string

I definitely agree that this is perfect for an extension method, but I think it can be improved a bit.

public static string Remove(this string source, string remove,  int firstN)
    {
        if(firstN <= 0 || string.IsNullOrEmpty(source) || string.IsNullOrEmpty(remove))
        {
            return source;
        }
        int index = source.IndexOf(remove);
        return index < 0 ? source : source.Remove(index, remove.Length).Remove(remove, --firstN);
    }

This does a bit of recursion which is always fun.

Here is a simple unit test as well:

   [TestMethod()]
    public void RemoveTwiceTest()
    {
        string source = "look up look up look it up";
        string remove = "look";
        int firstN = 2;
        string expected = " up  up look it up";
        string actual;
        actual = source.Remove(remove, firstN);
        Assert.AreEqual(expected, actual);

    }

tomcat - CATALINA_BASE and CATALINA_HOME variables

That is the parent folder of bin which contains tomcat.exe file:

CATALINA_HOME='C:\Program Files\Apache Software Foundation\Tomcat 6.0'

CATALINA_BASE is the same as CATALINA_HOME.

How to expand/collapse a diff sections in Vimdiff?

Actually if you do Ctrl+W W, you won't need to add that extra Ctrl. Does the same thing.

ImportError: No module named apiclient.discovery

Make sure you only have google-api-python-client installed. If you have apiclient installed, it will cause a collision. So, run the following:

sudo pip uninstall apiclient

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

You can consider to replace default WordPress jQuery script with Google Library by adding something like the following into theme functions.php file:

function modify_jquery() {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'modify_jquery');

Code taken from here: http://www.wpbeginner.com/wp-themes/replace-default-wordpress-jquery-script-with-google-library/

Change Color of Fonts in DIV (CSS)

To do links, you can do

.social h2 a:link {
  color: pink;
  font-size: 14px;   
}

You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.

Resetting a form in Angular 2 after submit

If you call only reset() function, the form controls will not set to pristine state. android.io docs have a solution for this issue.

component.ts

  active = true; 

  resetForm() {
      this.form.reset();
      this.active = false;
      setTimeout(() => this.active = true, 0);
  }

component.html

<form *ngIf="active">