Programs & Examples On #Itunes app

How to detect a loop in a linked list?

public boolean hasLoop(Node start){   
   TreeSet<Node> set = new TreeSet<Node>();
   Node lookingAt = start;

   while (lookingAt.peek() != null){
       lookingAt = lookingAt.next;

       if (set.contains(lookingAt){
           return false;
        } else {
        set.put(lookingAt);
        }

        return true;
}   
// Inside our Node class:        
public Node peek(){
   return this.next;
}

Forgive me my ignorance (I'm still fairly new to Java and programming), but why wouldn't the above work?

I guess this doesn't solve the constant space issue... but it does at least get there in a reasonable time, correct? It will only take the space of the linked list plus the space of a set with n elements (where n is the number of elements in the linked list, or the number of elements until it reaches a loop). And for time, worst-case analysis, I think, would suggest O(nlog(n)). SortedSet look-ups for contains() are log(n) (check the javadoc, but I'm pretty sure TreeSet's underlying structure is TreeMap, whose in turn is a red-black tree), and in the worst case (no loops, or loop at very end), it will have to do n look-ups.

How to disable RecyclerView scrolling?

Came across with a fragment that contains multiple RecycleView so I only need one scrollbar instead of one scrollbar in each RecycleView.

So I just put the ScrollView in the parent container that contains the 2 RecycleViews and use android:isScrollContainer="false" in the RecycleView

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutManager="LinearLayoutManager"
    android:isScrollContainer="false" />

Using sed to mass rename files

The sed command

s/\(.\).\(.*\)/mv & \1\2/

means to replace:

\(.\).\(.*\)

with:

mv & \1\2

just like a regular sed command. However, the parentheses, & and \n markers change it a little.

The search string matches (and remembers as pattern 1) the single character at the start, followed by a single character, follwed by the rest of the string (remembered as pattern 2).

In the replacement string, you can refer to these matched patterns to use them as part of the replacement. You can also refer to the whole matched portion as &.

So what that sed command is doing is creating a mv command based on the original file (for the source) and character 1 and 3 onwards, effectively removing character 2 (for the destination). It will give you a series of lines along the following format:

mv F00001-0708-RG-biasliuyda F0001-0708-RG-biasliuyda
mv abcdef acdef

and so on.

How to check if a network port is open on linux?

In the Above,I found multiple solutions.But some solutions having a hanging issue or taking to much time in case of the port was not opened.Below solution worked for me :

import socket 

def port_check(HOST):
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.settimeout(2) #Timeout in case of port not open
   try:
      s.connect((HOST, 22)) #Port ,Here 22 is port 
      return True
   except:
      return False

port_check("127.0.1.1")

Raise warning in Python without interrupting program

import warnings
warnings.warn("Warning...........Message")

See the python documentation: here

Accept server's self-signed ssl certificate in Java client

The accepted answer needs an Option 3

ALSO Option 2 is TERRIBLE. It should NEVER be used (esp. in production) since it provides a FALSE sense of security. Just use HTTP instead of Option 2.

OPTION 3

Use the self-signed certificate to make the Https connection.

Here is an example:

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.KeyStore;

/*
 * Use a SSLSocket to send a HTTP GET request and read the response from an HTTPS server.
 * It assumes that the client is not behind a proxy/firewall
 */

public class SSLSocketClientCert
{
    private static final String[] useProtocols = new String[] {"TLSv1.2"};
    public static void main(String[] args) throws Exception
    {
        URL inputUrl = null;
        String certFile = null;
        if(args.length < 1)
        {
            System.out.println("Usage: " + SSLSocketClient.class.getName() + " <url>");
            System.exit(1);
        }
        if(args.length == 1)
        {
            inputUrl = new URL(args[0]);
        }
        else
        {
            inputUrl = new URL(args[0]);
            certFile = args[1];
        }
        SSLSocket sslSocket = null;
        PrintWriter outWriter = null;
        BufferedReader inReader = null;
        try
        {
            SSLSocketFactory sslSocketFactory = getSSLSocketFactory(certFile);

            sslSocket = (SSLSocket) sslSocketFactory.createSocket(inputUrl.getHost(), inputUrl.getPort() == -1 ? inputUrl.getDefaultPort() : inputUrl.getPort());
            String[] enabledProtocols = sslSocket.getEnabledProtocols();
            System.out.println("Enabled Protocols: ");
            for(String enabledProtocol : enabledProtocols) System.out.println("\t" + enabledProtocol);

            String[] supportedProtocols = sslSocket.getSupportedProtocols();
            System.out.println("Supported Protocols: ");
            for(String supportedProtocol : supportedProtocols) System.out.println("\t" + supportedProtocol + ", ");

            sslSocket.setEnabledProtocols(useProtocols);

            /*
             * Before any data transmission, the SSL socket needs to do an SSL handshake.
             * We manually initiate the handshake so that we can see/catch any SSLExceptions.
             * The handshake would automatically  be initiated by writing & flushing data but
             * then the PrintWriter would catch all IOExceptions (including SSLExceptions),
             * set an internal error flag, and then return without rethrowing the exception.
             *
             * This means any error messages are lost, which causes problems here because
             * the only way to tell there was an error is to call PrintWriter.checkError().
             */
            sslSocket.startHandshake();
            outWriter = sendRequest(sslSocket, inputUrl);
            readResponse(sslSocket);
            closeAll(sslSocket, outWriter, inReader);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            closeAll(sslSocket, outWriter, inReader);
        }
    }

    private static PrintWriter sendRequest(SSLSocket sslSocket, URL inputUrl) throws IOException
    {
        PrintWriter outWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream())));
        outWriter.println("GET " + inputUrl.getPath() + " HTTP/1.1");
        outWriter.println("Host: " + inputUrl.getHost());
        outWriter.println("Connection: Close");
        outWriter.println();
        outWriter.flush();
        if(outWriter.checkError())        // Check for any PrintWriter errors
            System.out.println("SSLSocketClient: PrintWriter error");
        return outWriter;
    }

    private static void readResponse(SSLSocket sslSocket) throws IOException
    {
        BufferedReader inReader = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
        String inputLine;
        while((inputLine = inReader.readLine()) != null)
            System.out.println(inputLine);
    }

    // Terminate all streams
    private static void closeAll(SSLSocket sslSocket, PrintWriter outWriter, BufferedReader inReader) throws IOException
    {
        if(sslSocket != null) sslSocket.close();
        if(outWriter != null) outWriter.close();
        if(inReader != null) inReader.close();
    }

    // Create an SSLSocketFactory based on the certificate if it is available, otherwise use the JVM default certs
    public static SSLSocketFactory getSSLSocketFactory(String certFile)
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException
    {
        if (certFile == null) return (SSLSocketFactory) SSLSocketFactory.getDefault();
        Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(new File(certFile)));

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("server", certificate);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

        return sslContext.getSocketFactory();
    }
}

Parse strings to double with comma and point

Extension to parse decimal number from string.

  • No matter number will be on the beginning, in the end, or in the middle of a string.
  • No matter if there will be only number or lot of "garbage" letters.
  • No matter what is delimiter configured in the cultural settings on the PC: it will parse dot and comma both correctly.
  • Ability to set decimal symbol manually.

    public static class StringExtension
    {
        public static double DoubleParseAdvanced(this string strToParse, char decimalSymbol = ',')
        {
            string tmp = Regex.Match(strToParse, @"([-]?[0-9]+)([\s])?([0-9]+)?[." + decimalSymbol + "]?([0-9 ]+)?([0-9]+)?").Value;
    
            if (tmp.Length > 0 && strToParse.Contains(tmp))
            {
                var currDecSeparator = System.Windows.Forms.Application.CurrentCulture.NumberFormat.NumberDecimalSeparator;
    
                tmp = tmp.Replace(".", currDecSeparator).Replace(decimalSymbol.ToString(), currDecSeparator);
    
                return double.Parse(tmp);
            }
    
            return 0;
        }
    }
    

How to use:

"It's 4.45 O'clock now".DoubleParseAdvanced(); // will return 4.45
"It's 4,45 O'clock now".DoubleParseAdvanced(); // will return 4.45
"It's 4:45 O'clock now".DoubleParseAdvanced(':'); // will return 4.45

Check whether a path is valid

Get the invalid chars from System.IO.Path.GetInvalidPathChars(); and check if your string (Directory path) contains those or not.

View stored procedure/function definition in MySQL

Perfect, try it:

SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES
    WHERE ROUTINE_SCHEMA = 'yourdb' AND ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_NAME = "procedurename";

How to merge a list of lists with same type of items to a single list of items?

Do you mean this?

var listOfList = new List<List<int>>() {
    new List<int>() { 1, 2 },
    new List<int>() { 3, 4 },
    new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));

foreach (var x in result) Console.WriteLine(x);

Results in: 9 9 9 1 2 3 4 5 6

Where is SQLite database stored on disk?

There is no "standard place" for a sqlite database. The file's location is specified to the library, and may be in your home directory, in the invoking program's folder, or any other place.

If it helps, sqlite databases are, by convention, named with a .db file extension.

How do I express "if value is not empty" in the VBA language?

Try this:

If Len(vValue & vbNullString) > 0 Then
  ' we have a non-Null and non-empty String value
  doSomething()
Else
  ' We have a Null or empty string value
  doSomethingElse()
End If

How to loop through a dataset in powershell?

The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()

for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{ 
  write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}

Additionally foreach allows you to iterate through a collection or array without needing to figure out the length.

Rewritten (and edited for compile) -

foreach ($Row in $ds.Tables[1].Rows)
{ 
  write-host "value is : $($Row[0])"
}

What's the simplest way to list conflicted files in Git?

Utility git wizard https://github.com/makelinux/git-wizard counts separately unresolved conflicted changes (collisions) and unmerged files. Conflicts must be resolved manually or with mergetool. Resolved unmerged changes can me added and committed usually with git rebase --continue.

A div with auto resize when changing window width\height

Code Snippet:

div{height: calc(100vh - 10vmax)}

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Is there a difference between x++ and ++x in java?

If it's like many other languages you may want to have a simple try:

i = 0;
if (0 == i++) // if true, increment happened after equality check
if (2 == ++i) // if true, increment happened before equality check

If the above doesn't happen like that, they may be equivalent

Download a file with Android, and showing the progress in a ProgressDialog

You can observer the progress of the download manager using LiveData and coroutines, see the gist below

https://gist.github.com/FhdAlotaibi/678eb1f4fa94475daf74ac491874fc0e

data class DownloadItem(val bytesDownloadedSoFar: Long = -1, val totalSizeBytes: Long = -1, val status: Int)

class DownloadProgressLiveData(private val application: Application, private val requestId: Long) : LiveData<DownloadItem>(), CoroutineScope {

    private val downloadManager by lazy {
        application.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    }

    private val job = Job()

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.IO + job

    override fun onActive() {
        super.onActive()
        launch {
            while (isActive) {
                val query = DownloadManager.Query().setFilterById(requestId)
                val cursor = downloadManager.query(query)
                if (cursor.moveToFirst()) {
                    val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
                    Timber.d("Status $status")
                    when (status) {
                        DownloadManager.STATUS_SUCCESSFUL,
                        DownloadManager.STATUS_PENDING,
                        DownloadManager.STATUS_FAILED,
                        DownloadManager.STATUS_PAUSED -> postValue(DownloadItem(status = status))
                        else -> {
                            val bytesDownloadedSoFar = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                            val totalSizeBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                            postValue(DownloadItem(bytesDownloadedSoFar.toLong(), totalSizeBytes.toLong(), status))
                        }
                    }
                    if (status == DownloadManager.STATUS_SUCCESSFUL || status == DownloadManager.STATUS_FAILED)
                        cancel()
                } else {
                    postValue(DownloadItem(status = DownloadManager.STATUS_FAILED))
                    cancel()
                }
                cursor.close()
                delay(300)
            }
        }
    }

