Programs & Examples On #Sdl mixer

SDL_mixer is a sample multi-channel audio mixer library. It supports any number of simultaneously playing channels of 16 bit stereo audio, plus a single channel of music, mixed by the popular FLAC, MikMod MOD, Timidity MIDI, Ogg Vorbis, and SMPEG MP3 libraries.

If statement with String comparison fails

If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.

Removing Conda environment

To remove complete conda environment :

conda remove --name YOUR_CONDA_ENV_NAME --all

Reload .profile in bash shell script (in unix)?

Try this:

cd 
source .bash_profile

jQuery: load txt file and insert into div

 <script type="text/javascript">     
   $("#textFileID").html("Loading...").load("URL TEXT");
 </script>  

 <div id="textFileID"></div>

How to download a branch with git?

You could use git remote like:

git fetch origin

and then setup a local branch to track the remote branch like below:

git branch --track [local-branch-name] origin/remote-branch-name

You would now have the contents of the remote github branch in local-branch-name.

You could switch to that local-branch-name and start work:

git checkout [local-branch-name]

How to handle Pop-up in Selenium WebDriver using Java

public void Test(){

     WebElement sign = fc.findElement(By.xpath(".//*[@id='login-scroll']/a"));
        sign.click();
        WebElement LoginAsGuest=fc.findElement(By.xpath(".//*[@id='guest-login-option']"));
        LoginAsGuest.click();
        WebElement email_id= fc.findElement(By.xpath(".//*[@id='guestemail']"));
        email_id.sendKeys("[email protected]");
        WebElement ContinueButton=fc.findElement(By.xpath(".//*[@id='contibutton']"));
        ContinueButton.click();

}

What is the difference between Class.getResource() and ClassLoader.getResource()?

I tried reading from input1.txt which was inside one of my packages together with the class which was trying to read it.

The following works:

String fileName = FileTransferClient.class.getResource("input1.txt").getPath();

System.out.println(fileName);

BufferedReader bufferedTextIn = new BufferedReader(new FileReader(fileName));

The most important part was to call getPath() if you want the correct path name in String format. DO NOT USE toString() because it will add some extra formatting text which will TOTALLY MESS UP the fileName (you can try it and see the print out).

Spent 2 hours debugging this... :(

Move div to new line

What about something like this.

<div id="movie_item">
    <div class="movie_item_poster">
        <img src="..." style="max-width: 100%; max-height: 100%;">
    </div>

     <div id="movie_item_content">
        <div class="movie_item_content_year">year</div>
        <div class="movie_item_content_title">title</div>
        <div class="movie_item_content_plot">plot</div>
    </div>

    <div class="movie_item_toolbar">
        Lorem Ipsum...
    </div>
</div>

You don't have to float both movie_item_poster AND movie_item_content. Just float one of them...

#movie_item {
    position: relative;
    margin-top: 10px;
    height: 175px;
}

.movie_item_poster {
    float: left;
    height: 150px;
    width: 100px;
}

.movie_item_content {
    position: relative;
}

.movie_item_content_title {
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
}

.movie_item_toolbar {
    clear: both;
    vertical-align: bottom;
    width: 100%;
    height: 25px;
}

Here it is as a JSFiddle.

Overlapping elements in CSS

You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.

You have to set translate property in such way that both the <div> overlap each other then You can use JavaScript to show and hide both the <div> according to your requirements

Comparison of DES, Triple DES, AES, blowfish encryption for data

Although TripleDESCryptoServiceProvider is a safe and good method but it's too slow. If you want to refer to MSDN you will get that advise you to use AES rather TripleDES. Please check below link: http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider.aspx you will see this attention in the remark section:

Note A newer symmetric encryption algorithm, Advanced Encryption Standard (AES), is available. Consider using the AesCryptoServiceProvider class instead of the TripleDESCryptoServiceProvider class. Use TripleDESCryptoServiceProvider only for compatibility with legacy applications and data.

Good luck

Creating JSON on the fly with JObject

You can use Newtonsoft library and use it as follows

using Newtonsoft.Json;



public class jb
{
     public DateTime Date { set; get; }
     public string Artist { set; get; }
     public int Year { set; get; }
     public string album { set; get; }

}
var jsonObject = new jb();

jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";


System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
         new System.Web.Script.Serialization.JavaScriptSerializer();

string sJSON = oSerializer.Serialize(jsonObject );

How do I run Visual Studio as an administrator by default?

For Windows 8

  1. right click on the shortcut
  2. click on properties
  3. click on the "Shortcut" tab
  4. click on Advanced

You will find Run As administrator (Checkbox)

C#: How do you edit items and subitems in a listview?

private void listView1_MouseDown(object sender, MouseEventArgs e)
{
    li = listView1.GetItemAt(e.X, e.Y);
    X = e.X;
    Y = e.Y;
}

private void listView1_MouseUp(object sender, MouseEventArgs e)
{
    int nStart = X;
    int spos = 0;
    int epos = listView1.Columns[1].Width;
    for (int i = 0; i < listView1.Columns.Count; i++)
    {
        if (nStart > spos && nStart < epos)
        {
            subItemSelected = i;
            break;
        }

        spos = epos;
        epos += listView1.Columns[i].Width;
    }
    li.SubItems[subItemSelected].Text = "9";
}

How do I get a value of a <span> using jQuery?

<script>
    $(document).ready(function () {

            $.each($(".classBalence").find("span"), function () {
            if ($(this).text() >1) {
                $(this).css("color", "green")

            }
            if ($(this).text() < 1) {
                $(this).css("color", "red")
                $(this).css("font-weight", "bold")
            }
        });

    });
    </script>

How to get different colored lines for different plots in a single figure?

Matplot colors your plot with different colors , but incase you wanna put specific colors

    import matplotlib.pyplot as plt
    import numpy as np
            
    x = np.arange(10)
            
    plt.plot(x, x)
    plt.plot(x, 2 * x,color='blue')
    plt.plot(x, 3 * x,color='red')
    plt.plot(x, 4 * x,color='green')
    plt.show()

Can I force a page break in HTML printing?

Let's say you have a blog with articles like this:

<div class="article"> ... </div>

Just adding this to the CSS worked for me:

@media print {
  .article { page-break-after: always; }
}

(tested and working on Chrome 69 and Firefox 62).

Reference:

How to completely uninstall Android Studio from windows(v10)?

Firstly uninstall Android Studio from control panel using program and features. Later you also need to enable displaying of hidden files and folders and delete the following:

users/${yourUserName}/appData/Local/Android

adb not finding my device / phone (MacOS X)

I was trying to connect an old phone that I use to test apps on older API versions. Today adb was not finding it.

After trying pretty much everything here, I figured out that the phone was not even showing the system notification about the USB connection going on.

So I looked around for that issue, and found the solution here (credits to the original source):

  1. Remove phone from PC and remove battery to shut off phone.
  2. Plug USB cable into PC.
  3. Plug USB cable (other end) into phone.
  4. The PC install new hardware appropriate drivers for a few minutes (phone without battery)
  5. Unplug USB cable from phone
  6. Put battery back in and turn on phone
  7. As the phone boots, hold down Volume up and down. Phone boots into safe mode.
  8. Plug USB cable into phone.
  9. I saw notification about USB MTP-connecting on the phone. PC have found my phone!
  10. After the reboot in normal mode problem was fixed

Not sure step 4. is of any use here on macOS, however I did all the steps and it worked well.

Java: String - add character n-times

For the case of repeating a single character (not a String), you could use Arrays.fill:

  String original = "original ";
  char c = 'c';
  int number = 9;

  char[] repeat = new char[number];
  Arrays.fill(repeat, c);
  original += new String(repeat);

Scheduled run of stored procedure on SQL server

Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

Had the same problem i added compile 'com.google.android.gms:play-services-measurement:8.4.0' and deleted apply plugin: 'com.google.gms.google-services' I was using classpath 'com.google.gms:google-services:2.0.0-alpha6' in the build project.

Vagrant stuck connection timeout retrying

I've found out that on MacOS with VirtualBox adding this to Vagrantfile will let you go further:

config.vm.provider 'virtualbox' do |vb|
  vb.customize ['modifyvm', :id, '--cableconnected1', 'on']
end

How to download/upload files from/to SharePoint 2013 using CSOM?

A little late this comment but I will leave here my results working with the library of SharePoin Online and it is very easy to use and implement in your project, just go to the NuGet administrator of .Net and Add Microsoft.SharePoint.CSOM to your project .

https://developer.microsoft.com/en-us/office/blogs/new-sharepoint-csom-version-released-for-office-365-may-2017/

The following code snippet will help you connect your credentials to your SharePoint site, you can also read and download files from a specific site and folder.

using System;
using System.IO;
using System.Linq;
using System.Web;
using Microsoft.SharePoint.Client;
using System.Security;

using ClientOM = Microsoft.SharePoint.Client;

namespace MvcApplication.Models.Home
{
    public class SharepointModel
    {
        public ClientContext clientContext { get; set; }
        private string ServerSiteUrl = "https://somecompany.sharepoint.com/sites/ITVillahermosa";
        private string LibraryUrl = "Shared Documents/Invoices/";
        private string UserName = "[email protected]";
        private string Password = "********";
        private Web WebClient { get; set; }

        public SharepointModel()
        {
            this.Connect();
        }

