Programs & Examples On #Asyncfileupload

Async file upload is the process of asynchronously uploading files from a web page.

How do I upload a file to an SFTP server in C# (.NET)?

Following code shows how to upload a file to a SFTP server using our Rebex SFTP component.

// create client, connect and log in 
Sftp client = new Sftp();
client.Connect(hostname);
client.Login(username, password);

// upload the 'test.zip' file to the current directory at the server 
client.PutFile(@"c:\data\test.zip", "test.zip");

client.Disconnect();

You can write a complete communication log to a file using a LogWriter property as follows. Examples output (from FTP component but the SFTP output is similar) can be found here.

client.LogWriter = new Rebex.FileLogWriter(
   @"c:\temp\log.txt", Rebex.LogLevel.Debug); 

or intercept the communication using events as follows:

Sftp client = new Sftp();
client.CommandSent += new SftpCommandSentEventHandler(client_CommandSent);
client.ResponseRead += new SftpResponseReadEventHandler(client_ResponseRead);
client.Connect("sftp.example.org");

//... 
private void client_CommandSent(object sender, SftpCommandSentEventArgs e)
{
    Console.WriteLine("Command: {0}", e.Command);
}

private void client_ResponseRead(object sender, SftpResponseReadEventArgs e)
{
    Console.WriteLine("Response: {0}", e.Response);
}

For more info see tutorial or download a trial and check samples.

Command output redirect to file and terminal

In case somebody needs to append the output and not overriding, it is possible to use "-a" or "--append" option of "tee" command :

ls 2>&1 | tee -a /tmp/ls.txt
ls 2>&1 | tee --append /tmp/ls.txt

AJAX POST and Plus Sign ( + ) -- How to Encode?

If you have to do a curl in php, you should use urlencode() from PHP but individually!

strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+")

If you do urlencode(strPOST), you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!

Example 1

$strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+") will give Item1=Value1&Item2=%2B

Example 2

$strPOST = urlencode("Item1=" . $Value1 . "&Item2=+") will give Item1%3DValue1%26Item2%3D%2B

Example 1 is the good way to prepare string for POST in curl

Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!

C# list.Orderby descending

var newList = list.OrderBy(x => x.Product.Name).Reverse()

This should do the job.

List Directories and get the name of the Directory

You seem to be using Python as if it were the shell. Whenever I've needed to do something like what you're doing, I've used os.walk()

For example, as explained here: [x[0] for x in os.walk(directory)] should give you all of the subdirectories, recursively.

FIND_IN_SET() vs IN()

attachedCompanyIDs is one big string, so mysql try to find company in this its cast to integer

when you use where in

so if comapnyid = 1 :

companyID IN ('1,2,3')

this is return true

but if the number 1 is not in the first place

 companyID IN ('2,3,1')

its return false

Passing data to a bootstrap modal

I think you can make this work using jQuery's .on event handler.

Here's a fiddle you can test; just make sure to expand the HTML frame in the fiddle as much as possible so you can view the modal.

http://jsfiddle.net/Au9tc/605/

HTML

<p>Link 1</p>
<a data-toggle="modal" data-id="ISBN564541" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>

<p>&nbsp;</p>


<p>Link 2</p>
<a data-toggle="modal" data-id="ISBN-001122" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>

<div class="modal hide" id="addBookDialog">
 <div class="modal-header">
    <button class="close" data-dismiss="modal">×</button>
    <h3>Modal header</h3>
  </div>
    <div class="modal-body">
        <p>some content</p>
        <input type="text" name="bookId" id="bookId" value=""/>
    </div>
</div>

JAVASCRIPT

$(document).on("click", ".open-AddBookDialog", function () {
     var myBookId = $(this).data('id');
     $(".modal-body #bookId").val( myBookId );
     // As pointed out in comments, 
     // it is unnecessary to have to manually call the modal.
     // $('#addBookDialog').modal('show');
});

Windows CMD command for accessing usb?

Try this batch :

@echo off
Title List of connected external devices by Hackoo
Mode con cols=100 lines=20 & Color 9E
wmic LOGICALDISK where driveType=2 get deviceID > wmic.txt
for /f "skip=1" %%b IN ('type wmic.txt') DO (echo %%b & pause & Dir %%b)
Del wmic.txt
pause

How to add checkboxes to JTABLE swing

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

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

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

table_with_BooleanType_column

could be generated from simple code:

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

public class TableCheckBox extends JFrame {

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

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

            private static final long serialVersionUID = 1L;

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

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

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

Store multiple values in single key in json

{
  "number" : ["1","2","3"],
  "alphabet" : ["a", "b", "c"]
}

PHP date add 5 year to current date

Using Carbon:

$dt = Carbon::now();
echo $dt->addYears(5); 

updating Google play services in Emulator

I know it's late answer but I had same problem for last two days, and none of the above solutions worked for me. My app supports min sdk 16, Jelly Bean 4.1.x, so I wanted to test my app on emulator with 16 android api version and I needed Google Play Services.

In short, solution that worked for me is:

  • make new emulator Nexus 5X (with Play Store support) - Jelly Bean 4.1.x, 16 API level (WITHOUT Google APIs)
  • manually download apks of Google Play Store and Google Play Services (it is necessary that both apks have similar version, they need to start with same number, for example 17.x)
  • drag and drop those apks into new emulator
  • congratulations you have updated Google Play Services on your 4.1.x emulator

Here are the steps and errors I have encountered during the problem.

So I have made new emulator in my AVD. I picked Nexus 5X (with Play Store support). After that I picked Jelly Bean 16 api level (with Google APIs). When I opened my app dialog pop up with message You need to update your Google play services. When I clicked on Update button, nothing happened. I did update everything necessary in SDK manager, but nothing worked. I didn't have installed Google Play Store on my emulator, even tho I picked Nexus 5X which comes with preinstalled Play Store. So I couldn't find Google Play Store tab in Extended Controls (tree dots next to my emulator).

Because nothings worked, I decided to try to install Google Play Services manually, by downloading APK and dragging it into emulator. When I tried this, I encountered problem The APK failed to install. Error: INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES. I figured that this was the problem because I picked Jelly Bean 16 api level (with Google APIs). So I made new emulator

Nexus 5X (with Play Store support) - Jelly Bean 16 api level (WITHOUT Google APIs)

This allowed me to install my Google Play Service manually. But when I run my app, it still didn't want to open it. Problem was that my emulator was missing Google Play Store. So I installed it manually like Google Play Service. But when it was successfully installed, dialog started popping out every second with message Unfortunately Google Play Services has stopped. Problem was that version of my Google Play Store was 17.x and Google Play Service was 19.x. So at the end I installed Google Play Service with version 17.x, and everything worked.

How to get current date & time in MySQL?

You can use NOW():

INSERT INTO servers (server_name, online_status, exchange, disk_space, network_shares, c_time)
VALUES('m1', 'ONLINE', 'exchange', 'disk_space', 'network_shares', NOW())

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

How to trigger a phone call when clicking a link in a web page on mobile phone

Want to add an answer here for the sake of completeness.

<a href="tel:1234567">Call 123-4567</a>

Works just fine on most devices. However, on desktops this will appear as a link which does nothing when you click on it so you should consider using CSS to make it conditionally visible only on mobile devices.

Also, you should know that Skype (which is fairly popular) uses a different syntax by default (but can be parametered to use tel:).

<a href="callto:1234567">Call 123-4567</a>

However, I think in latest mobile browsers (I know for sure on Android) now the tel syntax should offer a popup of available applications that can be used to complete the calling action.

How to change ViewPager's page?

Supplemental answer

I was originally having trouble getting a reference to the ViewPager from other class methods because the addOnTabSelectedListener made an anonymous inner class, which in turn required the ViewPager variable to be declared final. The solution was to use a class member variable and not use the anonymous inner class.

public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        // don't use an anonymous inner class here
        tabLayout.addOnTabSelectedListener(tabListener);

    }

    TabLayout.OnTabSelectedListener tabListener = new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };

    // The view pager can now be accessed here, too.
    public void someMethod() {
        viewPager.setCurrentItem(0);
    }

}

How to read file with async/await properly?

To use await/async you need methods that return promises. The core API functions don't do that without wrappers like promisify:

const fs = require('fs');
const util = require('util');

// Convert fs.readFile into Promise version of same    
const readFile = util.promisify(fs.readFile);

function getStuff() {
  return readFile('test');
}

// Can't use `await` outside of an async function so you need to chain
// with then()
getStuff().then(data => {
  console.log(data);
})

As a note, readFileSync does not take a callback, it returns the data or throws an exception. You're not getting the value you want because that function you supply is ignored and you're not capturing the actual return value.

Extract substring from a string

When finding multiple occurrences of a substring matching a pattern

    String input_string = "foo/adsfasdf/adf/bar/erqwer/";
    String regex = "(foo/|bar/)"; // Matches 'foo/' and 'bar/'

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input_string);

    while(matcher.find()) {
      String str_matched = input_string.substring(matcher.start(), matcher.end());
        // Do something with a match found
    }

How to scroll UITableView to specific position

Use [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES]; Scrolls the receiver until a row identified by index path is at a particular location on the screen.

And

scrollToNearestSelectedRowAtScrollPosition:animated:

Scrolls the table view so that the selected row nearest to a specified position in the table view is at that position.

Find (and kill) process locking port 3000 on Mac

Add to ~/.bash_profile:

function killTcpListen () {
  kill -QUIT $(sudo lsof -sTCP:LISTEN -i tcp:$1 -t)
}

Then source ~/.bash_profile and run

killTcpListen 8080

How to install python developer package?

If you use yum search you can find the python dev package for your version of python.

For me I was using python 3.5. I ran the following

yum search python | grep devel

Which returned the following

enter image description here

I was then able to install the correct package for my version of python with the following cmd.

sudo yum install python35u-devel.x86_64

This works on centos for ubuntu or debian you would need to use apt-get

Using android.support.v7.widget.CardView in my project (Eclipse)

You need to add this in your build.gradle:

dependencies {
    ...
    compile 'com.android.support:cardview-v7:+'
}

And then Sync Project with Gradle Files. Finally, you can use CardView as it's described here.

Python Dictionary contains List as Value - How to update?

Probably something like this:

original_list = dictionary.get('C1')
new_list = []
for item in original_list:
  new_list.append(item+10)
dictionary['C1'] = new_list

How do I revert a Git repository to a previous commit?

I believe some people may come to this question wanting to know how to rollback committed changes they've made in their master - ie throw everything away and go back to origin/master, in which case, do this:

git reset --hard origin/master

https://superuser.com/questions/273172/how-to-reset-master-to-origin-master

JQuery show/hide when hover

I hope my script help you.

<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>

My script

<script>
$(".mostrar-producto").mouseover(function(){
     $(".producto").fadeIn();
 });

 $(".mostrar-producto").mouseleave(function(){
      $(".producto").fadeOut();
  });
</script>

Python: Converting from ISO-8859-1/latin1 to UTF-8

concept = concept.encode('ascii', 'ignore') 
concept = MySQLdb.escape_string(concept.decode('latin1').encode('utf8').rstrip())

I do this, I am not sure if that is a good approach but it works everytime !!

How do I make the return type of a method generic?

 private static T[] prepareArray<T>(T[] arrayToCopy, T value)
    {
        Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
        arrayToCopy[arrayToCopy.Length - 1] = value;
        return (T[])arrayToCopy;
    }

I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

Login to remote site with PHP cURL

I had same question and I found this answer on this website.

And I changed it just a little bit (the curl_close at last line)

$username = 'myuser';
$password = 'mypass';
$loginUrl = 'http://www.example.com/login/';

//init curl
$ch = curl_init();

//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);

// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);

//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&pass='.$password);

//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//execute the request (the login)
$store = curl_exec($ch);

//the login is now done and you can continue to get the
//protected content.

//set the URL to the protected file
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/protected/download.zip');

//execute the request
$content = curl_exec($ch);

curl_close($ch);

//save the data to disk
file_put_contents('~/download.zip', $content);

I think this was what you were looking for.Am I right?