    override fun onInactive() {
        super.onInactive()
        job.cancel()
    }

}

How to get your Netbeans project into Eclipse

Sharing my experience, how to import simple Netbeans java project into Eclipse workspace. Please follow the following steps:

  1. Copy the Netbeans project folder into Eclipse workspace.
  2. Create .project file, inside the project folder at root level. Below code is the sample reference. Change your project name appropriately.

    <?xml version="1.0" encoding="UTF-8"?>
    <projectDescription>
        <name>PROJECT_NAME</name>
        <comment></comment>
        <projects>
        </projects>
        <buildSpec>
            <buildCommand>
                <name>org.eclipse.jdt.core.javabuilder</name>
                <arguments>
                </arguments>
            </buildCommand>
        </buildSpec>
        <natures>
            <nature>org.eclipse.jdt.core.javanature</nature>
        </natures>
    </projectDescription>
    
  3. Now open Eclipse and follow the steps,

    File > import > Existing Projects into Workspace > Select root directory > Finish

  4. Now we need to correct the build path for proper compilation of src, by following these steps:

    Right Click on project folder > Properties > Java Build Path > Click Source tab > Add Folder

(Add the correct src path from project and remove the incorrect ones). Find the image ref link how it looks.

  1. You are done. Let me know for any queries. Thanks.

OrderBy descending in Lambda expression?

LastOrDefault() is usually not working but with the Tolist() it will work. There is no need to use OrderByDescending use Tolist() like this.

GroupBy(p => p.Nws_ID).ToList().LastOrDefault();

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Escaping Strings in JavaScript

You can also try this for the double quotes:

JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);

How to write lists inside a markdown table?

Yes, you can merge them using HTML. When I create tables in .md files from Github, I always like to use HTML code instead of markdown.

Github Flavored Markdown supports basic HTML in .md file. So this would be the answer:

Markdown mixed with HTML:

| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |
| <ul><li>item1</li><li>item2</li></ul>| See the list | from the first column|

Or pure HTML:

<table>
  <tbody>
    <tr>
      <th>Tables</th>
      <th align="center">Are</th>
      <th align="right">Cool</th>
    </tr>
    <tr>
      <td>col 3 is</td>
      <td align="center">right-aligned</td>
      <td align="right">$1600</td>
    </tr>
    <tr>
      <td>col 2 is</td>
      <td align="center">centered</td>
      <td align="right">$12</td>
    </tr>
    <tr>
      <td>zebra stripes</td>
      <td align="center">are neat</td>
      <td align="right">$1</td>
    </tr>
    <tr>
      <td>
        <ul>
          <li>item1</li>
          <li>item2</li>
        </ul>
      </td>
      <td align="center">See the list</td>
      <td align="right">from the first column</td>
    </tr>
  </tbody>
</table>

This is how it looks on Github:

Cursor inside cursor

You have a variety of problems. First, why are you using your specific @@FETCH_STATUS values? It should just be @@FETCH_STATUS = 0.

Second, you are not selecting your inner Cursor into anything. And I cannot think of any circumstance where you would select all fields in this way - spell them out!

Here's a sample to go by. Folder has a primary key of "ClientID" that is also a foreign key for Attend. I'm just printing all of the Attend UIDs, broken down by Folder ClientID:

Declare @ClientID int;
Declare @UID int;

DECLARE Cur1 CURSOR FOR
    SELECT ClientID From Folder;

OPEN Cur1
FETCH NEXT FROM Cur1 INTO @ClientID;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Processing ClientID: ' + Cast(@ClientID as Varchar);
    DECLARE Cur2 CURSOR FOR
        SELECT UID FROM Attend Where ClientID=@ClientID;
    OPEN Cur2;
    FETCH NEXT FROM Cur2 INTO @UID;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Found UID: ' + Cast(@UID as Varchar);
        FETCH NEXT FROM Cur2 INTO @UID;
    END;
    CLOSE Cur2;
    DEALLOCATE Cur2;
    FETCH NEXT FROM Cur1 INTO @ClientID;
END;
PRINT 'DONE';
CLOSE Cur1;
DEALLOCATE Cur1;

Finally, are you SURE you want to be doing something like this in a stored procedure? It is very easy to abuse stored procedures and often reflects problems in characterizing your problem. The sample I gave, for example, could be far more easily accomplished using standard select calls.

Read properties file outside JAR file

Here if you mention .getPath() then that will return the path of Jar and I guess you will need its parent to refer to all other config files placed with the jar. This code works on Windows. Add the code within the main class.