        public void Connect()
        {
            try
            {
                using (clientContext = new ClientContext(ServerSiteUrl))
                {
                    var securePassword = new SecureString();
                    foreach (char c in Password)
                    {
                        securePassword.AppendChar(c);
                    }

                    clientContext.Credentials = new SharePointOnlineCredentials(UserName, securePassword);
                    WebClient = clientContext.Web;
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public string UploadMultiFiles(HttpRequestBase Request, HttpServerUtilityBase Server)
        {
            try
            {
                HttpPostedFileBase file = null;
                for (int f = 0; f < Request.Files.Count; f++)
                {
                    file = Request.Files[f] as HttpPostedFileBase;

                    string[] SubFolders = LibraryUrl.Split('/');
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), filename);
                    file.SaveAs(path);

                    clientContext.Load(WebClient, website => website.Lists, website => website.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    //https://somecompany.sharepoint.com/sites/ITVillahermosa/Shared Documents/
                    List documentsList = clientContext.Web.Lists.GetByTitle("Documents"); //Shared Documents -> Documents
                    clientContext.Load(documentsList, i => i.RootFolder.Folders, i => i.RootFolder);
                    clientContext.ExecuteQuery();

                    string SubFolderName = SubFolders[1];//Get SubFolder 'Invoice'
                    var folderToBindTo = documentsList.RootFolder.Folders;
                    var folderToUpload = folderToBindTo.Where(i => i.Name == SubFolderName).First();

                    var fileCreationInformation = new FileCreationInformation();
                    //Assign to content byte[] i.e. documentStream
                    fileCreationInformation.Content = System.IO.File.ReadAllBytes(path);
                    //Allow owerwrite of document
                    fileCreationInformation.Overwrite = true;
                    //Upload URL
                    fileCreationInformation.Url = ServerSiteUrl + LibraryUrl + filename;

                    Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);

                    //Update the metadata for a field having name "DocType"
                    uploadFile.ListItemAllFields["Title"] = "UploadedCSOM";

                    uploadFile.ListItemAllFields.Update();
                    clientContext.ExecuteQuery();
                }

                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public string DownloadFiles()
        {
            try
            {
                string tempLocation = @"c:\Downloads\Sharepoint\";
                System.IO.DirectoryInfo di = new DirectoryInfo(tempLocation);
                foreach (FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }

                FileCollection files = WebClient.GetFolderByServerRelativeUrl(this.LibraryUrl).Files;
                clientContext.Load(files);
                clientContext.ExecuteQuery();

                if (clientContext.HasPendingRequest)
                    clientContext.ExecuteQuery();

                foreach (ClientOM.File file in files)
                {
                    FileInformation fileInfo = ClientOM.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    var filePath = tempLocation + file.Name;
                    using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
                    {
                        fileInfo.Stream.CopyTo(fileStream);
                    }
                }

                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

    }
}

Then to invoke the functions from the controller in this case MVC ASP.NET is done in the following way.


using MvcApplication.Models.Home;
using System;
using System.Web.Mvc;

namespace MvcApplication.Controllers
{
    public class SharepointController : MvcBoostraBaseController
    {
        [HttpPost]
        public ActionResult Upload(FormCollection form)
        {
            try
            {
                SharepointModel sharepointModel = new SharepointModel();
                return Json(sharepointModel.UploadMultiFiles(Request, Server), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return ThrowJSONError(ex);
            }
        }

        public ActionResult Download(string ServerUrl, string RelativeUrl)
        {
            try
            {
                SharepointModel sharepointModel = new SharepointModel();
                return Json(sharepointModel.DownloadFiles(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return ThrowJSONError(ex);
            }
        }
    }
}

If you need the source code of this project you can request it to [email protected]

Python: import module from another directory at the same level in project hierarchy

In the "root" __init__.py you can also do a

import sys
sys.path.insert(1, '.')

which should make both modules importable.

Better way to call javascript function in a tag

Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.

Both of your suggestions break with CSP enabled because they allow inline Javascript (which could be injected by a hacker) to execute in your page.

The best practice is to subscribe to the event in Javascript, as in Konrad Rudolph's answer.

Netbeans 8.0.2 The module has not been deployed

UPDATE: this was solved by rebooting but there was another error when running app. This time tomcat woudnt start. To solve this (bugs with latest apache and netbeans versions) follow: Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Use the method provided in the Date object as follows:

var ts_hms = new Date();

console.log(
    ts_hms.getFullYear() + '-' + 
    ("0" + (ts_hms.getMonth() + 1)).slice(-2) + '-' + 
    ("0" + (ts_hms.getDate())).slice(-2) + ' ' +
    ("0" + ts_hms.getHours()).slice(-2) + ':' +
    ("0" + ts_hms.getMinutes()).slice(-2) + ':' +
    ("0" + ts_hms.getSeconds()).slice(-2));

It looks really dirty, but it should work fine with JavaScript core methods

Check whether a variable is a string in Ruby

foo.instance_of? String

or

foo.kind_of? String 

if you you only care if it is derrived from String somewhere up its inheritance chain

How to write data to a text file without overwriting the current data

First of all check if the filename already exists, If yes then create a file and close it at the same time then append your text using AppendAllText. For more info check the code below.


string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt"; 
string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;


 if (!File.Exists(str_Path))
 {
     File.Create(str_Path).Close();
    File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }
 else if (File.Exists(str_Path))
 {

     File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

Select box arrow style

http://jsfiddle.net/u3cybk2q/2/ check on windows, iOS and Android (iexplorer patch)

_x000D_
_x000D_
.styled-select select {_x000D_
   background: transparent;_x000D_
   width: 240px;_x000D_
   padding: 5px;_x000D_
   font-size: 16px;_x000D_
   line-height: 1;_x000D_
   border: 0;_x000D_
   border-radius: 0;_x000D_
   height: 34px;_x000D_
   -webkit-appearance: none;_x000D_
}_x000D_
.styled-select {_x000D_
   width: 240px;_x000D_
   height: 34px;_x000D_
   overflow: visible;_x000D_
   background: url(http://nightly.enyojs.com/latest/lib/moonstone/dist/moonstone/images/caret-black-small-down-icon.png) no-repeat right #FFF;_x000D_
   border: 1px solid #ccc;_x000D_
}_x000D_
.styled-select select::-ms-expand {_x000D_
    display: none;_x000D_
}
_x000D_
<div class="styled-select">_x000D_
   <select>_x000D_
      <option>Here is the first option</option>_x000D_
      <option>The second option</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

find all subsets that sum to a particular value

public class SumOfSubSet {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int a[] = {1,2};
        int sum=0;
        if(a.length<=0) {
            System.out.println(sum);
        }else {
        for(int i=0;i<a.length;i++) {
            sum=sum+a[i];
            for(int j=i+1;j<a.length;j++) {
                sum=sum+a[i]+a[j];
            }
        }
        System.out.println(sum);

        }


    }

}

How to convert a list into data table

private DataTable CreateDataTable(IList<T> item)
{
    Type type = typeof(T);
    var properties = type.GetProperties();

    DataTable dataTable = new DataTable();
    foreach (PropertyInfo info in properties)
    {
        dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
    }

    foreach (T entity in item)
    {
        object[] values = new object[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            values[i] = properties[i].GetValue(entity);
        }

        dataTable.Rows.Add(values);
    }
    return dataTable;
}

Using G++ to compile multiple .cpp and .h files

You can use several g++ commands and then link, but the easiest is to use a traditional Makefile or some other build system: like Scons (which are often easier to set up than Makefiles).

How do we change the URL of a working GitLab install?

GitLab Omnibus

For an Omnibus install, it is a little different.

The correct place in an Omnibus install is:

/etc/gitlab/gitlab.rb
    external_url 'http://gitlab.example.com'

Finally, you'll need to execute sudo gitlab-ctl reconfigure and sudo gitlab-ctl restart so the changes apply.


I was making changes in the wrong places and they were getting blown away.

The incorrect paths are:

/opt/gitlab/embedded/service/gitlab-rails/config/gitlab.yml
/var/opt/gitlab/.gitconfig
/var/opt/gitlab/nginx/conf/gitlab-http.conf

Pay attention to those warnings that read:

# This file is managed by gitlab-ctl. Manual changes will be
# erased! To change the contents below, edit /etc/gitlab/gitlab.rb
# and run `sudo gitlab-ctl reconfigure`.

MySQL integer field is returned as string in PHP

In my case mysqlnd.so extension had been installed. BUT i hadn't pdo_mysqlnd.so. So, the problem had been solved by replacing pdo_mysql.so with pdo_mysqlnd.so.

Google Maps API warning: NoApiKeys

Creating and using the key is the way to go. The usage is free until your application reaches 25.000 calls per day on 90 consecutive days.

BTW.: In the google Developer documentation it says you shall add the api key as option {key:yourKey} when calling the API to create new instances. This however doesn't shush the console warning. You have to add the key as a parameter when including the api.

<script src="https://maps.googleapis.com/maps/api/js?key=yourKEYhere"></script>

Get the key here: GoogleApiKey Generation site

How to get Git to clone into current directory

Hmm... specifing the absolute current path using $(pwd) worked for me.

git clone https://github.com/me/myproject.git $(pwd)

git version: 2.21.0

add an onclick event to a div

Assign the onclick like this:

divTag.onclick = printWorking;

The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>, but this is generally not recommended.

Getting Class type from String

It should be:

Class.forName(String classname)

Remove a character at a certain position in a string - javascript

var str = 'Hello World',
    i = 3,
    result = str.substr(0, i-1)+str.substring(i);

alert(result);

Value of i should not be less then 1.

bundle install returns "Could not locate Gemfile"

You just need to change directories to your app, THEN run bundle install :)

SQL Count for each date

I had similar question however mine involved a column Convert(date,mydatetime). I had to alter the best answer as follows:

Select
     count(created_date) as counted_leads,
     Convert(date,created_date) as count_date 
from table
group by Convert(date,created_date)

Equals(=) vs. LIKE

Besides the wildcards, the difference between = AND LIKE will depend on both the kind of SQL server and on the column type.

Take this example:

CREATE TABLE testtable (
  varchar_name VARCHAR(10),
  char_name CHAR(10),
  val INTEGER
);

INSERT INTO testtable(varchar_name, char_name, val)
    VALUES ('A', 'A', 10), ('B', 'B', 20);

SELECT 'VarChar Eq Without Space', val FROM testtable WHERE varchar_name='A'
UNION ALL
SELECT 'VarChar Eq With Space', val FROM testtable WHERE varchar_name='A '
UNION ALL
SELECT 'VarChar Like Without Space', val FROM testtable WHERE varchar_name LIKE 'A'
UNION ALL
SELECT 'VarChar Like Space', val FROM testtable WHERE varchar_name LIKE 'A '
UNION ALL
SELECT 'Char Eq Without Space', val FROM testtable WHERE char_name='A'
UNION ALL
SELECT 'Char Eq With Space', val FROM testtable WHERE char_name='A '
UNION ALL
SELECT 'Char Like Without Space', val FROM testtable WHERE char_name LIKE 'A'
UNION ALL
SELECT 'Char Like With Space', val FROM testtable WHERE char_name LIKE 'A '
  • Using MS SQL Server 2012, the trailing spaces will be ignored in the comparison, except with LIKE when the column type is VARCHAR.

  • Using MySQL 5.5, the trailing spaces will be ignored for =, but not for LIKE, both with CHAR and VARCHAR.

  • Using PostgreSQL 9.1, spaces are significant with both = and LIKE using VARCHAR, but not with CHAR (see documentation).

    The behaviour with LIKE also differs with CHAR.

    Using the same data as above, using an explicit CAST on the column name also makes a difference:

    SELECT 'CAST none', val FROM testtable WHERE char_name LIKE 'A'
    UNION ALL
    SELECT 'CAST both', val FROM testtable WHERE
        CAST(char_name AS CHAR) LIKE CAST('A' AS CHAR)
    UNION ALL
    SELECT 'CAST col', val FROM testtable WHERE CAST(char_name AS CHAR) LIKE 'A'
    UNION ALL
    SELECT 'CAST value', val FROM testtable WHERE char_name LIKE CAST('A' AS CHAR)
    

    This only returns rows for "CAST both" and "CAST col".

How to filter array when object key value is in array

You can do it with Array.prototype.filter(),

var data = { records : [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] }
var empIds = [1,4,5]
var filteredArray = data.records.filter(function(itm){
  return empIds.indexOf(itm.empid) > -1;
});

filteredArray = { records : filteredArray };

If? the ?callBack? returns a ?true? value, then the ?itm? passed to that particular callBack will be filtered out. You can read more about it here.??????

How can I enable CORS on Django REST Framework

The link you referenced in your question recommends using django-cors-headers, whose documentation says to install the library

pip install django-cors-headers

and then add it to your installed apps:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
)

Please browse the configuration section of its documentation, paying particular attention to the various CORS_ORIGIN_ settings. You'll need to set some of those based on your needs.

What's the default password of mariadb on fedora?

The default password is empty. More accurately, you don't even NEED a password to login as root on the localhost. You just need to BE root. But if you need to set the password the first time (if you allow remote access to root), you need to use:

sudo mysql_secure_installation

Enter empty password, then follow the instructions.

The problem you are having is that you need to BE root when you try to login as root from the local machine.

On Linux: mariadb will accept a connection as root on the socket (localhost) ONLY IF THE USER ASKING IT IS ROOT. Which means that even if you try

mysql -u root -p

And have the correct password you will be refused access. Same goes for

mysql_secure_installation

Mariadb will always refuse the password because the current user is not root. So you need to call them with sudo (or as the root user on your machine) So locally you just want to use:

sudo mysql

and

sudo mysql_secure_installation

When moving from mysql to mariadb it took I will for me to figure this out.

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

How can I use Bash syntax in Makefile targets?

There is a way to do this without explicitly setting your SHELL variable to point to bash. This can be useful if you have many makefiles since SHELL isn't inherited by subsequent makefiles or taken from the environment. You also need to be sure that anyone who compiles your code configures their system this way.

If you run sudo dpkg-reconfigure dash and answer 'no' to the prompt, your system will not use dash as the default shell. It will then point to bash (at least in Ubuntu). Note that using dash as your system shell is a bit more efficient though.

How can I let a user download multiple files when a button is clicked?

The best way to do this is to have your files zipped and link to that:

The other solution can be found here: How to make a link open multiple pages when clicked

Which states the following:

HTML:

<a href="#" class="yourlink">Download</a>

JS:

$('a.yourlink').click(function(e) {
    e.preventDefault();
    window.open('mysite.com/file1');
    window.open('mysite.com/file2');
    window.open('mysite.com/file3');
});

Having said this, I would still go with zipping the file, as this implementation requires JavaScript and can also sometimes be blocked as popups.

How to overcome root domain CNAME restrictions?

You have to put a period at the end of the external domain so it doesn't think you mean customer1.mycompanydomain.com.localdomain;

So just change:

customer1.com IN CNAME customer1.mycompanydomain.com

To

customer1.com IN CNAME customer1.mycompanydomain.com.

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I had the same issue after upgrading my system. In my case, the problem was caused by the order of loading configuration files. In the /etc/httpd/httpd.confinitally it was defined as follows:

IncludeOptional conf.d/*.conf
IncludeOptional sites-enabled/*.conf

After some hours of attempts, I tried the following order:

IncludeOptional sites-enabled/*.conf
IncludeOptional conf.d/*.conf

And it works fine now.

What does template <unsigned int N> mean?

It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:

unsigned int x = N;

In fact, we can create algorithms which evaluate at compile time (from Wikipedia):

template <int N>
struct Factorial 
{
     enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

push_back vs emplace_back

One more example for lists:

// constructs the elements in place.                                                
emplace_back("element");

// creates a new object and then copies (or moves) that object.
push_back(ExplicitDataType{"element"});

How do I force a DIV block to extend to the bottom of a page even if it has no content?

you can kinda hack it with the min-height declaration

<div style="min-height: 100%">stuff</div>

SQL, Postgres OIDs, What are they and why are they useful?

OID's are still in use for Postgres with large objects (though some people would argue large objects are not generally useful anyway). They are also used extensively by system tables. They are used for instance by TOAST which stores larger than 8KB BYTEA's (etc.) off to a separate storage area (transparently) which is used by default by all tables. Their direct use associated with "normal" user tables is basically deprecated.

The oid type is currently implemented as an unsigned four-byte integer. Therefore, it is not large enough to provide database-wide uniqueness in large databases, or even in large individual tables. So, using a user-created table's OID column as a primary key is discouraged. OIDs are best used only for references to system tables.

Apparently the OID sequence "does" wrap if it exceeds 4B 6. So in essence it's a global counter that can wrap. If it does wrap, some slowdown may start occurring when it's used and "searched" for unique values, etc.

See also https://wiki.postgresql.org/wiki/FAQ#What_is_an_OID.3F

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

The usual rules should apply for how you send the request. If the request is to retrieve information (e.g. a partial search 'hint' result, or a new page to be displayed, etc...) you can use GET. If the data being sent is part of a request to change something (update a database, delete a record, etc..) then use POST.

Server-side, there's no reason to use the raw input, unless you want to grab the entire post/get data block in a single go. You can retrieve the specific information you want via the _GET/_POST arrays as usual. AJAX libraries such as MooTools/jQuery will handle the hard part of doing the actual AJAX calls and encoding form data into appropriate formats for you.

Is there a way to take the first 1000 rows of a Spark Dataframe?

Limit is very simple, example limit first 50 rows

val df_subset = data.limit(50)

How to both read and write a file in C#

Don't forget the easy route:

    static void Main(string[] args)
    {
        var text = File.ReadAllText(@"C:\words.txt");
        File.WriteAllText(@"C:\words.txt", text + "DERP");
    }

Why doesn't height: 100% work to expand divs to the screen height?

This may not be ideal but you can allways do it with javascript. Or in my case jQuery

<script>
var newheight = $('.innerdiv').css('height');
$('.mainwrapper').css('height', newheight);
</script>

How to differentiate single click event and double click event?

This answer is made obsolete through time, check @kyw's solution.

I created a solution inspired by the gist posted by @AdrienSchuler. Use this solution only when you want to bind a single click AND a double click to an element. Otherwise I recommend using the native click and dblclick listeners.

These are the differences:

  • Vanillajs, No dependencies
  • Don't wait on the setTimeout to handle the click or doubleclick handler
  • When double clicking it first fires the click handler, then the doubleclick handler

Javascript:

function makeDoubleClick(doubleClickCallback, singleClickCallback) {
    var clicks = 0, timeout;
    return function() {
        clicks++;
        if (clicks == 1) {
            singleClickCallback && singleClickCallback.apply(this, arguments);
            timeout = setTimeout(function() { clicks = 0; }, 400);
        } else {
            timeout && clearTimeout(timeout);
            doubleClickCallback && doubleClickCallback.apply(this, arguments);
            clicks = 0;
        }
    };
}

Usage:

var singleClick = function(){ console.log('single click') };
var doubleClick = function(){ console.log('double click') };
element.addEventListener('click', makeDoubleClick(doubleClick, singleClick));

Below is the usage in a jsfiddle, the jQuery button is the behavior of the accepted answer.

jsfiddle

Set line spacing

Yup, as everyone's saying, line-height is the thing. Any font you are using, a mid-height character (such as a or ¦, not going through the upper or lower) should go with the same height-length at line-height: 0.6 to 0.65.

_x000D_
_x000D_
<div style="line-height: 0.65; font-family: 'Fira Code', monospace, sans-serif">_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa_x000D_
</div>_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div style="line-height: 0.6; font-family: 'Fira Code', monospace, sans-serif">_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦_x000D_
</div>_x000D_
<br>_x000D_
<br>_x000D_
<strong>BUT</strong>_x000D_
<br>_x000D_
<br>_x000D_
<div style="line-height: 0.65; font-family: 'Fira Code', monospace, sans-serif">_x000D_
ddd<br>_x000D_
ƒƒƒ<br>_x000D_
ggg_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to handle checkboxes in ASP.NET MVC forms?

How about something like this?

bool isChecked = false;
if (Boolean.TryParse(Request.Form.GetValues(”chkHuman”)[0], out isChecked) == false)
    ModelState.AddModelError(”chkHuman”, “Nice try.”);

Fundamental difference between Hashing and Encryption algorithms

Basic overview of hashing and encryption/decryption techniques are.

Hashing:

If you hash any plain text again you can not get the same plain text from hashed text. Simply, It's a one-way process.

hashing


Encryption and Decryption:

If you encrypt any plain text with a key again you can get same plain text by doing decryption on encrypted text with same(symetric)/diffrent(asymentric) key.

encryption and decryption


UPDATE: To address the points mentioned in the edited question.

1. When to use hashes vs encryptions

Hashing is useful if you want to send someone a file. But you are afraid that someone else might intercept the file and change it. So a way that the recipient can make sure that it is the right file is if you post the hash value publicly. That way the recipient can compute the hash value of the file received and check that it matches the hash value.

Encryption is good if you say have a message to send to someone. You encrypt the message with a key and the recipient decrypts with the same (or maybe even a different) key to get back the original message. credits


2. What makes a hash or encryption algorithm different (from a theoretical/mathematical level) i.e. what makes hashes irreversible (without aid of a rainbow tree)

Basically hashing is an operation that loses information but not encryption. Let's look at the difference in simple mathematical way for our easy understanding, of course both have much more complicated mathematical operation with repetitions involved in it

Encryption/Decryption (Reversible):


Addition:

4 + 3 = 7  

This can be reversed by taking the sum and subtracting one of the addends

7 - 3 = 4     

Multiplication:

4 * 5 = 20  

This can be reversed by taking the product and dividing by one of the factors

20 / 4 = 5    

So, here we could assume one of the addends/factors is a decrpytion key and result(7,20) is an excrypted text.


Hashing (Not Reversible):


Modulo division:

22 % 7 = 1   

This can not be reversed because there is no operation that you can do to the quotient and the dividend to reconstitute the divisor (or vice versa).

Can you find an operation to fill in where the '?' is?

1  ?  7 = 22  
1  ?  22 = 7

So hash functions have the same mathematical quality as modulo division and looses the information.

credits

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

I was facing same problem.

When I rightclick-> run on server then select my server manually it worked.

Do

Alt+Shift+X

then mannually select your server. It might help.

How to get body of a POST in php?

If you have the pecl/http extension installed, you can also use this:

$request = new http\Env\Request();
$request->getBody();

How to create a new component in Angular 4 using CLI

cd to your project and run,

> ng generate component "componentname"
ex: ng generate component shopping-cart

OR

> ng g c shopping-cart

(This will create new folder under "app" folder with name "shopping-cart" and create .html,.ts, .css. specs files.)

If you do not want to generate .spec file

> ng g c shopping-cart --skipTests true

If you want to create component in any specific folder under "app"

> ng g c ecommerce/shopping-cart

(you will get folder structure "app/ecommerce/shopping-cart")

Correct way to set Bearer token with CURL

<?php
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "your api goes here",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer eyJ0eciOiJSUzI1NiJ9.eyJMiIsInNjb3BlcyI6W119.K3lW1STQhMdxfAxn00E4WWFA3uN3iIA"
  ),
 ));

$response = curl_exec($curl);
$data = json_decode($response, true);

echo $data;

?>

Flattening a shallow list in Python

If you have to flat a more complicated list with not iterable elements or with depth more than 2 you can use following function:

def flat_list(list_to_flat):
    if not isinstance(list_to_flat, list):
        yield list_to_flat
    else:
        for item in list_to_flat:
            yield from flat_list(item)

It will return a generator object which you can convert to a list with list() function. Notice that yield from syntax is available starting from python3.3, but you can use explicit iteration instead.
Example:

>>> a = [1, [2, 3], [1, [2, 3, [1, [2, 3]]]]]
>>> print(list(flat_list(a)))
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Autoplay an audio with HTML5 embed tag while the player is invisible

You can use this simple code:

<embed src="audio.mp3" AutoPlay loop hidden>

for the result seen here: https://hataken.000webhostapp.com/list-anime.html

How to search a specific value in all tables (PostgreSQL)?

to search every column of every table for a particular value

This does not define how to match exactly.
Nor does it define what to return exactly.

Assuming:

  • Find any row with any column containing the given value in its text representation - as opposed to equaling the given value.
  • Return the table name (regclass) and the tuple ID (ctid), because that's simplest.

Here is a dead simple, fast and slightly dirty way:

CREATE OR REPLACE FUNCTION search_whole_db(_like_pattern text)
  RETURNS TABLE(_tbl regclass, _ctid tid) AS
$func$
BEGIN
   FOR _tbl IN
      SELECT c.oid::regclass
      FROM   pg_class c
      JOIN   pg_namespace n ON n.oid = relnamespace
      WHERE  c.relkind = 'r'                           -- only tables
      AND    n.nspname !~ '^(pg_|information_schema)'  -- exclude system schemas
      ORDER BY n.nspname, c.relname
   LOOP
      RETURN QUERY EXECUTE format(
         'SELECT $1, ctid FROM %s t WHERE t::text ~~ %L'
       , _tbl, '%' || _like_pattern || '%')
      USING _tbl;
   END LOOP;
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM search_whole_db('mypattern');

Provide the search pattern without enclosing %.

Why slightly dirty?

If separators and decorators for the row in text representation can be part of the search pattern, there can be false positives:

  • column separator: , by default
  • whole row is enclosed in parentheses:()
  • some values are enclosed in double quotes "
  • \ may be added as escape char

And the text representation of some columns may depend on local settings - but that ambiguity is inherent to the question, not to my solution.

Each qualifying row is returned once only, even when it matches multiple times (as opposed to other answers here).

This searches the whole DB except for system catalogs. Will typically take a long time to finish. You might want to restrict to certain schemas / tables (or even columns) like demonstrated in other answers. Or add notices and a progress indicator, also demonstrated in another answer.

The regclass object identifier type is represented as table name, schema-qualified where necessary to disambiguate according to the current search_path:

What is the ctid?

You might want to escape characters with special meaning in the search pattern. See:

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

I think you could have used:
value.ToString("F"+NumberOfDecimals)

value = 10,502
value.ToString("F2") //10,50
value = 10,5 
value.ToString("F2") //10,50

Here is a detailed description of Numeric Format Strings

Is it possible to dynamically compile and execute C# code fragments?

You can compile a piece C# of code into memory and generate assembly bytes with Roslyn. It's already mentioned but would be worth adding some Roslyn example for this here. The following is the complete example:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;

namespace RoslynCompileSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // define source code, then parse it (to the type used for compilation)
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
                using System;

                namespace RoslynCompileSample
                {
                    public class Writer
                    {
                        public void Write(string message)
                        {
                            Console.WriteLine(message);
                        }
                    }
                }");

            // define other necessary objects for compilation
            string assemblyName = Path.GetRandomFileName();
            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
            };

            // analyse and generate IL code from syntax tree
            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                // write IL code into memory
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    // handle exceptions
                    IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic => 
                        diagnostic.IsWarningAsError || 
                        diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in failures)
                    {
                        Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                    }
                }
                else
                {
                    // load this 'virtual' DLL so that we can use
                    ms.Seek(0, SeekOrigin.Begin);
                    Assembly assembly = Assembly.Load(ms.ToArray());

                    // create instance of the desired class and call the desired function
                    Type type = assembly.GetType("RoslynCompileSample.Writer");
                    object obj = Activator.CreateInstance(type);
                    type.InvokeMember("Write",
                        BindingFlags.Default | BindingFlags.InvokeMethod,
                        null,
                        obj,
                        new object[] { "Hello World" });
                }
            }

            Console.ReadLine();
        }
    }
}

MySQL JOIN the most recent row only?

You can also do this

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
LEFT JOIN  (
              SELECT * FROM  customer_data ORDER BY id DESC
          ) customer_data ON (customer_data.customer_id = c.customer_id)
GROUP BY  c.customer_id          
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

Error Code: 1005. Can't create table '...' (errno: 150)

MyISAM has been just mentioned. Simply try adding ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; at the end of a statement, assuming that your other tables were created with MyISAM.

CREATE TABLE IF NOT EXISTS `tablename` (
  `key` bigint(20) NOT NULL AUTO_INCREMENT,
  FOREIGN KEY `key` (`key`) REFERENCES `othertable`(`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Restart container within pod

The whole reason for having kubernetes is so it manages the containers for you so you don't have to care so much about the lifecyle of the containers in the pod.

Since you have a deployment setup that uses replica set. You can delete the pod using kubectl delete pod test-1495806908-xn5jn and kubernetes will manage the creation of a new pod with the 2 containers without any downtime. Trying to manually restart single containers in pods negates the whole benefits of kubernetes.

vim - How to delete a large block of text without counting the lines?

There are many better answers here, but for completeness I will mention the method I used to use before reading some of the great answers mentioned above.

Suppose you want to delete from lines 24-39. You can use the ex command

:24,39d

You can also yank lines using

:24,39y

And find and replace just over lines 24-39 using

:24,39s/find/replace/g

Convert JS Object to form data

If you have an object, you can easily create a FormData object and append the names and values from that object to formData.

You haven't posted any code, so it's a general example;

var form_data = new FormData();

for ( var key in item ) {
    form_data.append(key, item[key]);
}

$.ajax({
    url         : 'http://example.com/upload.php',
    data        : form_data,
    processData : false,
    contentType : false,
    type: 'POST'
}).done(function(data){
    // do stuff
});

There are more examples in the documentation on MDN

Sort an array of objects in React and render them

Try lodash sortBy

import * as _ from "lodash";
_.sortBy(data.applications,"id").map(application => (
    console.log("application")
    )
)

Read more : lodash.sortBy

How to install CocoaPods?

You can install cocoapods via brew in mac os.

first, open your terminal,

run this code (for install homebrew if you have not):

     ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null

then install homebrew easily via this command:

brew install cocoapods

Android Studio was unable to find a valid Jvm (Related to MAC OS)

I ran this bad boy:

launchctl setenv STUDIO_JDK /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/

How to add an extra language input to Android?

Sliding the space bar only works if you gave more then one input language selected.

In that case the space bar will also indicate the selected language and show arrows to indicate Sliding will change selection.

This is easy fast and changes the dictionary at the same time.

First response seems the mist accurate.

Regards

getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

What I found is that if another app is dialog type and allows touches to be sent to background app then almost any background app will crash with this error. I think we need to check every time a transaction is performed if the instance was saved or restored.

When to use the different log levels

I've always considered warning the first log level that for sure means there is a problem (for example, perhaps a config file isn't where it should be and we're going to have to run with default settings). An error implies, to me, something that means the main goal of the software is now impossible and we're going to try to shut down cleanly.

How can I access an internal class from an external assembly?

Well, you can't. Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.

What are good grep tools for Windows?

dnGREP is an open source grep tool for Windows. It supports a number of cool features including:

  • Undo for replace
  • Ability to search by right clicking on folder in explorer
  • Advance search options such as phonetic search and xpath
  • Search inside PDF files, archives, and Word documents

IMHO, it has a nice and clean interface too :)

Get GPS location from the web browser

Use this, and you will find all informations at http://www.w3schools.com/html/html5_geolocation.asp

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
}
</script>

unable to start mongodb local server

Don't kill the process using the -9 signal as it would cause damage: http://www.mongodb.org/display/DOCS/Starting+and+Stopping+Mongo#StartingandStoppingMongo-SendingaUnixINTorTERMsignal

Use sudo killall -15 mongod instead

Change color of Button when Mouse is over

As others already said, there seems to be no good solution to do that easily.
But to keep your code clean I suggest creating a seperate class that hides the ugly XAML.

How to use after we created the ButtonEx-class:

<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpfEx="clr-namespace:WpfExtensions"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <wpfEx:ButtonEx HoverBackground="Red"></wpfEx:ButtonEx>
    </Grid>
</Window>

ButtonEx.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WpfExtensions
{
    /// <summary>
    /// Standard button with extensions
    /// </summary>
    public partial class ButtonEx : Button
    {
        readonly static Brush DefaultHoverBackgroundValue = new BrushConverter().ConvertFromString("#FFBEE6FD") as Brush;

        public ButtonEx()
        {
            InitializeComponent();
        }

        public Brush HoverBackground
        {
            get { return (Brush)GetValue(HoverBackgroundProperty); }
            set { SetValue(HoverBackgroundProperty, value); }
        }
        public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.Register(
          "HoverBackground", typeof(Brush), typeof(ButtonEx), new PropertyMetadata(DefaultHoverBackgroundValue));
    }
}

ButtonEx.xaml
Note: This contains all the original XAML from System.Windows.Controls.Button

<Button x:Class="WpfExtensions.ButtonEx"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
            x:Name="buttonExtension">
    <Button.Resources>
        <Style x:Key="FocusVisual">
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="10" StrokeDashArray="1 2"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
        <SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
        <SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
        <SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
        <SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
        <SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
        <SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
        <SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
        <SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
    </Button.Resources>
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
            <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
            <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Padding" Value="1"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
                            <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsDefaulted" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter Property="Background" TargetName="border" Value="{Binding Path=HoverBackground, ElementName=buttonExtension}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
                            </Trigger>
                            <Trigger Property="IsPressed" Value="true">
                                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
                                <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

Tip: You can add an UserControl with name "ButtonEx" to your project in VS Studio and then copy paste the stuff above in.

AngularJS access scope from outside js function

<input type="text" class="form-control timepicker2" ng-model='programRow.StationAuxiliaryTime.ST88' />

accessing scope value

assume that programRow.StationAuxiliaryTime is an array of object

 $('.timepicker2').on('click', function () 
    {
            var currentElement = $(this);

            var scopeValues = angular.element(currentElement).scope();
            var model = currentElement.attr('ng-model');
            var stationNumber = model.split('.')[2];
            var val = '';
            if (model.indexOf("StationWaterTime") > 0) {
                val = scopeValues.programRow.StationWaterTime[stationNumber];
            }
            else {
                val = scopeValues.programRow.StationAuxiliaryTime[stationNumber];
            }
            currentElement.timepicker('setTime', val);
        });

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

Well I don't even understand the culprit of this problem. But in my case the problem is totally different. I've tried running netstat -o or netstat -ab, both show that there is not any app currently listening on port 62434 which is the one my app tries to listen on. So it's really confusing to me.

I just tried thinking of what I had made so that it stopped working (it did work before). Well then I thought of the Internet sharing I made on my Ethernet adapter with a private virtual LAN (using Hyper-v in Windows 10). I just needed to turn off the sharing and it worked just fine again.

Hope this helps someone else having the same issue. And of course if someone could explain this, please add more detail in your own answer or maybe as some comment to my answer.

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

Assuming that the mouse cursor should return to the document after window resize, we can create a callback-like behavior with onmouseover event. Don't forget that this solution may not work for touch-enabled screens as expected.

var resizeTimer;
var resized = false;
$(window).resize(function() {
   clearTimeout(resizeTimer);
   resizeTimer = setTimeout(function() {
       if(!resized) {
           resized = true;
           $(document).mouseover(function() {
               resized = false;
               // do something here
               $(this).unbind("mouseover");
           })
       }
    }, 500);
});

Casting interfaces for deserialization in JSON.NET

My solution was added the interface elements in the constructor.

public class Customer: ICustomer{
     public Customer(Details details){
          Details = details;
     }

     [JsonProperty("Details",NullValueHnadling = NullValueHandling.Ignore)]
     public IDetails Details {get; set;}
}

How can I indent multiple lines in Xcode?

Tab for Indent SHIFT + Tab Re-indent

Error in Eclipse: "The project cannot be built until build path errors are resolved"

  1. Right click your Project > Properties > Java Build Path > Libraries

  2. Remove the file with red "X" (something like JRE...)

  3. Add Library

That's how I solved my problem.

How to execute my SQL query in CodeIgniter

http://www.bsourcecode.com/codeigniter/codeigniter-select-query/

$query = $this->db->query("select * from tbl_user");

OR

$query = $this->db->select("*");
            $this->db->from('table_name');
            $query=$this->db->get();

CSS @font-face not working in ie

I have found if the font face declarations are inside a media query IE (both edge and 11) won't load them; they need to be the first thing declared in the stylesheet and not wrapped in a media query

How can I specify a local gem in my Gemfile?

If you want the branch too:

gem 'foo', path: "point/to/your/path", branch: "branch-name"

Strip Leading and Trailing Spaces From Java String

Use String#trim() method or String allRemoved = myString.replaceAll("^\\s+|\\s+$", "") for trim both the end.

For left trim:

String leftRemoved = myString.replaceAll("^\\s+", "");

For right trim:

String rightRemoved = myString.replaceAll("\\s+$", "");

How to animate CSS Translate

According to CanIUse you should have it with multiple prefixes.

$('div').css({
    "-webkit-transform":"translate(100px,100px)",
    "-ms-transform":"translate(100px,100px)",
    "transform":"translate(100px,100px)"
  });?

Uncaught SyntaxError: Unexpected token with JSON.parse

Why you need JSON.parse? It's already in array of object format.

Better use JSON.stringify as below : var b = JSON.stringify(products);

This may help you.

How to check if a line has one of the strings in a list?

strings = ("string1", "string2", "string3")
for line in file:
    if any(s in line for s in strings):
        print "yay!"

How to display loading message when an iFrame is loading?

You can use below code .

 iframe {background:url(../images/loader.gif) center center no-repeat; height: 100%;}

Unable to set default python version to python3 in ubuntu

To change to python3, you can use the following command in terminal alias python=python3.

C# event with custom arguments

I might be late in the game, but how about:

public event Action<MyEvent> EventTriggered = delegate { }; 

private void Trigger(MyEvent e) 
{ 
     EventTriggered(e);
} 

Setting the event to an anonymous delegate avoids for me to check to see if the event isn't null.

I find this comes in handy when using MVVM, like when using ICommand.CanExecute Method.

Difference between ${} and $() in Bash

  1. $() means: "first evaluate this, and then evaluate the rest of the line".

    Ex :

    echo $(pwd)/myFile.txt
    

    will be interpreted as

    echo /my/path/myFile.txt
    

    On the other hand ${} expands a variable.

    Ex:

    MY_VAR=toto
    echo ${MY_VAR}/myFile.txt
    

    will be interpreted as

    echo toto/myFile.txt
    
  2. Why can't I use it as bash$ while ((i=0;i<10;i++)); do echo $i; done

    I'm afraid the answer is just that the bash syntax for while just isn't the same as the syntax for for.

How to create a TextArea in Android

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="100dp">
<EditText
    android:id="@+id/question_input"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:ems="10"
    android:inputType="text|textMultiLine"
    android:lineSpacingExtra="5sp"
    android:padding="5dp"
    android:textAlignment="textEnd"
    android:typeface="normal" />

</android.support.v4.widget.NestedScrollView>

Find and replace words/lines in a file

public static void replaceFileString(String old, String new) throws IOException {
    String fileName = Settings.getValue("fileDirectory");
    FileInputStream fis = new FileInputStream(fileName);
    String content = IOUtils.toString(fis, Charset.defaultCharset());
    content = content.replaceAll(old, new);
    FileOutputStream fos = new FileOutputStream(fileName);
    IOUtils.write(content, new FileOutputStream(fileName), Charset.defaultCharset());
    fis.close();
    fos.close();
}

above is my implementation of Meriton's example that works for me. The fileName is the directory (ie. D:\utilities\settings.txt). I'm not sure what character set should be used, but I ran this code on a Windows XP machine just now and it did the trick without doing that temporary file creation and renaming stuff.

Flatten List in LINQ

Like this?

var iList = Method().SelectMany(n => n);

Save the console.log in Chrome to a file

On Linux (at least) you can set CHROME_LOG_FILE in the environment to have chrome write a log of the Console activity to the named file each time it runs. The log is overwritten every time chrome starts. This way, if you have an automated session that runs chrome, you don't have a to change the way chrome is started, and the log is there after the session ends.

export CHROME_LOG_FILE=chrome.log

How to get the unique ID of an object which overrides hashCode()?

System.identityHashCode(yourObject) will give the 'original' hash code of yourObject as an integer. Uniqueness isn't necessarily guaranteed. The Sun JVM implementation will give you a value which is related to the original memory address for this object, but that's an implementation detail and you shouldn't rely on it.

EDIT: Answer modified following Tom's comment below re. memory addresses and moving objects.

How to highlight text using javascript

Simple TypeScript example

NOTE: While I agree with @Stefan in many things, I only needed a simple match highlighting:

module myApp.Search {
    'use strict';

    export class Utils {
        private static regexFlags = 'gi';
        private static wrapper = 'mark';

        private static wrap(match: string): string {
            return '<' + Utils.wrapper + '>' + match + '</' + Utils.wrapper + '>';
        }

        static highlightSearchTerm(term: string, searchResult: string): string {
            let regex = new RegExp(term, Utils.regexFlags);

            return searchResult.replace(regex, match => Utils.wrap(match));
        }
    }
}

And then constructing the actual result:

module myApp.Search {
    'use strict';

    export class SearchResult {
        id: string;
        title: string;

        constructor(result, term?: string) {
            this.id = result.id;
            this.title = term ? Utils.highlightSearchTerm(term, result.title) : result.title;
        }
    }
}

How do I exit a WPF application programmatically?

To exit your application you can call

System.Windows.Application.Current.Shutdown();

As described in the documentation to the Application.Shutdown method you can also modify the shutdown behavior of your application by specifying a ShutdownMode:

Shutdown is implicitly called by Windows Presentation Foundation (WPF) in the following situations:

  • When ShutdownMode is set to OnLastWindowClose.
  • When the ShutdownMode is set to OnMainWindowClose.
  • When a user ends a session and the SessionEnding event is either unhandled, or handled without cancellation.

Please also note that Application.Current.Shutdown(); may only be called from the thread that created the Application object, i.e. normally the main thread.

"Undefined reference to" template class constructor

This link explains where you're going wrong:

[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?

Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.

This offers another solution:

How can I avoid linker errors with my template functions?

However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.

Laravel stylesheets and javascript don't load for non-base routes

Better way to use like,

<link rel="stylesheet" href="{{asset('assets/libraries/css/app.css')}}">

How to animate RecyclerView items when they appear

A good place to start is this: https://github.com/wasabeef/recyclerview-animators/blob/master/animators/src/main/java/jp/wasabeef/recyclerview/adapters/AnimationAdapter.java

You don't even need the full library, that class is enough. Then if you just implement your Adapter class giving an animator like this:

@Override
protected Animator[] getAnimators(View view) {
    return new Animator[]{
            ObjectAnimator.ofFloat(view, "translationY", view.getMeasuredHeight(), 0)
    };
}

@Override
public long getItemId(final int position) {
    return getWrappedAdapter().getItemId(position);
}

you'll see items appearing from the bottom as they scroll, also avoiding the problem with the fast scroll.

phonegap open link in browser

Like this :

<a href="#" onclick="window.open('https://www.nbatou.com', '_system'); return false;">https://www.nbatou.com</a>

How to change workspace and build record Root Directory on Jenkins?

I would suggest editing the /etc/default/jenkins

vi /etc/default/jenkins

And changing the $JENKINS_HOME variable (around line 23) to

JENKINS_HOME=/home/jenkins

Then restart the Jenkins with usual

/etc/init.d/jenkins start

Cheers!

Android: Access child views from a ListView

A quick search of the docs for the ListView class has turned up getChildCount() and getChildAt() methods inherited from ViewGroup. Can you iterate through them using these? I'm not sure but it's worth a try.

Found it here

How to get the URL without any parameters in JavaScript?

You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]

Check if a value is within a range of numbers

You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple if" statements to do it, either:

if (x >= 0.001 && x <= 0.009) {
  // something
}

You could write yourself a "between()" function:

function between(x, min, max) {
  return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
  // something
}

Python POST binary data

You can use unirest, It provides easy method to post request. `

import unirest
 
def callback(response):
 print "code:"+ str(response.code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "body:"+ str(response.body)
 print "******************"
 print "raw_body:"+ str(response.raw_body)
 
# consume async post request
def consumePOSTRequestASync():
 params = {'test1':'param1','test2':'param2'}
 
 # we need to pass a dummy variable which is open method
 # actually unirest does not provide variable to shift between
 # application-x-www-form-urlencoded and
 # multipart/form-data
  
 params['dummy'] = open('dummy.txt', 'r')
 url = 'http://httpbin.org/post'
 headers = {"Accept": "application/json"}
 # call get service with headers and params
 unirest.post(url, headers = headers,params = params, callback = callback)
 
 
# post async request multipart/form-data
consumePOSTRequestASync()

Calling Java from Python

Here is my summary of this problem: 5 Ways of Calling Java from Python

http://baojie.org/blog/2014/06/16/call-java-from-python/ (cached)

Short answer: Jpype works pretty well and is proven in many projects (such as python-boilerpipe), but Pyjnius is faster and simpler than JPype

I have tried Pyjnius/Jnius, JCC, javabridge, Jpype and Py4j.

Py4j is a bit hard to use, as you need to start a gateway, adding another layer of fragility.

Configure hibernate to connect to database via JNDI Datasource

I was getting the same error in my IBM Websphere with c3p0 jar files. I have Oracle 10g database. I simply added the oraclejdbc.jar files in the Application server JVM in IBM Classpath using Websphere Console and the error was resolved.

The oraclejdbc.jar should be set with your C3P0 jar files in your Server Class path whatever it be tomcat, glassfish of IBM.

How to use EditText onTextChanged event when I press the number?

In Kotlin Android EditText listener is set using,

   val searchTo : EditText = findViewById(R.id.searchTo)
   searchTo.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable) {

        // you can call or do what you want with your EditText here

        // yourEditText...
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})

Base64 encoding and decoding in client-side Javascript

I have tried the Javascript routines at phpjs.org and they have worked well.

I first tried the routines suggested in the chosen answer by Ranhiru Cooray - http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html

I found that they did not work in all circumstances. I wrote up a test case where these routines fail and posted them to GitHub at:

https://github.com/scottcarter/base64_javascript_test_data.git

I also posted a comment to the blog post at ntt.cc to alert the author (awaiting moderation - the article is old so not sure if comment will get posted).

Linux command for extracting war file?

Or

jar xvf myproject.war

How to display a Yes/No dialog box on Android?

AlertDialog.Builder altBx = new AlertDialog.Builder(this);
    altBx.setTitle("My dialog box");
    altBx.setMessage("Welcome, Please Enter your name");
    altBx.setIcon(R.drawable.logo);

    altBx.setPositiveButton("Ok", new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface dialog, int which)
      {
          if(edt.getText().toString().length()!=0)
          {
              // Show any message
          }
          else 
          {

          }
      }
    });
    altBx.setNeutralButton("Cancel", new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface dialog, int which)
      {
          //show any message
      }

    });
  altBx.show();  

Xcode 10: A valid provisioning profile for this executable was not found

Check if you're using an Ad Hoc Distribution provisioning profile and not an App Store Distribution provisioning profile instead, I was getting this error because of that.

How do I install chkconfig on Ubuntu?

sysv-rc-conf is an alternate option for Ubuntu.

sudo apt-get install sysv-rc-conf

sysv-rc-conf --list xxxx

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Here is my attempt:

Function RegParse(ByVal pattern As String, ByVal html As String)
    Dim regex   As RegExp
    Set regex = New RegExp

    With regex
        .IgnoreCase = True  'ignoring cases while regex engine performs the search.
        .pattern = pattern  'declaring regex pattern.
        .Global = False     'restricting regex to find only first match.

        If .Test(html) Then         'Testing if the pattern matches or not
            mStr = .Execute(html)(0)        '.Execute(html)(0) will provide the String which matches with Regex
            RegParse = .Replace(mStr, "$1") '.Replace function will replace the String with whatever is in the first set of braces - $1.
        Else
            RegParse = "#N/A"
        End If

    End With
End Function

Update a column in MySQL

This is what I did for bulk update:

UPDATE tableName SET isDeleted = 1 where columnName in ('430903GW4j683537882','430903GW4j667075431','430903GW4j658444015')

When creating a service with sc.exe how to pass in context parameters?

I had issues getting this to work on Windows 7. It seemed to ignore the first argument I passed in so I used binPath= "C:\path\to\service.exe -bogusarg -realarg1 -realarg2" and it worked.

Difference between const reference and normal parameter

The important difference is that when passing by const reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in.

Because the reference is a const reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.

There are crucial differences. If the parameter is a const reference, but the object passed it was not in fact const then the value of the object may be changed during the function call itself.

E.g.

int a;

void DoWork(const int &n)
{
    a = n * 2;  // If n was a reference to a, n will have been doubled 

    f();  // Might change the value of whatever n refers to 
}

int main()
{
    DoWork(a);
}

Also if the object passed in was not actually const then the function could (even if it is ill advised) change its value with a cast.

e.g.

void DoWork(const int &n)
{
    const_cast<int&>(n) = 22;
}

This would cause undefined behaviour if the object passed in was actually const.

When the parameter is passed by const reference, extra costs include dereferencing, worse object locality, fewer opportunities for compile optimizing.

When the parameter is passed by value and extra cost is the need to create a parameter copy. Typically this is only of concern when the object type is large.

Xcode/Simulator: How to run older iOS version?

If you have iAds in your binary you will not be able to run it on anything before iOS 4.0 and it will be rejected if you try and submit a binary like this.

You can still run the simulator from 3.2 onwards after upgrading.

In the iPhone Simulator try selecting Hardware -> Version -> 3.2

Using a PHP variable in a text input value = statement

I have been doing PHP for my project, and I can say that the following code works for me. You should try it.

echo '<input type = "text" value = '.$idtest.'>'; 

Gradients in Internet Explorer 9

I understand that IE9 still won't be supporting CSS gradients. Which is a shame, because it's supporting loads of other great new stuff.

You might want to look into CSS3Pie as a way of getting all versions of IE to support various CSS3 features (including gradients, but also border-radius and box-shadow) with the minimum of fuss.

I believe CSS3Pie works with IE9 (I've tried it on the pre-release versions, but not yet on the current beta).

SQL Server : Arithmetic overflow error converting expression to data type int

SELECT                          
    DATEPART(YEAR, dateTimeStamp) AS [Year]                         
    , DATEPART(MONTH, dateTimeStamp) AS [Month]                         
    , COUNT(*) AS NumStreams                        
    , [platform] AS [Platform]                      
    , deliverableName AS [Deliverable Name]                     
    , SUM(billableDuration) AS NumSecondsDelivered

Assuming that your quoted text is the exact text, one of these columns can't do the mathematical calculations that you want. Double click on the error and it will highlight the line that's causing the problems (if it's different than what's posted, it may not be up there); I tested your code with the variables and there was no problem, meaning that one of these columns (which we don't know more specific information about) is creating this error.

One of your expressions needs to be casted/converted to an int in order for this to go through, which is the meaning of Arithmetic overflow error converting expression to data type int.

Change color inside strings.xml

Try this

For red color,

<string name="hello_worldRed"><![CDATA[<b><font color=#FF0000>Hello world!</font></b>]]></string>

For blue,

<string name="hello_worldBlue"><![CDATA[<b><font color=#0000FF>Hello world!</font></b>]]></string>

In java code,

//red color text
TextView redColorTextView = (TextView)findViewById(R.id.redText);
String redString = getResources().getString(R.string.hello_worldRed)
redColorTextView.setText(Html.fromHtml(redString));

//Blue color text
TextView blueColorTextView = (TextView)findViewById(R.id.blueText);
String blueString = getResources().getString(R.string.hello_worldBlue)
blueColorTextView.setText(Html.fromHtml(blueString));

get all keys set in memcached

Bash

To get list of keys in Bash, follow the these steps.

First, define the following wrapper function to make it simple to use (copy and paste into shell):

function memcmd() {
  exec {memcache}<>/dev/tcp/localhost/11211
  printf "%s\n%s\n" "$*" quit >&${memcache}
  cat <&${memcache}
}

Memcached 1.4.31 and above

You can use lru_crawler metadump all command to dump (most of) the metadata for (all of) the items in the cache.

As opposed to cachedump, it does not cause severe performance problems and has no limits on the amount of keys that can be dumped.

Example command by using the previously defined function:

memcmd lru_crawler metadump all

See: ReleaseNotes1431.


Memcached 1.4.30 and below

Get list of slabs by using items statistics command, e.g.:

memcmd stats items

For each slub class, you can get list of items by specifying slub id along with limit number (0 - unlimited):

memcmd stats cachedump 1 0
memcmd stats cachedump 2 0
memcmd stats cachedump 3 0
memcmd stats cachedump 4 0
...

Note: You need to do this for each memcached server.

To list all the keys from all stubs, here is the one-liner (per one server):

for id in $(memcmd stats items | grep -o ":[0-9]\+:" | tr -d : | sort -nu); do
    memcmd stats cachedump $id 0
done

Note: The above command could cause severe performance problems while accessing the items, so it's not advised to run on live.


Notes:

stats cachedump only dumps the HOT_LRU (IIRC?), which is managed by a background thread as activity happens. This means under a new enough version which the 2Q algo enabled, you'll get snapshot views of what's in just one of the LRU's.

If you want to view everything, lru_crawler metadump 1 (or lru_crawler metadump all) is the new mostly-officially-supported method that will asynchronously dump as many keys as you want. you'll get them out of order but it hits all LRU's, and unless you're deleting/replacing items multiple runs should yield the same results.

Source: GH-405.


Related:

Change working directory in my current shell context when running Node script

There is no built-in method for Node to change the CWD of the underlying shell running the Node process.

You can change the current working directory of the Node process through the command process.chdir().

var process = require('process');
process.chdir('../');

When the Node process exists, you will find yourself back in the CWD you started the process in.

window.open target _self v window.location.href?

Definitely the second method is preferred because you don't have the overhead of another function invocation:

window.location.href = "webpage.htm";

Get checkbox values using checkbox name using jquery

$("input[name='bla[]']").each( function () {
    alert($(this).val());
});

Using Mockito to mock classes with generic parameters

Create a test utility method. Specially useful if you need it for more than once.

@Test
public void testMyTest() {
    // ...
    Foo<Bar> mockFooBar = mockFoo();
    when(mockFooBar.getValue).thenReturn(new Bar());

    Foo<Baz> mockFooBaz = mockFoo();
    when(mockFooBaz.getValue).thenReturn(new Baz());

    Foo<Qux> mockFooQux = mockFoo();
    when(mockFooQux.getValue).thenReturn(new Qux());
    // ...
}

@SuppressWarnings("unchecked") // still needed :( but just once :)
private <T> Foo<T> mockFoo() {
    return mock(Foo.class);
}

Display HTML snippets in HTML

The deprecated <xmp> tag essentially does that but is no longer part of the XHTML spec. It should still work though in all current browsers.

Here's another idea, a hack/parlor trick, you could put the code in a textarea like so:

<textarea disabled="true" style="border: none;background-color:white;">
    <p>test</p>
</textarea>

Putting angle brackets and code like this inside a text area is invalid HTML and will cause undefined behavior in different browsers. In Internet Explorer the HTML is interpreted, whereas Mozilla, Chrome and Safari leave it uninterpreted.

If you want it to be non-editable and look different then you could easily style it using CSS. The only issue would be that browsers will add that little drag handle in the bottom-right corner to resize the box. Or alternatively, try using an input tag instead.

The right way to inject code into your textarea is to use server side language like this PHP for example:

<textarea disabled="true" style="border: none;background-color:white;">
    <?php echo '<p>test</p>'; ?>
</textarea>

Then it bypasses the html interpreter and puts uninterpreted text into the textarea consistently across all browsers.

Other than that, the only way is really to escape the code yourself if static HTML or using server-side methods such as .NET's HtmlEncode() if using such technology.

What does "<>" mean in Oracle

In mysql extended version, <> gives out error. You are using mysql_query Eventually, you have to use extended version of my mysql. Old will be replaced in future browser. Rather use something like

$con = mysqli_connect("host", "username", "password", "databaseName");

mysqli_query($con, "select orderid != 650");

Return 0 if field is null in MySQL

Yes IFNULL function will be working to achieve your desired result.

SELECT uo.order_id, uo.order_total, uo.order_status,
        (SELECT IFNULL(SUM(uop.price * uop.qty),0) 
         FROM uc_order_products uop 
         WHERE uo.order_id = uop.order_id
        ) AS products_subtotal,
        (SELECT IFNULL(SUM(upr.amount),0) 
         FROM uc_payment_receipts upr 
         WHERE uo.order_id = upr.order_id
        ) AS payment_received,
        (SELECT IFNULL(SUM(uoli.amount),0) 
         FROM uc_order_line_items uoli 
         WHERE uo.order_id = uoli.order_id
        ) AS line_item_subtotal
        FROM uc_orders uo
        WHERE uo.order_status NOT IN ("future", "canceled")
        AND uo.uid = 4172;

Corrupted Access .accdb file: "Unrecognized Database Format"

Well, I have tried something I hope it helps ..

They changed the schema a little bit ..

Use the following :

1- Change the AccessDataSource to SQLDataSource in the toolbox.

2- In the drop down menu choose your access database (xxxx.accdb or xxxx.mdb)

3- Next -> Next -> Test Query -> Finish.

Worked for me.

wait until all threads finish their work in java

Use this in your main thread: while(!executor.isTerminated()); Put this line of code after starting all the threads from executor service. This will only start the main thread after all the threads started by executors are finished. Make sure to call executor.shutdown(); before the above loop.

How to dismiss keyboard iOS programmatically when pressing return

//Hide keyBoard by touching background in view

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self view] endEditing:YES];
}

Programmatically get the version number of a DLL

You can use System.Reflection.Assembly.Load*() methods and then grab their AssemblyInfo.

HTML character codes for this ? or this ?

I usually use the excellent Gucharmap to look up Unicode characters. It's installed on all recent Linux installations with Gnome under the name "Character Map". I don't know of any equivalent tools for Windows or Mac OS X, but its homepage lists a few.

How to use JavaScript variables in jQuery selectors?

var name = this.name;
$("input[name=" + name + "]").hide();

OR you can do something like this.

var id = this.id;
$('#' + id).hide();

OR you can give some effect also.

$("#" + this.id).slideUp();

If you want to remove the entire element permanently form the page.

$("#" + this.id).remove();

You can also use it in this also.

$("#" + this.id).slideUp('slow', function (){
    $("#" + this.id).remove();
});

How to cache data in a MVC application

Reference the System.Web dll in your model and use System.Web.Caching.Cache

    public string[] GetNames()
    {
      string[] names = Cache["names"] as string[];
      if(names == null) //not in cache
      {
        names = DB.GetNames();
        Cache["names"] = names;
      }
      return names;
    }

A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout) Check it.

Fire event on enter key press for a textbox

You could wrap the textbox and button in an ASP:Panel, and set the DefaultButton property of the Panel to the Id of your Submit button.

<asp:Panel ID="Panel1" runat="server" DefaultButton="SubmitButton">
    <asp:TextBox ID="TextBox1" runat="server" />
    <asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
</asp:Panel>

Now anytime the focus is within the Panel, the 'SubmitButton_Click' event will fire when enter is pressed.

git: can't push (unpacker error) related to permission issues

For the permission error using git repository on AWS instance, I successfully solved it by creating a group, and assigning it to the repository folder recursively(-R), and give the written right to this group, and then assign the default aws instance user(ec2-user or ubuntu) to this group.

1. Create a goup name share_group or something else

     sudo groupadd share_group

2. change the repository folder from 'root' group to 'share_group'

     sudo chgrp -R share_group /path/to/your/repository

3. add the write authority to share_group

     sudo chmod -R g+w /path/to/your/repository

4. The last step is to assign current user--default user when login (by default ec2 is 'ec2-user', user of ubuntu instance is 'ubuntu' in ubuntu on aws) to share_group. I am using ubuntu insance on aws, so my default user is ubuntu.

     sudo usermod -a -G share_group ubuntu

By the way, to see the ownership of the folder or file just type:

    ls -l  /path/to/your/repository

'

Output:

    drwxr-x--x  2 root shared_group
(explanation please see:https://wiki.archlinux.org/index.php/File_permissions_and_attributes).

After step 3, you will see

    drwx--x--x  2 root root

changed to

    drwxr-x--x  2 root share_group 

In this case, I did not assign user 'ubuntu' to root group, for the consideration of security. You can just try to assign you default user to root according to step 4 (just skip the first 3 steps


In another way, tried the solution by :

    chmod -Rf u+w /path/to/git/repo/objects
It did not work for me, I think it should be the reason that my repository folder belong to the root user, not to Ubuntu user, and 'git' by default use the default user(ec2-user or Ubuntu user. You can try to change the user and test it.

Finally, below code definitely work for me, but 777 is not good for security

    sudo chmod -R 777 /path/to/your/repo

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

add your file android/app/build.gradle

 defaultConfig {
        applicationId "com.ubicacion"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        multiDexEnabled true // ?
        missingDimensionStrategy 'react-native-camera', 'general'
    }

Import pfx file into particular certificate store from command line

With Windows 2012 R2 (Win 8.1) and up, you also have the "official" Import-PfxCertificate cmdlet

Here are some essential parts of code (an adaptable example):

Invoke-Command -ComputerName $Computer -ScriptBlock {
        param(
            [string] $CertFileName,
            [string] $CertRootStore,
            [string] $CertStore,
            [string] $X509Flags,
            $PfxPass)
        $CertPath = "$Env:SystemRoot\$CertFileName"
        $Pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
        # Flags to send in are documented here: https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509keystorageflags%28v=vs.110%29.aspx
        $Pfx.Import($CertPath, $PfxPass, $X509Flags) #"Exportable,PersistKeySet")
        $Store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList $CertStore, $CertRootStore
        $Store.Open("MaxAllowed")
        $Store.Add($Pfx)
        if ($?)
        {
            "${Env:ComputerName}: Successfully added certificate."
        }
        else
        {
            "${Env:ComputerName}: Failed to add certificate! $($Error[0].ToString() -replace '[\r\n]+', ' ')"
        }
        $Store.Close()
        Remove-Item -LiteralPath $CertPath
    } -ArgumentList $TempCertFileName, $CertRootStore, $CertStore, $X509Flags, $Password

Based on mao47's code and some research, I wrote up a little article and a simple cmdlet for importing/pushing PFX certificates to remote computers.

Here's my article with more details and complete code that also works with PSv2 (default on Server 2008 R2 / Windows 7), so long as you have SMB enabled and administrative share access.

CKEditor instance already exists

This functions works for me in CKEditor version 4.4.5, it does not have any memory leaks

 function CKEditor_Render(CkEditor_id) {
        var instance = CKEDITOR.instances[CkEditor_id];
        if (CKEDITOR.instances.instance) {
            CKEDITOR.instances.instance.destroy();
        }
        CKEDITOR.replace(CkEditor_id);
    }

// call this function as below

var id = 'ckeditor'; // Id of your textarea

CKEditor_Render(id);

javascript variable reference/alias

in 2019 I need to write minified jquery plugins so I need it too this alias and so testing these examples and others ,from other sources,I found a way without copy in the memory of whe entire object ,but creating only a reference. I tested this already with firefox and watching task manager's tab memory on firefox before. The code is:

var {p: d} ={p: document};
console.log(d.body);

string.Replace in AngularJs

var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;

It works for me. Use an intermediate variable.

Why calling react setState method doesn't mutate the state immediately?

From React's documentation:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

If you want a function to be executed after the state change occurs, pass it in as a callback.

this.setState({value: event.target.value}, function () {
    console.log(this.state.value);
});

why is plotting with Matplotlib so slow?

For the first solution proposed by Joe Kington ( .copy_from_bbox & .draw_artist & canvas.blit), I had to capture the backgrounds after the fig.canvas.draw() line, otherwise the background had no effect and I got the same result as you mentioned. If you put it after the fig.show() it still does not work as proposed by Michael Browne.

So just put the background line after the canvas.draw():

[...]
fig.show()

# We need to draw the canvas before we start animating...
fig.canvas.draw()

# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]

Jquery Hide table rows

this might work for you...

$('.trhideclass1').hide();

 

<tr class="trhideclass1">
  <td>Label</td>
  <td>InputFile</td>
</tr>

printing a two dimensional array in python

A combination of list comprehensions and str joins can do the job:

inf = float('inf')
A = [[0,1,4,inf,3],
     [1,0,2,inf,4],
     [4,2,0,1,5],
     [inf,inf,1,0,3],
     [3,4,5,3,0]]

print('\n'.join([''.join(['{:4}'.format(item) for item in row]) 
      for row in A]))

yields

   0   1   4 inf   3
   1   0   2 inf   4
   4   2   0   1   5
 inf inf   1   0   3
   3   4   5   3   0

Using for-loops with indices is usually avoidable in Python, and is not considered "Pythonic" because it is less readable than its Pythonic cousin (see below). However, you could do this:

for i in range(n):
    for j in range(n):
        print '{:4}'.format(A[i][j]),
    print

The more Pythonic cousin would be:

for row in A:
    for val in row:
        print '{:4}'.format(val),
    print

However, this uses 30 print statements, whereas my original answer uses just one.

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

After installing Update 2 for Visual Studio 2015 I started getting the same error. I tried everything above with no luck. However, I found a solution that works for me:

  1. Delete YourSolutionFolder\\.vs\config\applicationhost.config file (note: .vs is a hidden folder)
  2. Open Visual Studio, right-click on web site > Properties > Debug tab > Web Server Settings > App URL - change port number.

max value of integer

In C, the integer(for 32 bit machine) is 32 bit and it ranges from -32768 to +32767.

Wrong. 32-bit signed integer in 2's complement representation has the range -231 to 231-1 which is equal to -2,147,483,648 to 2,147,483,647.

How to detect DataGridView CheckBox event change?

This also handles the keyboard activation.

    private void dgvApps_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if(dgvApps.CurrentCell.GetType() == typeof(DataGridViewCheckBoxCell))
        {
            if (dgvApps.CurrentCell.IsInEditMode)
            {
                if (dgvApps.IsCurrentCellDirty)
                {
                    dgvApps.EndEdit();
                }
            }
        }
    }


    private void dgvApps_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
          // handle value changed.....
    }

Is there a way to instantiate a class by name in Java?

String str = (String)Class.forName("java.lang.String").newInstance();

Python - Using regex to find multiple matches and print them out

Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.

How to use the start command in a batch file?

I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?

Basically, you use the /B and /C options:

START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1

Convert UTF-8 encoded NSData to NSString

Sometimes, the methods in the other answers don't work. In my case, I'm generating a signature with my RSA private key and the result is NSData. I found that this seems to work:

Objective-C

NSData *signature;
NSString *signatureString = [signature base64EncodedStringWithOptions:0];

Swift

let signatureString = signature.base64EncodedStringWithOptions(nil)

Angular: conditional class with *ngClass

You should use something ([ngClass] instead of *ngClass) like that:

<ol class="breadcrumb">
  <li [ngClass]="{active: step==='step1'}" (click)="step='step1; '">Step1</li>
  (...)

How to use IntelliJ IDEA to find all unused code?

In latest IntelliJ versions, you should run it from Analyze->Run Inspection By Name:

enter image description here

Than, pick Unused declaration:

enter image description here

And finally, uncheck the Include test sources:

enter image description here

Given a view, how do I get its viewController?

To get reference to UIViewController having UIView, you could make extension of UIResponder (which is super class for UIView and UIViewController), which allows to go up through the responder chain and thus reaching UIViewController (otherwise returning nil).

extension UIResponder {
    func getParentViewController() -> UIViewController? {
        if self.nextResponder() is UIViewController {
            return self.nextResponder() as? UIViewController
        } else {
            if self.nextResponder() != nil {
                return (self.nextResponder()!).getParentViewController()
            }
            else {return nil}
        }
    }
}

//Swift 3
extension UIResponder {
    func getParentViewController() -> UIViewController? {
        if self.next is UIViewController {
            return self.next as? UIViewController
        } else {
            if self.next != nil {
                return (self.next!).getParentViewController()
            }
            else {return nil}
        }
    }
}

let vc = UIViewController()
let view = UIView()
vc.view.addSubview(view)
view.getParentViewController() //provide reference to vc

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

This can occur when Safari is in private mode browsing. While in private browsing, local storage is not available at all.

One solution is to warn the user that the app needs non-private mode to work.

UPDATE: This has been fixed in Safari 11, so the behaviour is now aligned with other browsers.

ORA-00918: column ambiguously defined in SELECT *

You can also see this error when selecting for a union where corresponding columns can be null.

select * from (select D.dept_no, D.nullable_comment
                  from dept D
       union
               select R.dept_no, NULL
                 from redundant_dept R
)

This apparently confuses the parser, a solution is to assign a column alias to the always null column.

select * from (select D.dept_no, D.comment
                  from dept D
       union
               select R.dept_no, NULL "nullable_comment"
                 from redundant_dept R
)

The alias does not have to be the same as the corresponding column, but the column heading in the result is driven by the first query from among the union members, so it's probably a good practice.

PHP: How to handle <![CDATA[ with SimpleXMLElement?

This is working perfect for me.

$content = simplexml_load_string(
    $raw_xml
    , null
    , LIBXML_NOCDATA
);

How to find encoding of a file via script on Linux?

In php you can check like below :

Specifying encoding list explicitly :

php -r "echo 'probably : ' . mb_detect_encoding(file_get_contents('myfile.txt'), 'UTF-8, ASCII, JIS, EUC-JP, SJIS, iso-8859-1') . PHP_EOL;"

More accurate "mb_list_encodings":

php -r "echo 'probably : ' . mb_detect_encoding(file_get_contents('myfile.txt'), mb_list_encodings()) . PHP_EOL;"

Here in first example, you can see that i put a list of encodings (detect list order) that might be matching. To have more accurate result you can use all possible encodings via : mb_list_encodings()

Note mb_* functions require php-mbstring

apt-get install php-mbstring

php error: Class 'Imagick' not found

Ubuntu

sudo apt-get install php5-dev pecl imagemagick libmagickwand-dev
sudo pecl install imagick
sudo apt-get install php5-imagick
sudo service apache2 restart

Some dependencies will probably already be met but excluding the Apache service, that's everything required for PHP to use the Imagick class.

A regex for version number parsing

I tend to agree with split suggestion.

Ive created a "tester" for your problem in perl

#!/usr/bin/perl -w


@strings = ( "1.2.3", "1.2.*", "1.*","*" );

%regexp = ( svrist => qr/(?:(\d+)\.(\d+)\.(\d+)|(\d+)\.(\d+)|(\d+))?(?:\.\*)?/,
            onebyone => qr/^(\d+\.)?(\d+\.)?(\*|\d+)$/,
            greg => qr/^(\*|\d+(\.\d+){0,2}(\.\*)?)$/,
            vonc => qr/^((?:\d+(?!\.\*)\.)+)(\d+)?(\.\*)?$|^(\d+)\.\*$|^(\*|\d+)$/,
            ajb => qr/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/,
            jrudolph => qr/^(((\d+)\.)?(\d+)\.)?(\d+|\*)$/
          );

  foreach my $r (keys %regexp){
    my $reg = $regexp{$r};
    print "Using $r regexp\n";
foreach my $s (@strings){
  print "$s : ";

    if ($s =~m/$reg/){
    my ($main, $maj, $min,$rev,$ex1,$ex2,$ex3) = ("any","any","any","any","any","any","any");
    $main = $1 if ($1 && $1 ne "*") ;
    $maj = $2 if ($2 && $2 ne "*") ;
    $min = $3 if ($3 && $3 ne "*") ;
    $rev = $4 if ($4 && $4 ne "*") ;
    $ex1 = $5 if ($5 && $5 ne "*") ;
    $ex2 = $6 if ($6 && $6 ne "*") ;
    $ex3 = $7 if ($7 && $7 ne "*") ;
    print "$main $maj $min $rev $ex1 $ex2 $ex3\n";

  }else{
  print " nomatch\n";
  }
  }
print "------------------------\n";
}

Current output:

> perl regex.pl
Using onebyone regexp
1.2.3 : 1. 2. 3 any any any any
1.2.* : 1. 2. any any any any any
1.* : 1. any any any any any any
* : any any any any any any any
------------------------
Using svrist regexp
1.2.3 : 1 2 3 any any any any
1.2.* : any any any 1 2 any any
1.* : any any any any any 1 any
* : any any any any any any any
------------------------
Using vonc regexp
1.2.3 : 1.2. 3 any any any any any
1.2.* : 1. 2 .* any any any any
1.* : any any any 1 any any any
* : any any any any any any any
------------------------
Using ajb regexp
1.2.3 : 1 2 3 any any any any
1.2.* : 1 2 any any any any any
1.* : 1 any any any any any any
* : any any any any any any any
------------------------
Using jrudolph regexp
1.2.3 : 1.2. 1. 1 2 3 any any
1.2.* : 1.2. 1. 1 2 any any any
1.* : 1. any any 1 any any any
* : any any any any any any any
------------------------
Using greg regexp
1.2.3 : 1.2.3 .3 any any any any any
1.2.* : 1.2.* .2 .* any any any any
1.* : 1.* any .* any any any any
* : any any any any any any any
------------------------

Phone Number Validation MVC

Along with the above answers Try this for min and max length:

In Model

[StringLength(13, MinimumLength=10)]
public string MobileNo { get; set; }

In view

 <div class="col-md-8">
           @Html.TextBoxFor(m => m.MobileNo, new { @class = "form-control" , type="phone"})
           @Html.ValidationMessageFor(m => m.MobileNo,"Invalid Number")
           @Html.CheckBoxFor(m => m.IsAgreeTerms, new {@checked="checked",style="display:none" })
  </div>

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->

return .Cell(i,1) <> Empty

draw diagonal lines in div background with CSS

If you'd like the cross to be partially transparent, the naive approach would be to make linear-gradient colors semi-transparent. But that doesn't work out good due to the alpha blending at the intersection, producing a differently colored diamond. The solution to this is to leave the colors solid but add transparency to the gradient container instead:

_x000D_
_x000D_
.cross {_x000D_
  position: relative;_x000D_
}_x000D_
.cross::after {_x000D_
  pointer-events: none;_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0; bottom: 0; left: 0; right: 0;_x000D_
}_x000D_
_x000D_
.cross1::after {_x000D_
  background:_x000D_
    linear-gradient(to top left, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%),_x000D_
    linear-gradient(to top right, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%);_x000D_
}_x000D_
_x000D_
.cross2::after {_x000D_
  background:_x000D_
    linear-gradient(to top left, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%),_x000D_
    linear-gradient(to top right, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%);_x000D_
  opacity: 0.35;_x000D_
}_x000D_
_x000D_
div { width: 180px; text-align: justify; display: inline-block; margin: 20px; }
_x000D_
<div class="cross cross1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>_x000D_
_x000D_
<div class="cross cross2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>
_x000D_
_x000D_
_x000D_

How to get the max of two values in MySQL?

Use GREATEST()

E.g.:

SELECT GREATEST(2,1);

Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)

Ajax Upload image

You can use jquery.form.js plugin to upload image via ajax to the server.

http://malsup.com/jquery/form/

Here is the sample jQuery ajax image upload script

(function() {
$('form').ajaxForm({
    beforeSubmit: function() {  
        //do validation here


    },

    beforeSend:function(){
       $('#loader').show();
       $('#image_upload').hide();
    },
    success: function(msg) {

        ///on success do some here
    }
}); })();  

If you have any doubt, please refer following ajax image upload tutorial here

http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/

What does the function then() mean in JavaScript?

I suspect doSome returns this, which is myObj, which also has a then method. Standard method chaining...

if doSome is not returning this, being the object on which doSome was executed, rest assured it is returning some object with a then method...

as @patrick points out, there is no then() for standard js

Eclipse: stop code from running (java)

The easiest way to do this is to click on the Terminate button(red square) in the console:

enter image description here

Can you display HTML5 <video> as a full screen background?

I might be a bit late to answer this but this will be useful for new people looking for this answer.

The answers above are good, but to have a perfect video background you have to check at the aspect ratio as the video might cut or the canvas around get deformed when resizing the screen or using it on different screen sizes.

I got into this issue not long ago and I found the solution using media queries.

Here is a tutorial that I wrote on how to create a Fullscreen Video Background with only CSS

I will add the code here as well:

HTML:

<div class="videoBgWrapper">
    <video loop muted autoplay poster="img/videoframe.jpg" class="videoBg">
        <source src="videosfolder/video.webm" type="video/webm">
        <source src="videosfolder/video.mp4" type="video/mp4">
        <source src="videosfolder/video.ogv" type="video/ogg">
    </video>
</div>

CSS:

.videoBgWrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: -100;
}
.videoBg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

@media (min-aspect-ratio: 16/9) {
  .videoBg{
    width: 100%;
    height: auto;
  }
}
@media (max-aspect-ratio: 16/9) {
  .videoBg {
    width: auto;
    height: 100%;
  }
}

I hope you find it useful.

How to scan multiple paths using the @ComponentScan annotation?

There is another type-safe alternative to specifying a base-package location as a String. See the API here, but I've also illustrated below:

@ComponentScan(basePackageClasses = {ExampleController.class, ExampleModel.class, ExmapleView.class})

Using the basePackageClasses specifier with your class references will tell Spring to scan those packages (just like the mentioned alternatives), but this method is both type-safe and adds IDE support for future refactoring -- a huge plus in my book.

Reading from the API, Spring suggests creating a no-op marker class or interface in each package you wish to scan that serves no other purpose than to be used as a reference for/by this attribute.

IMO, I don't like the marker-classes (but then again, they are pretty much just like the package-info classes) but the type safety, IDE support, and drastically reducing the number of base packages needed to include for this scan is, with out a doubt, a far better option.

Read file from resources folder in Spring Boot

See my answer here: https://stackoverflow.com/a/56854431/4453282

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

Use these 2 imports.

Declare

@Autowired
ResourceLoader resourceLoader;

Use this in some function

Resource resource=resourceLoader.getResource("classpath:preferences.json");

In your case, as you need the file you may use following

File file = resource.getFile()

Reference:http://frugalisminds.com/spring/load-file-classpath-spring-boot/ As already mentioned in previous answers don't use ResourceUtils it doesn't work after deployment of JAR, this will work in IDE as well as after deployment

What is the string length of a GUID?

Binary strings store raw-byte data, whilst character strings store text. Use binary data when storing hexi-decimal values such as SID, GUID and so on. The uniqueidentifier data type contains a globally unique identifier, or GUID. This value is derived by using the NEWID() function to return a value that is unique to all objects. It's stored as a binary value but it is displayed as a character string.

Here is an example.

USE AdventureWorks2008R2;
GO
CREATE TABLE MyCcustomerTable
(
    user_login   varbinary(85) DEFAULT SUSER_SID()
    ,data_value   varbinary(1)
);
GO

INSERT MyCustomerTable (data_value)
    VALUES (0x4F);
GO

Applies to: SQL Server The following example creates the cust table with a uniqueidentifier data type, and uses NEWID to fill the table with a default value. In assigning the default value of NEWID(), each new and existing row has a unique value for the CustomerID column.

-- Creating a table using NEWID for uniqueidentifier data type.  
CREATE TABLE cust  
(  
 CustomerID uniqueidentifier NOT NULL  
   DEFAULT newid(),  
 Company varchar(30) NOT NULL,  
 ContactName varchar(60) NOT NULL,   
 Address varchar(30) NOT NULL,   
 City varchar(30) NOT NULL,  
 StateProvince varchar(10) NULL,  
 PostalCode varchar(10) NOT NULL,   
 CountryRegion varchar(20) NOT NULL,   
 Telephone varchar(15) NOT NULL,  
 Fax varchar(15) NULL  
);  
GO  
-- Inserting 5 rows into cust table.  
INSERT cust  
(CustomerID, Company, ContactName, Address, City, StateProvince,   
 PostalCode, CountryRegion, Telephone, Fax)  
VALUES  
 (NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,  
 '90110', 'Finland', '981-443655', '981-443655')  
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',  
 '08737-363', 'Brasil', '(14) 555-8122', '')  
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,   
 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')  
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,  
 '8010', 'Austria', '7675-3425', '7675-3426')  
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,  
 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');  
GO

Force unmount of NFS-mounted directory

Couldn't find a working answer here; but on linux you can run "umount.nfs4 /volume -f" and it definitely unmounts it.

Iterating a JavaScript object's properties using jQuery

Note: Most modern browsers will now allow you to navigate objects in the developer console. This answer is antiquated.

This method will walk through object properties and write them to the console with increasing indent:

function enumerate(o,s){

    //if s isn't defined, set it to an empty string
    s = typeof s !== 'undefined' ? s : "";

    //if o is null, we need to output and bail
    if(typeof o == "object" && o === null){

       console.log(s+k+": null");

    } else {    

        //iterate across o, passing keys as k and values as v
        $.each(o, function(k,v){

            //if v has nested depth
           if(typeof v == "object" && v !== null){

                //write the key to the console
                console.log(s+k+": ");

                //recursively call enumerate on the nested properties
                enumerate(v,s+"  ");

            } else {

                //log the key & value
                console.log(s+k+": "+String(v));
            }
        });
    }
}

Just pass it the object you want to iterate through:

    var response = $.ajax({
        url: myurl,
        dataType: "json"
    })
    .done(function(a){
       console.log("Returned values:");
       enumerate(a);
    })
    .fail(function(){ console.log("request failed");});

How do I return a char array from a function?

As you're using C++ you could use std::string.