And one useful related question. About how to keep a session alive in cUrl: https://stackoverflow.com/a/13020494/2226796

How to Migrate to WKWebView?

You have to use WKWebView, which is available as of iOS8 in Framework 'WebKit' to get the speedup. If you need backwards compatibility, you have to use UIWebView for iOS7 and older.

I set up a little code to provide the UIViewController frame for the new WKWebView. It can be installed via cocoapods. Have a look here:

STKWebKitViewController on github

How to test for $null array in PowerShell

If your solution requires returning 0 instead of true/false, I've found this to be useful:

PS C:\> [array]$foo = $null
PS C:\> ($foo | Measure-Object).Count
0

This operation is different from the count property of the array, because Measure-Object is counting objects. Since there are none, it will return 0.

Should composer.lock be committed to version control?

After doing it both ways for a few projects my stance is that composer.lock should not be committed as part of the project.

composer.lock is build metadata which is not part of the project. The state of dependencies should be controlled through how you're versioning them (either manually or as part of your automated build process) and not arbitrarily by the last developer to update them and commit the lock file.

If you are concerned about your dependencies changing between composer updates then you have a lack of confidence in your versioning scheme. Versions (1.0, 1.1, 1.2, etc) should be immutable and you should avoid "dev-" and "X.*" wildcards outside of initial feature development.

Committing the lock file is a regression for your dependency management system as the dependency version has now gone back to being implicitly defined.

Also, your project should never have to be rebuilt or have its dependencies reacquired in each environment, especially prod. Your deliverable (tar, zip, phar, a directory, etc) should be immutable and promoted through environments without changing.

Java - Getting Data from MySQL database

  • First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].

  • Add the Jar file to your workspace [build path].

  • Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.

  • Define the database name, userName, and Password for your connection.

  • Use the resultSet to get the data based one the column name from your database table.

Sample code is here:

public class JdbcMySQLExample{

public static void main(String[] args) {

    String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
    String user = "root";
    String password = "root";
    
    String query = "SELECT * from YOUR_TABLE_NAME";

    try (Connection con = DriverManager.getConnection(url, user, password);
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(query)) {

        if (rs.next()) {
            
            System.out.println(rs.getString(1));
        }

    } catch (SQLException ex) {
          System.out.println(ex);
       
    } 
}

Round to at most 2 decimal places (only if necessary)

Using Brian Ustas's solution:

function roundDecimal(value, precision) {
    var multiplier = Math.pow(10, precision);
    return Math.round(value * multiplier) / multiplier;
}

Get list of Excel files in a folder using VBA

Ok well this might work for you, a function that takes a path and returns an array of file names in the folder. You could use an if statement to get just the excel files when looping through the array.

Function listfiles(ByVal sPath As String)

    Dim vaArray     As Variant
    Dim i           As Integer
    Dim oFile       As Object
    Dim oFSO        As Object
    Dim oFolder     As Object
    Dim oFiles      As Object

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(sPath)
    Set oFiles = oFolder.Files

    If oFiles.Count = 0 Then Exit Function

    ReDim vaArray(1 To oFiles.Count)
    i = 1
    For Each oFile In oFiles
        vaArray(i) = oFile.Name
        i = i + 1
    Next

    listfiles = vaArray

End Function

It would be nice if we could just access the files in the files object by index number but that seems to be broken in VBA for whatever reason (bug?).

Which TensorFlow and CUDA version combinations are compatible?

I had installed CUDA 10.1 and CUDNN 7.6 by mistake. You can use following configurations (This worked for me - as of 9/10). :

  • Tensorflow-gpu == 1.14.0
  • CUDA 10.1
  • CUDNN 7.6
  • Ubuntu 18.04

But I had to create symlinks for it to work as tensorflow originally works with CUDA 10.

sudo ln -s /opt/cuda/targets/x86_64-linux/lib/libcublas.so /opt/cuda/targets/x86_64-linux/lib/libcublas.so.10.0
sudo cp /usr/lib/x86_64-linux-gnu/libcublas.so.10 /usr/local/cuda-10.1/lib64/
sudo ln -s /usr/local/cuda-10.1/lib64/libcublas.so.10 /usr/local/cuda-10.1/lib64/libcublas.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcusolver.so.10 /usr/local/cuda/lib64/libcusolver.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcurand.so.10 /usr/local/cuda/lib64/libcurand.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcufft.so.10 /usr/local/cuda/lib64/libcufft.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcudart.so /usr/local/cuda/lib64/libcudart.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcusparse.so.10 /usr/local/cuda/lib64/libcusparse.so.10.0

And add the following to my ~/.bashrc -

export PATH=/usr/local/cuda/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
export PATH=/usr/local/cuda-10.1/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.1/lib64:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/cuda/targets/x86_64-linux/lib/

Golang append an item to a slice

In order to make your code work without having to return the slice from Test, you can pass a pointer like this:

package main

import (
    "fmt"
)

var a = make([]int, 7, 8)

func Test(slice *[]int) {
    *slice = append(*slice, 100)

    fmt.Println(*slice)
}

func main() {

    for i := 0; i < 7; i++ {
        a[i] = i
    }

    Test(&a)

    fmt.Println(a)
}

Need to find a max of three numbers in java

It would help if you provided the error you are seeing. Look at http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html and you will see that max only returns the max between two numbers, so likely you code is not even compiling.

Solve all your compilation errors first.

Then your homework will consist of finding the max of three numbers by comparing the first two together, and comparing that max result with the third value. You should have enough to find your answer now.

How to get a list of programs running with nohup

You can also just use the top command and your user ID will indicate the jobs running and the their times.

$ top

(this will show all running jobs)

$ top -U [user ID]

(This will show jobs that are specific for the user ID)

Check if PHP session has already started

The only thing you need to do is:

<?php
if(!isset($_SESSION))
{
session_start();
}
?>

Get value from input (AngularJS)

If your markup is bound to a controller, directive or anything else with a $scope:

console.log($scope.movie);

How can I install Apache Ant on Mac OS X?

For MacOS Maveriks (10.9 and perhaps later versions too), Apache Ant does not come bundled with the operating system and so must be installed manually. You can use brew to easily install ant. Simply execute the following command in a terminal window to install brew:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

It's a medium sized download which took me 10min to download and install. Just follow the process which involves installing various components. If you already have brew installed, make sure it's up to date by executing:

brew update

Once installed you can simply type:

brew install ant

Ant is now installed and available through the "ant" command in the terminal.

To test the installation, just type "ant -version" into a terminal window. You should get the following output:

Apache Ant(TM) version X.X.X compiled on MONTH DAY YEAR

Source: Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

If you are getting errors installing Brew, try uninstalling first using the command:

rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup

Thanks to OrangeDog and other users for providing additional information.

prevent iphone default keyboard when focusing an <input>

inputmode attribute

<input inputmode='none'>

The inputmode global attribute is an enumerated attribute that hints at the type of data that might be entered by the user while editing the element or its contents. It can have the following values:

none - No virtual keyboard. For when the page implements its own keyboard input control.


I am using this successfully (Tested on Chrome/Android)

CSS-Tricks: Everything You Ever Wanted to Know About inputmode

Remove Trailing Spaces and Update in Columns in SQL Server

If you are using SQL Server (starting with vNext) or Azure SQL Database then you can use the below query.

SELECT TRIM(ColumnName) from TableName;

For other SQL SERVER Database you can use the below query.

SELECT LTRIM(RTRIM(ColumnName)) from TableName

LTRIM - Removes spaces from the left

example: select LTRIM(' test ') as trim = 'test '

RTRIM - Removes spaces from the right

example: select RTRIM(' test ') as trim = ' test'

Linq to Sql: Multiple left outer joins

Don't have access to VisualStudio (I'm on my Mac), but using the information from http://bhaidar.net/cs/archive/2007/08/01/left-outer-join-in-linq-to-sql.aspx it looks like you may be able to do something like this:

var query = from o in dc.Orders
            join v in dc.Vendors on o.VendorId equals v.Id into ov
            from x in ov.DefaultIfEmpty()
            join s in dc.Status on o.StatusId equals s.Id into os
            from y in os.DefaultIfEmpty()
            select new { o.OrderNumber, x.VendorName, y.StatusName }

How do I import CSV file into a MySQL table?

I see something strange. You are using for ESCAPING the same character you use for ENCLOSING. So the engine does not know what to do when it founds a '"' and I think that is why nothing seems to be in the right place. I think that if you remove the line of ESCAPING, should run great. Like:

LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

Unless you analyze (manually, visually, ... ) your CSV and find which character uses for escape. Sometimes is '\'. But if you do not have it, do not use it.

Find out if string ends with another string in C++

My two cents:

bool endsWith(std::string str, std::string suffix)
{
   return str.find(suffix, str.size() - suffix.size()) != string::npos;
}

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

I created a working demo of a landscape/portrait layout but the zoom must be disabled for it to work without JavaScript:

http://matthewjamestaylor.com/blog/ipad-layout-with-landscape-portrait-modes

How do you add swap to an EC2 instance?

You can add a 1 GB swap to your instance with these commands:

sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
sudo mkswap /swapfile
sudo swapon /swapfile

To enable it by default after reboot, add this line to /etc/fstab:

/swapfile swap swap defaults 0 0

How do I run a Python program in the Command Prompt in Windows 7?

Python comes with a script that takes care of setting up the windows path file for you.

After installation, open command prompt

cmd

Go to the directory you installed Python in

cd C:\Python27

Run python and the win_add2path.py script in Tools\Scripts

python.exe Tools\Scripts\win_add2path.py

Now you can use python as a command anywhere.

Select datatype of the field in postgres

run psql -E and then \d student_details

Searching for file in directories recursively

For file and directory search purpose I would want to offer use specialized multithreading .NET library that possess a wide search opportunities and works very fast.

All information about library you can find on GitHub: https://github.com/VladPVS/FastSearchLibrary

If you want to download it you can do it here: https://github.com/VladPVS/FastSearchLibrary/releases

If you have any questions please ask them.

It is one demonstrative example how you can use it:

class Searcher
{
    private static object locker = new object(); 

    private FileSearcher searcher;

    List<FileInfo> files;

    public Searcher()
    {
        files = new List<FileInfo>(); // create list that will contain search result
    }

    public void Startsearch()
    {
        CancellationTokenSource tokenSource = new CancellationTokenSource();
        // create tokenSource to get stop search process possibility

        searcher = new FileSearcher(@"C:\", (f) =>
        {
            return Regex.IsMatch(f.Name, @".*[Dd]ragon.*.jpg$");
        }, tokenSource);  // give tokenSource in constructor


        searcher.FilesFound += (sender, arg) => // subscribe on FilesFound event
        {
            lock (locker) // using a lock is obligatorily
            {
                arg.Files.ForEach((f) =>
                {
                    files.Add(f); // add the next received file to the search results list
                    Console.WriteLine($"File location: {f.FullName}, \nCreation.Time: {f.CreationTime}");
                });

                if (files.Count >= 10) // one can choose any stopping condition
                    searcher.StopSearch();
            }
        };

        searcher.SearchCompleted += (sender, arg) => // subscribe on SearchCompleted event
        {
            if (arg.IsCanceled) // check whether StopSearch() called
                Console.WriteLine("Search stopped.");
            else
                Console.WriteLine("Search completed.");

            Console.WriteLine($"Quantity of files: {files.Count}"); // show amount of finding files
        };

        searcher.StartSearchAsync();
        // start search process as an asynchronous operation that doesn't block the called thread
    }
}

How to send an email with Gmail as provider using Python?

I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:

https://support.google.com/accounts/answer/6010255

In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:

https://www.google.com/settings/security/lesssecureapps

Once that is set (see my screenshot below), it should work.

enter image description here

Login now works:

smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('[email protected]', 'me_pass')

Response after change:

(235, '2.7.0 Accepted')

Response prior:

smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')

Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

https://accounts.google.com/DisplayUnlockCaptcha

Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

UPDATE: This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:

235 == 'Authentication successful'
503 == 'Error: already authenticated'