File jarDir = new File(MyAppName.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String jarDirpath = jarDir.getParent();

System.out.println(jarDirpath);

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Highlight the difference between two strings in PHP

Another solution (for side-by-side comparison as opposed to a unified view): https://github.com/danmysak/side-by-side.

Bash: infinite sleep (infinite blocking)

What about sending a SIGSTOP to itself?

This should pause the process until SIGCONT is received. Which is in your case: never.

kill -STOP "$$";
# grace time for signal delivery
sleep 60;

Left/Right float button inside div

You can use justify-content: space-between in .test like so:

_x000D_
_x000D_
.test {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


For those who want to use Bootstrap 4 can use justify-content-between:

_x000D_
_x000D_
div {_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can I do Android Programming in C++, C?

You should use Android NDK to develop performance-critical portions of your apps in native code. See Android NDK.

Anyway i don't think it is the right way to develop an entire application.

Changing navigation title programmatically

In Swift 4:

Swift 4

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Your title"
}

I hope it helps, regards!

String to LocalDate

Datetime formatting is performed by the org.joda.time.format.DateTimeFormatter class. Three classes provide factory methods to create formatters, and this is one. The others are ISODateTimeFormat and DateTimeFormatterBuilder.

DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MMM-dd");
LocalDate lDate = new LocalDate().parse("2005-nov-12",format);

final org.joda.time.LocalDate class is an immutable datetime class representing a date without a time zone. LocalDate is thread-safe and immutable, provided that the Chronology is as well. All standard Chronology classes supplied are thread-safe and immutable.

count number of characters in nvarchar column

Doesn't SELECT LEN(column_name) work?

Why use deflate instead of gzip for text files served by Apache?

GZip is simply deflate plus a checksum and header/footer. Deflate is faster, though, as I learned the hard way.

gzip vs deflate graph

How to call Android contacts list?

Be careful while working with android contact list.

Reading contact list in above methods work on most android devices except HTC One and Sony Xperia. It wasted my six weeks trying to figure out what is wrong!

Most tutorials available online are almost similar - first read "ALL" contacts, then show in Listview with ArrayAdapter. This is not memory efficient solution. Instead of looking for solutions on other websites first, have a look at developer.android.com. If any solution is not available on developer.android.com you should look somewhere else.

The solution is to use CursorAdapter instead of ArrayAdapter for retrieving contact list. Using ArrayAdapter would work on most devices, but it's not efficient. The CursorAdapter retrieves only a portion of contact list at run time while the ListView is being scrolled.

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ...
    // Gets the ListView from the View list of the parent activity
    mContactsList =
        (ListView) getActivity().findViewById(R.layout.contact_list_view);
    // Gets a CursorAdapter
    mCursorAdapter = new SimpleCursorAdapter(
            getActivity(),
            R.layout.contact_list_item,
            null,
            FROM_COLUMNS, TO_IDS,
            0);
    // Sets the adapter for the ListView
    mContactsList.setAdapter(mCursorAdapter);
}

Retrieving a List of Contacts: Retrieving a List of Contacts

Regular expression for letters, numbers and - _

This is the pattern you are looking for

/^[\w-_.]*$/

What this means:

  • ^ Start of string
  • [...] Match characters inside
  • \w Any word character so 0-9 a-z A-Z
  • -_. Match - and _ and .
  • * Zero or more of pattern or unlimited
  • $ End of string

If you want to limit the amount of characters:

/^[\w-_.]{0,5}$/

{0,5} Means 0-5 characters

How to keep :active css style after click a button

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

HTML

<input type="checkbox" id="activate-div">
  <label for="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>
  </label>

CSS

#activate-div{display:none}    

.my-div{background-color:#FFF} 

#activate-div:checked ~ label 
.my-div{background-color:#000}



To make button change content:

HTML

<input type="checkbox" id="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>

<label for="activate-div">
   //MY BUTTON STUFF
</label>

CSS

#activate-div{display:none}

.my-div{background-color:#FFF} 

#activate-div:checked + 
.my-div{background-color:#000}

Hope it helps!!

How to set min-font-size in CSS

In CSS3 there is a simple but brilliant hack for that:

font-size:calc(12px + 1.5vw);

This is because the static part of calc() defines the minimum. Even though the dynamic part might shrink to something near 0.

Horizontal list items

Updated Answer

I've noticed a lot of people are using this answer so I decided to update it a little bit. If you want to see the original answer, check below. The new answer demonstrates how you can add some style to your list.

_x000D_
_x000D_
ul > li {_x000D_
    display: inline-block;_x000D_
    /* You can also add some margins here to make it look prettier */_x000D_
    zoom:1;_x000D_
    *display:inline;_x000D_
    /* this fix is needed for IE7- */_x000D_
}
_x000D_
<ul>_x000D_
    <li> <a href="#">some item</a>_x000D_
_x000D_
    </li>_x000D_
    <li> <a href="#">another item</a>_x000D_
_x000D_
    </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Auto Scale TextView Text to Fit within Bounds

A workaround for Android 4.x:

I found AutoResizeTextView and it works great on my Android 2.1 emulator. I loved it so much. But unfortunately it failed on my own 4.0.4 cellphone and 4.1 emulator. After trying I found it could be easily resolved by adding following attributes in AutoResizeTextView class in the xml:

android:ellipsize="none"

android:singleLine="true"

With the 2 lines above, now AutoResizeTextView working perfectly on my 2.1 & 4.1 emulators and my own 4.0.4 cellphone now.

Hope this helps you. :-)

JSON.stringify output to div in pretty print way

A lot of people create very strange responses to these questions that make alot more work than necessary.

The easiest way to do this consists of the following

  1. Parse JSON String using JSON.parse(value)
  2. Stringify Parsed string into a nice format - JSON.stringify(input,undefined,2)
  3. Set output to the value of step 2.

In actual code, an example will be (combining all steps together):

    var input = document.getElementById("input").value;
    document.getElementById("output").value = JSON.stringify(JSON.parse(input),undefined,2);

output.value is going to be the area where you will want to display a beautified JSON.

How to create table using select query in SQL Server?

An example statement that uses a sub-select :

select * into MyNewTable
from
(
select 
  * 
from 
[SomeOtherTablename]
where 
  EventStartDatetime >= '01/JAN/2018' 
)
) mysourcedata
;

note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.

The database should reply with a message like: (9999 row(s) affected)

IDEA: javac: source release 1.7 requires target release 1.7

If Maven build works fine, try to synchronizing structure of Maven and IntelliJ IDEA projects.

In the Maven tool window, click refresh button refresh. On pressing this button, IntelliJ IDEA parses the project structure in the Maven tool window.

Note that this might not help if you're using EAP build, since Maven synchronization feature may be broken sometimes.

Routing with Multiple Parameters using ASP.NET MVC

Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:

public ActionResult GetImages(string artistName, string apiKey)

MVC will auto-populate the parameters when given a URL like:

/Artist/GetImages/?artistName=cher&apiKey=XXX

One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:

public ActionResult GetImages(string id, string apiKey)

would be populated correctly with a URL like the following:

/Artist/GetImages/cher?apiKey=XXX

In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:

routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

If you wanted to support a url like

/Artist/GetImages/cher/api-key

you could add a route like:

routes.MapRoute(
            "ArtistImages",                                              // Route name
            "{controller}/{action}/{artistName}/{apikey}",                           // URL with parameters
            new { controller = "Home", action = "Index", artistName = "", apikey = "" }  // Parameter defaults
        );

and a method like the first example above.

Test iOS app on device without apple developer program or jailbreak

With Xcode 7 you are no longer required to have a developer account in order to test your apps on your device:

enter image description here

Check it out here.

Please notice that this is the officially supported by Apple, so there's no need of jailbroken devices or testing on the simulator, but you'll have to use Xcode 7 (currently in beta by the time of this post) or later.

I successfully deployed an app to my iPhone without a developer account. You'll have to use your iCloud account to solve the provisioning profile issues. Just add your iCloud account and assign it in the Team dropdown (in the Identity menu) and the Fix Issue button should do the rest.


UPDATE:

Some people are having problems with iOS 8.4, here is how to fix it.

How to find the index of an element in an int array?

Copy this method into your class

 public int getArrayIndex(int[] arr,int value) {

        int k=0;
        for(int i=0;i<arr.length;i++){

            if(arr[i]==value){
                k=i;
                break;
            }
        }
    return k;
}

Call this method with pass two perameters Array and value and store its return value in a integer variable.

int indexNum = getArrayIndex(array,value);

Thank you

How to get folder path from file path with CMD

In order to assign these to variables, be sure not to add spaces in front or after the equals sign:

set filepath=%~dp1
set filename=%~nx1

Then you should have no issues.

converting drawable resource image into bitmap

Drawable myDrawable = getResources().getDrawable(R.drawable.logo);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

Since API 22 getResources().getDrawable() is deprecated, so we can use following solution.

Drawable vectorDrawable = VectorDrawableCompat.create(getResources(), R.drawable.logo,  getContext().getTheme());
Bitmap myLogo = ((BitmapDrawable) vectorDrawable).getBitmap();

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

Get host domain from URL?

Try like this;

Uri.GetLeftPart( UriPartial.Authority )

Defines the parts of a URI for the Uri.GetLeftPart method.


http://www.contoso.com/index.htm?date=today --> http://www.contoso.com

http://www.contoso.com/index.htm#main --> http://www.contoso.com

nntp://news.contoso.com/[email protected] --> nntp://news.contoso.com

file://server/filename.ext --> file://server

Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search");
Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Authority));

Demo

How to access the content of an iframe with jQuery?

<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">

$(function() {

    //here you have the control over the body of the iframe document
    var iBody = $("#iView").contents().find("body");

    //here you have the control over any element (#myContent)
    var myContent = iBody.find("#myContent");

});

</script>
</head>
<body>
  <iframe src="mifile.html" id="iView" style="width:200px;height:70px;border:dotted 1px red" frameborder="0"></iframe>
</body>
</html>

Is there a goto statement in Java?

The keyword exists, but it is not implemented.

The only good reason to use goto that I can think of is this:

for (int i = 0; i < MAX_I; i++) {
    for (int j = 0; j < MAX_J; j++) {
        // do stuff
        goto outsideloops; // to break out of both loops
    }
}
outsideloops:

In Java you can do this like this:

loops:
for (int i = 0; i < MAX_I; i++) {
    for (int j = 0; j < MAX_J; j++) {
        // do stuff
        break loops;
    }
}

How to send a html email with the bash command "sendmail"?

I understand you asked for sendmail but why not use the default mail? It can easily send html emails.

Works on: RHEL 5.10/6.x & CentOS 5.8

Example:

cat ~/campaigns/release-status.html | mail -s "$(echo -e "Release Status [Green]\nContent-Type: text/html")" [email protected] -v

CodeShare: http://www.codeshare.io/8udx5

Get Android API level of phone currently running my application

Integer.valueOf(android.os.Build.VERSION.SDK);

Values are:

Platform Version   API Level
Android 9.0        28
Android 8.1        27
Android 8.0        26
Android 7.1        25
Android 7.0        24
Android 6.0        23
Android 5.1        22
Android 5.0        21
Android 4.4W       20
Android 4.4        19
Android 4.3        18
Android 4.2        17
Android 4.1        16
Android 4.0.3      15
Android 4.0        14
Android 3.2        13
Android 3.1        12
Android 3.0        11
Android 2.3.3      10
Android 2.3        9
Android 2.2        8
Android 2.1        7
Android 2.0.1      6
Android 2.0        5
Android 1.6        4
Android 1.5        3
Android 1.1        2
Android 1.0        1

CAUTION: don't use android.os.Build.VERSION.SDK_INT if <uses-sdk android:minSdkVersion="3" />.

You will get exception on all devices with Android 1.5 and lower because Build.VERSION.SDK_INT is since SDK 4 (Donut 1.6).

Notify ObservableCollection when Item changes

I solved this case by using static Action


public class CatalogoModel 
{
    private String _Id;
    private String _Descripcion;
    private Boolean _IsChecked;

    public String Id
    {
        get { return _Id; }
        set { _Id = value; }
    }
    public String Descripcion
    {
        get { return _Descripcion; }
        set { _Descripcion = value; }
    }
    public Boolean IsChecked
    {
        get { return _IsChecked; }
        set
        {
           _IsChecked = value;
            NotifyPropertyChanged("IsChecked");
            OnItemChecked.Invoke();
        }
    }

    public static Action OnItemChecked;
} 

public class ReglaViewModel : ViewModelBase
{
    private ObservableCollection<CatalogoModel> _origenes;

    CatalogoModel.OnItemChecked = () =>
            {
                var x = Origenes.Count;  //Entra cada vez que cambia algo en _origenes
            };
}

Lua string to int

here is what you should put

local stringnumber = "10"
local a = tonumber(stringnumber)
print(a + 10)

output:

20

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

As an alternative you may want to check out BridgeIt at bridgeit.mobi. Open source, it has resolved the browser performance / consistency issue discussed above in that it leverages the standard browser on the device vs. the web-view browser. It also allows you to access the native features without having to worry about app store deployments and/or native containers.

I've used if for simple camera based access and scanner access and it works well for simple apps. Documentation is a bit light. Not sure how it would do on more complex apps.

Git Bash won't run my python files?

That command did not work for me, I used:

$ export PATH="$PATH:/c/Python27"

Then to make sure that git remembers the python path every time you open git type the following.

echo 'export PATH="$PATH:/c/Python27"' > .profile

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

What tool can decompile a DLL into C++ source code?

There really isn't any way of doing this as most of the useful information is discarded in the compilation process. However, you may want to take a look at this site to see if you can find some way of extracting something from the DLL.

How to get the top position of an element?

$("#myTable").offset().top;

This will give you the computed offset (relative to document) of any object.

How to make Excel VBA variables available to multiple macros?

Declare them outside the subroutines, like this:

Public wbA as Workbook
Public wbB as Workbook
Sub MySubRoutine()
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine
End Sub
Sub OtherSubRoutine()
    MsgBox wbA.Name, vbInformation
End Sub

Alternately, you can pass variables between subroutines:

Sub MySubRoutine()
Dim wbA as Workbook
Dim wbB as Workbook
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine wbA, wbB
End Sub
Sub OtherSubRoutine(wb1 as Workbook, wb2 as Workbook)
    MsgBox wb1.Name, vbInformation
    MsgBox wb2.Name, vbInformation
End Sub

Or use Functions to return values:

Sub MySubroutine()
    Dim i as Long
    i = MyFunction()
    MsgBox i
End Sub
Function MyFunction()
    'Lots of code that does something
    Dim x As Integer, y as Double
    For x = 1 to 1000
        'Lots of code that does something
    Next
    MyFunction = y
End Function

In the second method, within the scope of OtherSubRoutine you refer to them by their parameter names wb1 and wb2. Passed variables do not need to use the same names, just the same variable types. This allows you some freedom, for example you have a loop over several workbooks, and you can send each workbook to a subroutine to perform some action on that Workbook, without making all (or any) of the variables public in scope.

A Note About User Forms

Personally I would recommend keeping Option Explicit in all of your modules and forms (this prevents you from instantiating variables with typos in their names, like lCoutn when you meant lCount etc., among other reasons).

If you're using Option Explicit (which you should), then you should qualify module-scoped variables for style and to avoid ambiguity, and you must qualify user-form Public scoped variables, as these are not "public" in the same sense. For instance, i is undefined, though it's Public in the scope of UserForm1:

enter image description here

You can refer to it as UserForm1.i to avoid the compile error, or since forms are New-able, you can create a variable object to contain reference to your form, and refer to it that way:

enter image description here

NB: In the above screenshots x is declared Public x as Long in another standard code module, and will not raise the compilation error. It may be preferable to refer to this as Module2.x to avoid ambiguity and possible shadowing in case you re-use variable names...

Laravel 4: Redirect to a given url

Both Redirect::to() and Redirect::away() should work.

Difference

Redirect::to() does additional URL checks and generations. Those additional steps are done in Illuminate\Routing\UrlGenerator and do the following, if the passed URL is not a fully valid URL (even with protocol):

Determines if URL is secure
rawurlencode() the URL
trim() URL

src : https://medium.com/@zwacky/laravel-redirect-to-vs-redirect-away-dd875579951f

jquery append external html file into my page

Use html instead of append:

$.get("banner.html", function(data){
    $(this).children("div:first").html(data);
});

what is difference between success and .done() method of $.ajax

.success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine.

The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.

promise.done(doneCallback).fail(failCallback)

.done() has only one callback and it is the success callback

How do I sort a list of dictionaries by a value of the dictionary?

You have to implement your own comparison function that will compare the dictionaries by values of name keys. See Sorting Mini-HOW TO from PythonInfo Wiki

Laravel - check if Ajax request

Those who prefer to use laravel helpers they can check if a request is ajax using laravel request() helper.

if(request()->ajax())
   // code

What is newline character -- '\n'

From the sed man page:

Normally, sed cyclically copies a line of input, not including its terminating newline character, into a pattern space, (unless there is something left after a "D" function), applies all of the commands with addresses that select that pattern space, copies the pattern space to the standard output, appending a newline, and deletes the pattern space.

It's operating on the line without the newline present, so the pattern you have there can't ever match. You need to do something else - like match against $ (end-of-line) or ^ (start-of-line).

Here's an example of something that worked for me:

$ cat > states
California
Massachusetts
Arizona
$ sed -e 's/$/\
> /' states
California

Massachusetts

Arizona

I typed a literal newline character after the \ in the sed line.

Can we add div inside table above every <tr>?

In the html tables, <table> tag expect <tr> tag right after itself and <tr> tag expect <td> tag right after itself. So if you want to put a div in table, you can put it in between <td> and </td> tags as data.

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div>_x000D_
        <p>It works well</p>_x000D_
      </div>_x000D_
     </td>_x000D_
  </tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

Is there a vr (vertical rule) in html?

You could create a custom tag as such:

<html>
<head>
<style>
vr {
display: inline-block;
// This is where you'd set the ruler color
background-color: black;
// This is where you'd set the ruler width
width: 2px;
//this is where you'd set the spacing between the ruler and surrounding text
margin: 0px 5px 0px 5px;
height: 100%;
vertical-align: top;
}
</style>
</head>
<body>
this is text <vr></vr> more text
</body>
</html>

(If anyone knows a way that I could turn this into an "open-ended" tag, like <hr> let me know and I will edit it in)

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

It occurs when you don't specify the no of parameters the __init__() or any other method looking for.

For example:

class Dog:
    def __init__(self):
        print("IN INIT METHOD")

    def __unicode__(self,):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")

obj=Dog("JIMMY",1,2,3,"WOOF")

When you run the above programme, it gives you an error like that:

TypeError: __init__() takes 1 positional argument but 6 were given

How we can get rid of this thing?

Just pass the parameters, what __init__() method looking for

class Dog:
    def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
        self.name_of_dog = dogname
        self.date_of_birth = dob_d
        self.month_of_birth = dob_m
        self.year_of_birth = dob_y
        self.sound_it_make = dogSpeakText

    def __unicode__(self, ):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")


obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))

How to update Python?

I have always just installed the new version on top and never had any issues. Do make sure that your path is updated to point to the new version though.

Always pass weak reference of self into block in ARC?

As Leo points out, the code you added to your question would not suggest a strong reference cycle (a.k.a., retain cycle). One operation-related issue that could cause a strong reference cycle would be if the operation is not getting released. While your code snippet suggests that you have not defined your operation to be concurrent, but if you have, it wouldn't be released if you never posted isFinished, or if you had circular dependencies, or something like that. And if the operation isn't released, the view controller wouldn't be released either. I would suggest adding a breakpoint or NSLog in your operation's dealloc method and confirm that's getting called.

You said:

I understand the notion of retain cycles, but I am not quite sure what happens in blocks, so that confuses me a little bit

The retain cycle (strong reference cycle) issues that occur with blocks are just like the retain cycle issues you're familiar with. A block will maintain strong references to any objects that appear within the block, and it will not release those strong references until the block itself is released. Thus, if block references self, or even just references an instance variable of self, that will maintain strong reference to self, that is not resolved until the block is released (or in this case, until the NSOperation subclass is released.

For more information, see the Avoid Strong Reference Cycles when Capturing self section of the Programming with Objective-C: Working with Blocks document.

If your view controller is still not getting released, you simply have to identify where the unresolved strong reference resides (assuming you confirmed the NSOperation is getting deallocated). A common example is the use of a repeating NSTimer. Or some custom delegate or other object that is erroneously maintaining a strong reference. You can often use Instruments to track down where objects are getting their strong references, e.g.:

record reference counts in Xcode 6

Or in Xcode 5:

record reference counts in Xcode 5

PHP: How to remove all non printable characters in a string?

All of the solutions work partially, and even below probably does not cover all of the cases. My issue was in trying to insert a string into a utf8 mysql table. The string (and its bytes) all conformed to utf8, but had several bad sequences. I assume that most of them were control or formatting.

function clean_string($string) {
  $s = trim($string);
  $s = iconv("UTF-8", "UTF-8//IGNORE", $s); // drop all non utf-8 characters

  // this is some bad utf-8 byte sequence that makes mysql complain - control and formatting i think
  $s = preg_replace('/(?>[\x00-\x1F]|\xC2[\x80-\x9F]|\xE2[\x80-\x8F]{2}|\xE2\x80[\xA4-\xA8]|\xE2\x81[\x9F-\xAF])/', ' ', $s);

  $s = preg_replace('/\s+/', ' ', $s); // reduce all multiple whitespace to a single space

  return $s;
}

To further exacerbate the problem is the table vs. server vs. connection vs. rendering of the content, as talked about a little here

What is java pojo class, java bean, normal class?

POJO = Plain Old Java Object. It has properties, getters and setters for respective properties. It may also override Object.toString() and Object.equals().

Java Beans : See Wiki link.

Normal Class : Any java Class.

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

This is not an answer, but it's hard to read if I put results in comment.

I get these results with a Mac Pro (Westmere 6-Cores Xeon 3.33 GHz). I compiled it with clang -O3 -msse4 -lstdc++ a.cpp -o a (-O2 get same result).

clang with uint64_t size=atol(argv[1])<<20;

unsigned    41950110000 0.811198 sec    12.9263 GB/s
uint64_t    41950110000 0.622884 sec    16.8342 GB/s

clang with uint64_t size=1<<20;

unsigned    41950110000 0.623406 sec    16.8201 GB/s
uint64_t    41950110000 0.623685 sec    16.8126 GB/s

I also tried to:

  1. Reverse the test order, the result is the same so it rules out the cache factor.
  2. Have the for statement in reverse: for (uint64_t i=size/8;i>0;i-=4). This gives the same result and proves the compile is smart enough to not divide size by 8 every iteration (as expected).

Here is my wild guess:

The speed factor comes in three parts:

  • code cache: uint64_t version has larger code size, but this does not have an effect on my Xeon CPU. This makes the 64-bit version slower.

  • Instructions used. Note not only the loop count, but the buffer is accessed with a 32-bit and 64-bit index on the two versions. Accessing a pointer with a 64-bit offset requests a dedicated 64-bit register and addressing, while you can use immediate for a 32-bit offset. This may make the 32-bit version faster.

  • Instructions are only emitted on the 64-bit compile (that is, prefetch). This makes 64-bit faster.

The three factors together match with the observed seemingly conflicting results.

Error :The remote server returned an error: (401) Unauthorized

The answers did help, but I think a full implementation of this will help a lot of people.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Dom
{
    class Dom
    {
        public static string make_Sting_From_Dom(string reportname)
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                // Retrieve resource as a stream               
                Stream data = client.OpenRead(new Uri(reportname.Trim()));
                // Retrieve the text
                StreamReader reader = new StreamReader(data);
                string htmlContent = reader.ReadToEnd();
                string mtch = "TILDE";
                bool b = htmlContent.Contains(mtch);

                if (b)
                {
                    int index = htmlContent.IndexOf(mtch);
                    if (index >= 0)
                        Console.WriteLine("'{0} begins at character position {1}",
                        mtch, index + 1);
                }
                // Cleanup
                data.Close();
                reader.Close();
                return htmlContent;
            }
            catch (Exception)
            {
                throw;
            }
        }

        static void Main(string[] args)
        {
            make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
        }
    }
}

How to search and replace text in a file?

Late answer, but this is what I use to find and replace inside a text file:

with open("test.txt") as r:
  text = r.read().replace("THIS", "THAT")
with open("test.txt", "w") as w:
  w.write(text)

DEMO

Check whether a string matches a regex in JS

_x000D_
_x000D_
const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't
_x000D_
_x000D_
_x000D_

Spring: How to get parameters from POST body?

You will need these imports...

import javax.servlet.*;
import javax.servlet.http.*;

And, if you're using Maven, you'll also need this in the dependencies block of the pom.xml file in your project's base directory.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Then the above-listed fix by Jason will work:

@ResponseBody
    public ResponseEntity<Boolean> saveData(HttpServletRequest request,
        HttpServletResponse response, Model model){
        String jsonString = request.getParameter("json");
    }

Remove element from JSON Object

To iterate through the keys of an object, use a for .. in loop:

for (var key in json_obj) {
    if (json_obj.hasOwnProperty(key)) {
        // do something with `key'
    }
}

To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.

Removing a property of an object can be done by using the delete keyword:

var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

Documentation:

Asynchronous Function Call in PHP

I think some code about the cURL solution is needed here, so I will share mine (it was written mixing several sources as the PHP Manual and comments).

It does some parallel HTTP requests (domains in $aURLs) and print the responses once each one is completed (and stored them in $done for other possible uses).

The code is longer than needed because the realtime print part and the excess of comments, but feel free to edit the answer to improve it:

<?php
/* Strategies to avoid output buffering, ignore the block if you don't want to print the responses before every cURL is completed */
ini_set('output_buffering', 'off'); // Turn off output buffering
ini_set('zlib.output_compression', false); // Turn off PHP output compression       
//Flush (send) the output buffer and turn off output buffering
ob_end_flush(); while (@ob_end_flush());        
apache_setenv('no-gzip', true); //prevent apache from buffering it for deflate/gzip
ini_set('zlib.output_compression', false);
header("Content-type: text/plain"); //Remove to use HTML
ini_set('implicit_flush', true); // Implicitly flush the buffer(s)
ob_implicit_flush(true);
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
$string=''; for($i=0;$i<1000;++$i){$string.=' ';} output($string); //Safari and Internet Explorer have an internal 1K buffer.
//Here starts the program output

function output($string){
    ob_start();
    echo $string;
    if(ob_get_level()>0) ob_flush();
    ob_end_clean();  // clears buffer and closes buffering
    flush();
}

function multiprint($aCurlHandles,$print=true){
    global $done;
    // iterate through the handles and get your content
    foreach($aCurlHandles as $url=>$ch){
        if(!isset($done[$url])){ //only check for unready responses
            $html = curl_multi_getcontent($ch); //get the content           
            if($html){
                $done[$url]=$html;
                if($print) output("$html".PHP_EOL);
            }           
        }
    }
};

function full_curl_multi_exec($mh, &$still_running) {
    do {
      $rv = curl_multi_exec($mh, $still_running); //execute the handles 
    } while ($rv == CURLM_CALL_MULTI_PERFORM); //CURLM_CALL_MULTI_PERFORM means you should call curl_multi_exec() again because there is still data available for processing
    return $rv;
} 

set_time_limit(60); //Max execution time 1 minute

$aURLs = array("http://domain/script1.php","http://domain/script2.php");  // array of URLs

$done=array();  //Responses of each URL

    //Initialization
    $aCurlHandles = array(); // create an array for the individual curl handles
    $mh = curl_multi_init(); // init the curl Multi and returns a new cURL multi handle
    foreach ($aURLs as $id=>$url) { //add the handles for each url        
        $ch = curl_init(); // init curl, and then setup your options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // returns the result - very important
        curl_setopt($ch, CURLOPT_HEADER, 0); // no headers in the output
        $aCurlHandles[$url] = $ch;
        curl_multi_add_handle($mh,$ch);
    }

    //Process
    $active = null; //the number of individual handles it is currently working with
    $mrc=full_curl_multi_exec($mh, $active); 
    //As long as there are active connections and everything looks OK…
    while($active && $mrc == CURLM_OK) { //CURLM_OK means is that there is more data available, but it hasn't arrived yet.  
        // Wait for activity on any curl-connection and if the network socket has some data…
        if($descriptions=curl_multi_select($mh,1) != -1) {//If waiting for activity on any curl_multi connection has no failures (1 second timeout)     
            usleep(500); //Adjust this wait to your needs               
            //Process the data for as long as the system tells us to keep getting it
            $mrc=full_curl_multi_exec($mh, $active);        
            //output("Still active processes: $active".PHP_EOL);        
            //Printing each response once it is ready
            multiprint($aCurlHandles);  
        }
    }

    //Printing all the responses at the end
    //multiprint($aCurlHandles,false);      

    //Finalize
    foreach ($aCurlHandles as $url=>$ch) {
        curl_multi_remove_handle($mh, $ch); // remove the handle (assuming  you are done with it);
    }
    curl_multi_close($mh); // close the curl multi handler
?>

Alternative to Intersect in MySQL

Your query would always return an empty recordset since cut_name= '?????' and cut_name='??' will never evaluate to true.

In general, INTERSECT in MySQL should be emulated like this:

SELECT  *
FROM    mytable m
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    othertable o
        WHERE   (o.col1 = m.col1 OR (m.col1 IS NULL AND o.col1 IS NULL))
                AND (o.col2 = m.col2 OR (m.col2 IS NULL AND o.col2 IS NULL))
                AND (o.col3 = m.col3 OR (m.col3 IS NULL AND o.col3 IS NULL))
        )