The message says to use the browser to sign in:

SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')

After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.

How can I convert a cv::Mat to a gray scale in OpenCv?

May be helpful for late comers.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

using namespace cv;
using namespace std;

int main(int argc, char *argv[])
{
  if (argc != 2) {
    cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
    return -1;
}else{
    Mat image;
    Mat grayImage;

    image = imread(argv[1], IMREAD_COLOR);
    if (!image.data) {
        cout << "Could not open the image file" << endl;
        return -1;
    }
    else {
        int height = image.rows;
        int width = image.cols;

        cvtColor(image, grayImage, CV_BGR2GRAY);


        namedWindow("Display window", WINDOW_AUTOSIZE);
        imshow("Display window", image);

        namedWindow("Gray Image", WINDOW_AUTOSIZE);
        imshow("Gray Image", grayImage);
        cvWaitKey(0);
        image.release();
        grayImage.release();
        return 0;
    }

  }

}

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

String.IsNullOrEmpty(string value) returns true if the string is null or empty. For reference an empty string is represented by "" (two double quote characters)

String.IsNullOrWhitespace(string value) returns true if the string is null, empty, or contains only whitespace characters such as a space or tab.

To see what characters count as whitespace consult this link: http://msdn.microsoft.com/en-us/library/t809ektx.aspx

If my interface must return Task what is the best way to have a no-operation implementation?

To add to Reed Copsey's answer about using Task.FromResult, you can improve performance even more if you cache the already completed task since all instances of completed tasks are the same:

public static class TaskExtensions
{
    public static readonly Task CompletedTask = Task.FromResult(false);
}

With TaskExtensions.CompletedTask you can use the same instance throughout the entire app domain.


The latest version of the .Net Framework (v4.6) adds just that with the Task.CompletedTask static property

Task completedTask = Task.CompletedTask;

What, why or when it is better to choose cshtml vs aspx?

Razor is a view engine for ASP.NET MVC, and also a template engine. Razor code and ASP.NET inline code (code mixed with markup) both get compiled first and get turned into a temporary assembly before being executed. Thus, just like C# and VB.NET both compile to IL which makes them interchangable, Razor and Inline code are both interchangable.

Therefore, it's more a matter of style and interest. I'm more comfortable with razor, rather than ASP.NET inline code, that is, I prefer Razor (cshtml) pages to .aspx pages.

Imagine that you want to get a Human class, and render it. In cshtml files you write:

<div>Name is @Model.Name</div>

While in aspx files you write:

<div>Name is <%= Human.Name %></div>

As you can see, @ sign of razor makes mixing code and markup much easier.

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

I had this same issue and wondered why it didn't happen with a bitbucket repo that was cloned with https. Looking into it a bit I found that the config for the BB repo had a URL that included my username. So I manually edited the config for my GH repo like so and voila, no more username prompt. I'm on Windows.

Edit your_repo_dir/.git/config (remember: .git folder is hidden)

Change:

https://github.com/WEMP/project-slideshow.git

to:

https://*username*@github.com/WEMP/project-slideshow.git

Save the file. Do a git pull to test it.

The proper way to do this is probably by using git bash commands to edit the setting, but editing the file directly didn't seem to be a problem.

Check if value is zero or not null in python

Zero and None both treated as same for if block, below code should work fine.

if number or number==0:
    return True

Mongoose's find method with $or condition does not work properly

async() => {
let body = await model.find().or([
  { name: 'something'},
  { nickname: 'somethang'}
]).exec();
console.log(body);
}
/* Gives an array of the searched query!
returns [] if not found */

hexadecimal string to byte array in python

You can use the Codecs module in the Python Standard Library, i.e.

import codecs

codecs.decode(hexstring, 'hex_codec')

Python: finding lowest integer

To find the minimum value of a list, you might just as well use min:

x = min(float(s) for s in l) # min of a generator

Or, if you want the result as a string, rather than a float, use a key function:

x = min(l, key=float)

Select elements by attribute in CSS

It's worth noting CSS3 substring attribute selectors

[attribute^=value] { /* starts with selector */
/* Styles */
}

[attribute$=value] { /* ends with selector */
/* Styles */
}

[attribute*=value] { /* contains selector */
/* Styles */
}

Click toggle with jQuery

You could use the toggle function:

$('.offer').toggle(function() {
    $(this).find(':checkbox').attr('checked', true);
}, function() {
    $(this).find(':checkbox').attr('checked', false);
});

How to format html table with inline styles to look like a rendered Excel table?

This is quick-and-dirty (and not formally valid HTML5), but it seems to work -- and it is inline as per the question:

<table border='1' style='border-collapse:collapse'>

No further styling of <tr>/<td> tags is required (for a basic table grid).

Java: notify() vs. notifyAll() all over again

Taken from blog on Effective Java:

The notifyAll method should generally be used in preference to notify. 

If notify is used, great care must be taken to ensure liveness.

So, what i understand is (from aforementioned blog, comment by "Yann TM" on accepted answer and Java docs):

  • notify() : JVM awakens one of the waiting threads on this object. Thread selection is made arbitrarily without fairness. So same thread can be awakened again and again. So system's state changes but no real progress is made. Thus creating a livelock.
  • notifyAll() : JVM awakens all threads and then all threads race for the lock on this object. Now, CPU scheduler selects a thread which acquires lock on this object. This selection process would be much better than selection by JVM. Thus, ensuring liveness.

No Android SDK found - Android Studio

I am on Mac Os. In my case, my host file was black. I added following entries (these entries should be there by default, but they weren't).

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255     broadcasthost
::1                          localhost

After re-running android studio, it prompted the sdk download.

What is the purpose of backbone.js?

If you're going to build complex user interfaces in the browser then you will probably find yourself eventually inventing most of the pieces that make up frameworks like Backbone.js and Sammy.js. So the question is, are you building something complicated enough in the browser to merit using it (so you don't end up inventing the same thing yourself).

If what you plan to build is something where the UI regularly changes how it displays but does not go to the server to get entire new pages then you probably need something like Backbone.js or Sammy.js. The cardinal example of something like that is Google's GMail. If you've ever used it you'll notice that it downloads one big chunk of HTML, CSS, and JavaScript when you first log in and then after that everything happens in the background. It can move between reading an email and processing the inbox and searching and back through all of them again without ever asking for a whole new page to be rendered.

It's that kind of app that these frameworks excel at making easier to develop. Without them you'll either end up glomming together a diverse set of individual libraries to get parts of the functionality (for example, jQuery BBQ for history management, Events.js for events, etc.) or you'll end up building everything yourself and having to maintain and test everything yourself as well. Contrast that with something like Backbone.js that has thousands of people watching it on Github, hundreds of forks where people may be working on it, and hundreds of questions already asked and answered here on Stack Overflow.

But none of it is of any importance if what you plan to build is not complicated enough to be worth the learning curve associated with a framework. If you're still building PHP, Java, or something else sites where the back end server is still doing all the heavy lifting of building the web pages upon request by the user and JavaScript/jQuery is just icing upon that process, you aren't going to need or are not yet ready for Backbone.js.

Is SQL syntax case sensitive?

I don't think SQL Server is case-sensitive, at least not by default.

When I'm querying manually via Management Studio, I mess up case all the time and it cheerfully accepts it:

select cOL1, col2 FrOM taBLeName WheRE ...

Trying to get property of non-object - Laravel 5

Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

I have found another reason: different versions used for icons in toolbox and references in the project. After inserting the objects in some form, the error started.

Can constructors throw exceptions in Java?

Yes, it can throw an exception and you can declare that in the signature of the constructor too as shown in the example below:

public class ConstructorTest
{
    public ConstructorTest() throws InterruptedException
    {
        System.out.println("Preparing object....");
        Thread.sleep(1000);
        System.out.println("Object ready");
    }

    public static void main(String ... args)
    {
        try
        {
            ConstructorTest test = new ConstructorTest();
        }
        catch (InterruptedException e)
        {
            System.out.println("Got interrupted...");
        }
    }
}

PHP class: Global variable as property in class

If you want to access a property from inside a class you should:

private $classNumber = 8;

Java 8: merge lists with stream API

Already answered above, but here's another approach you could take. I can't find the original post I adapted this from, but here's the code for the sake of your question. As noted above, the flatMap() function is what you'd be looking to utilize with Java 8. You can throw it in a utility class and just call "RandomUtils.combine(list1, list2, ...);" and you'd get a single List with all values. Just be careful with the wildcard - you could change this if you want a less generic method. You can also modify it for Sets - you just have to take care when using flatMap() on Sets to avoid data loss from equals/hashCode methods due to the nature of the Set interface.

Edit - If you use a generic method like this for the Set interface, and you happen to use Lombok, make sure you understand how Lombok handles equals/hashCode generation.

  /**
    * Combines multiple lists into a single list containing all elements of
    * every list.
    * 
    * @param <T> - The type of the lists.
    * @param lists - The group of List implementations to combine
    * @return a single List<?> containing all elements of the passed in lists.
    */
   public static <T> List<?> combine(final List<?>... lists) {
      return Stream.of(lists).flatMap(List::stream).collect(Collectors.toList());
   }

Convert Pixels to Points

Starting with the given:

  • There are 72 points in an inch (that is what a point is, 1/72 of an inch)
  • on a system set for 150dpi, there are 150 pixels per inch.
  • 1 in = 72pt = 150px (for 150dpi setting)

If you want to find points (pt) based on pixels (px):

 72 pt    x pt
------ = -----                  (1) for 150dpi system
150 px    y px

Rearranging:

x = (y/150) * 72                (2) for 150dpi system

so:

points = (pixels / 150) * 72    (3) for 150dpi system

Set div height to fit to the browser using CSS

I do not think you need float.