If both your tables have columns marked as NOT NULL, you can omit the IS NULL parts and rewrite the query with a slightly more efficient IN:

SELECT  *
FROM    mytable m
WHERE   (col1, col2, col3) IN
        (
        SELECT  col1, col2, col3
        FROM    othertable o
        )

jQuery form validation on button click

$(document).ready(function() {
    $("#form1").validate({
        rules: {
            field1: "required"
        },
        messages: {
            field1: "Please specify your name"
        }
    })
});

<form id="form1" name="form1">
     Field 1: <input id="field1" type="text" class="required">
    <input id="btn" type="submit" value="Validate">
</form>

You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.

What is "Advanced" SQL?

When you see them spelled out in requirements they tend to include:

  • Views
  • Stored Procedures
  • User Defined Functions
  • Triggers
  • sometimes Cursors

Inner and outer joins are a must but i rarely ever see it mentioned in requirements. And it's surprising how many so-called db professionals cannot get their head around a simple outer join.

how to list all sub directories in a directory

To just get the simple list of folders without full path, you can use:

Directory.GetDirectories(parentDirectory).Select(d => Path.GetRelativePath(parentDirectory, d)

Why does a base64 encoded string have an = sign at the end

Its defined in RFC 2045 as a special padding character if fewer than 24 bits are available at the end of the encoded data.

The Eclipse executable launcher was unable to locate its companion launcher jar windows

You have to copy in Users/user/.p2 and .eclipse from old location when it come from and older location. For example i made a copy from computer to another, and i had this error, then i copied those folders and it worked !

Create a data.frame with m columns and 2 rows

For completeness:

Along the lines of Chase's answer, I usually use as.data.frame to coerce the matrix to a data.frame:

m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))

EDIT: speed test data.frame vs. as.data.frame

system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  8.005   0.108   8.165 

system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  3.759   0.048   3.802 

Yes, it appears to be faster (by about 2 times).

Cannot hide status bar in iOS7

For 2019 ...

To make an app with NO status bars,

Click info.plist, right-click to "Add row".

Add these two, with these settings:

enter image description here

That's all there is to it.

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

I solved the error by changing the port for the project.

I did the following steps:

  1. Right click on the project.
  2. Go to properties.
  3. Go to Server tab.
  4. On tab section, change the project URL for other port, like 8080 or 3000.

Good luck!

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

Pip - Fatal error in launcher: Unable to create process using '"'

This worked for me under Windows 10 x64:

Ensure that the Python directories are in the path, e.g.:

# Edit Environment variables so that variable "path" points to the new location.
# Insert these at the start of the list (or delete other Python directories), as Windows takes the first match it finds.
# Run the program "Edit the System Environment Variables".
# Or see Control Panel under "System Properties".
S:\Research\bin\Python375\Scripts\
S:\Research\bin\Python375\

Then:

python -m pip install --upgrade --force-reinstall pip

In my particular case, the error was caused by shifting the Python directory to a new location.

How to insert a newline in front of a pattern?

In my case the below method works.

sed -i 's/playstation/PS4/' input.txt

Can be written as:

sed -i 's/playstation/PS4\nplaystation/' input.txt

PS4
playstation

Consider using \\n while using it in a string literal.

  • sed : is stream editor

  • -i : Allows to edit the source file

  • +: Is delimiter.

I hope the above information works for you .

Returning a boolean from a Bash function

Following up on @Bruno Bronosky and @mrteatime, I offer the suggestion that you just write your boolean return "backwards". This is what I mean:

foo()
{
    if [ "$1" == "bar" ]; then
        true; return
    else
        false; return
    fi;
}

That eliminates the ugly two line requirement for every return statement.

Login to Microsoft SQL Server Error: 18456

Check out this blog article from the data platform team.

http://blogs.msdn.com/b/sql_protocols/archive/2006/02/21/536201.aspx

You really need to look at the state part of the error message to find the root cause of the issue.

2, 5 = Invalid userid
6 = Attempt to use a Windows login name with SQL Authentication
7 = Login disabled and password mismatch
8 = Password mismatch
9 = Invalid password
11, 12 = Valid login but server access failure
13 = SQL Server service paused
18 = Change password required

Afterwards, Google how to fix the issue.

ASP.NET: Session.SessionID changes between requests

my problem was that we had this set in web.config

<httpCookies httpOnlyCookies="true" requireSSL="true" />

this means that when debugging in non-SSL (the default), the auth cookie would not get sent back to the server. this would mean that the server would send a new auth cookie (with a new session) for every request back to the client.

the fix is to either set requiressl to false in web.config and true in web.release.config or turn on SSL while debugging:

turn on SSL

if-else statement inside jsx: ReactJS

There's a Babel plugin that allows you to write conditional statements inside JSX without needing to escape them with JavaScript or write a wrapper class. It's called JSX Control Statements:

<View style={styles.container}>
  <If condition={ this.state == 'news' }>
    <Text>data</Text>
  </If>
</View>

It takes a bit of setting up depending on your Babel configuration, but you don't have to import anything and it has all the advantages of conditional rendering without leaving JSX which leaves your code looking very clean.

How to validate phone numbers using regex

Have you had a look over at RegExLib?

Entering US phone number brought back quite a list of possibilities.

Getters \ setters for dummies

What's so confusing about it... getters are functions that are called when you get a property, setters, when you set it. example, if you do

obj.prop = "abc";

You're setting the property prop, if you're using getters/setters, then the setter function will be called, with "abc" as an argument. The setter function definition inside the object would ideally look something like this:

set prop(var) {
   // do stuff with var...
}

I'm not sure how well that is implemented across browsers. It seems Firefox also has an alternative syntax, with double-underscored special ("magic") methods. As usual Internet Explorer does not support any of this.

minimum double value in C/C++

The original question concerns infinity. So, why not use

#define Infinity  ((double)(42 / 0.0))

according to the IEEE definition? You can negate that of course.

How to list AD group membership for AD users using input list?

Or add "sort name" to list alphabetically

Get-ADPrincipalGroupMembership username | select name | sort name

Tracking CPU and Memory usage per process

Download process monitor

  1. Start Process Monitor

  2. Set a filter if required

  3. Enter menu Options > Profiling Events

  4. Click "Generate thread prof?iling events", choose the frequency, and click OK.

  5. To see the collected historical data at any time, enter menu Tools > Process Activity Summary

Deleting all files from a folder using PHP?

Another solution: This Class delete all files, subdirectories and files in the sub directories.

class Your_Class_Name {
    /**
     * @see http://php.net/manual/de/function.array-map.php
     * @see http://www.php.net/manual/en/function.rmdir.php 
     * @see http://www.php.net/manual/en/function.glob.php
     * @see http://php.net/manual/de/function.unlink.php
     * @param string $path
     */
    public function delete($path) {
        if (is_dir($path)) {
            array_map(function($value) {
                $this->delete($value);
                rmdir($value);
            },glob($path . '/*', GLOB_ONLYDIR));
            array_map('unlink', glob($path."/*"));
        }
    }
}

An array of List in c#

use

List<int>[] a = new List<int>[100];

Session state can only be used when enableSessionState is set to true either in a configuration

Actually jessehouwing gave the solution for normal scenario.

But in my case I have enabled 2 types of session in my web.config file

It's like below.

First one :

<modules runAllManagedModulesForAllRequests="true">
        <remove name="Session" />
        <add name="Session" type="System.Web.SessionState.SessionStateModule, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>

Second one :

<sessionState mode="Custom" customProvider="DefaultSessionProvider">
            <providers>
                <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PawLoyalty" applicationName="PawLoyalty"/>
            </providers>
 </sessionState>

So in my case I have to comment Second one.B'cos that thing for the production.When I commented out second one my problem vanished.

StringIO in Python3

On Python 3 numpy.genfromtxt expects a bytes stream. Use the following:

numpy.genfromtxt(io.BytesIO(x.encode()))

Setting a system environment variable from a Windows batch file?

The XP Support Tools (which can be installed from your XP CD) come with a program called setx.exe:

C:\Program Files\Support Tools>setx /?

SETX: This program is used to set values in the environment
of the machine or currently logged on user using one of three modes.

1) Command Line Mode: setx variable value [-m]
   Optional Switches:
    -m  Set value in the Machine environment. Default is User.

...
For more information and example use: SETX -i

I think Windows 7 actually comes with setx as part of a standard install.

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

After installing openjdk with brew and runnning brew info openjdk I got this

enter image description here

And from that I got this command here, and after running it I got Java working

sudo ln -sfn /usr/local/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk

How to reduce the image file size using PIL

See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS filter when you do.

Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.

Adding a simple spacer to twitter bootstrap

My approach. Tricky, but works well for me

<p>&nbsp;</p>

Prevent a webpage from navigating away using JavaScript

Unlike other methods presented here, this bit of code will not cause the browser to display a warning asking the user if he wants to leave; instead, it exploits the evented nature of the DOM to redirect back to the current page (and thus cancel navigation) before the browser has a chance to unload it from memory.

Since it works by short-circuiting navigation directly, it cannot be used to prevent the page from being closed; however, it can be used to disable frame-busting.

(function () {
    var location = window.document.location;

    var preventNavigation = function () {
        var originalHashValue = location.hash;

        window.setTimeout(function () {
            location.hash = 'preventNavigation' + ~~ (9999 * Math.random());
            location.hash = originalHashValue;
        }, 0);
    };

    window.addEventListener('beforeunload', preventNavigation, false);
    window.addEventListener('unload', preventNavigation, false);
})();

Disclaimer: You should never do this. If a page has frame-busting code on it, please respect the wishes of the author.

Does HTTP use UDP?

From RFC 2616:

HTTP communication usually takes place over TCP/IP connections. The default port is TCP 80, but other ports can be used. This does not preclude HTTP from being implemented on top of any other protocol on the Internet, or on other networks. HTTP only presumes a reliable transport; any protocol that provides such guarantees can be used; the mapping of the HTTP/1.1 request and response structures onto the transport data units of the protocol in question is outside the scope of this specification.

So although it doesn't explicitly say so, UDP is not used because it is not a "reliable transport".

EDIT - more recently, the QUIC protocol (which is more strictly a pseudo-transport or a session layer protocol) does use UDP for carrying HTTP/2.0 traffic and much of Google's traffic already uses this protocol. It's currently progressing towards standardisation as HTTP/3.

Can two or more people edit an Excel document at the same time?

The new version of SharePoint and Office (SharePoint 2010 and Office 2010) respectively are supposed to allow for this. This also includes the web based versions. I have seen Word and Excel in action do this, not sure about other client applications.

I am not sure about the specific implementation features you are asking about in terms of security though. Sorry.,=

Here is a discussion

http://blogs.msdn.com/b/sharepoint/archive/2009/10/19/sharepoint-2010.aspx

Using SUMIFS with multiple AND OR conditions

You might consider referencing the actual date/time in the source column for Quote_Month, then you could transform your OR into a couple of ANDs, something like (assuing the date's in something I've chosen to call Quote_Date)

=SUMIFS(Quote_Value,"<=90",Quote_Date,">="&DATE(2013,11,1),Quote_Date,"<="&DATE(2013,12,31),Salesman,"=JBloggs",Days_To_Close)

(I moved the interesting conditions to the front).

This approach works here because that "OR" condition is actually specifying a date range - it might not work in other cases.

extract month from date in python

Alternate solution

Create a column that will store the month:

data['month'] = data['date'].dt.month

Create a column that will store the year:

data['year'] = data['date'].dt.year

CSS Flex Box Layout: full-width row and columns

You've almost done it. However setting flex: 0 0 <basis> declaration to the columns would prevent them from growing/shrinking; And the <basis> parameter would define the width of columns.

In addition, you could use CSS3 calc() expression to specify the height of columns with the respect to the height of the header.

#productShowcaseTitle {
  flex: 0 0 100%; /* Let it fill the entire space horizontally */
  height: 100px;
}

#productShowcaseDetail,
#productShowcaseThumbnailContainer {
  height: calc(100% - 100px); /* excluding the height of the header */
}

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
  flex: 0 0 100%; /* Let it fill the entire space horizontally */_x000D_
  height: 100px;_x000D_
  background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
  flex: 0 0 66%; /* ~ 2 * 33.33% */_x000D_
  height: calc(100% - 100px); /* excluding the height of the header */_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
  flex: 0 0 34%;  /* ~ 33.33% */_x000D_
  height: calc(100% - 100px); /* excluding the height of the header */_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
  <div id="productShowcaseTitle"></div>_x000D_
  <div id="productShowcaseDetail"></div>_x000D_
  <div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vendor prefixes omitted due to brevity)


Alternatively, if you could change your markup e.g. wrapping the columns by an additional <div> element, it would be achieved without using calc() as follows:

<div class="contentContainer"> <!-- Added wrapper -->
    <div id="productShowcaseDetail"></div>
    <div id="productShowcaseThumbnailContainer"></div>
</div>
#productShowcaseContainer {
  display: flex;
  flex-direction: column;
  height: 600px; width: 580px;
}

.contentContainer { display: flex; flex: 1; }
#productShowcaseDetail { flex: 3; }
#productShowcaseThumbnailContainer { flex: 2; }

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.contentContainer {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
  height: 100px;_x000D_
  background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
  flex: 3;_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
  <div id="productShowcaseTitle"></div>_x000D_
_x000D_
  <div class="contentContainer"> <!-- Added wrapper -->_x000D_
    <div id="productShowcaseDetail"></div>_x000D_
    <div id="productShowcaseThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vendor prefixes omitted due to brevity)

Node JS Error: ENOENT

You can include a different jade file into your template, that to from a different directory

views/
     layout.jade
static/
     page.jade

To include the layout file from views dir to static/page.jade

page.jade

extends ../views/layout

How to check if X server is running?

The bash script solution:

if ! xset q &>/dev/null; then
    echo "No X server at \$DISPLAY [$DISPLAY]" >&2
    exit 1
fi

Doesn't work if you login from another console (Ctrl+Alt+F?) or ssh. For me this solution works in my Archlinux:

#!/bin/sh
ps aux|grep -v grep|grep "/usr/lib/Xorg"
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
  echo "X server running"
  exit 1
fi

You can change /usr/lib/Xorg for only Xorg or the proper command on your system.

Connect different Windows User in SQL Server Management Studio (2005 or later)

While there's no way to connect to multiple servers as different users in a single instance of SSMS, what you're looking for is the following RUNAS syntax:

runas /netonly /user:domain\username program.exe

When you use the "/netonly" switch, you can log in using remote credentials on a domain that you're not currently a member of, even if there's no trust set up. It just tells runas that the credentials will be used for accessing remote resources - the application interacts with the local computer as the currently logged-in user, and interacts with remote computers as the user whose credentials you've given.

You'd still have to run multiple instances of SSMS, but at least you could connect as different windows users in each one.


For example: runas /netonly /user:domain\username ssms.exe

Uncaught ReferenceError: angular is not defined - AngularJS not working

i forgot to add below line to my HTML code after i add problem has resolved.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>

Can I get the name of the current controller in the view?

controller_path holds the path of the controller used to serve the current view. (ie: admin/settings).

and

controller_name holds the name of the controller used to serve the current view. (ie: settings).

How to create a sticky footer that plays well with Bootstrap 3

For those who are searching for a light answer, you can get a simple working example from here:

html {
    position: relative;
    min-height: 100%;
}
body {
    margin-bottom: 60px /* Height of the footer */
}
footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 60px /* Example value */
}

Just play with the body's margin-bottom for adding space between the content and footer.

How do I detect IE 8 with jQuery?

This should work for all IE8 minor versions

if ($.browser.msie  && parseInt($.browser.version, 10) === 8) {
  alert('IE8'); 
} else {
  alert('Non IE8');
}

-- update

Please note that $.browser is removed from jQuery 1.9

Set a border around a StackPanel.

You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.

If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

ModalPopupExtender OK Button click event not firing?

I've found a way to validate a modalpopup without a postback.

In the ModalPopupExtender I set the OnOkScript to a function e.g ValidateBeforePostBack(), then in the function I call Page_ClientValidate for the validation group I want, do a check and if it fails, keep the modalpopup showing. If it passes, I call __doPostBack.

function ValidateBeforePostBack(){ 
     Page_ClientValidate('MyValidationGroupName'); 
     if (Page_IsValid) { __doPostBack('',''); } 
     else { $find('mpeBehaviourID').show(); } 
}

run a python script in terminal without the python command

There are three parts:

  1. Add a 'shebang' at the top of your script which tells how to execute your script
  2. Give the script 'run' permissions.
  3. Make the script in your PATH so you can run it from anywhere.

Adding a shebang

You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:

#!path/to/interpretter

To find the path to your python interpretter on your machine you can run the command:

which python

This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:

#!/usr/bin/python

Run Permissions

You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:

chmod +x myscript.py

Add the script to your path

The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:

echo $PATH

This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:

which <commandname>

Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:

export PATH=/my/directory/with/pythonscript:$PATH

Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile

How to access to the parent object in c#

Store a reference to the meter instance as a member in Production:

public class Production {
  //The other members, properties etc...
  private Meter m;

  Production(Meter m) {
    this.m = m;
  }
}

And then in the Meter-class:

public class Meter
{
   private int _powerRating = 0; 
   private Production _production;

   public Meter()
   {
      _production = new Production(this);
   }
}

Also note that you need to implement an accessor method/property so that the Production class can actually access the powerRating member of the Meter class.

Loading a properties file from Java package

use the below code please :

    Properties p = new Properties(); 
    StringBuffer path = new StringBuffer("com/al/common/email/templates/");
    path.append("foo.properties");
    InputStream fs = getClass().getClassLoader()
                                    .getResourceAsStream(path.toString());

if(fs == null){ System.err.println("Unable to load the properties file"); } else{ try{ p.load(fs); } catch (IOException e) { e.printStackTrace(); } }

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

How to use PHP OPCache?

With PHP 5.6 on Amazon Linux (should be the same on RedHat or CentOS):

yum install php56-opcache

and then restart apache.

Does PHP have threading?

There is nothing available that I'm aware of. The next best thing would be to simply have one script execute another via CLI, but that's a bit rudimentary. Depending on what you are trying to do and how complex it is, this may or may not be an option.

Post to another page within a PHP script

Solution is in target="_blank" like this:

http://www.ozzu.com/website-design-forum/multiple-form-submit-actions-t25024.html

edit form like this:

<form method="post" action="../booking/step1.php" onsubmit="doubleSubmit(this)">

And use this script:

    <script type="text/javascript">
<!--
function doubleSubmit(f)
{
  // submit to action in form
  f.submit();
  // set second action and submit
  f.target="_blank";
  f.action="../booking/vytvor.php";
  f.submit();
  return false;
}
//-->
</script>

ERROR: Error 1005: Can't create table (errno: 121)

Something I noticed was that I had "other_database" and "Other_Database" in my databases. That caused this problem as I actually had same reference in other database which caused this mysterious error!

how to prevent adding duplicate keys to a javascript array

The logic is wrong. Consider this:

x = ["a","b","c"]
x[0]     // "a"
x["0"]   // "a"
0 in x   // true
"0" in x // true
x.hasOwnProperty(0)   // true
x.hasOwnProperty("0") // true

There is no reason to loop to check for key (or indices for arrays) existence. Now, values are a different story...

Happy coding

How to query for Xml values and attributes from table in SQL Server?

I've been trying to do something very similar but not using the nodes. However, my xml structure is a little different.

You have it like this:

<Metrics>
    <Metric id="TransactionCleanupThread.RefundOldTrans" type="timer" ...>

If it were like this instead:

<Metrics>
    <Metric>
        <id>TransactionCleanupThread.RefundOldTrans</id>
        <type>timer</type>
        .
        .
        .

Then you could simply use this SQL statement.

SELECT
    Sqm.SqmId,
    Data.value('(/Sqm/Metrics/Metric/id)[1]', 'varchar(max)') as id,
    Data.value('(/Sqm/Metrics/Metric/type)[1]', 'varchar(max)') AS type,
    Data.value('(/Sqm/Metrics/Metric/unit)[1]', 'varchar(max)') AS unit,
    Data.value('(/Sqm/Metrics/Metric/sum)[1]', 'varchar(max)') AS sum,
    Data.value('(/Sqm/Metrics/Metric/count)[1]', 'varchar(max)') AS count,
    Data.value('(/Sqm/Metrics/Metric/minValue)[1]', 'varchar(max)') AS minValue,
    Data.value('(/Sqm/Metrics/Metric/maxValue)[1]', 'varchar(max)') AS maxValue,
    Data.value('(/Sqm/Metrics/Metric/stdDeviation)[1]', 'varchar(max)') AS stdDeviation,
FROM Sqm

To me this is much less confusing than using the outer apply or cross apply.

I hope this helps someone else looking for a simpler solution!

javascript functions to show and hide divs

The beauty of jQuery would allow us to do the following:

$(function()
{
    var benefits = $('#benefits');

    // this is the show function
    $('a[name=1]').click(function()
    { 
        benefits.show();
    });

    // this is the hide function
    $('a', benefits).click(function()
    {
        benefits.hide();
    });
});

Alternatively you could have 1 button toggle the display, like this:

$(function()
{
    // this is the show and hide function, all in 1!
    $('a[name=1]').click(function()
    { 
        $('#benefits').toggle();
    });
});

SQL Server - Convert varchar to another collation (code page) to fix character encoding

Character set conversion is done implicitly on the database connection level. You can force automatic conversion off in the ODBC or ADODB connection string with the parameter "Auto Translate=False". This is NOT recommended. See: https://msdn.microsoft.com/en-us/library/ms130822.aspx

There has been a codepage incompatibility in SQL Server 2005 when Database and Client codepage did not match. https://support.microsoft.com/kb/KbView/904803

SQL-Management Console 2008 and upwards is a UNICODE application. All values entered or requested are interpreted as such on the application level. Conversation to and from the column collation is done implicitly. You can verify this with:

SELECT CAST(N'±' as varbinary(10)) AS Result

This will return 0xB100 which is the Unicode character U+00B1 (as entered in the Management Console window). You cannot turn off "Auto Translate" for Management Studio.

If you specify a different collation in the select, you eventually end up in a double conversion (with possible data loss) as long as "Auto Translate" is still active. The original character is first transformed to the new collation during the select, which in turn gets "Auto Translated" to the "proper" application codepage. That's why your various COLLATION tests still show all the same result.

You can verify that specifying the collation DOES have an effect in the select, if you cast the result as VARBINARY instead of VARCHAR so the SQL Server transformation is not invalidated by the client before it is presented:

SELECT cast(columnName COLLATE SQL_Latin1_General_CP850_BIN2 as varbinary(10)) from tableName
SELECT cast(columnName COLLATE SQL_Latin1_General_CP1_CI_AS as varbinary(10)) from tableName