_x000D_
_x000D_
html,_x000D_
body,_x000D_
.container {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.div1, .div2 {_x000D_
  display: inline-block;_x000D_
  margin: 0;_x000D_
  min-height: 100%;_x000D_
}_x000D_
_x000D_
.div1 {_x000D_
  width: 25%;_x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
.div2 {_x000D_
  width: 75%;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="div1"></div><!--_x000D_
  --><div class="div2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

display: inline-block; is used to display blocks as inline (just like spans but keeping the block effect)

Comments in the html is used because you have 75% + 25% = 100%. The space in-between the divs counts (so you have 75% + 1%? + 25% = 101%, meaning line break)

docker-compose up for only certain containers

To start a particular service defined in your docker-compose file. for example if your have a docker-compose.yml

docker-compose start db  

given a compose file like as:

version: '3.3'

services:
   db:
     image: mysql:5.7
     ports:
       - "3306:3306"
     volumes:
       - ./db_data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: yourPassword
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: yourPassword

   wordpress:
     depends_on:
       - db
     image: wordpress:latest
     ports:
       - "80:80"
     volumes:
       - ./l3html:/var/www/html
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: yourPassword
volumes:
    db_data:
    l3html:

Some times you want to start mySQL only (sometimes you just want to populate a database) before you start your entire suite.

Read Variable from Web.Config

Assuming the key is contained inside the <appSettings> node:

ConfigurationSettings.AppSettings["theKey"];

As for "writing" - put simply, dont.

The web.config is not designed for that, if you're going to be changing a value constantly, put it in a static helper class.

Angular 2 'component' is not a known element

This question may seem old and odd, but when I was trying to load a module(lazy loading) and getting the same error, I realized I was missing an exports clause for the component that shipped as a part of a larger module.

This Angular.io Link explains why: Components/Services inside a module, remains private(or protected) by default. To make them public, you have to export them.

Expanding on @Robin Djikof's answer with @live-love code sample, this is what was technically missing in my case(Angular 8):

@NgModule({
  declarations: [
    SomeOtherComponent,
    ProductListComponent
  ],
  imports: [
    DependantModule
  ],
  exports: [ProductListComponent] 
  //<- This line makes ProductListComponent available outside the module, 
  //while keeping SomeOtherComponent private to the module
})
export class SomeLargeModule { }

How to draw a graph in PHP?

<?
# ------- The graph values in the form of associative array
$values=array(
    "Jan" => 110,
    "Feb" => 130,
    "Mar" => 215,
    "Apr" => 81,
    "May" => 310,
    "Jun" => 110,
    "Jul" => 190,
    "Aug" => 175,
    "Sep" => 390,
    "Oct" => 286,
    "Nov" => 150,
    "Dec" => 196
);


$img_width=450;
$img_height=300; 
$margins=20;


# ---- Find the size of graph by substracting the size of borders
$graph_width=$img_width - $margins * 2;
$graph_height=$img_height - $margins * 2; 
$img=imagecreate($img_width,$img_height);


$bar_width=20;
$total_bars=count($values);
$gap= ($graph_width- $total_bars * $bar_width ) / ($total_bars +1);


# -------  Define Colors ----------------
$bar_color=imagecolorallocate($img,0,64,128);
$background_color=imagecolorallocate($img,240,240,255);
$border_color=imagecolorallocate($img,200,200,200);
$line_color=imagecolorallocate($img,220,220,220);

# ------ Create the border around the graph ------

imagefilledrectangle($img,1,1,$img_width-2,$img_height-2,$border_color);
imagefilledrectangle($img,$margins,$margins,$img_width-1-$margins,$img_height-1-$margins,$background_color);


# ------- Max value is required to adjust the scale -------
$max_value=max($values);
$ratio= $graph_height/$max_value;


# -------- Create scale and draw horizontal lines  --------
$horizontal_lines=20;
$horizontal_gap=$graph_height/$horizontal_lines;

for($i=1;$i<=$horizontal_lines;$i++){
    $y=$img_height - $margins - $horizontal_gap * $i ;
    imageline($img,$margins,$y,$img_width-$margins,$y,$line_color);
    $v=intval($horizontal_gap * $i /$ratio);
    imagestring($img,0,5,$y-5,$v,$bar_color);

}


# ----------- Draw the bars here ------
for($i=0;$i< $total_bars; $i++){ 
    # ------ Extract key and value pair from the current pointer position
    list($key,$value)=each($values); 
    $x1= $margins + $gap + $i * ($gap+$bar_width) ;
    $x2= $x1 + $bar_width; 
    $y1=$margins +$graph_height- intval($value * $ratio) ;
    $y2=$img_height-$margins;
    imagestring($img,0,$x1+3,$y1-10,$value,$bar_color);imagestring($img,0,$x1+3,$img_height-15,$key,$bar_color);        
    imagefilledrectangle($img,$x1,$y1,$x2,$y2,$bar_color);
}
header("Content-type:image/png");
imagepng($img);
$_REQUEST['asdfad']=234234;

?>

Check an integer value is Null in c#

There is already a correct answer from Adam, but you have another option to refactor your code:

if (Age.GetValueOrDefault() == 0)
{
    // it's null or 0
}

PHP Echo a large block of text

To expand on @hookedonwinter's answer, here's an alternate (cleaner, in my opinion) syntax:

<?php if (is_single()): ?>
    <p>This will be shown if "is_single()" is true.</p>
<?php else: ?>
    <p>This will be shown otherwise.</p>
<?php endif; ?>

Keylistener in Javascript

Here's an update for modern browsers in 2019

_x000D_
_x000D_
let playerSpriteX = 0;_x000D_
_x000D_
document.addEventListener('keyup', (e) => {_x000D_
  if (e.code === "ArrowUp")        playerSpriteX += 10_x000D_
  else if (e.code === "ArrowDown") playerSpriteX -= 10_x000D_
_x000D_
  document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;_x000D_
});
_x000D_
Click on this window to focus it, and hit keys up and down_x000D_
<br><br><br>_x000D_
<div id="test">playerSpriteX = 0</div>
_x000D_
_x000D_
_x000D_


Original answer from 2013

window.onkeyup = function(e) {
   var key = e.keyCode ? e.keyCode : e.which;

   if (key == 38) {
       playerSpriteX += 10;
   }else if (key == 40) {
       playerSpriteX -= 10;
   }
}

FIDDLE

Mathematical functions in Swift

You can use them right inline:

var square = 9.4
var floored = floor(square)
var root = sqrt(floored)

println("Starting with \(square), we rounded down to \(floored), then took the square root to end up with \(root)")

Convert JSON to Map

This way its works like a Map...

JSONObject fieldsJson = new JSONObject(json);
String value = fieldsJson.getString(key);

<dependency>
    <groupId>org.codehaus.jettison</groupId>
    <artifactId>jettison</artifactId>
    <version>1.1</version>
</dependency>

Sort Dictionary by keys

Swift 5

Input your dictionary that you want to sort alphabetically by keys.

// Sort inputted dictionary with keys alphabetically.
func sortWithKeys(_ dict: [String: Any]) -> [String: Any] {
    let sorted = dict.sorted(by: { $0.key < $1.key })
    var newDict: [String: Any] = [:]
    for sortedDict in sorted {
        newDict[sortedDict.key] = sortedDict.value
    }
    return newDict
}

dict.sorted(by: { $0.key < $1.key }) by it self returns a tuple (value, value) instead of a dictionary [value: value]. Thus, the for loop parses the tuple to return as a dictionary. That way, you put in a dictionary & get a dictionary back.

How do I select child elements of any depth using XPath?

If you are using the XmlDocument and XmlNode.

Say:

XmlNode f = root.SelectSingleNode("//form[@id='myform']");

Use:

XmlNode s = f.SelectSingleNode(".//input[@type='submit']");

It depends on the tool that you use. But .// will select any child, any depth from a reference node.

How can I easily switch between PHP versions on Mac OSX?

I found this very good tutorial on how to install and switch php versions on OSX.

I can switch the version like

$ sphp 7.0 => PHP 7.0
$ sphp 7.3 => PHP 7.3
$ sphp 7.4 => PHP 7.4

Exactly what I want!

How to view unallocated free space on a hard disk through terminal

The filesystem size can be different from the patition size. To repair you need to do this

df -h

see what is the name of the partition say /dev/sda3

resize2fs /dev/sda3

how to check the version of jar file?

Just to expand on the answers above, inside the META-INF/MANIFEST.MF file in the JAR, you will likely see a line: Manifest-Version: 1.0 ? This is NOT the jar versions number!

You need to look for Implementation-Version which, if present, is a free-text string so entirely up to the JAR's author as to what you'll find in there. See also Oracle docs and Package Version specificaion

Reload content in modal (twitter bootstrap)

It will works for all version of twitterbootstrap

Javascript code :

<script type="text/javascript">
/* <![CDATA[ */
(function(){
   var bsModal = null;
   $("[data-toggle=modal]").click(function(e) {
      e.preventDefault();
      var trgId = $(this).attr('data-target'); 
      if ( bsModal == null ) 
       bsModal = $(trgId).modal;
      $.fn.bsModal = bsModal;
      $(trgId + " .modal-body").load($(this).attr("href"));
      $(trgId).bsModal('show');
    });
 })();
/* <![CDATA[ */
</script>

links to modal are

<a data-toggle="modal" data-target="#myModal" href="edit1.aspx">Open modal 1</a>
<a data-toggle="modal" data-target="#myModal" href="edit2.aspx">Open modal 2</a>
<a data-toggle="modal" data-target="#myModal" href="edit3.aspx">Open modal 3</a>

pop up modal

<div id="myModal" class="modal hide fade in">
<div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
    <input type="submit" class="btn btn-success" value="Save"/>
</div>

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

Simplest SOAP example

You can use the jquery.soap plugin to do the work for you.

This script uses $.ajax to send a SOAPEnvelope. It can take XML DOM, XML string or JSON as input and the response can be returned as either XML DOM, XML string or JSON too.

Example usage from the site:

$.soap({
    url: 'http://my.server.com/soapservices/',
    method: 'helloWorld',

    data: {
        name: 'Remy Blom',
        msg: 'Hi!'
    },

    success: function (soapResponse) {
        // do stuff with soapResponse
        // if you want to have the response as JSON use soapResponse.toJSON();
        // or soapResponse.toString() to get XML string
        // or soapResponse.toXML() to get XML DOM
    },
    error: function (SOAPResponse) {
        // show error
    }
});

Div with horizontal scrolling only

try this:

HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
</div>

CSS:

.container {
  width: 200px;
  height: 100px;
  display: flex;
  overflow-x: auto;
}

.item {
  width: 100px;
  flex-shrink: 0;
  height: 100px;
}

The white-space: nowrap; property dont let you wrap text. Just see here for an example: https://codepen.io/oezkany/pen/YoVgYK

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

For those who like to reduce typing (i.e., everyone!): pd.set_option('max_colwidth', None) does the same thing

Initializing C# auto-properties

Update - the answer below was written before C# 6 came along. In C# 6 you can write:

public class Foo
{
    public string Bar { get; set; } = "bar";
}

You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):

public class Foo
{
    public string Bar { get; }

    public Foo(string bar)
    {
        Bar = bar;
    }
}

It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)

Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.

This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.

CSS media queries: max-width OR max-height

There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:

@media only screen 
and (min-width : 415px){
    /* Styles */
}

@media only screen 
and (min-width : 769px){
    /* Styles */
}

@media only screen 
and (min-width : 992px){
    /* Styles */
}

But if you are writing media queries for smaller device first, then it would be something like:

@media only screen 
and (max-width : 991px){
    /* Styles */
}

@media only screen 
and (max-width : 768px){
    /* Styles */
}

@media only screen 
and (max-width : 414px){
    /* Styles */
}

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

How to parse SOAP XML?

PHP version > 5.0 has a nice SoapClient integrated. Which doesn't require to parse response xml. Here's a quick example

$client = new SoapClient("http://path.to/wsdl?WSDL");
$res = $client->SoapFunction(array('param1'=>'value','param2'=>'value'));
echo $res->PaymentNotification->payment;

How do I print the full value of a long string in gdb?

Using set elements ... isn't always the best way. It would be useful if there were a distinct set string-elements ....

So, I use these functions in my .gdbinit:

define pstr
  ptype $arg0._M_dataplus._M_p
  printf "[%d] = %s\n", $arg0._M_string_length, $arg0._M_dataplus._M_p
end

define pcstr
  ptype $arg0
  printf "[%d] = %s\n", strlen($arg0), $arg0
end

Caveats:

  • The first is c++ lib dependent as it accesses members of std::string, but is easily adjusted.
  • The second can only be used on a running program as it calls strlen.

Error when testing on iOS simulator: Couldn't register with the bootstrap server

No rebuild or reinstall needed for my issue, and in my case the error appeared when trying to run the app on the iPhone. Simulator worked fine.

Solution: Delete app off phone, do a cold restart of phone and now all is well.

python JSON object must be str, bytes or bytearray, not 'dict

import json
data = json.load(open('/Users/laxmanjeergal/Desktop/json.json'))
jtopy=json.dumps(data) #json.dumps take a dictionary as input and returns a string as output.
dict_json=json.loads(jtopy) # json.loads take a string as input and returns a dictionary as output.
print(dict_json["shipments"])

How to set upload_max_filesize in .htaccess?

php_value memory_limit 30M
php_value post_max_size 100M
php_value upload_max_filesize 30M

Use all 3 in .htaccess after everything at last line. php_value post_max_size must be more than than the remaining two.

Disable validation of HTML5 form elements

you can add some javascript to surpress those obnoxious validation bubbles and add your own validators.

document.addEventListener('invalid', (function(){
    return function(e) {
      //prevent the browser from showing default error bubble / hint
      e.preventDefault();
      // optionally fire off some custom validation handler
      // myValidation();
    };
})(), true);

Correct way to focus an element in Selenium WebDriver using Java

FWIW, I had what I think is a related problem and came up with a workaround: I wrote a Chrome Extension that did an document.execCommand('paste') into a textarea with focus on window unload in order to populate the element with the system clipboard contents. This worked 100% of the time manually, but the execCommand returned false almost all the time when run under Selenium.

I added a driver.refresh() after the initial driver.get( myChromeExtensionURL ), and now it works 100% of the time. This was with Selenium driver version 2.16.333243 and Chrome version 43 on Mac OS 10.9.

When I was researching the problem, I didn't see any mentions of this workaround, so I thought I'd document my discovery for those following in my Selenium/focus/execCommand('paste') footsteps.

trigger body click with jQuery

You should have something like this:

$('body').click(function() {
   // do something here
});

The callback function will be called when the user clicks somewhere on the web page. You can trigger the callback programmatically with:

$('body').trigger('click');

Extracting specific columns in numpy array

You can use the following:

extracted_data = data.ix[:,['Column1','Column2']]

apt-get for Cygwin?

You can do this using Cygwin’s setup.exe from Windows command line. Example:

cd C:\cygwin64
setup-x86_64 -q -P wget,tar,gawk,bzip2,subversion,vim

For a more convenient installer, you may want to use the apt-cyg package manager. Its syntax is similar to apt-get, which is a plus. For this, follow the above steps and then use Cygwin Bash for the following steps:

wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg
install apt-cyg /bin

Now that apt-cyg is installed. Here are a few examples of installing some packages:

apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates

Access files stored on Amazon S3 through web browser

You can use a bucket policy to give anonymous users full read access to your objects. Depending on whether you need them to LIST or just perform a GET, you'll want to tweak this. (I.e. permissions for listing the contents of a bucket have the action set to "s3:ListBucket").

http://docs.aws.amazon.com/AmazonS3/latest/dev/AccessPolicyLanguage_UseCases_s3_a.html

Your policy will look something like the following. You can use the S3 console at http://aws.amazon.com/console to upload it.

 {
  "Version":"2008-10-17",
  "Statement":[{
    "Sid":"AddPerm",
      "Effect":"Allow",
      "Principal": {
            "AWS": "*"
         },
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::bucket/*"
      ]
    }
  ]
}

If you're truly opening up your objects to the world, you'll want to look into setting up CloudWatch rules on your billing so you can shut off permissions to your objects if they become too popular.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Insert the image directly in the Jupyter notebook.

Note: You should have a local copy of the image on your computer

You can insert the image in the Jupyter notebook itself. This way you don't need to keep the image separately in the folder.

Steps:

  1. Convert the cell to markdown by:

    • pressing M on the selected cell
      OR
    • From menu bar, Cell > Cell Type > Markdown.
      (Note: It's important to convert the cell to Markdown, otherwise the "Insert Image" option in Step 2 will not be active)
  2. Now go to menu bar and select Edit -> Insert Image.

  3. Select image from your disk and upload.

  4. Press Ctrl+Enter or Shift+Enter.

This will make the image as part of the notebook and you don't need to upload in the directory or Github. I feel this looks more clean and not prone to broken URL issue.

Static array vs. dynamic array in C++

Local arrays are created on the stack, and have automatic storage duration -- you don't need to manually manage memory, but they get destroyed when the function they're in ends. They necessarily have a fixed size:

int foo[10];

Arrays created with operator new[] have dynamic storage duration and are stored on the heap (technically the "free store"). They can have any size, but you need to allocate and free them yourself since they're not part of the stack frame:

int* foo = new int[10];
delete[] foo;

How to check if user input is not an int value

Maybe you can try this:

int function(){
Scanner input = new Scanner(System.in);   
System.out.print("Enter an integer between 1-100: ");   
int range;
while(true){   
    if(input.hasNextInt()){   
    range = input.nextInt();
    if(0<=range && range <= 100)
        break;
    else
        continue;
    }
    input.nextLine();  //Comsume the garbage value
    System.out.println("Enter an integer between 1-100:");
}
return range;
}

TextView Marquee not working

I have created a custom class AlwaysMarqueTextView

public class AlwaysMarqueeTextView extends TextView
{
    protected boolean a;

    public AlwaysMarqueeTextView(Context context)
    {
        super(context);
        a = false;
    }

    public AlwaysMarqueeTextView(Context context, AttributeSet attributeset)
    {
        super(context, attributeset);
        a = false;
    }

    public AlwaysMarqueeTextView(Context context, AttributeSet attributeset, int i)
    {
        super(context, attributeset, i);
        a = false;
    }

    public boolean isFocused()
    {
        return a || super.isFocused();
    }

    public void setAlwaysMarquee(boolean flag)
    {
        setSelected(flag);
        setSingleLine(flag);
        if(flag)
        setEllipsize(TruncateAt.MARQUEE);
        a = flag;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) 
    {
        if(focused)

            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused)
    {
        if(focused)
            super.onWindowFocusChanged(focused);
    }
}

And you can startMarquee when desire.. like

//textView.setSelected(true); No need of Selection..
textview.setAlwaysMarquee(true); 

What is the difference between atan and atan2 in C++?

With atan2 you can determine the quadrant as stated here.

You can use atan2 if you need to determine the quadrant.

What is the cleanest way to ssh and run multiple commands in Bash?

For simple commands you can use:

ssh <ssh_args> command1 '&&' command2

or

ssh <ssh_args> command1 \&\& command2

How to change Visual Studio 2012,2013 or 2015 License Key?

See my UPDATE at the end, before reading the following answer.

I have windows 8 and another pc with windows 8.1

I had License error saying "Prerelease software. License expired".

The only solution that I found which is inspired by the above solutions (Thanks!) was to run process monitor and see the exact registry keys that are accessed when I start the VS2013 which were:

HKCR\Licenses\E79B3F9C-6543-4897-BBA5-5BFB0A02BB5C

like what are mentioned in the previous posts. However the process monitor said that this registry is access denied.

So I opened regedit and found that registry key and I could not open it. It says I have no permission to see it.

SO I had to change its permission:

  1. Right click on the "HKCR\Licenses\E79B3F9C-6543-4897-BBA5-5BFB0A02BB5C" key
  2. Permissions
  3. Add
  4. In "Enter object names to select" I have added my windows user name. Ok.
  5. check on Full control
  6. Advanced
  7. Owner click on "Change"
  8. In "Enter object names to select" I have added my windows user name. Ok.
  9. Ok. Ok. Ok.

I found that this registry key has several sub keys, however you have to restart regedit to see them.

By seeing which other registry keys are access denied in process monitor , I knew that VS2013 will specifically deal with these subkeys which are ACCESS DENIED also: 06181 0bcad

and these subkeys should be changed their permissions as well like above.

After making these permission changes everything worked well.

The same thing has been done to Microsoft visual studio 2010 because an error in the license as well and the solution worked well.

UPDATE : It turned out that starting visual studio as administrator solved this issue without this registry massage. Seems that this happened to my pc after changing the 'required password to login' removed in the user settings. (I wanted to let the pc start running without any password after restart from a crash or anything else). This made a lot of programs not able to write into some folders like temp folders unless I start the application as admin. Even printing from excel would not work, if excel is not started as admin.

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

I do not know much about JavaScript, but I think Timers may be what you are looking for.

http://developer.android.com/reference/java/util/Timer.html

From the link:

One-shot are scheduled to run at an absolute time or after a relative delay. Recurring tasks are scheduled with either a fixed period or a fixed rate.

How can I check out a GitHub pull request with git?

Get the remote PR branch into local branch:

git fetch origin ‘remote_branch’:‘local_branch_name’

Set the upstream of local branch to remote branch.

git branch --set-upstream-to=origin/PR_Branch_Name local_branch

When you want to push the local changes to PR branch again

git push origin HEAD:remote_PR_Branch_name

How to use multiple @RequestMapping annotations in spring?

From my test (spring 3.0.5), @RequestMapping(value={"", "/"}) - only "/" works, "" does not. However I found out this works: @RequestMapping(value={"/", " * "}), the " * " matches anything, so it will be the default handler in case no others.

"SMTP Error: Could not authenticate" in PHPMailer

  1. first go to https://myaccount.google.com
  2. Select Security tab
  3. Scroll down and select 'Less secure app access'
  4. Turn on access

This will solve my “SMTP Error: Could not authenticate” in PHPMailer error.

Convert System.Drawing.Color to RGB and Hex Value

I'm failing to see the problem here. The code looks good to me.

The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString(), c.G.ToString(), and c.B.ToString() can't actually fail (the only way I can see them failing is with a NullReferenceException, and none of them can actually be null).

You could clean the whole thing up using the following:

private static String HexConverter(System.Drawing.Color c)
{
    return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

private static String RGBConverter(System.Drawing.Color c)
{
    return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}

Keyboard shortcut to clear cell output in Jupyter notebook

I just looked and found cell|all output|clear which worked with:

Server Information: You are using Jupyter notebook.

The version of the notebook server is: 6.1.5 The server is running on this version of Python: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]

Current Kernel Information: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.

visual c++: #include files from other projects in the same solution

Expanding on @Benav's answer, my preferred approach is to:

  1. Add the solution directory to your include paths:
    • right click on your project in the Solution Explorer
    • select Properties
    • select All Configurations and All Platforms from the drop-downs
    • select C/C++ > General
    • add $(SolutionDir) to the Additional Include Directories
  2. Add references to each project you want to use:
    • right click on your project's References in the Solution Explorer
    • select Add Reference...
    • select the project(s) you want to refer to

Now you can include headers from your referenced projects like so:

#include "OtherProject/Header.h"

Notes:

  • This assumes that your solution file is stored one folder up from each of your projects, which is the default organization when creating projects with Visual Studio.
  • You could now include any file from a path relative to the solution folder, which may not be desirable but for the simplicity of the approach I'm ok with this.
  • Step 2 isn't necessary for #includes, but it sets the correct build dependencies, which you probably want.

PHP-FPM and Nginx: 502 Bad Gateway

Don't forget that php-fpm is a service. After installing it, make sure you start it:

# service php-fpm start
# chkconfig php-fpm on

Callback functions in Java

Create an Interface, and Create the Same Interface Property in Callback Class.

interface dataFetchDelegate {
    void didFetchdata(String data);
}
//callback class
public class BackendManager{
   public dataFetchDelegate Delegate;

   public void getData() {
       //Do something, Http calls/ Any other work
       Delegate.didFetchdata("this is callbackdata");
   }

}

Now in the class where you want to get called back implement the above Created Interface. and Also Pass "this" Object/Reference of your class to be called back.

public class Main implements dataFetchDelegate
{       
    public static void main( String[] args )
    {
        new Main().getDatafromBackend();
    }

    public void getDatafromBackend() {
        BackendManager inc = new BackendManager();
        //Pass this object as reference.in this Scenario this is Main Object            
        inc.Delegate = this;
        //make call
        inc.getData();
    }

    //This method is called after task/Code Completion
    public void didFetchdata(String callbackData) {
        // TODO Auto-generated method stub
        System.out.println(callbackData);
    }
}

Input type DateTime - Value format?

For what it's worth, with iOS7 dropping support for datetime you need to use datetime-local which doesn't accept timezone portion (which makes sense).

Doesn't work (iOS anyway):

 <input type="datetime-local" value="2000-01-01T00:00:00+05:00" />

Works:

<input type="datetime-local" value="2000-01-01T00:00:00" />

PHP for value (windows safe):

strftime('%Y-%m-%dT%H:%M:%S', strtotime($my_datetime_input))

Checking if a variable is an integer in PHP

$page = (isset($_GET['p']) ? (int)$_GET['p'] : 1);
if ($page > 0)
{
  ...
}

Try casting and checking if it's a number initially.

What is the difference between static func and class func in Swift?

Is it simply that static is for static functions of structs and enums, and class for classes and protocols?

That's the main difference. Some other differences are that class functions are dynamically dispatched and can be overridden by subclasses.

Protocols use the class keyword, but it doesn't exclude structs from implementing the protocol, they just use static instead. Class was chosen for protocols so there wouldn't have to be a third keyword to represent static or class.

From Chris Lattner on this topic:

We considered unifying the syntax (e.g. using "type" as the keyword), but that doesn't actually simply things. The keywords "class" and "static" are good for familiarity and are quite descriptive (once you understand how + methods work), and open the door for potentially adding truly static methods to classes. The primary weirdness of this model is that protocols have to pick a keyword (and we chose "class"), but on balance it is the right tradeoff.

And here's a snippet that shows some of the override behavior of class functions:

class MyClass {
    class func myFunc() {
        println("myClass")
    }
}

class MyOtherClass: MyClass {
    override class func myFunc() {
        println("myOtherClass")
    }
}

var x: MyClass = MyOtherClass()
x.dynamicType.myFunc() //myOtherClass
x = MyClass()
x.dynamicType.myFunc() //myClass

How to check if a file exists in a shell script

Internally, the rm command must test for file existence anyway,
so why add another test? Just issue

rm filename

and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.

If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

MySQL JOIN the most recent row only?

You may want to try the following:

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
JOIN      (
              SELECT    MAX(id) max_id, customer_id 
              FROM      customer_data 
              GROUP BY  customer_id
          ) c_max ON (c_max.customer_id = c.customer_id)
JOIN      customer_data cd ON (cd.id = c_max.max_id)
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

Note that a JOIN is just a synonym for INNER JOIN.

Test case:

CREATE TABLE customer (customer_id int);
CREATE TABLE customer_data (
   id int, 
   customer_id int, 
   title varchar(10),
   forename varchar(10),
   surname varchar(10)
);

INSERT INTO customer VALUES (1);
INSERT INTO customer VALUES (2);
INSERT INTO customer VALUES (3);

INSERT INTO customer_data VALUES (1, 1, 'Mr', 'Bobby', 'Smith');
INSERT INTO customer_data VALUES (2, 1, 'Mr', 'Bob', 'Smith');
INSERT INTO customer_data VALUES (3, 2, 'Mr', 'Jane', 'Green');
INSERT INTO customer_data VALUES (4, 2, 'Miss', 'Jane', 'Green');
INSERT INTO customer_data VALUES (5, 3, 'Dr', 'Jack', 'Black');

Result (query without the LIMIT and WHERE):

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
JOIN      (
              SELECT    MAX(id) max_id, customer_id 
              FROM      customer_data 
              GROUP BY  customer_id
          ) c_max ON (c_max.customer_id = c.customer_id)
JOIN      customer_data cd ON (cd.id = c_max.max_id);

+-----------------+
| name            |
+-----------------+
| Mr Bob Smith    |
| Miss Jane Green |
| Dr Jack Black   |
+-----------------+
3 rows in set (0.00 sec)

Only detect click event on pseudo-element

This is edited answer by Fasoeu with latest CSS3 and JS ES6

Edited demo without using JQuery.

Shortest example of code:

<p><span>Some text</span></p>
p {
    position: relative;
    pointer-events: none;
}
p::before {
    content: "";
    position: absolute;
    pointer-events: auto;
}
p span {
    display: contents;
    pointer-events: auto;
}
const all_p = Array.from(document.querySelectorAll('p'));

for (let p of all_p) {
    p.addEventListener("click", listener, false);
};

Explanation:

pointer-events control detection of events, removing receiving events from target, but keep receiving from pseudo-elements make possible to click on ::before and ::after and you will always know what you are clicking on pseudo-element, however if you still need to click, you put all content in nested element (span in example), but because we don't want to apply any additional styles, display: contents; become very handy solution and it supported by most browsers. pointer-events: none; as already mentioned in original post also widely supported.

The JavaScript part also used widely supported Array.from and for...of, however they are not necessary to use in code.

How to use a findBy method with comparative criteria

You have to use either DQL or the QueryBuilder. E.g. in your Purchase-EntityRepository you could do something like this:

$q = $this->createQueryBuilder('p')
          ->where('p.prize > :purchasePrize')
          ->setParameter('purchasePrize', 200)
          ->getQuery();

$q->getResult();

For even more complex scenarios take a look at the Expr() class.

printf() prints whole array

Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

printf prints using the format specifier and the address provided. Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

Convert a matrix to a 1 dimensional array

You can use Joshua's solution but I think you need Elts_int <- as.matrix(tmp_int)

Or for loops:

z <- 1 ## Initialize
counter <- 1 ## Initialize
for(y in 1:48) { ## Assuming 48 columns otherwise, swap 48 and 32
for (x in 1:32) {  
z[counter] <- tmp_int[x,y]
counter <- 1 + counter
}
}

z is a 1d vector.

T-SQL - function with default parameters

One way around this problem is to use stored procedures with an output parameter.

exec sp_mysprocname @returnvalue output, @firstparam = 1, @secondparam=2

values you do not pass in default to the defaults set in the stored procedure itself. And you can get the results from your output variable.

How to compare two Carbon Timestamps?

First, Eloquent automatically converts it's timestamps (created_at, updated_at) into carbon objects. You could just use updated_at to get that nice feature, or specify edited_at in your model in the $dates property:

protected $dates = ['edited_at'];

Now back to your actual question. Carbon has a bunch of comparison functions:

  • eq() equals
  • ne() not equals
  • gt() greater than
  • gte() greater than or equals
  • lt() less than
  • lte() less than or equals

Usage:

if($model->edited_at->gt($model->created_at)){
    // edited at is newer than created at
}

Best way to unselect a <select> in jQuery?

$("#selectID option:selected").each(function(){
  $(this).removeAttr("selected");
});

This would iterate through each item and unselect only the ones which are checked

C# looping through an array

Your for loop doesn't need to just add one. You can loop by three.

for(int i = 0; i < theData.Length; i+=3)
{
  string value1 = theData[i];
  string value2 = theData[i+1];
  string value3 = theData[i+2];
}

Basically, you are just using indexes to grab the values in your array. One point to note here, I am not checking to see if you go past the end of your array. Make sure you are doing bounds checking!

Set the Value of a Hidden field using JQuery

Drop the hash - that's for identifying the id attribute.

How can Bash execute a command in a different directory context?

(cd /path/to/your/special/place;/bin/your-special-command ARGS)

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        HTMLParser.__init__(self)
        if output_list is None:
            self.output_list = []
        else:
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.output_list.append(dict(attrs).get('href'))

Test:

>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

If Else in LINQ

Answer above is not suitable for complicate Linq expression. All you need is:

// set up the "main query"
var test = from p in _db.test select _db.test;
// if str1 is not null, add a where-condition
if(str1 != null)
{
    test = test.Where(p => p.test == str);
}

bootstrap popover not showing on top of all elements

<div class="testDiv">
<a tabindex = "-1" id="testPop" title="stuff" data-toggle="popover" data-trigger="focus" data-placement="bottom" data-container=".testDiv">
 <i class="fa fa-info-circle"></i>
</a>

</div>

Above answers were helpful as setting value in data-container did the job but if i set data-container="body" then it doesn't align properly in my case. So i specified the class of the parent div of popover and it worked fine.

html

data-container=".testDiv"

js

$("#testPop").popover({container: '.testDiv'})

Check if space is in a string

You can see whether the output of the following code is 0 or not.

'import re
x='  beer   '
len(re.findall('\s', x))

Laravel - Return json along with http status code

This is how I do it in Laravel 5

return Response::json(['hello' => $value],201);

Or using a helper function:

return response()->json(['hello' => $value], 201); 

Is there a max array length limit in C++?

As has already been pointed out, array size is limited by your hardware and your OS (man ulimit). Your software though, may only be limited by your creativity. For example, can you store your "array" on disk? Do you really need long long ints? Do you really need a dense array? Do you even need an array at all?

One simple solution would be to use 64 bit Linux. Even if you do not physically have enough ram for your array, the OS will allow you to allocate memory as if you do since the virtual memory available to your process is likely much larger than the physical memory. If you really need to access everything in the array, this amounts to storing it on disk. Depending on your access patterns, there may be more efficient ways of doing this (ie: using mmap(), or simply storing the data sequentially in a file (in which case 32 bit Linux would suffice)).

Accessing constructor of an anonymous class

From the Java Language Specification, section 15.9.5.1:

An anonymous class cannot have an explicitly declared constructor.

Sorry :(

EDIT: As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:

public class Test {
    public static void main(String[] args) throws Exception {
        final int fakeConstructorArg = 10;

        Object a = new Object() {
            {
                System.out.println("arg = " + fakeConstructorArg);
            }
        };
    }
}

It's grotty, but it might just help you. Alternatively, use a proper nested class :)

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Note that while mysql reads the info of the location of the socketfile from the my.cnf file, the mysql_secure_installation program seems to not do that correctly at times.

So if you are like me and shuffle things around at installationtime you might get into the situation where you can connect to the database with mysql just fine, but the thing can not be secured (not using that script anyway).

To fix this the suggestion from sreddy works well: make a softlink from where the script would expect the socket to where it actually is. Example:

ln -s /tmp/mysql.sock /var/lib/mysql/mysql.sock

(I use /tmp/ as a default location for sockets)

How can I hide a checkbox in html?

if you want your check box to keep its height and width but only be invisible:

.hiddenCheckBox{
    visibility: hidden;
}

if you want your check box to be invisible without any with and height:

.hiddenCheckBox{
    display: none;
}

How to remove a Gitlab project?

  • 1.Gitlab Home Page
  • 2.Select your projects button under Projects Menus
  • 3.Click your desired project
  • 4.Select Settings (from left sidebar)
  • 5.Click Advanced settings Expand the Advanced settings this will be middle of the page
  • 6.Click Remove
  • 7.Project In the Modal write your project name

Hope you can Successfully remove your project. Happy Coding :)

Write variable to file, including name

Is something like this what you're looking for?

def write_vars_to_file(f, **vars):
    for name, val in vars.items():
        f.write("%s = %s\n" % (name, repr(val)))

Usage:

>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}

How to express a NOT IN query with ActiveRecord/Rails?

If someone want to use two or more conditions, you can do that:

your_array = [1,2,3,4]
your_string = "SOMETHING"

YourModel.where('variable1 NOT IN (?) AND variable2=(?)',Array.wrap(your_array),your_string)

Difference between "@id/" and "@+id/" in Android

In Short

android:id="@+id/my_button"

+id Plus sign tells android to add or create a new id in Resources.

while

android:layout_below="@id/my_button"

it just help to refer the already generated id..

Creating a list of pairs in java

Sounds like you need to create your own pair class (see discussion here). Then make a List of that pair class you created

Fastest Convert from Collection to List<T>

you can convert like below code snippet

Collection<A> obj=new Collection<return ListRetunAPI()>

How to copy directory recursively in python and overwrite all?

Have a look at the shutil package, especially rmtree and copytree. You can check if a file / path exists with os.paths.exists(<path>).

import shutil
import os

def copy_and_overwrite(from_path, to_path):
    if os.path.exists(to_path):
        shutil.rmtree(to_path)
    shutil.copytree(from_path, to_path)

Vincent was right about copytree not working, if dirs already exist. So distutils is the nicer version. Below is a fixed version of shutil.copytree. It's basically copied 1-1, except the first os.makedirs() put behind an if-else-construct:

import os
from shutil import *
def copytree(src, dst, symlinks=False, ignore=None):
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    if not os.path.isdir(dst): # This one line does the trick
        os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks, ignore)
            else:
                # Will raise a SpecialFileError for unsupported file types
                copy2(srcname, dstname)
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
        except EnvironmentError, why:
            errors.append((srcname, dstname, str(why)))
    try:
        copystat(src, dst)
    except OSError, why:
        if WindowsError is not None and isinstance(why, WindowsError):
            # Copying file access times may fail on Windows
            pass
        else:
            errors.extend((src, dst, str(why)))
    if errors:
        raise Error, errors

How do I make a dictionary with multiple keys to one value?

It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.

let's go to the code example,

In [6]: a = 10

In [7]: id(a)
Out[7]: 10914656

In [8]: b = 10

In [9]: id(b)
Out[9]: 10914656

In [10]: c = 11

In [11]: id(c)
Out[11]: 10914688

In [12]: d = 21

In [13]: id(d)
Out[13]: 10915008

In [14]: e = 11

In [15]: id(e)
Out[15]: 10914688

In [16]: e = 21

In [17]: id(e)
Out[17]: 10915008

In [18]: e is d
Out[18]: True
In [19]: e = 30

In [20]: id(e)
Out[20]: 10915296

From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.

so any variable which is having same value shares the memory.

Not for list and dictionary objects

let's come to your question.

when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.

you can simply use it like this

In [49]: dictionary = {
    ...:     'k1':1,
    ...:     'k2':1,
    ...:     'k3':2,
    ...:     'k4':2}
    ...:     
    ...:     

In [50]: id(dictionary['k1'])
Out[50]: 10914368

In [51]: id(dictionary['k2'])
Out[51]: 10914368

In [52]: id(dictionary['k3'])
Out[52]: 10914400

In [53]: id(dictionary['k4'])
Out[53]: 10914400

From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P

How to style SVG with external CSS?

A very quick solution to have dynamic style with an external css stylesheet, in case you are using the <object> tag to embed your svg.

This example will add a class to the root <svg> tag on click on a parent element.

file.svg :

<?xml-stylesheet type="text/css" href="../svg.css"?>
 <svg xmlns="http://www.w3.org/2000/svg" viewBox="">
  <g>
   <path/>
  </g>
 </svg>

html :

<a class="parent">
  <object data="file.svg"></object>
</a>

Jquery :

$(function() {
  $(document).on('click', '.parent', function(){
    $(this).find('object').contents().find('svg').attr("class","selected");
  }
});

on click parent element :

 <svg xmlns="http://www.w3.org/2000/svg" viewBox="" class="selected">

then you can manage your css

svg.css :

path {
 fill:none;
 stroke:#000;
 stroke-miterlimit:1.41;
 stroke-width:0.7px;
}

.selected path {
 fill:none;
 stroke:rgb(64, 136, 209);
 stroke-miterlimit:1.41;
 stroke-width:0.7px;
}

Undo a particular commit in Git that's been pushed to remote repos

Identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes. In a way, git revert is the converse of git cherry-pick -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.

Automating running command on Linux from Windows using PuTTY

You can write a TCL script and establish SSH session to that Linux machine and issue commands automatically. Check http://wiki.tcl.tk/11542 for a short tutorial.

How can I force clients to refresh JavaScript files?

Simplest solution? Don't let the browser cache at all. Append the current time (in ms) as a query.

(You are still in beta, so you could make a reasonable case for not optimizing for performance. But YMMV here.)

Animate text change in UILabel

Swift 2.0:

UIView.transitionWithView(self.view, duration: 1.0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
    self.sampleLabel.text = "Animation Fade1"
    }, completion: { (finished: Bool) -> () in
        self.sampleLabel.text = "Animation Fade - 34"
})

OR

UIView.animateWithDuration(0.2, animations: {
    self.sampleLabel.alpha = 1
}, completion: {
    (value: Bool) in
    self.sampleLabel.alpha = 0.2
})

How to change XML Attribute

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

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

xmlDoc.Load(xmlFile);

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

xmlDoc.Save(xmlFile);

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

I hope you find it useful

Difference between Encapsulation and Abstraction

There is a great article that touches on differences between Abstraction, Encapsulation and Information hiding in depth: http://www.tonymarston.co.uk/php-mysql/abstraction.txt

Here is the conclusion from the article:

Abstraction, information hiding, and encapsulation are very different, but highly-related, concepts. One could argue that abstraction is a technique that helps us identify which specific information should be visible, and which information should be hidden. Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible.

element with the max height from a set of elements

_x000D_
_x000D_
ul, li {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
  width: calc(100% / 3);_x000D_
}_x000D_
_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
    <br> Line 2_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
    <br> Line 2_x000D_
    <br> Line 3_x000D_
    <br> Line 4_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
    <br> Line 2_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

MassAssignmentException in Laravel

Read this section of Laravel doc : http://laravel.com/docs/eloquent#mass-assignment

Laravel provides by default a protection against mass assignment security issues. That's why you have to manually define which fields could be "mass assigned" :

class User extends Model
{
    protected $fillable = ['username', 'email', 'password'];
}

Warning : be careful when you allow the mass assignment of critical fields like password or role. It could lead to a security issue because users could be able to update this fields values when you don't want to.

How do you add an in-app purchase to an iOS application?

Just translate Jojodmo code to Swift:

class InAppPurchaseManager: NSObject , SKProductsRequestDelegate, SKPaymentTransactionObserver{





//If you have more than one in-app purchase, you can define both of
//of them here. So, for example, you could define both kRemoveAdsProductIdentifier
//and kBuyCurrencyProductIdentifier with their respective product ids
//
//for this example, we will only use one product

let kRemoveAdsProductIdentifier = "put your product id (the one that we just made in iTunesConnect) in here"

@IBAction func tapsRemoveAds() {

    NSLog("User requests to remove ads")

    if SKPaymentQueue.canMakePayments() {
        NSLog("User can make payments")

        //If you have more than one in-app purchase, and would like
        //to have the user purchase a different product, simply define
        //another function and replace kRemoveAdsProductIdentifier with
        //the identifier for the other product
        let set : Set<String> = [kRemoveAdsProductIdentifier]
        let productsRequest = SKProductsRequest(productIdentifiers: set)
        productsRequest.delegate = self
        productsRequest.start()

    }
    else {
        NSLog("User cannot make payments due to parental controls")
        //this is called the user cannot make payments, most likely due to parental controls
    }
}


func purchase(product : SKProduct) {

    let payment = SKPayment(product: product)
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
    SKPaymentQueue.defaultQueue().addPayment(payment)
}

func restore() {
    //this is called when the user restores purchases, you should hook this up to a button
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
    SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}


func doRemoveAds() {
    //TODO: implement
}

/////////////////////////////////////////////////
//////////////// store delegate /////////////////
/////////////////////////////////////////////////
// MARK: - store delegate -


func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {

    if let validProduct = response.products.first {
        NSLog("Products Available!")
        self.purchase(validProduct)
    }
    else {
        NSLog("No products available")
        //this is called if your product id is not valid, this shouldn't be called unless that happens.
    }
}

func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {


    NSLog("received restored transactions: \(queue.transactions.count)")
    for transaction in queue.transactions {
        if transaction.transactionState == .Restored {
            //called when the user successfully restores a purchase
            NSLog("Transaction state -> Restored")

            //if you have more than one in-app purchase product,
            //you restore the correct product for the identifier.
            //For example, you could use
            //if(productID == kRemoveAdsProductIdentifier)
            //to get the product identifier for the
            //restored purchases, you can use
            //
            //NSString *productID = transaction.payment.productIdentifier;
            self.doRemoveAds()
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
            break;
        }
    }
}


func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {

    for transaction in transactions {
        switch transaction.transactionState {
        case .Purchasing: NSLog("Transaction state -> Purchasing")
            //called when the user is in the process of purchasing, do not add any of your own code here.
        case .Purchased:
            //this is called when the user has successfully purchased the package (Cha-Ching!)
            self.doRemoveAds() //you can add your code for what you want to happen when the user buys the purchase here, for this tutorial we use removing ads
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
            NSLog("Transaction state -> Purchased")
        case .Restored:
            NSLog("Transaction state -> Restored")
            //add the same code as you did from SKPaymentTransactionStatePurchased here
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
        case .Failed:
            //called when the transaction does not finish
            if transaction.error?.code == SKErrorPaymentCancelled {
                NSLog("Transaction state -> Cancelled")
                //the user cancelled the payment ;(
            }
            SKPaymentQueue.defaultQueue().finishTransaction(transaction)
        case .Deferred:
            // The transaction is in the queue, but its final status is pending external action.
            NSLog("Transaction state -> Deferred")

        }


    }
}
} 

How to merge two json string in Python?

As of Python 3.5, you can merge two dicts with:

merged = {**dictA, **dictB}

(https://www.python.org/dev/peps/pep-0448/)

So:

jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)

etc.

"git rebase origin" vs."git rebase origin/master"

git rebase origin means "rebase from the tracking branch of origin", while git rebase origin/master means "rebase from the branch master of origin"

You must have a tracking branch in ~/Desktop/test, which means that git rebase origin knows which branch of origin to rebase with. If no tracking branch exists (in the case of ~/Desktop/fallstudie), git doesn't know which branch of origin it must take, and fails.

To fix this, you can make the branch track origin/master with:

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

Or, if master isn't the currently checked-out branch:

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

Draw horizontal rule in React Native

You could simply use an empty View with a bottom border.

<View
  style={{
    borderBottomColor: 'black',
    borderBottomWidth: 1,
  }}
/>

How to specify the current directory as path in VBA?

If the path you want is the one to the workbook running the macro, and that workbook has been saved, then

ThisWorkbook.Path

is what you would use.

How can I select rows by range?

Have you tried your own code?
This should work:

SELECT * FROM people WHERE age BETWEEN x AND y

How can I hide an HTML table row <tr> so that it takes up no space?

HTML:

<input type="checkbox" id="attraction" checked="checked" onchange="updateMap()">poi.attraction</input>

JavaScript:

function updateMap() {
     map.setOptions({'styles': getStyles() });
} 

function getStyles() {
    var styles = [];
    for (var i=0; i < types.length; i++) {
      var style = {};
      var type = types[i];
      var enabled = document.getElementById(type).checked;
      style['featureType'] = 'poi.' + type;
      style['elementType'] = 'labels';
      style['stylers'] = [{'visibility' : (enabled ? 'on' : 'off') }];
      styles.push(style);
    }
    return styles;
}

How to call a REST web service API from JavaScript?

Your Javascript:

function UserAction() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             alert(this.responseText);
         }
    };
    xhttp.open("POST", "Your Rest URL Here", true);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send("Your JSON Data Here");
}

Your Button action::

<button type="submit" onclick="UserAction()">Search</button>

For more info go through the following link (Updated 2017/01/11)

What does 'public static void' mean in Java?

It's three completely different things:

public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.

static means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.

void means that the method has no return value. If the method returned an int you would write int instead of void.

The combination of all three of these is most commonly seen on the main method which most tutorials will include.

How does collections.defaultdict work?

The behavior of defaultdict can be easily mimicked using dict.setdefault instead of d[key] in every call.

In other words, the code:

from collections import defaultdict

d = defaultdict(list)

print(d['key'])                        # empty list []
d['key'].append(1)                     # adding constant 1 to the list
print(d['key'])                        # list containing the constant [1]

is equivalent to:

d = dict()

print(d.setdefault('key', list()))     # empty list []
d.setdefault('key', list()).append(1)  # adding constant 1 to the list
print(d.setdefault('key', list()))     # list containing the constant [1]

The only difference is that, using defaultdict, the list constructor is called only once, and using dict.setdefault the list constructor is called more often (but the code may be rewriten to avoid this, if really needed).

Some may argue there is a performance consideration, but this topic is a minefield. This post shows there isn't a big performance gain in using defaultdict, for example.

IMO, defaultdict is a collection that adds more confusion than benefits to the code. Useless for me, but others may think different.

Array formula on Excel for Mac

This doesn't seem to work in Mac Excel 2016. After a bit of digging, it looks like the key combination for entering the array formula has changed from ?+RETURN to CTRL+SHIFT+RETURN.

How do I mount a remote Linux folder in Windows through SSH?

Apparently the free NetDrive software from Novell can access SFTP file servers.

HTML/CSS--Creating a banner/header

Remove the position: absolute; attribute in the style

What does the "static" modifier after "import" mean?

The basic idea of static import is that whenever you are using a static class,a static variable or an enum,you can import them and save yourself from some typing.

I will elaborate my point with example.

import java.lang.Math;

class WithoutStaticImports {

 public static void main(String [] args) {
  System.out.println("round " + Math.round(1032.897));
  System.out.println("min " + Math.min(60,102));
 }
}

Same code, with static imports:

import static java.lang.System.out;
import static java.lang.Math.*;

class WithStaticImports {
  public static void main(String [] args) {
    out.println("round " + round(1032.897));
    out.println("min " + min(60,102));
  }
}

Note: static import can make your code confusing to read.

Exception: "URI formats are not supported"

string uriPath =
    "file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj";
string localPath = new Uri(uriPath).LocalPath;

compareTo() vs. equals()

  • equals: required for checking equality and restricting duplicates. Many classes of Java Library use this in case they wanted to find duplicates. e.g. HashSet.add(ob1) will only add if that doesn't exist. So if you are extending some classes like this then override equals().

  • compareTo: required for ordering of element. Again for stable sorting you require equality, so there is a return 0.

Android Camera Preview Stretched

OK, so I think there is no sufficient answer for general camera preview stretching problem. Or at least I didn't find one. My app also suffered this stretching syndrome and it took me a while to puzzle together a solution from all the user answers on this portal and internet.

I tried @Hesam's solution but it didn't work and left my camera preview majorly distorted.

First I show the code of my solution (the important parts of the code) and then I explain why I took those steps. There is room for performance modifications.

Main activity xml layout:

<RelativeLayout 
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    />
</RelativeLayout>

Camera Preview:

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

private SurfaceHolder prHolder;
private Camera prCamera;
public List<Camera.Size> prSupportedPreviewSizes;
private Camera.Size prPreviewSize;

@SuppressWarnings("deprecation")
public YoCameraPreview(Context context, Camera camera) {
    super(context);
    prCamera = camera;

    prSupportedPreviewSizes = prCamera.getParameters().getSupportedPreviewSizes();

    prHolder = getHolder();
    prHolder.addCallback(this);
    prHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void surfaceCreated(SurfaceHolder holder) {
    try {
        prCamera.setPreviewDisplay(holder);
        prCamera.startPreview();
    } catch (IOException e) {
        Log.d("Yologram", "Error setting camera preview: " + e.getMessage());
    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    if (prHolder.getSurface() == null){
      return;
    }

    try {
        prCamera.stopPreview();
    } catch (Exception e){
    }

    try {
        Camera.Parameters parameters = prCamera.getParameters();
        List<String> focusModes = parameters.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        }
        parameters.setPreviewSize(prPreviewSize.width, prPreviewSize.height);

        prCamera.setParameters(parameters);
        prCamera.setPreviewDisplay(prHolder);
        prCamera.startPreview();

    } catch (Exception e){
        Log.d("Yologram", "Error starting camera preview: " + e.getMessage());
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

    setMeasuredDimension(width, height);

    if (prSupportedPreviewSizes != null) {
        prPreviewSize = 
            getOptimalPreviewSize(prSupportedPreviewSizes, width, height);
    }    
}

public Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {

    final double ASPECT_TOLERANCE = 0.1;
    double targetRatio = (double) h / w;

    if (sizes == null)
        return null;

    Camera.Size optimalSize = null;
    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    for (Camera.Size size : sizes) {
        double ratio = (double) size.width / size.height;
        if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
            continue;

        if (Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    if (optimalSize == null) {
        minDiff = Double.MAX_VALUE;
        for (Camera.Size size : sizes) {
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
    }

    return optimalSize;
}
}

Main activity:

public class MainActivity extends Activity {

...

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     
    setContentView(R.layout.activity_main);

        maCamera = getCameraInstance();

        maLayoutPreview = (FrameLayout) findViewById(R.id.camera_preview);

        maPreview = new CameraPreview(this, maCamera);

        Point displayDim = getDisplayWH();
        Point layoutPreviewDim = calcCamPrevDimensions(displayDim, 
                maPreview.getOptimalPreviewSize(maPreview.prSupportedPreviewSizes, 
                    displayDim.x, displayDim.y));
        if (layoutPreviewDim != null) {
            RelativeLayout.LayoutParams layoutPreviewParams = 
                (RelativeLayout.LayoutParams) maLayoutPreview.getLayoutParams();
            layoutPreviewParams.width = layoutPreviewDim.x;
            layoutPreviewParams.height = layoutPreviewDim.y;
            layoutPreviewParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            maLayoutPreview.setLayoutParams(layoutPreviewParams);
        }
        maLayoutPreview.addView(maPreview);
}

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private Point getDisplayWH() {

    Display display = this.getWindowManager().getDefaultDisplay();
    Point displayWH = new Point();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        display.getSize(displayWH);
        return displayWH;
    }
    displayWH.set(display.getWidth(), display.getHeight());
    return displayWH;
}

private Point calcCamPrevDimensions(Point disDim, Camera.Size camDim) {

    Point displayDim = disDim;
    Camera.Size cameraDim = camDim;

    double widthRatio = (double) displayDim.x / cameraDim.width;
    double heightRatio = (double) displayDim.y / cameraDim.height;

    // use ">" to zoom preview full screen
    if (widthRatio < heightRatio) {
        Point calcDimensions = new Point();
        calcDimensions.x = displayDim.x;
        calcDimensions.y = (displayDim.x * cameraDim.height) / cameraDim.width;
        return calcDimensions;
    }
    // use "<" to zoom preview full screen
    if (widthRatio > heightRatio) { 
        Point calcDimensions = new Point();
        calcDimensions.x = (displayDim.y * cameraDim.width) / cameraDim.height;
        calcDimensions.y = displayDim.y;
        return calcDimensions;
    }
    return null;
}   
}

My commentary:

The point of all this is, that although you calculate the optimal camera size in getOptimalPreviewSize() you only pick the closest ratio to fit your screen. So unless the ratio is exactly the same the preview will stretch.

Why will it stretch? Because your FrameLayout camera preview is set in layout.xml to match_parent in width and height. So that is why the preview will stretch to full screen.

What needs to be done is to set camera preview layout width and height to match the chosen camera size ratio, so the preview keeps its aspect ratio and won't distort.

I tried to use the CameraPreview class to do all the calculations and layout changes, but I couldn't figure it out. I tried to apply this solution, but SurfaceView doesn't recognize getChildCount () or getChildAt (int index). I think, I got it working eventually with a reference to maLayoutPreview, but it was misbehaving and applied the set ratio to my whole app and it did so after first picture was taken. So I let it go and moved the layout modifications to the MainActivity.

In CameraPreview I changed prSupportedPreviewSizes and getOptimalPreviewSize() to public so I can use it in MainActivity. Then I needed the display dimensions (minus the navigation/status bar if there is one) and chosen optimal camera size. I tried to get the RelativeLayout (or FrameLayout) size instead of display size, but it was returning zero value. This solution didn't work for me. The layout got it's value after onWindowFocusChanged (checked in the log).

So I have my methods for calculating the layout dimensions to match the aspect ratio of chosen camera size. Now you just need to set LayoutParams of your camera preview layout. Change the width, height and center it in parent.

There are two choices how to calculate the preview dimensions. Either you want it to fit the screen with black bars (if windowBackground is set to null) on the sides or top/bottom. Or you want the preview zoomed to full screen. I left comment with more information in calcCamPrevDimensions().

Remove non-numeric characters (except periods and commas) from a string

You could use preg_replace to swap out all non-numeric characters and the comma and period/full stop as follows:

$testString = '12.322,11T';
echo preg_replace('/[^0-9,.]+/', '', $testString);

The pattern can also be expressed as /[^\d,.]+/

Running code after Spring Boot starts

I really like the suggestion for usage of the EventListener annotation by @cahen (https://stackoverflow.com/a/44923402/9122660) since it is very clean. Unfortunately I could not get this to work in a Spring + Kotlin setup. What does work for Kotlin is adding the class as a method parameter:

@EventListener 
fun doSomethingAfterStartup(event: ApplicationReadyEvent) {
    System.out.println("hello world, I have just started up");
}

remove item from array using its name / value

it worked for me..

countries.results= $.grep(countries.results, function (e) { 
      if(e.id!= currentID) {
       return true; 
      }
     });

Python webbrowser.open() to open Chrome browser

Here's a somewhat robust way to get the path to Chrome.

(Note that you should do this only if you specifically need Chrome, and not the default browser, or Chromium, or something else.)

def try_find_chrome_path():
    result = None
    if _winreg:
        for subkey in ['ChromeHTML\\shell\\open\\command', 'Applications\\chrome.exe\\shell\\open\\command']:
            try: result = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
            except WindowsError: pass
            if result is not None:
                result_split = shlex.split(result, False, True)
                result = result_split[0] if result_split else None
                if os.path.isfile(result):
                    break
                result = None
    else:
        expected = "google-chrome" + (".exe" if os.name == 'nt' else "")
        for parent in os.environ.get('PATH', '').split(os.pathsep):
            path = os.path.join(parent, expected)
            if os.path.isfile(path):
                result = path
                break
    return result

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

See creating a registry key.

This problem can occur not only due to permissions, but also due to event source key missing because it wasn't registered successfully (you need admin privileges to do it - if you just open Visual Studio as usual and run the program normally it won't be enough). Make sure that your event source "MyApp" is actually registered, i.e. that it appears in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application.

From MSDN EventLog.CreateEventSource():

To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative privileges.

So you must either run the event source registration code as an admin (also, check if the source already exists before - see the above MSDN example) or you can manually add the key to the registry:

  1. create a regkey HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\MyApp;
  2. inside, create a string value EventMessageFile and set its value to e.g. C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll

JPA : How to convert a native query result set to POJO class collection

First declare following annotations:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface NativeQueryResultEntity {
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NativeQueryResultColumn {
    int index();
}

Then annotate your POJO as follows:

@NativeQueryResultEntity
public class ClassX {
    @NativeQueryResultColumn(index=0)
    private String a;

    @NativeQueryResultColumn(index=1)
    private String b;
}

Then write annotation processor:

public class NativeQueryResultsMapper {

    private static Logger log = LoggerFactory.getLogger(NativeQueryResultsMapper.class);

    public static <T> List<T> map(List<Object[]> objectArrayList, Class<T> genericType) {
        List<T> ret = new ArrayList<T>();
        List<Field> mappingFields = getNativeQueryResultColumnAnnotatedFields(genericType);
        try {
            for (Object[] objectArr : objectArrayList) {
                T t = genericType.newInstance();
                for (int i = 0; i < objectArr.length; i++) {
                    BeanUtils.setProperty(t, mappingFields.get(i).getName(), objectArr[i]);
                }
                ret.add(t);
            }
        } catch (InstantiationException ie) {
            log.debug("Cannot instantiate: ", ie);
            ret.clear();
        } catch (IllegalAccessException iae) {
            log.debug("Illegal access: ", iae);
            ret.clear();
        } catch (InvocationTargetException ite) {
            log.debug("Cannot invoke method: ", ite);
            ret.clear();
        }
        return ret;
    }

    // Get ordered list of fields
    private static <T> List<Field> getNativeQueryResultColumnAnnotatedFields(Class<T> genericType) {
        Field[] fields = genericType.getDeclaredFields();
        List<Field> orderedFields = Arrays.asList(new Field[fields.length]);
        for (int i = 0; i < fields.length; i++) {
            if (fields[i].isAnnotationPresent(NativeQueryResultColumn.class)) {
                NativeQueryResultColumn nqrc = fields[i].getAnnotation(NativeQueryResultColumn.class);
                orderedFields.set(nqrc.index(), fields[i]);
            }
        }
        return orderedFields;
    }
}

Use above framework as follows:

String sql = "select a,b from x order by a";
Query q = entityManager.createNativeQuery(sql);

List<ClassX> results = NativeQueryResultsMapper.map(q.getResultList(), ClassX.class);

Pass a javascript variable value into input type hidden value

Check out this jQuery page for some interesting examples of how to play with the value attribute, and how to call it:

http://api.jquery.com/val/

Otherwise - if you want to use jQuery rather than javascript in passing variables to an input of any kind, use the following to set the value of the input on an event click(), submit() et al:

on some event; assign or set the value of the input:

$('#inputid').val($('#idB').text());

where:

<input id = "inputid" type = "hidden" />

<div id = "idB">This text will be passed to the input</div>

Using such an approach, make sure the html input does not already specify a value, or a disabled attribute, obviously.

Beware the differences betwen .html() and .text() when dealing with html forms.

How to read and write to a text file in C++?

Look at this tutorial or this one, they are both pretty simple. If you are interested in an alternative this is how you do file I/O in C.

Some things to keep in mind, use single quotes ' when dealing with single characters, and double " for strings. Also it is a bad habit to use global variables when not necessary.

Have fun!