This will get you 0xF1 or 0xB1 respectively if columnName contains just the character '±'

You still might get the correct result and yet a wrong character, if the font you are using does not provide the proper glyph.

Please double check the actual internal representation of your character by casting the query to VARBINARY on a proper sample and verify whether this code indeed corresponds to the defined database collation SQL_Latin1_General_CP850_BIN2

SELECT CAST(columnName as varbinary(10)) from tableName

Differences in application collation and database collation might go unnoticed as long as the conversion is always done the same way in and out. Troubles emerge as soon as you add a client with a different collation. Then you might find that the internal conversion is unable to match the characters correctly.

All that said, you should keep in mind that Management Studio usually is not the final reference when interpreting result sets. Even if it looks gibberish in MS, it still might be the correct output. The question is whether the records show up correctly in your applications.

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

Just Modified the previous example to print even collection containing user defined objects.

public class ToStringHelper {

    private  static String separator = "\n";

    public ToStringHelper(String seperator) {
        super();
        ToStringHelper.separator = seperator;

    }

    public  static String toString(List<?> l) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : l) {
            String v = ToStringBuilder.reflectionToString(object);
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static String toString(Map<?,?> m) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : m.keySet()) {
            String v = ToStringBuilder.reflectionToString(m.get(object));
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static String toString(Set<?> s) {
        StringBuilder sb = new StringBuilder();
        String sep = "";
        for (Object object : s) {
            String v = ToStringBuilder.reflectionToString(object);
            int start = v.indexOf("[");
            int end = v.indexOf("]");
            String st =  v.substring(start,end+1);
            sb.append(sep).append(st);
            sep = separator;
        }
        return sb.toString();
    }

    public static void print(List<?> l) {
        System.out.println(toString(l));    
    }
    public static void print(Map<?,?> m) {
        System.out.println(toString(m));    
    }
    public static void print(Set<?> s) {
        System.out.println(toString(s));    
    }

}

Python data structure sort list alphabetically

You can use built-in sorted function.

print sorted(['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'])

What does \d+ mean in regular expression terms?

\d is a digit, + is 1 or more, so a sequence of 1 or more digits

How do I include image files in Django templates?

I do understand, that your question was about files stored in MEDIA_ROOT, but sometimes it can be possible to store content in static, when you are not planning to create content of that type anymore.
May be this is a rare case, but anyway - if you have a huge amount of "pictures of the day" for your site - and all these files are on your hard drive?

In that case I see no contra to store such a content in STATIC.
And all becomes really simple:

static

To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. You can use this regardless if you're using RequestContext or not.

{% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />

copied from Official django 1.4 documentation / Built-in template tags and filters

Xcode 4: How do you view the console?

There's two options:

  1. Log Navigator (command-7 or view|navigators|log) and select your debug session.

  2. "View | Show Debug Area" to view the NSLog output and interact with the debugger.

Here's a pic with both on. You wouldn't normally have both on, but I can only link one image per post! http://i.stack.imgur.com/4gG4P.png

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

How to keep console window open

Write Console.ReadKey(); in the last line of main() method. This line prevents finishing the console. I hope it would help you.

Create a list with initial capacity in Python

def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

Results. (evaluate each function 144 times and average the duration)

simple append 0.0102
pre-allocate  0.0098

Conclusion. It barely matters.

Premature optimization is the root of all evil.

iPhone - Get Position of UIView within entire UIWindow

Swift 5+:

let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)

Segmentation fault on large array sizes

You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.

If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

int* array = new int[1000000];

But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to 1000000 elements.

How to Decode Json object in laravel and apply foreach loop on that in laravel

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

Clear listview content?

As of Android versions M and N, following works for me and would be the correct approach. Emptying the ListView or setting the Adapter to null is not the right approach and would lead to null pointer issue, invalid ListView and/or crash of the app.

Simply do:

    mList.clear();
    mAdapter.notifyDataSetChanged();

i.e. first you clear the list altogether, and then let the adapter know about this change. Android will take care of correctly updating the UI with an empty list. In my case, my list is an ArrayList.

In case you are doing this operation from a different thread, run this code on the UI thread:

    runOnUiThread(mRunnable);

Where mRunnable would be:

    Runnable mRunnable = new Runnable() {
        public void run() {
            mList.clear();
            mAdapter.notifyDataSetChanged();
        }
    };;

FORCE INDEX in MySQL - where do I put it?

FORCE_INDEX is going to be deprecated after MySQL 8:

Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in 
a future release of MySQL, and at some time thereafter to be removed altogether.

https://dev.mysql.com/doc/refman/8.0/en/index-hints.html

You should be using JOIN_INDEX, GROUP_INDEX, ORDER_INDEX, and INDEX instead, for v8.

What is unexpected T_VARIABLE in PHP?

In my case it was an issue of the PHP version.

The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.

Differences between dependencyManagement and dependencies in Maven

In Eclipse, there is one more feature in the dependencyManagement. When dependencies is used without it, the unfound dependencies are noticed in the pom file. If dependencyManagement is used, the unsolved dependencies remain unnoticed in the pom file and errors appear only in the java files. (imports and such...)

Use a LIKE statement on SQL Server XML Datatype

Yet another option is to cast the XML as nvarchar, and then search for the given string as if the XML vas a nvarchar field.

SELECT * 
FROM Table
WHERE CAST(Column as nvarchar(max)) LIKE '%TEST%'

I love this solution as it is clean, easy to remember, hard to mess up, and can be used as a part of a where clause.

EDIT: As Cliff mentions it, you could use:

...nvarchar if there's characters that don't convert to varchar

Python 3 - Encode/Decode vs Bytes/Str

To add to add to the previous answer, there is even a fourth way that can be used

import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)

How do I declare a model class in my Angular 2 component using TypeScript?

export class Car {
  id: number;
  make: string;
  model: string;
  color: string;
  year: Date;

  constructor(car) {
      {
        this.id = car.id;
        this.make = car.make || '';
        this.model = car.model || '';
        this.color = car.color || '';
        this.year = new Date(car.year).getYear();
      }
  }
}

The || can become super useful for very complex data objects to default data that doesn't exist.

. .

In your component.ts or service.ts file you can deserialize response data into the model:

// Import the car model
import { Car } from './car.model.ts';

// If single object
car = new Car(someObject);

// If array of cars
cars = someDataToDeserialize.map(c => new Car(c));

dispatch_after - GCD in Swift?

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    // ...
});

The dispatch_after(_:_:_:) function takes three parameters:

a delay
a dispatch queue
a block or closure

The dispatch_after(_:_:_:) function invokes the block or closure on the dispatch queue that is passed to the function after a given delay. Note that the delay is created using the dispatch_time(_:_:) function. Remember this because we also use this function in Swift.

I recommend to go through the tutorial Raywenderlich Dispatch tutorial

How to change JDK version for an Eclipse project

See the page Set Up JDK in Eclipse. From the add button you can add a different version of the JDK...

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

SQLAlchemy upsert for Postgres >=9.5

Since the large post above covers many different SQL approaches for Postgres versions (not only non-9.5 as in the question), I would like to add how to do it in SQLAlchemy if you are using Postgres 9.5. Instead of implementing your own upsert, you can also use SQLAlchemy's functions (which were added in SQLAlchemy 1.1). Personally, I would recommend using these, if possible. Not only because of convenience, but also because it lets PostgreSQL handle any race conditions that might occur.

Cross-posting from another answer I gave yesterday (https://stackoverflow.com/a/44395983/2156909)

SQLAlchemy supports ON CONFLICT now with two methods on_conflict_do_update() and on_conflict_do_nothing():

Copying from the documentation:

from sqlalchemy.dialects.postgresql import insert

stmt = insert(my_table).values(user_email='[email protected]', data='inserted data')
stmt = stmt.on_conflict_do_update(
    index_elements=[my_table.c.user_email],
    index_where=my_table.c.user_email.like('%@gmail.com'),
    set_=dict(data=stmt.excluded.data)
    )
conn.execute(stmt)

http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html?highlight=conflict#insert-on-conflict-upsert

How do I detect the Python version at runtime?

Try this code, this should work:

import platform
print(platform.python_version())

How do I format a date in Jinja2?

Here's the filter that I ended up using for strftime in Jinja2 and Flask

@app.template_filter('strftime')
def _jinja2_filter_datetime(date, fmt=None):
    date = dateutil.parser.parse(date)
    native = date.replace(tzinfo=None)
    format='%b %d, %Y'
    return native.strftime(format) 

And then you use the filter like so:

{{car.date_of_manufacture|strftime}}

Pod install is staying on "Setting up CocoaPods Master repo"

pod setup works and should only take 10 mins on a solid connection. After that run: pod install --verbose and you should see all the comments you would normally see when running a dependancy manager.

Hope that helps

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

submitting a form when a checkbox is checked

Use JavaScript by adding an onChange attribute to your input tags

<input onChange="this.form.submit()" ... />

How to convert string to boolean in typescript Angular 4

I have been trying different values with JSON.parse(value) and it seems to do the work:

// true
Boolean(JSON.parse("true"));
Boolean(JSON.parse("1"));
Boolean(JSON.parse(1));
Boolean(JSON.parse(true));

// false
Boolean(JSON.parse("0")); 
Boolean(JSON.parse(0));
Boolean(JSON.parse("false"));
Boolean(JSON.parse(false));

Read connection string from web.config

Everybody seems to be suggesting that adding

using System.Configuration;

which is true.

But might I suggest that you think about installing ReSharper's Visual Studio extension?

With it installed, instead of seeing an error that a class isn't defined, you'll see a prompt that tells you which assembly it is in, asking you if you want it to add the needed using statement.

Creating folders inside a GitHub repository without using Git

Another thing you can do is just drag a folder from your computer into the GitHub repository page. This folder does have to have at least 1 item in it, though.

When should one use a spinlock instead of mutex?

Spinlock and Mutex synchronization mechanisms are very common today to be seen.

Let's think about Spinlock first.

Basically it is a busy waiting action, which means that we have to wait for a specified lock is released before we can proceed with the next action. Conceptually very simple, while implementing it is not on the case. For example: If the lock has not been released then the thread was swap-out and get into the sleep state, should do we deal with it? How to deal with synchronization locks when two threads simultaneously request access ?

Generally, the most intuitive idea is dealing with synchronization via a variable to protect the critical section. The concept of Mutex is similar, but they are still different. Focus on: CPU utilization. Spinlock consumes CPU time to wait for do the action, and therefore, we can sum up the difference between the two:

In homogeneous multi-core environments, if the time spend on critical section is small than use Spinlock, because we can reduce the context switch time. (Single-core comparison is not important, because some systems implementation Spinlock in the middle of the switch)

In Windows, using Spinlock will upgrade the thread to DISPATCH_LEVEL, which in some cases may be not allowed, so this time we had to use a Mutex (APC_LEVEL).

Can an interface extend multiple interfaces in Java?

From the Oracle documentation page about multiple inheritance type,we can find the accurate answer here. Here we should first know the type of multiple inheritance in java:-

  1. Multiple inheritance of state.
  2. Multiple inheritance of implementation.
  3. Multiple inheritance of type.

Java "doesn't support the multiple inheritance of state, but it support multiple inheritance of implementation with default methods since java 8 release and multiple inheritance of type with interfaces.

Then here the question arises for "diamond problem" and how Java deal with that:-

  1. In case of multiple inheritance of implementation java compiler gives compilation error and asks the user to fix it by specifying the interface name. Example here:-

                interface A {
                    void method();
                }
    
                interface B extends A {
                    @Override
                    default void method() {
                        System.out.println("B");
                    }
                }
    
                interface C extends A { 
                    @Override
                    default void method() {
                        System.out.println("C");
                    }
                }
    
                interface D extends B, C {
    
                }
    

So here we will get error as:- interface D inherits unrelated defaults for method() from types B and C interface D extends B, C

You can fix it like:-

interface D extends B, C {
                @Override
                default void method() {
                    B.super.method();
                }
            }
  1. In multiple inheritance of type java allows it because interface doesn't contain mutable fields and only one implementation will belong to the class so java doesn't give any issue and it allows you to do so.

In Conclusion we can say that java doesn't support multiple inheritance of state but it does support multiple inheritance of implementation and multiple inheritance of type.

No newline at end of file

Source files are often concatenated by tools (C, C++: header files, Javascript: bundlers). If you omit the newline character, you could introduce nasty bugs (where the last line of one source is concatenated with the first line of the next source file). Hopefully all the source code concat tools out there insert a newline between concatenated files anyway but that doesn't always seem to be the case.

The crux of the issue is - in most languages, newlines have semantic meaning and end-of-file is not a language defined alternative for the newline character. So you ought to terminate every statement/expression with a newline character -- including the last one.

how to set ul/li bullet point color?

I believe this is controlled by the css color property applied to the element.

How to store phone numbers on MySQL databases?

varchar, Don't store separating characters you may want to format the phone numbers differently for different uses. so store (619) 123-4567 as 6191234567 I work with phone directory data and have found this to be the best practice.

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Predict() - Maybe I'm not understanding it

instead of newdata you are using newdate in your predict code, verify once. and just use Coupon$estimate <- predict(model, Coupon) It will work.

How to make clang compile to llvm IR

Given some C/C++ file foo.c:

> clang -S -emit-llvm foo.c

Produces foo.ll which is an LLVM IR file.

The -emit-llvm option can also be passed to the compiler front-end directly, and not the driver by means of -cc1:

> clang -cc1 foo.c -emit-llvm

Produces foo.ll with the IR. -cc1 adds some cool options like -ast-print. Check out -cc1 --help for more details.


To compile LLVM IR further to assembly, use the llc tool:

> llc foo.ll

Produces foo.s with assembly (defaulting to the machine architecture you run it on). llc is one of the LLVM tools - here is its documentation.

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

Make sure to import component in declarations array

@NgModule({
  declarations: [ExampleComponent],
  imports: [
      CommonModule,
      ExampleRoutingModule,
      ReactiveFormsModule
  ]
})

What is the best way to declare global variable in Vue.js?

A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.

An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478

How to create a folder with name as current date in batch (.bat) files

This works for me, try:

ECHO %DATE:~7,2%_%DATE:~4,2%_%DATE:~12,2%

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

How to auto import the necessary classes in Android Studio with shortcut?

Go on the missing declaration with cursor and press alt+enter enter image description here

Allow 2 decimal places in <input type="number">

On input:

step="any"
class="two-decimals"

On script:

$(".two-decimals").change(function(){
  this.value = parseFloat(this.value).toFixed(2);
});

Is it worth using Python's re.compile?

This is a good question. You often see people use re.compile without reason. It lessens readability. But sure there are lots of times when pre-compiling the expression is called for. Like when you use it repeated times in a loop or some such.

It's like everything about programming (everything in life actually). Apply common sense.

MySQL Trigger - Storing a SELECT in a variable

You can declare local variables in MySQL triggers, with the DECLARE syntax.

Here's an example:

DROP TABLE IF EXISTS foo;
CREATE TABLE FOO (
  i SERIAL PRIMARY KEY
);

DELIMITER //
DROP TRIGGER IF EXISTS bar //

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = NEW.i;
  SET @a = x; -- set user variable outside trigger
END//

DELIMITER ;

SET @a = 0;

SELECT @a; -- returns 0

INSERT INTO foo () VALUES ();

SELECT @a; -- returns 1, the value it got during the trigger

When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row".

You can use LIMIT or MAX() to make sure that the local variable is set to a single value.

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT age FROM users WHERE name = 'Bill'); 
  -- ERROR 1242 if more than one row with 'Bill'
END//

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
  -- OK even when more than one row with 'Bill'
END//

Trim a string in C

Not the best way but it works

char* Trim(char* str)
{
    int len = strlen(str);
    char* buff = new char[len];
    int i = 0;
    memset(buff,0,len*sizeof(char));
    do{
        if(isspace(*str)) continue;
        buff[i] = *str; ++i;
    } while(*(++str) != '\0');
    return buff;
}

How to run shell script file using nodejs?

You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.

hi.sh

echo "Hi There!"

node_program.js

const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
        (error, stdout, stderr) => {
            console.log(stdout);
            console.log(stderr);
            if (error !== null) {
                console.log(`exec error: ${error}`);
            }
        });

Here, when I run the nodejs file, it will execute the shell file and the output would be:

Run

node node_program.js

output

Hi There!

You can execute any script just by mentioning the shell command or shell script in exec callback.

Hope this helps! Happy coding :)

How to get next/previous record in MySQL?

Next row

SELECT * FROM `foo` LIMIT number++ , 1

Previous row

SELECT * FROM `foo` LIMIT number-- , 1

sample next row

SELECT * FROM `foo` LIMIT 1 , 1
SELECT * FROM `foo` LIMIT 2 , 1
SELECT * FROM `foo` LIMIT 3 , 1

sample previous row

SELECT * FROM `foo` LIMIT -1 , 1
SELECT * FROM `foo` LIMIT -2 , 1
SELECT * FROM `foo` LIMIT -3 , 1

SELECT * FROM `foo` LIMIT 3 , 1
SELECT * FROM `foo` LIMIT 2 , 1
SELECT * FROM `foo` LIMIT 1 , 1

How can I get the length of text entered in a textbox using jQuery?

var myLength = $("#myTextbox").val().length;

How to add Python to Windows registry

English

In case that it serves to someone, I leave here the Windows 10 base register for Python 3.4.4 - 64 bit:

Español

Por si alguien lo necesita todavía, este es el registro base de Windows 10 para Python 3.4.4:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4]
"DisplayName"="Python 3.4 (64-bit)"
"SupportUrl"="http://www.python.org/"
"Version"="3.4.4"
"SysVersion"="3.4"
"SysArchitecture"="64bit"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help]

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help\Main Python Documentation]
@="C:\\Python34\\Doc\\python364.chm"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Idle]
@="C:\\Python34\\Lib\\idlelib\\idle.pyw"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\IdleShortcuts]
@=dword:00000001

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstalledFeatures]

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath]
@="C:\\Python34\\"
"ExecutablePath"="C:\\Python34\\python.exe"
"WindowedExecutablePath"="C:\\Python34\\pythonw.exe"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\PythonPath]
@="C:\\Python34\\Lib\\;C:\\Python34\\DLLs\\"

Is it necessary to assign a string to a variable before comparing it to another?

if ([statusString isEqualToString:@"Wrong"]) {
    // do something
}

Maven: How to run a .java file from command line passing arguments

In addition to running it with mvn exec:java, you can also run it with mvn exec:exec

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"

gulp command not found - error after installing gulp

Try to add to your PATH variable the following:

C:\Users\YOUR_USER\AppData\Roaming\npm

I had the same problem and I solved adding the path to my node modules.

How to `wget` a list of URLs in a text file?

If you're on OpenWrt or using some old version of wget which doesn't gives you -i option:

#!/bin/bash
input="text_file.txt"
while IFS= read -r line
do
  wget $line
done < "$input"

Furthermore, if you don't have wget, you can use curl or whatever you use for downloading individual files.

How to set a single, main title above all the subplots with Pyplot?

If your subplots also have titles, you may need to adjust the main title size:

plt.suptitle("Main Title", size=16)

Typescript ReferenceError: exports is not defined

npm install @babel/plugin-transform-modules-commonjs

and add to to .babelrc plugins resolved my question.

'NOT NULL constraint failed' after adding to models.py

You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True and create and run migration.

How to configure Docker port mapping to use Nginx as an upstream proxy?

@gdbj's answer is a great explanation and the most up to date answer. Here's however a simpler approach.

So if you want to redirect all traffic from nginx listening to 80 to another container exposing 8080, minimum configuration can be as little as:

nginx.conf:

server {
    listen 80;

    location / {
        proxy_pass http://client:8080; # this one here
        proxy_redirect off;
    }

}

docker-compose.yml

version: "2"
services:
  entrypoint:
    image: some-image-with-nginx
    ports:
      - "80:80"
    links:
      - client  # will use this one here

  client:
    image: some-image-with-api
    ports:
      - "8080:8080"

Docker docs

How to fire an event on class change using jQuery?

You could replace the original jQuery addClass and removeClass functions with your own that would call the original functions and then trigger a custom event. (Using a self-invoking anonymous function to contain the original function reference)

(function( func ) {
    $.fn.addClass = function() { // replace the existing function on $.fn
        func.apply( this, arguments ); // invoke the original function
        this.trigger('classChanged'); // trigger the custom event
        return this; // retain jQuery chainability
    }
})($.fn.addClass); // pass the original function as an argument

(function( func ) {
    $.fn.removeClass = function() {
        func.apply( this, arguments );
        this.trigger('classChanged');
        return this;
    }
})($.fn.removeClass);

Then the rest of your code would be as simple as you'd expect.

$(selector).on('classChanged', function(){ /*...*/ });

Update:

This approach does make the assumption that the classes will only be changed via the jQuery addClass and removeClass methods. If classes are modified in other ways (such as direct manipulation of the class attribute through the DOM element) use of something like MutationObservers as explained in the accepted answer here would be necessary.

Also as a couple improvements to these methods:

  • Trigger an event for each class being added (classAdded) or removed (classRemoved) with the specific class passed as an argument to the callback function and only triggered if the particular class was actually added (not present previously) or removed (was present previously)
  • Only trigger classChanged if any classes are actually changed

    (function( func ) {
        $.fn.addClass = function(n) { // replace the existing function on $.fn
            this.each(function(i) { // for each element in the collection
                var $this = $(this); // 'this' is DOM element in this context
                var prevClasses = this.getAttribute('class'); // note its original classes
                var classNames = $.isFunction(n) ? n(i, prevClasses) : n.toString(); // retain function-type argument support
                $.each(classNames.split(/\s+/), function(index, className) { // allow for multiple classes being added
                    if( !$this.hasClass(className) ) { // only when the class is not already present
                        func.call( $this, className ); // invoke the original function to add the class
                        $this.trigger('classAdded', className); // trigger a classAdded event
                    }
                });
                prevClasses != this.getAttribute('class') && $this.trigger('classChanged'); // trigger the classChanged event
            });
            return this; // retain jQuery chainability
        }
    })($.fn.addClass); // pass the original function as an argument
    
    (function( func ) {
        $.fn.removeClass = function(n) {
            this.each(function(i) {
                var $this = $(this);
                var prevClasses = this.getAttribute('class');
                var classNames = $.isFunction(n) ? n(i, prevClasses) : n.toString();
                $.each(classNames.split(/\s+/), function(index, className) {
                    if( $this.hasClass(className) ) {
                        func.call( $this, className );
                        $this.trigger('classRemoved', className);
                    }
                });
                prevClasses != this.getAttribute('class') && $this.trigger('classChanged');
            });
            return this;
        }
    })($.fn.removeClass);
    

With these replacement functions you can then handle any class changed via classChanged or specific classes being added or removed by checking the argument to the callback function:

$(document).on('classAdded', '#myElement', function(event, className) {
    if(className == "something") { /* do something */ }
});