Programs & Examples On #Directoryindex

how to create virtual host on XAMPP

I see two errors:

<VirtualHost *:80> -> Fix to :8081, your POrt the server runs on
    ServerName comm-app.local
    DocumentRoot "C:/xampp/htdocs/CommunicationApp/public"
    SetEnv APPLICATION_ENV "development"
    <Directory "C:/xampp/htdocs/CommunicationApp/public" -> This is probably why it crashes, missing >
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
 -> MIssing close container: </VirtualHost> 

Fixed version:

<VirtualHost *:8081>
    ServerName comm-app.local
    DocumentRoot "C:/xampp/htdocs/CommunicationApp/public"
    SetEnv APPLICATION_ENV "development"
    <Directory "C:/xampp/htdocs/CommunicationApp/public">
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

One thing to mention:

You can always try and run command:

service apache2 configtest

This will tell you when you got a malformed configuration and maybe even can tell you where the problem is.

Furthermore it helps avoid unavailability in a LIVE system:

service apache2 restart

will shutdown and then fail to start, this configtest you know beforehand "oops I did something wrong, I should fix this first" but the apache itself is still running with old configuration. :)

Htaccess: add/remove trailing slash from URL

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]


<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>

This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

G:\xampp\apache\conf\extra\httpd-vhosts.conf

#start block
NameVirtualHost *:80

<VirtualHost *:80>
   ServerName localhost
   #change your directory name
   DocumentRoot "G:\xampp\htdocs"
</VirtualHost>

#Your vertual Host
<VirtualHost *:80>
    DocumentRoot "G:/xampp/htdocs/dev2018/guessbook"
    ServerName dev.foreign-recruitment
    <Directory "G:/xampp/htdocs/dev2018/guessbook/">

    </Directory>
</VirtualHost>
#end block

Apache: The requested URL / was not found on this server. Apache

Non-trivial reasons:

  • if your .htaccess is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert )
  • if your .htaccess is in UTF8 Without-BOM, make it WITH BOM.

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

I don't think that replacing "Require all denied" with "Require all granted" in this directive:

<Directory>

    Options FollowSymLinks
    AllowOverride None
    #Require all denied
    Require all granted
</Directory>

as suggested by Jan Czarny and seonded by user3801675 is the most secure way of solving this problem.

According to the Apache configuration files, that line denies access to the entirety of your server's filesystem. Replacing it might indeed allow access to your virtual host folders but at the price of allowing access to your entire computer as well!

Gev Balyan's approach seems to be the most secure approach here. It was the answer to the "access denied problems" plaguing me after setting up my new Apache server this morning.

The requested URL /about was not found on this server

It worked for me like this:

Go to Wordpress Admin Dashboard > “Settings” > “Permalinks” > “Common settings”, set the radio button to “Custom Structure” and paste into the text box:

/index.php/%year%/%monthnum%/%day%/%postname%/

and click the Save button.

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

Apache VirtualHost and localhost

It may be because your web folder (as mentioned "/Applications/MAMP/htdocs/mysite/web") is empty.

My suggestion is first to make your project and then work on making the virtual host.

I went with a similar situation. I was using an empty folder in the DocumentRoot in httpd-vhosts.confiz and I couldn't access my shahg101.com site.

Error message "Forbidden You don't have permission to access / on this server"

I was getting the same error and couldn't figure out the problem for ages. If you happen to be on a Linux distribution that includes SELinux such as CentOS, you need to make sure SELinux permissions are set correctly for your document root files or you will get this error. This is a completely different set of permissions to the standard file system permissions.

I happened to use the tutorial Apache and SELinux, but there seems to be plenty around once you know what to look for.

Make index.html default, but allow index.php to be visited if typed in

RewriteEngine on
RewriteRule ^(.*)\.html$ $1.php%{QUERY_STRING} [L]

Put these two lines at the top of your .htaccess file. It will show .html in the URL for your .php pages.

RewriteEngine on
RewriteRule ^(.*)\.php$ $1.html%{QUERY_STRING} [L]

Use this for showing .php in URL for your .html pages.

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

For many it's a permission issue, but for me it turns out the error was brought about by a mistake in the form I was trying to submit. To be specific i had accidentally put a "greater than" sign after the value of "action". So I would suggest you take a second look at your code.

client denied by server configuration

In my case, I modified directory tag.

From

<Directory "D:/Devel/matysart/matysart_dev1">
  Allow from all
  Order Deny,Allow
</Directory>

To

<Directory "D:/Devel/matysart/matysart_dev1">
  Require local
</Directory>

And it seriously worked. It's seems changed with Apache 2.4.2.

How to check whether mod_rewrite is enable on server?

just make a new page and add this code

 <?php
 if(!function_exists('apache_get_modules') ){ phpinfo(); exit; }
 $res = 'Module Unavailable';
 if(in_array('mod_rewrite',apache_get_modules())) 
 $res = 'Module Available';
?>
<html>
<head>
<title>A mod_rewrite availability check !</title></head>
<body>
<p><?php echo apache_get_version(),"</p><p>mod_rewrite $res"; ?></p>
</body>
</html>

and run this page then find will able to know module is Available or not if not then you can ask to your hosting or if you want to enable it in local machine then check this youtube step by step tutorial related to enable rewrite module in wamp apache https://youtu.be/xIspOX9FuVU?t=1m43s Wamp server icon -> Apache -> Apache Modules and check the rewrite module option

CodeIgniter 404 Page Not Found, but why?

  1. Change your controller name first letter to uppercase.
  2. Change your url same as your controller name.

e.g:

Your controller name is YourController

Your url must be:

http://example.com/index.php/YourController/method

Not be:

http://example.com/index.php/yourcontroller/method

Python coding standards/best practices

I follow the Python Idioms and Efficiency guidelines, by Rob Knight. I think they are exactly the same as PEP 8, but are more synthetic and based on examples.

If you are using wxPython you might also want to check Style Guide for wxPython code, by Chris Barker, as well.

file_get_contents behind a proxy?

There's a similar post here: http://techpad.co.uk/content.php?sid=137 which explains how to do it.

function file_get_contents_proxy($url,$proxy){

    // Create context stream
    $context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
    $context = stream_context_create($context_array);

    // Use context stream with file_get_contents
    $data = file_get_contents($url,false,$context);

    // Return data via proxy
    return $data;

}

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

if anyone is getting error like SEVERE: Error filterStart Apr 29, 2013 4:49:20 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Context [/TraceMW] startup failed due to previous errors

then please check whether your tomcat/lib directory contains cors-filter-1.5.jar or not. if you dot have u will get above error and ur application will not be available.

So, i just managed to copy the jar file from other tomcat folder and i didnt get the above mentioned error later.

How to use sessions in an ASP.NET MVC 4 application?

Due to the stateless nature of the web, sessions are also an extremely useful way of persisting objects across requests by serialising them and storing them in a session.

A perfect use case of this could be if you need to access regular information across your application, to save additional database calls on each request, this data can be stored in an object and unserialised on each request, like so:

Our reusable, serializable object:

[Serializable]
public class UserProfileSessionData
{
    public int UserId { get; set; }

    public string EmailAddress { get; set; }

    public string FullName { get; set; }
}

Use case:

public class LoginController : Controller {

    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            var profileData = new UserProfileSessionData {
                UserId = model.UserId,
                EmailAddress = model.EmailAddress,
                FullName = model.FullName
            }

            this.Session["UserProfile"] = profileData;
        }
    }

    public ActionResult LoggedInStatusMessage()
    {
        var profileData = this.Session["UserProfile"] as UserProfileSessionData;

        /* From here you could output profileData.FullName to a view and
        save yourself unnecessary database calls */
    }

}

Once this object has been serialised, we can use it across all controllers without needing to create it or query the database for the data contained within it again.

Inject your session object using Dependency Injection

In a ideal world you would 'program to an interface, not implementation' and inject your serializable session object into your controller using your Inversion of Control container of choice, like so (this example uses StructureMap as it's the one I'm most familiar with).

public class WebsiteRegistry : Registry
{
    public WebsiteRegistry()
    {
        this.For<IUserProfileSessionData>().HybridHttpOrThreadLocalScoped().Use(() => GetUserProfileFromSession());   
    }

    public static IUserProfileSessionData GetUserProfileFromSession()
    {
        var session = HttpContext.Current.Session;
        if (session["UserProfile"] != null)
        {
            return session["UserProfile"] as IUserProfileSessionData;
        }

        /* Create new empty session object */
        session["UserProfile"] = new UserProfileSessionData();

        return session["UserProfile"] as IUserProfileSessionData;
    }
}

You would then register this in your Global.asax.cs file.

For those that aren't familiar with injecting session objects, you can find a more in-depth blog post about the subject here.

A word of warning:

It's worth noting that sessions should be kept to a minimum, large sessions can start to cause performance issues.

It's also recommended to not store any sensitive data in them (passwords, etc).

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

In case you're having this problem in flex/adobe air and find yourself here first, i've found a solution, and have posted it on a related question: ADD COLUMN to sqlite db IF NOT EXISTS - flex/air sqlite?

My comment here: https://stackoverflow.com/a/24928437/2678219

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

Plotting a list of (x, y) coordinates in python matplotlib

If you have a numpy array you can do this:

import numpy as np
from matplotlib import pyplot as plt

data = np.array([
    [1, 2],
    [2, 3],
    [3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()

How do I get the current time only in JavaScript

Short and simple:

new Date().toLocaleTimeString(); // 11:18:48 AM
//---
new Date().toLocaleDateString(); // 11/16/2015
//---
new Date().toLocaleString(); // 11/16/2015, 11:18:48 PM

4 hours later (use milisec: sec==1000):

new Date(new Date().getTime() + 4*60*60*1000).toLocaleTimeString(); // 3:18:48 PM or 15:18:48

2 days before:

new Date(new Date().getTime() - 2*24*60*60*1000).toLocaleDateString() // 11/14/2015

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

You haven't set the timezone only added a Z to the end of the date/time, so it will look like a GMT date/time but this doesn't change the value.

Set the timezone to GMT and it will be correct.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

iCheck check if checkbox is checked

Use following code to check if iCheck is checked or not using single method.

$('Selector').on('ifChanged', function(event){

    //Check if checkbox is checked or not
    var checkboxChecked = $(this).is(':checked');

    if(checkboxChecked) {
        alert("checked");
    }else{
        alert("un-checked");
    }
});

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

You need to add following jar file in your classpath: slf4j-simple-1.6.2.jar. If you don't have it, please download it. Please refer to http://www.slf4j.org/codes.html#multiple_bindings

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

Click the items in the list view. Add a button that will edit the selected items. Add the code

try
{              
    LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}

How to make a redirection on page load in JSF 1.x

FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");

Best practice to call ConfigureAwait for all server-side code

Update: ASP.NET Core does not have a SynchronizationContext. If you are on ASP.NET Core, it does not matter whether you use ConfigureAwait(false) or not.

For ASP.NET "Full" or "Classic" or whatever, the rest of this answer still applies.

Original post (for non-Core ASP.NET):

This video by the ASP.NET team has the best information on using async on ASP.NET.

I had read that it is more performant since it doesn't have to switch thread contexts back to the original thread context.

This is true with UI applications, where there is only one UI thread that you have to "sync" back to.

In ASP.NET, the situation is a bit more complex. When an async method resumes execution, it grabs a thread from the ASP.NET thread pool. If you disable the context capture using ConfigureAwait(false), then the thread just continues executing the method directly. If you do not disable the context capture, then the thread will re-enter the request context and then continue to execute the method.

So ConfigureAwait(false) does not save you a thread jump in ASP.NET; it does save you the re-entering of the request context, but this is normally very fast. ConfigureAwait(false) could be useful if you're trying to do a small amount of parallel processing of a request, but really TPL is a better fit for most of those scenarios.

However, with ASP.NET Web Api, if your request is coming in on one thread, and you await some function and call ConfigureAwait(false) that could potentially put you on a different thread when you are returning the final result of your ApiController function.

Actually, just doing an await can do that. Once your async method hits an await, the method is blocked but the thread returns to the thread pool. When the method is ready to continue, any thread is snatched from the thread pool and used to resume the method.

The only difference ConfigureAwait makes in ASP.NET is whether that thread enters the request context when resuming the method.

I have more background information in my MSDN article on SynchronizationContext and my async intro blog post.

Read/Write 'Extended' file properties (C#)

For those of not crazy about VB, here it is in c#:

Note, you have to add a reference to Microsoft Shell Controls and Automation from the COM tab of the References dialog.

public static void Main(string[] args)
{
    List<string> arrHeaders = new List<string>();

    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder objFolder;

    objFolder = shell.NameSpace(@"C:\temp\testprop");

    for( int i = 0; i < short.MaxValue; i++ )
    {
        string header = objFolder.GetDetailsOf(null, i);
        if (String.IsNullOrEmpty(header))
            break;
        arrHeaders.Add(header);
    }

    foreach(Shell32.FolderItem2 item in objFolder.Items())
    {
        for (int i = 0; i < arrHeaders.Count; i++)
        {
            Console.WriteLine(
              $"{i}\t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}");
        }
    }
}

How can I clone a private GitLab repository?

If you are using Windows,

  1. make a folder and open git bash from there

  2. in the git bash,

    git clone [email protected]:Example/projectName.git

How to change identity column values programmatically?

You can insert new rows with modified values and then delete old rows. Following example change ID to be same as foreign key PersonId

SET IDENTITY_INSERT [PersonApiLogin] ON

INSERT INTO [PersonApiLogin](
       [Id]
      ,[PersonId]
      ,[ApiId]
      ,[Hash]
      ,[Password]
      ,[SoftwareKey]
      ,[LoggedIn]
      ,[LastAccess])
SELECT [PersonId]
      ,[PersonId]
      ,[ApiId]
      ,[Hash]
      ,[Password]
      ,[SoftwareKey]
      ,[LoggedIn]
      ,[LastAccess]
FROM [db304].[dbo].[PersonApiLogin]
GO

DELETE FROM [PersonApiLogin]
WHERE [PersonId] <> ID
GO
SET IDENTITY_INSERT [PersonApiLogin] OFF
GO

Simple mediaplayer play mp3 from file path?

String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();   
mediaPlayer.start()

and this play from raw folder.

int resID = myContext.getResources().getIdentifier(playSoundName,"raw",myContext.getPackageName());

            MediaPlayer mediaPlayer = MediaPlayer.create(myContext,resID);
            mediaPlayer.prepare();
            mediaPlayer.start();

mycontext=application.this. use.

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

How to detect running app using ADB command

No need to use grep. ps in Android can filter by COMM value (last 15 characters of the package name in case of java app)

Let's say we want to check if com.android.phone is running:

adb shell ps m.android.phone
USER     PID   PPID  VSIZE  RSS     WCHAN    PC         NAME
radio     1389  277   515960 33964 ffffffff 4024c270 S com.android.phone

Filtering by COMM value option has been removed from ps in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof command:

adb shell pidof com.android.phone

It returns the PID if such process was found or an empty string otherwise.

Disable keyboard on EditText

Gathering solutions from multiple places here on StackOverflow, I think the next one sums it up:

If you don't need the keyboard to be shown anywhere on your activity, you can simply use the next flags which are used for dialogs (got from here) :

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

If you don't want it only for a specific EditText, you can use this (got from here) :

public static boolean disableKeyboardForEditText(@NonNull EditText editText) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        editText.setShowSoftInputOnFocus(false);
        return true;
    }
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
        try {
            final Method method = EditText.class.getMethod("setShowSoftInputOnFocus", new Class[]{boolean.class});
            method.setAccessible(true);
            method.invoke(editText, false);
            return true;
        } catch (Exception ignored) {
        }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
        try {
            Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class);
            method.setAccessible(true);
            method.invoke(editText, false);
            return true;
        } catch (Exception ignored) {
        }
    return false;
}

Or this (taken from here) :

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
           editText.setShowSoftInputOnFocus(false);
       else
           editText.setTextIsSelectable(true); 

IOException: Too many open files

The problem comes from your Java application (or a library you are using).

First, you should read the entire outputs (Google for StreamGobbler), and pronto!

Javadoc says:

The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

Secondly, waitFor() your process to terminate. You then should close the input, output and error streams.

Finally destroy() your Process.

My sources:

Difference in make_shared and normal shared_ptr in C++

About efficiency and concernig time spent on allocation, I made this simple test below, I created many instances through these two ways (one at a time):

for (int k = 0 ; k < 30000000; ++k)
{
    // took more time than using new
    std::shared_ptr<int> foo = std::make_shared<int> (10);

    // was faster than using make_shared
    std::shared_ptr<int> foo2 = std::shared_ptr<int>(new int(10));
}

The thing is, using make_shared took the double time compared with using new. So, using new there are two heap allocations instead of one using make_shared. Maybe this is a stupid test but doesn't it show that using make_shared takes more time than using new? Of course, I'm talking about time used only.

React Native Change Default iOS Simulator Device

You can also use npm for this by adding an entry to the scripts element of your package.json file. E.g.

"launch-ios": "react-native run-ios --simulator \"iPad Air 2\""

Then to use this: npm run launch-ios

Fitting a density curve to a histogram in R

Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

Skew-normal distributed data plot

This probably works better on data that is more skew-normal:

Another skew-normal plot

SOAP Action WSDL

I've just spent a while trying to get this to work an have a written a Ruby gem that accesses the API. You can read more on it's project page.

This is working code in Ruby:

require 'savon'
client = Savon::Client.new do
  wsdl.document = "http://realtime.nationalrail.co.uk/LDBWS/wsdl.aspx"
end

response = client.request 'http://thalesgroup.com/RTTI/2012-01-13/ldb/GetDepartureBoard' do

  namespaces = {
    "xmlns:soap" => "http://schemas.xmlsoap.org/soap/envelope/",
    "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
    "xmlns:xsd" => "http://www.w3.org/2001/XMLSchema"
  }

  soap.xml do |xml|
    xml.soap(:Envelope, namespaces) do |xml|
      xml.soap(:Header) do |xml|
        xml.AccessToken do |xml|
          xml.TokenValue('ENTER YOUR TOKEN HERE') 
        end
      end
      xml.soap(:Body) do |xml|
        xml.GetDepartureBoardRequest(xmlns: "http://thalesgroup.com/RTTI/2012-01-13/ldb/types") do |xml|
          xml.numRows(10)
          xml.crs("BHM")
          xml.filterCrs("BHM")
          xml.filterType("to")
        end
      end
    end
  end
end
p response.body

Hope that's helpful for someone!

how to install python distutils

If you are unable to install with either of these:

sudo apt-get install python-distutils
sudo apt-get install python3-distutils

Try this instead:

sudo apt-get install python-distutils-extra

Ref: https://groups.google.com/forum/#!topic/beagleboard/RDlTq8sMxro

HTML5 LocalStorage: Checking if a key exists

This method worked for me:

if ("username" in localStorage) {
    alert('yes');
} else {
    alert('no');
}

ScriptManager.RegisterStartupScript code not working - why?

Try this code...

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", "alert('Hi');", true);

Where UpdatePanel1 is the id for Updatepanel on your page

difference between System.out.println() and System.err.println()

In Java System.out.println() will print to the standard out of the system you are using. On the other hand, System.err.println() will print to the standard error.

If you are using a simple Java console application, both outputs will be the same (the command line or console) but you can reconfigure the streams so that for example, System.out still prints to the console but System.err writes to a file.

Also, IDEs like Eclipse show System.err in red text and System.out in black text by default.

File Upload without Form

Basing on this tutorial, here a very basic way to do that:

$('your_trigger_element_selector').on('click', function(){    
    var data = new FormData();
    data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
    // append other variables to data if you want: data.append('field_name_x', field_value_x);

    $.ajax({
        type: 'POST',               
        processData: false, // important
        contentType: false, // important
        data: data,
        url: your_ajax_path,
        dataType : 'json',  
        // in PHP you can call and process file in the same way as if it was submitted from a form:
        // $_FILES['input_file_name']
        success: function(jsonData){
            ...
        }
        ...
    }); 
});

Don't forget to add proper error handling

How to run shell script on host from docker container?

That REALLY depends on what you need that bash script to do!

For example, if the bash script just echoes some output, you could just do

docker run --rm -v $(pwd)/mybashscript.sh:/mybashscript.sh ubuntu bash /mybashscript.sh

Another possibility is that you want the bash script to install some software- say the script to install docker-compose. you could do something like

docker run --rm -v /usr/bin:/usr/bin --privileged -v $(pwd)/mybashscript.sh:/mybashscript.sh ubuntu bash /mybashscript.sh

But at this point you're really getting into having to know intimately what the script is doing to allow the specific permissions it needs on your host from inside the container.

How do I cancel a build that is in progress in Visual Studio?

Go to Visual Studio Build Menu -> cancel build , easy :)

c# foreach (property in object)... Is there a simple way of doing this?

Use Reflection to do this

SomeClass A = SomeClass(...)
PropertyInfo[] properties = A.GetType().GetProperties();

Importing two classes with same name. How to handle?

use the fully qualified name instead of importing the class.

e.g.

//import java.util.Date; //delete this
//import my.own.Date;

class Test{

   public static void main(String [] args){

      // I want to choose my.own.Date here. How?
      my.own.Date myDate = new my.own.Date();

      // I want to choose util.Date here. How ?
      java.util.Date javaDate = new java.util.Date();
   }
}

How to pretty print XML from the command line?

This took me forever to find something that works on my mac. Here's what worked for me:

brew install xmlformat
cat unformatted.html | xmlformat

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

$str = '\u0063\u0061\u0074'.'\ud83d\ude38';
$str2 = '\u0063\u0061\u0074'.'\ud83d';

// U+1F638
var_dump(
    "cat\xF0\x9F\x98\xB8" === escape_sequence_decode($str),
    "cat\xEF\xBF\xBD" === escape_sequence_decode($str2)
);

function escape_sequence_decode($str) {

    // [U+D800 - U+DBFF][U+DC00 - U+DFFF]|[U+0000 - U+FFFF]
    $regex = '/\\\u([dD][89abAB][\da-fA-F]{2})\\\u([dD][c-fC-F][\da-fA-F]{2})
              |\\\u([\da-fA-F]{4})/sx';

    return preg_replace_callback($regex, function($matches) {

        if (isset($matches[3])) {
            $cp = hexdec($matches[3]);
        } else {
            $lead = hexdec($matches[1]);
            $trail = hexdec($matches[2]);

            // http://unicode.org/faq/utf_bom.html#utf16-4
            $cp = ($lead << 10) + $trail + 0x10000 - (0xD800 << 10) - 0xDC00;
        }

        // https://tools.ietf.org/html/rfc3629#section-3
        // Characters between U+D800 and U+DFFF are not allowed in UTF-8
        if ($cp > 0xD7FF && 0xE000 > $cp) {
            $cp = 0xFFFD;
        }

        // https://github.com/php/php-src/blob/php-5.6.4/ext/standard/html.c#L471
        // php_utf32_utf8(unsigned char *buf, unsigned k)

        if ($cp < 0x80) {
            return chr($cp);
        } else if ($cp < 0xA0) {
            return chr(0xC0 | $cp >> 6).chr(0x80 | $cp & 0x3F);
        }

        return html_entity_decode('&#'.$cp.';');
    }, $str);
}

Bootstrap 3 Horizontal and Vertical Divider

The <hr> should be placed inside a <div> for proper functioning.

Place it like this to get desired width `

<div class='row'>
        <div class='col-lg-8 col-lg-offset-2'>
        <hr>
       </div>
       </div>

`

Hope this helps a future reader!

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

I found that I could access the checkbox directly using Worksheets("SheetName").CB_Checkboxname.value directly without relating to additional objects.

How to make the division of 2 ints produce a float instead of another int?

To lessen the impact on code readabilty, I'd suggest:

v = 1d* s/t;

Spark - Error "A master URL must be set in your configuration" when submitting an app

The default value of "spark.master" is spark://HOST:PORT, and the following code tries to get a session from the standalone cluster that is running at HOST:PORT, and expects the HOST:PORT value to be in the spark config file.

SparkSession spark = SparkSession
    .builder()
    .appName("SomeAppName")
    .getOrCreate();

"org.apache.spark.SparkException: A master URL must be set in your configuration" states that HOST:PORT is not set in the spark configuration file.

To not bother about value of "HOST:PORT", set spark.master as local

SparkSession spark = SparkSession
    .builder()
    .appName("SomeAppName")
    .config("spark.master", "local")
    .getOrCreate();

Here is the link for list of formats in which master URL can be passed to spark.master

Reference : Spark Tutorial - Setup Spark Ecosystem

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

Before you start, go to the directory "phpMyAdmin" preferably the one in your localhost, clear all of your cookies, and have your sql running by entering:

sudo /usr/local/mysql/support-files/mysql.server start

To fix the error , you will have to run the following commands in your terminal:

export PATH=$PATH:/usr/local/mysql/bin/

then:

mysql -u root

after which, you'll need to change your permissions inside the mySQL shell:

UPDATE user SET Password=PASSWORD('YOURNEWPASSWORD') WHERE User='root'; FLUSH PRIVILEGES; exit;

Refresh your phpMyAdmin window, re-enter the "root" username (or whichever is applicable), and your password and you should be good to go. Check http://machiine.com/2013/how-to-setup-phpmyadmin-on-a-mac-with-osx-10-8-mamp-part-3/ if you are willing to set up from scratch.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Distinct and Group By generally do the same kind of thing, for different purposes... They both create a 'working" table in memory based on the columns being Grouped on, (or selected in the Select Distinct clause) - and then populate that working table as the query reads data, adding a new "row" only when the values indicate the need to do so...

The only difference is that in the Group By there are additional "columns" in the working table for any calculated aggregate fields, like Sum(), Count(), Avg(), etc. that need to updated for each original row read. Distinct doesn't have to do this... In the special case where you Group By only to get distinct values, (And there are no aggregate columns in output), then it is probably exactly the same query plan.... It would be interesting to review the query execution plan for the two options and see what it did...

Certainly Distinct is the way to go for readability if that is what you are doing (When your purpose is to eliminate duplicate rows, and you are not calculating any aggregate columns)

Problem in running .net framework 4.0 website on iis 7.0

If you are running Delphi, or other native compiled CGI, this solution will work:

  1. As other pointed, go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header.

  2. If you have everything allowed, it will still not work. You need to click on "Edit Feature Settings" in Actions (on the right side), and check "Allow unspecified CGI modules", or "Allow unspecified ISAPI modules" respectively.

  3. Click OK

window.location.href not working

Please check you are using // not \\ by-mistake , like below

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"

How can I get query string values in JavaScript?

function getUrlVar(key){
    var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search); 
    return result && unescape(result[1]) || ""; 
}

https://gist.github.com/1771618

Why does my favicon not show up?

Try adding the profile attribute to your head tag and use "image/x-icon" for the type attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">

If the above code doesn't work, try using the full icon path for the href attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">

How to minify php page html output?

All of the preg_replace() solutions above have issues of single line comments, conditional comments and other pitfalls. I'd recommend taking advantage of the well-tested Minify project rather than creating your own regex from scratch.

In my case I place the following code at the top of a PHP page to minify it:

function sanitize_output($buffer) {
    require_once('min/lib/Minify/HTML.php');
    require_once('min/lib/Minify/CSS.php');
    require_once('min/lib/JSMin.php');
    $buffer = Minify_HTML::minify($buffer, array(
        'cssMinifier' => array('Minify_CSS', 'minify'),
        'jsMinifier' => array('JSMin', 'minify')
    ));
    return $buffer;
}
ob_start('sanitize_output');

Removing duplicates from a SQL query (not just "use distinct")

If I understand you correctly, you want a list of all pictures with the same name (and their different ids) such that their name occurs more than once in the table. I think this will do the trick:

SELECT U.NAME, P.PIC_ID
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND U.Name IN (
SELECT U.Name 
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND P.CAPTION LIKE '%car%';
GROUP BY U.Name HAVING COUNT(U.Name) > 1)

I haven't executed it, so there may be a syntax error or two there.

Java Does Not Equal (!=) Not Working?

Please use !statusCheck.equals("success") instead of !=.

Here are more details.

Adding a new entry to the PATH variable in ZSH

one liner, without opening ~/.zshrc file

echo -n 'export PATH=~/bin:$PATH' >> ~/.zshrc

or

echo -n 'export PATH=$HOME/bin:$PATH' >> ~/.zshrc

To see the effect, do source ~/.zshrc in the same tab or open a new tab

How to POST a FORM from HTML to ASPX page

Remove runat="server" parts of data posting/posted .aspx page.

Static Block in Java

Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation. http://www.jusfortechies.com/java/core-java/static-blocks.php

how to toggle (hide/show) a table onClick of <a> tag in java script

inside your function toggleTable when you do this line

document.getElementById("loginLink").onclick = toggleTable(....

you are actually calling the function again. so toggleTable gets called again, and again and again, you're falling in an infinite recursive call.

make it simple.

function toggleTable()
{
     var elem=document.getElementById("loginTable");
     var hide = elem.style.display =="none";
     if (hide) {
         elem.style.display="table";
    } 
    else {
       elem.style.display="none";
    }
}

see this fiddle

Google maps Marker Label with multiple characters

You can use MarkerWithLabel with SVG icons.

Update: The Google Maps Javascript API v3 now natively supports multiple characters in the MarkerLabel

proof of concept fiddle (you didn't provide your icon, so I made one up)

Note: there is an issue with labels on overlapping markers that is addressed by this fix, credit to robd who brought it up in the comments.

code snippet:

_x000D_
_x000D_
function initMap() {_x000D_
  var latLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
  var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
_x000D_
  var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
    zoom: 12,_x000D_
    center: latLng,_x000D_
    mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
  });_x000D_
_x000D_
  var marker = new MarkerWithLabel({_x000D_
    position: homeLatLng,_x000D_
    map: map,_x000D_
    draggable: true,_x000D_
    raiseOnDrag: true,_x000D_
    labelContent: "ABCD",_x000D_
    labelAnchor: new google.maps.Point(15, 65),_x000D_
    labelClass: "labels", // the CSS class for the label_x000D_
    labelInBackground: false,_x000D_
    icon: pinSymbol('red')_x000D_
  });_x000D_
_x000D_
  var iw = new google.maps.InfoWindow({_x000D_
    content: "Home For Sale"_x000D_
  });_x000D_
  google.maps.event.addListener(marker, "click", function(e) {_x000D_
    iw.open(map, this);_x000D_
  });_x000D_
}_x000D_
_x000D_
function pinSymbol(color) {_x000D_
  return {_x000D_
    path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',_x000D_
    fillColor: color,_x000D_
    fillOpacity: 1,_x000D_
    strokeColor: '#000',_x000D_
    strokeWeight: 2,_x000D_
    scale: 2_x000D_
  };_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initMap);
_x000D_
html,_x000D_
body,_x000D_
#map_canvas {_x000D_
  height: 500px;_x000D_
  width: 500px;_x000D_
  margin: 0px;_x000D_
  padding: 0px_x000D_
}_x000D_
.labels {_x000D_
  color: white;_x000D_
  background-color: red;_x000D_
  font-family: "Lucida Grande", "Arial", sans-serif;_x000D_
  font-size: 10px;_x000D_
  text-align: center;_x000D_
  width: 30px;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>_x000D_
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerwithlabel/src/markerwithlabel.js"></script>_x000D_
<div id="map_canvas" style="height: 400px; width: 100%;"></div>
_x000D_
_x000D_
_x000D_

SQL: Combine Select count(*) from multiple tables

Basically you do the counts as sub-queries within a standard select.

An example would be the following, this returns 1 row, two columns

SELECT
 (SELECT COUNT(*) FROM MyTable WHERE MyCol = 'MyValue') AS MyTableCount,
 (SELECT COUNT(*) FROM YourTable WHERE MyCol = 'MyValue') AS YourTableCount,

SQL 'LIKE' query using '%' where the search criteria contains '%'

The easiest solution is to dispense with "like" altogether:

Select * 
from table
where charindex(search_criteria, name) > 0

I prefer charindex over like. Historically, it had better performance, but I'm not sure if it makes much of difference now.

returning a Void object

Java 8 has introduced a new class, Optional<T>, that can be used in such cases. To use it, you'd modify your code slightly as follows:

interface B<E>{ Optional<E> method(); }

class A implements B<Void>{

    public Optional<Void> method(){
        // do something
        return Optional.empty();
    }
}

This allows you to ensure that you always get a non-null return value from your method, even when there isn't anything to return. That's especially powerful when used in conjunction with tools that detect when null can or can't be returned, e.g. the Eclipse @NonNull and @Nullable annotations.

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

Insert content into iFrame

You really don't need jQuery for that:

var doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write('Test');
doc.close();

jsFiddle Demo

If you absolutely have to use jQuery, you should use contents():

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append('Test');
});

jsFiddle Demo

Please don't forget that if you're using jQuery, you'll need to hook into the DOMReady function as follows:

$(function() {  
    var $iframe = $('#iframe');
    $iframe.ready(function() {
        $iframe.contents().find("body").append('Test');
    });
});

‘ant’ is not recognized as an internal or external command

Need to see whether you got ant folder moved by mistake or unknowingly. It is set in environment variables.I resolved this once as mentioned below.

I removed ant folder by mistake and placed in another folder.I went to command prompt and typed "path". It has given me path as "F:\apache-ant-1.9.4\". So I moved the ant back to F drive and it resolved the issue.

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes (64 KB) maximum.

If you need more consider using:

  • a MEDIUMBLOB for 16777215 bytes (16 MB)

  • a LONGBLOB for 4294967295 bytes (4 GB).

See Storage Requirements for String Types for more info.

What GRANT USAGE ON SCHEMA exactly do?

Well, this is my final solution for a simple db, for Linux:

# Read this before!
#
# * roles in postgres are users, and can be used also as group of users
# * $ROLE_LOCAL will be the user that access the db for maintenance and
#   administration. $ROLE_REMOTE will be the user that access the db from the webapp
# * you have to change '$ROLE_LOCAL', '$ROLE_REMOTE' and '$DB'
#   strings with your desired names
# * it's preferable that $ROLE_LOCAL == $DB

#-------------------------------------------------------------------------------

//----------- SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - START ----------//

cd /etc/postgresql/$VERSION/main
sudo cp pg_hba.conf pg_hba.conf_bak
sudo -e pg_hba.conf

# change all `md5` with `scram-sha-256`
# save and exit

//------------ SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - END -----------//

sudo -u postgres psql

# in psql:
create role $ROLE_LOCAL login createdb;
\password $ROLE_LOCAL
create role $ROLE_REMOTE login;
\password $ROLE_REMOTE

create database $DB owner $ROLE_LOCAL encoding "utf8";
\connect $DB $ROLE_LOCAL

# Create all tables and objects, and after that:

\connect $DB postgres

revoke connect on database $DB from public;
revoke all on schema public from public;
revoke all on all tables in schema public from public;

grant connect on database $DB to $ROLE_LOCAL;
grant all on schema public to $ROLE_LOCAL;
grant all on all tables in schema public to $ROLE_LOCAL;
grant all on all sequences in schema public to $ROLE_LOCAL;
grant all on all functions in schema public to $ROLE_LOCAL;

grant connect on database $DB to $ROLE_REMOTE;
grant usage on schema public to $ROLE_REMOTE;
grant select, insert, update, delete on all tables in schema public to $ROLE_REMOTE;
grant usage, select on all sequences in schema public to $ROLE_REMOTE;
grant execute on all functions in schema public to $ROLE_REMOTE;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on tables to $ROLE_LOCAL;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on sequences to $ROLE_LOCAL;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on functions to $ROLE_LOCAL;

alter default privileges for role $ROLE_REMOTE in schema public
    grant select, insert, update, delete on tables to $ROLE_REMOTE;

alter default privileges for role $ROLE_REMOTE in schema public
    grant usage, select on sequences to $ROLE_REMOTE;

alter default privileges for role $ROLE_REMOTE in schema public
    grant execute on functions to $ROLE_REMOTE;

# CTRL+D

Run R script from command line

Just for documentation, sometimes you need to run the script as sudo:

sudo Rscript path/to/your/file.R

Get list of all tables in Oracle?

Execute the below commands:

Show all tables in the Oracle Database

sql> SELECT table_name FROM dba_tables;

Show tables owned by the current user

sql> SELECT table_name FROM user_tables;

Show tables that are accessible by the current user

sql> SELECT table_name FROM all_tables ORDER BY table_name; The following picture illustrates the tables that can be returned from the user_tables, all_tables, and dba_tables views:

R cannot be resolved - Android error

I had tried all of the above with no prevail. It turned out PhoneGap was causing a conflict with the Android SDK. After uninstalling PhoneGap, the Resources file started regenerating again. Another project, needed PhoneGap so I re-installed, and once again, the Android project (a different project) stopped auto-generating the R file - Build Automatically was checked, did the Clean, and restarted Eclipse - no dice. I removed PhoneGap and it was working once again. This was PhoneGap v 1.5 with the MDS 1.1 plugin for Eclipse.

LDAP root query syntax to search more than one specific OU

After speaking with an LDAP expert, it's not possible this way. One query can't search more than one DC or OU.

Your options are:

  1. Run more then 1 query and parse the result.
  2. Use a filter to find the desired users/objects based off a different attribute like an AD group or by name.

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

https://jsfiddle.net/shuvamallick/3o0h5oka/

Cannot use object of type stdClass as array?

Have same problem today, solved like this:

If you call json_decode($somestring) you will get an Object and you need to access like $object->key , but if u call json_decode($somestring, true) you will get an dictionary and can access like $array['key']

Update all objects in a collection using LINQ

You can use LINQ to convert your collection to an array and then invoke Array.ForEach():

Array.ForEach(MyCollection.ToArray(), item=>item.DoSomeStuff());

Obviously this will not work with collections of structs or inbuilt types like integers or strings.

Immediate exit of 'while' loop in C++

while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    exit(0);
  cin>>gNum;
}

Trust me, that will exit the loop. If that doesn't work nothing will. Mind, this may not be what you want...

index.php not loading by default

I had a similar symptom. In my case though, my idiocy was in unintentionally also having an empty index.html file in the web root folder. Apache was serving this rather than index.php when I didn't explicitly request index.php, since DirectoryIndex was configured as follows in mods-available/dir.conf:

DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm

That is, 'index.html' appears ahead of 'index.php' in the priority list. Removing the index.html file from the web root naturally resolved the problem. D'oh!

How to get position of a certain element in strings vector, to use it as an index in ints vector?

If you want an index, you can use std::find in combination with std::distance.

auto it = std::find(Names.begin(), Names.end(), old_name_);
if (it == Names.end())
{
  // name not in vector
} else
{
  auto index = std::distance(Names.begin(), it);
}

Print current call stack from a method in Python code

If you use python debugger, not only interactive probing of variables but you can get the call stack with the "where" command or "w".

So at the top of your program

import pdb

Then in the code where you want to see what is happening

pdb.set_trace()

and you get dropped into a prompt

How do you get an iPhone's device name

For xamarin user, use this

UIKit.UIDevice.CurrentDevice.Name

Pass multiple parameters to rest API - Spring

you can pass multiple params in url like

http://localhost:2000/custom?brand=dell&limit=20&price=20000&sort=asc

and in order to get this query fields , you can use map like

    @RequestMapping(method = RequestMethod.GET, value = "/custom")
    public String controllerMethod(@RequestParam Map<String, String> customQuery) {

        System.out.println("customQuery = brand " + customQuery.containsKey("brand"));
        System.out.println("customQuery = limit " + customQuery.containsKey("limit"));
        System.out.println("customQuery = price " + customQuery.containsKey("price"));
        System.out.println("customQuery = other " + customQuery.containsKey("other"));
        System.out.println("customQuery = sort " + customQuery.containsKey("sort"));

        return customQuery.toString();
    }

What's the best way to share data between activities?

Assuming you are calling activity two from activity one using an Intent.
You can pass the data with the intent.putExtra(),

Take this for your reference. Sending arrays with Intent.putExtra

Hope that's what you want.

How to create a notification with NotificationCompat.Builder?

The NotificationCompat.Builder is the most easy way to create Notifications on all Android versions. You can even use features that are available with Android 4.1. If your app runs on devices with Android >=4.1 the new features will be used, if run on Android <4.1 the notification will be an simple old notification.

To create a simple Notification just do (see Android API Guide on Notifications):

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!")
    .setContentIntent(pendingIntent); //Required on Gingerbread and below

You have to set at least smallIcon, contentTitle and contentText. If you miss one the Notification will not show.

Beware: On Gingerbread and below you have to set the content intent, otherwise a IllegalArgumentException will be thrown.

To create an intent that does nothing, use:

final Intent emptyIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, NOT_USED, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

You can add sound through the builder, i.e. a sound from the RingtoneManager:

mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))

The Notification is added to the bar through the NotificationManager:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mId, mBuilder.build());

"Gradle Version 2.10 is required." Error

For people who are using Ionic/Cordova framework, we need to change the distributionUrl in GradleBuilder.js file to var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'http\\://services.gradle.org/distributions/gradle-2.10-all.zip';

The GradleBuilder.js locates at project/platforms/android/cordova/lib/builders/GradleBuilder.js

How to check whether particular port is open or closed on UNIX?

Try (maybe as root)

lsof -i -P

and grep the output for the port you are looking for.

For example to check for port 80 do

lsof -i -P | grep :80

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

If our CustomTableSeeder is in same directory with DatabaseSeeder we should use like below:

$this->call('database\seeds\CustomTableSeeder');

in our DatabaseSeeder File; then another error will be thrown that says: 'DB Class not found' then we should add our DB facade to our CustomTableSeeder File like below:

use Illuminate\Support\Facades\DB;

it worked for me!

Recover SVN password from local cache

Your SVN passwords in Ubuntu (12.04) are in:

~/.subversion/auth/svn.simple/

However in newer versions they are encrypted, as earlier someone mentioned. To find gnome-keyring passwords, I suggest You to use 'gkeyring' program.

To install it on Ubuntu – add repository :

sudo add-apt-repository ppa:kampka/ppa
sudo apt-get update

Install it:

sudo apt-get install gkeyring

And run as following:

gkeyring --id 15 --output=name,secret

Try different key ids to find pair matching what you are looking for. Thanks to kampka for the soft.

How to get the nth element of a python list or a default if not available

Just discovered that :

next(iter(myList), 5)

iter(l) returns an iterator on myList, next() consumes the first element of the iterator, and raises a StopIteration error except if called with a default value, which is the case here, the second argument, 5

This only works when you want the 1st element, which is the case in your example, but not in the text of you question, so...

Additionally, it does not need to create temporary lists in memory and it works for any kind of iterable, even if it does not have a name (see Xiong Chiamiov's comment on gruszczy's answer)

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

I use this script

EXEC sp_MSForEachTable ‘ALTER TABLE ? NOCHECK CONSTRAINT ALL’
EXEC sp_MSForEachTable ‘DELETE FROM ?’
EXEC sp_MSForEachTable ‘ALTER TABLE ? CHECK CONSTRAINT ALL’
GO

Convert a date format in PHP

$timestamp = strtotime(your date variable); 
$new_date = date('d-m-Y', $timestamp);

For more, see the documentation for strtotime.

Or even shorter:

$new_date = date('d-m-Y', strtotime(your date variable));

Manually map column names with class properties

The simple solution to the problem Kaleb is trying to solve is just to accept the property name if the column attribute doesn't exist:

Dapper.SqlMapper.SetTypeMap(
    typeof(T),
    new Dapper.CustomPropertyTypeMap(
        typeof(T),
        (type, columnName) =>
            type.GetProperties().FirstOrDefault(prop =>
                prop.GetCustomAttributes(false)
                    .OfType<ColumnAttribute>()
                    .Any(attr => attr.Name == columnName) || prop.Name == columnName)));

xml.LoadData - Data at the root level is invalid. Line 1, position 1

If your xml is in a string use the following to remove any byte order mark:

        xml = new Regex("\\<\\?xml.*\\?>").Replace(xml, "");

Difference between ProcessBuilder and Runtime.exec()

Yes there is a difference.

  • The Runtime.exec(String) method takes a single command string that it splits into a command and a sequence of arguments.

  • The ProcessBuilder constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)

So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.

Null check in VB

Your code is way more cluttered than necessary.

Replace (Not (X Is Nothing)) with X IsNot Nothing and omit the outer parentheses:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For i As Integer = 0 To comp.Container.Components.Count() - 1
        fixUIIn(comp.Container.Components(i), style)
    Next
End If

Much more readable. … Also notice that I’ve removed the redundant Step 1 and the probably redundant .Item.

But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each instead:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For Each component In comp.Container.Components
        fixUIIn(component, style)
    Next
End If

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

ValueError : I/O operation on closed file

Same error can raise by mixing: tabs + spaces.

with open('/foo', 'w') as f:
 (spaces OR  tab) print f       <-- success
 (spaces AND tab) print f       <-- fail

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

Essentially it means you don't have the index you are trying to reference. For example:

df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)

will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:

df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)

Hope that answers your question!

Oracle: How to find out if there is a transaction pending?

This is the query I normally use,

select s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from v$transaction t
inner join v$session s on t.addr = s.taddr;

How to convert all text to lowercase in Vim

use ggguG

gg: goes to the first line.

gu: change to lowercase.

G: goes to the last line.

How to import data from one sheet to another

VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4". VLOOKUP example

External Reference

To reference a cell of the same Workbook use the following pattern:

<Sheetname>!<Cell>

Example:

Table1!A1

To reference a cell of a different Workbook use this pattern:

[<Workbook_name>]<Sheetname>!<Cell>

Example:

[MyWorkbook]Table1!A1

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

ConcurrentHashMap

  • You should use ConcurrentHashMap when you need very high concurrency in your project.
  • It is thread safe without synchronizing the whole map.
  • Reads can happen very fast while write is done with a lock.
  • There is no locking at the object level.
  • The locking is at a much finer granularity at a hashmap bucket level.
  • ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it.
  • ConcurrentHashMap uses multitude of locks.

SynchronizedHashMap

  • Synchronization at Object level.
  • Every read/write operation needs to acquire lock.
  • Locking the entire collection is a performance overhead.
  • This essentially gives access to only one thread to the entire map & blocks all the other threads.
  • It may cause contention.
  • SynchronizedHashMap returns Iterator, which fails-fast on concurrent modification.

source

Boto3 to download all files from a S3 Bucket

I have the same needs and created the following function that download recursively the files.

The directories are created locally only if they contain files.

import boto3
import os

def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'):
    paginator = client.get_paginator('list_objects')
    for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
        if result.get('CommonPrefixes') is not None:
            for subdir in result.get('CommonPrefixes'):
                download_dir(client, resource, subdir.get('Prefix'), local, bucket)
        for file in result.get('Contents', []):
            dest_pathname = os.path.join(local, file.get('Key'))
            if not os.path.exists(os.path.dirname(dest_pathname)):
                os.makedirs(os.path.dirname(dest_pathname))
            resource.meta.client.download_file(bucket, file.get('Key'), dest_pathname)

The function is called that way:

def _start():
    client = boto3.client('s3')
    resource = boto3.resource('s3')
    download_dir(client, resource, 'clientconf/', '/tmp', bucket='my-bucket')

JavaScript object: access variable property by name as string

ThiefMaster's answer is 100% correct, although I came across a similar problem where I needed to fetch a property from a nested object (object within an object), so as an alternative to his answer, you can create a recursive solution that will allow you to define a nomenclature to grab any property, regardless of depth:

function fetchFromObject(obj, prop) {

    if(typeof obj === 'undefined') {
        return false;
    }

    var _index = prop.indexOf('.')
    if(_index > -1) {
        return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
    }

    return obj[prop];
}

Where your string reference to a given property ressembles property1.property2

Code and comments in JsFiddle.

LINQ: Distinct values

Are you trying to be distinct by more than one field? If so, just use an anonymous type and the Distinct operator and it should be okay:

var query = doc.Elements("whatever")
               .Select(element => new {
                             id = (int) element.Attribute("id"),
                             category = (int) element.Attribute("cat") })
               .Distinct();

If you're trying to get a distinct set of values of a "larger" type, but only looking at some subset of properties for the distinctness aspect, you probably want DistinctBy as implemented in MoreLINQ in DistinctBy.cs:

 public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
     this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     IEqualityComparer<TKey> comparer)
 {
     HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
     foreach (TSource element in source)
     {
         if (knownKeys.Add(keySelector(element)))
         {
             yield return element;
         }
     }
 }

(If you pass in null as the comparer, it will use the default comparer for the key type.)

How do I set specific environment variables when debugging in Visual Studio?

Visual Studio 2003 doesn't seem to allow you to set environment variables for debugging.

What I do in C/C++ is use _putenv() in main() and set any variables. Usually I surround it with a #if defined DEBUG_MODE / #endif to make sure only certain builds have it.

_putenv("MYANSWER=42");

I believe you can do the same thing with C# using os.putenv(), i.e.

os.putenv('MYANSWER', '42');

These will set the envrironment variable for that shell process only, and as such is an ephemeral setting, which is what you are looking for.

By the way, its good to use process explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx), which is a sysinternals tool. You can see what a given process' copy of the environment variables is, so you can validate that what you set is what you got.

Django Model() vs Model.objects.create()

The differences between Model() and Model.objects.create() are the following:


  1. INSERT vs UPDATE

    Model.save() does either INSERT or UPDATE of an object in a DB, while Model.objects.create() does only INSERT.

    Model.save() does

    • UPDATE If the object’s primary key attribute is set to a value that evaluates to True

    • INSERT If the object’s primary key attribute is not set or if the UPDATE didn’t update anything (e.g. if primary key is set to a value that doesn’t exist in the database).


  1. Existing primary key

    If primary key attribute is set to a value and such primary key already exists, then Model.save() performs UPDATE, but Model.objects.create() raises IntegrityError.

    Consider the following models.py:

    class Subject(models.Model):
       subject_id = models.PositiveIntegerField(primary_key=True, db_column='subject_id')
       name = models.CharField(max_length=255)
       max_marks = models.PositiveIntegerField()
    
    1. Insert/Update to db with Model.save()

      physics = Subject(subject_id=1, name='Physics', max_marks=100)
      physics.save()
      math = Subject(subject_id=1, name='Math', max_marks=50)  # Case of update
      math.save()
      

      Result:

      Subject.objects.all().values()
      <QuerySet [{'subject_id': 1, 'name': 'Math', 'max_marks': 50}]>
      
    2. Insert to db with Model.objects.create()

      Subject.objects.create(subject_id=1, name='Chemistry', max_marks=100)
      IntegrityError: UNIQUE constraint failed: m****t.subject_id
      

    Explanation: In the example, math.save() does an UPDATE (changes name from Physics to Math, and max_marks from 100 to 50), because subject_id is a primary key and subject_id=1 already exists in the DB. But Subject.objects.create() raises IntegrityError, because, again the primary key subject_id with the value 1 already exists.


  1. Forced insert

    Model.save() can be made to behave as Model.objects.create() by using force_insert=True parameter: Model.save(force_insert=True).


  1. Return value

    Model.save() return None where Model.objects.create() return model instance i.e. package_name.models.Model


Conclusion: Model.objects.create() does model initialization and performs save() with force_insert=True.

Excerpt from the source code of Model.objects.create()

def create(self, **kwargs):
    """
    Create a new object with the given kwargs, saving it to the database
    and returning the created object.
    """
    obj = self.model(**kwargs)
    self._for_write = True
    obj.save(force_insert=True, using=self.db)
    return obj

For more details follow the links:

  1. https://docs.djangoproject.com/en/stable/ref/models/querysets/#create

  2. https://github.com/django/django/blob/2d8dcba03aae200aaa103ec1e69f0a0038ec2f85/django/db/models/query.py#L440

How to send file contents as body entity using cURL

I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:

curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX

wget command to download a file and save as a different filename

wget -O yourfilename.zip remote-storage.url/theirfilename.zip

will do the trick for you.

Note:

a) its a capital O.

b) wget -O filename url will only work. Putting -O last will not.

HTML: how to force links to open in a new tab, not new window

I didn't try this but I think it works in all browsers:

target="_parent"

Android adding simple animations while setvisibility(view.Gone)

Try adding this line to the xml parent layout

 android:animateLayoutChanges="true"

Your layout will look like this

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:longClickable="false"
    android:orientation="vertical"
    android:weightSum="16">

    .......other code here

    </LinearLayout>

How to change MenuItem icon in ActionBar programmatically

I resolved this problem this way:

In onCreateOptionsMenu:

this.menu = menu;
this.menu.add("calendar");
ImageView imageView = new ImageView(getActivity());
imageView.setMinimumHeight(128);
imageView.setMinimumWidth(128);
imageView.setImageDrawable(yourDrawable);
MenuItem item = this.menu.getItem(0);
item.setActionView(imageView);

in onOptionsItemSelected:

if (item.getOrder() == 0) {
    //TODO
    return true;
}

What are the lengths of Location Coordinates, latitude and longitude?

Google Maps actually uses signed values to represent the position:

  • Latitude : max/min 90.0000000 to -90.0000000

  • Longitude : max/min 180.0000000 to -180.0000000

So if you want to work with Coordinates in your projects you would need DECIMAL(10,7) ie. for SQL.

Java JRE 64-bit download for Windows?

You can also just search on sites like Tucows and CNET, they have it there too.

Should I use != or <> for not equal in T-SQL?

Although they function the same way, != means exactly "not equal to", while <> means greater than and less than the value stored.

Consider >= or <=, and this will make sense when factoring in your indexes to queries... <> will run faster in some cases (with the right index), but in some other cases (index free) they will run just the same.

This also depends on how your databases system reads the values != and <>. The database provider may just shortcut it and make them function the same, so there isn't any benefit either way.PostgreSQL and SQL Server do not shortcut this; it is read as it appears above.

How to create a HTML Cancel button that redirects to a URL

There is no button type="cancel" in html. You can try like this

<a href="http://www.url.com/yourpage.php">Cancel</a>

You can make it look like a button by using CSS style properties.

How to set up ES cluster?

its super easy.

You'll need each machine to have it's own copy of ElasticSearch (simply copy the one you have now) -- the reason is that each machine / node whatever is going to keep it's own files that are sharded accross the cluster.

The only thing you really need to do is edit the config file to include the name of the cluster.

If all machines have the same cluster name elasticsearch will do the rest automatically (as long as the machines are all on the same network)

Read here to get you started: https://www.elastic.co/guide/en/elasticsearch/guide/current/deploy.html

When you create indexes (where the data goes) you define at that time how many replicas you want (they'll be distributed around the cluster)

Jquery - animate height toggle

I just thought to give you the reason why your solution did not work:

When $(document).ready() is executed only the $('#topbar-show') selector can find a matching element from the DOM. The #topbar-show element has not been created yet.

To get past this problem, you may use live event bindings

$('#topbar-show').live('click',function(e){});
$('#topbar-hide').live('click',function(e){});

This is the most simple way to fix you solution. The rest of these answer go further to provide you a better solutions instead that do not modify the hopefully permanent id attribute.

Java - get the current class name?

Try,

String className = this.getClass().getSimpleName();

This will work as long as you don't use it in a static method.

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

div inside php echo

You can also do this,

<?php 
if ( ($cart->count_product) > 0) { 
  $print .= "<div class='my_class'>"
  $print .= $cart->count_product; 
  $print .= "</div>"
} else { 
   $print = ''; 
} 
echo  $print;
?>

C# listView, how do I add items to columns 2, 3 and 4 etc?

Here is the msdn documentation on the listview object and the listviewItem object.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.aspx

I would highly recommend that you at least take the time to skim the documentation on any objects you use from the .net framework. While the documentation can be pretty poor at some times it is still invaluable especially when you run into situations like this.

But as James Atkinson said it's simply a matter of adding subitems to a listviewitem like so:

ListViewItem i = new ListViewItem("column1");
i.SubItems.Add("column2");
i.SubItems.Add("column3");

how to set active class to nav menu from twitter bootstrap

it is a workaround. try

<div class="nav-collapse">
  <ul class="nav">
    <li id="home" class="active"><a href="~/Home/Index">Home</a></li>
    <li><a href="#">Project</a></li>
    <li><a href="#">Customer</a></li>
    <li><a href="#">Staff</a></li>
    <li  id="demo"><a href="~/Home/demo">Broker</a></li>
    <li id='sale'><a href="#">Sale</a></li>
  </ul>
</div>

and on each page js add

$(document).ready(function () {
  $(".nav li").removeClass("active");//this will remove the active class from  
                                     //previously active menu item 
  $('#home').addClass('active');
  //for demo
  //$('#demo').addClass('active');
  //for sale 
  //$('#sale').addClass('active');
});

Remove empty lines in a text file via grep

Try the following:

grep -v -e '^$'

set date in input type date

Update: I'm doing this with date.toISOString().substr(0, 10). Gives the same result as the accepted answer and has good support.

Concatenating variables and strings in React

You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id} - you need to indicate which are variables and which are string literals. Since anything inside {} is an inline JSX expression, you can do:

href={"#demo" + this.state.id}

This will use the string literal #demo and concatenate it to the value of this.state.id. This can then be applied to all strings. Consider this:

var text = "world";

And this:

{"Hello " + text + " Andrew"}

This will yield:

Hello world Andrew 

You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr} (interpolated expression), which is closer to what you seem to be trying to do:

href={`#demo${this.state.id}`}

This will basically substitute the value of this.state.id, concatenating it to #demo. It is equivalent to doing: "#demo" + this.state.id.

Set the maximum character length of a UITextField in Swift

My Swift 4 version of shouldChangeCharactersIn

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

        guard let preText = textField.text as NSString?,
            preText.replacingCharacters(in: range, with: string).count <= MAX_TEXT_LENGTH else {
            return false
        }

        return true
    }

How to get the parents of a Python class?

New-style classes have an mro method you can call which returns a list of parent classes in method resolution order.

Compression/Decompression string with C#

This is an updated version for .NET 4.5 and newer using async/await and IEnumerables:

public static class CompressionExtensions
{
    public static async Task<IEnumerable<byte>> Zip(this object obj)
    {
        byte[] bytes = obj.Serialize();

        using (MemoryStream msi = new MemoryStream(bytes))
        using (MemoryStream mso = new MemoryStream())
        {
            using (var gs = new GZipStream(mso, CompressionMode.Compress))
                await msi.CopyToAsync(gs);

            return mso.ToArray().AsEnumerable();
        }
    }

    public static async Task<object> Unzip(this byte[] bytes)
    {
        using (MemoryStream msi = new MemoryStream(bytes))
        using (MemoryStream mso = new MemoryStream())
        {
            using (var gs = new GZipStream(msi, CompressionMode.Decompress))
            {
                // Sync example:
                //gs.CopyTo(mso);

                // Async way (take care of using async keyword on the method definition)
                await gs.CopyToAsync(mso);
            }

            return mso.ToArray().Deserialize();
        }
    }
}

public static class SerializerExtensions
{
    public static byte[] Serialize<T>(this T objectToWrite)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToWrite);

            return stream.GetBuffer();
        }
    }

    public static async Task<T> _Deserialize<T>(this byte[] arr)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            await stream.WriteAsync(arr, 0, arr.Length);
            stream.Position = 0;

            return (T)binaryFormatter.Deserialize(stream);
        }
    }

    public static async Task<object> Deserialize(this byte[] arr)
    {
        object obj = await arr._Deserialize<object>();
        return obj;
    }
}

With this you can serialize everything BinaryFormatter supports, instead only of strings.

Edit:

In case, you need take care of Encoding, you could just use Convert.ToBase64String(byte[])...

Take a look at this answer if you need an example!

Remove padding from columns in Bootstrap 3

Bootstrap 4 has the class .no-gutters that you can add to the row element.

<div class="container-fluid">
    <div class="row no-gutters">
        <div class="col-md-12">
            [YOUR CONTENT HERE]
        </div>
    </div>
</div>

Reference: http://getbootstrap.com/docs/4.0/layout/grid/#grid-options

VB.NET Switch Statement GoTo Case

Why not just do it like this:

Select Case parameter     
   Case "userID"                
      ' does something here.        
   Case "packageID"                
      ' does something here.        
   Case "mvrType"                 
      If otherFactor Then                         
         ' does something here.                 
      Else                         
         ' do processing originally part of GoTo here
         Exit Select  
      End If      
End Select

I'm not sure if not having a case else at the end is a big deal or not, but it seems like you don't really need the go to if you just put it in the else statement of your if.

WPF - add static items to a combo box

You can also add items in code:

cboWhatever.Items.Add("SomeItem");

Also, to add something where you control display/value, (almost categorically needed in my experience) you can do so. I found a good stackoverflow reference here:

Key Value Pair Combobox in WPF

Sum-up code would be something like this:

ComboBox cboSomething = new ComboBox();
cboSomething.DisplayMemberPath = "Key";
cboSomething.SelectedValuePath = "Value";
cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));

PHP Configuration: It is not safe to rely on the system's timezone settings

Obviously I'm a little out of season on this question but for the benefit of the next sufferer: I just had this problem and in my case (in contrast to OP who tried the same without success) the fix was to revise php.ini, changing

date.timezone = America/New York

to

date.timezone = America/New_York

That is adding the underscore.

How to create the most compact mapping n ? isprime(n) up to a limit N?

myInp=int(input("Enter a number: "))
if myInp==1:
    print("The number {} is neither a prime not composite no".format(myInp))
elif myInp>1:
    for i in range(2,myInp//2+1):
        if myInp%i==0:
            print("The Number {} is not a prime no".format(myInp))
            print("Because",i,"times",myInp//i,"is",myInp)
            break
    else:
        print("The Number {} is a prime no".format(myInp))
else:
    print("Alas the no {} is a not a prime no".format(myInp))

How to set specific Java version to Maven

On Macs, (assuming you have the right version installed)

JAVA_HOME=`/usr/libexec/java_home -v 1.8` mvn clean install -DskipTests

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

Decompile an APK, modify it and then recompile it

  1. First download the dex2jar tool from Following link http://code.google.com/p/dex2jar/downloads/list

  2. Extract the file it create dex2jar folder

  3. Now you pick your apk file and change its extension .apk to .zip after changing extension it seems to be zip file then extract this zip file you found classes.dex file

  4. Now pick classes.dex file and put it into dex2jar folder

  5. Now open cmd window and type the path of dex2jar folder

  6. Now type the command dex2jar.bat classes.dex and press Enter

  7. Now Open the dex2jar folder you found classes_dex2jar.jar file

  8. Next you download the java decompiler tool from the following link http://java.decompiler.free.fr/?q=jdgui

  9. Last Step Open the file classes_dex2jar.jar in java decompiler tool now you can see apk code

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

Eclipse "this compilation unit is not on the build path of a java project"

For example if there are 4 project and a root project, add the other child projects to build path of root project. If there is not selection of build path, add below codes to .project file.

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>rootProject</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.m2e.core.maven2Builder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
        <nature>org.eclipse.m2e.core.maven2Nature</nature>
    </natures>
</projectDescription>

How to check if a div is visible state or not?

Check if it's visible.

$("#singlechatpanel-1").is(':visible');

Check if it's hidden.

$("#singlechatpanel-1").is(':hidden');

Python List vs. Array - when to use?

Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. float or uint64_t).

The array.array type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl).

array.array is also a reasonable way to represent a mutable string in Python 2.x (array('B', bytes)). However, Python 2.6+ and 3.x offer a mutable byte string as bytearray.

However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.

To make a long story short: array.array is useful when you need a homogeneous C array of data for reasons other than doing math.

Refresh Page C# ASP.NET

You can just do a regular postback to refresh the page if you don't want to redirect. Posting back from any control will run the page lifecycle and refresh the page.

To do it from javascript, you can just call the __doPostBack() function.

What are the benefits to marking a field as `readonly` in C#?

There can be a performance benefit in WPF, as it removes the need for expensive DependencyProperties. This can be especially useful with collections

Sound effects in JavaScript / HTML5

To play the same sample multiple times, wouldn't it be possible to do something like this:

e.pause(); // Perhaps optional
e.currentTime = 0;
e.play();

(e is the audio element)

Perhaps I completely misunderstood your problem, do you want the sound effect to play multiple times at the same time? Then this is completely wrong.

What is the Swift equivalent to Objective-C's "@synchronized"?

I was looking for this myself and came to the conclusion there's no native construct inside of swift for this yet.

I did make up this small helper function based on some of the code I've seen from Matt Bridges and others.

func synced(_ lock: Any, closure: () -> ()) {
    objc_sync_enter(lock)
    closure()
    objc_sync_exit(lock)
}

Usage is pretty straight forward

synced(self) {
    println("This is a synchronized closure")
}

There is one problem I've found with this. Passing in an array as the lock argument seems to cause a very obtuse compiler error at this point. Otherwise though it seems to work as desired.

Bitcast requires both operands to be pointer or neither
  %26 = bitcast i64 %25 to %objc_object*, !dbg !378
LLVM ERROR: Broken function found, compilation aborted!

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

Converting java.sql.Date to java.util.Date

Since java.sql.Date extends java.util.Date, you should be able to do

java.util.Date newDate = result.getDate("VALUEDATE");

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

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

This was the method which worked best for me and didn't open up new tabs, but just downloaded the files/images I required:

var filesForDownload = [];
filesForDownload( { path: "/path/file1.txt", name: "file1.txt" } );
filesForDownload( { path: "/path/file2.jpg", name: "file2.jpg" } );
filesForDownload( { path: "/path/file3.png", name: "file3.png" } );
filesForDownload( { path: "/path/file4.txt", name: "file4.txt" } );

$jq('input.downloadAll').click( function( e )
{
    e.preventDefault();

    var temporaryDownloadLink = document.createElement("a");
    temporaryDownloadLink.style.display = 'none';

    document.body.appendChild( temporaryDownloadLink );

    for( var n = 0; n < filesForDownload.length; n++ )
    {
        var download = filesForDownload[n];
        temporaryDownloadLink.setAttribute( 'href', download.path );
        temporaryDownloadLink.setAttribute( 'download', download.name );

        temporaryDownloadLink.click();
    }

    document.body.removeChild( temporaryDownloadLink );
} );

Angular.js How to change an elements css class on click and to remove all others

Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.

You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).

Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.

Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV

(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.

Hope this helps someone, I've found expressions in ng-class to be very useful!

HTML

<ul>
  <li ng-repeat="person in people" 
  data-ng-class="{'active-selection': person.id == activeClass}">
    <a data-ng-click="selectPerson(person.id)">
      {{person.name}}
    </a>
  </li>
</ul>

JS

app.controller('MainCtrl', function($scope) {
  $scope.people = [{
    id: "1",
    name: "John",
  }, {
    id: "2",
    name: "Lucy"
  }, {
    id: "3",
    name: "Mark"
  }, {
    id: "4",
    name: "Sam"
  }];

  $scope.selectPerson = function(id) {
    $scope.activeClass = id;
    console.log(id);
  };
});    

CSS:

.active-selection {
  background-color: #eee;
}

javax.naming.NameNotFoundException

The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.

As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:

/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml

The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.

BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is

@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
   public void bussinesMethod(){

   }
}

No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.

Now in your client code you need to lookup "MyComponentName".

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

I had a very similar issue to this when testing a restored backup of a mysql and associated php system. No matter what configuration settings I added on mysql it was not making any difference. After troubleshooting the issue for some time I noticed in the mysql logs that the mysql config files were being largely ignored by mysql. The reason was due to the file permissions being too open which was due to the fact my zip backup and restore process was losing all file permissions. I modified my backup and restore scripts to use tar instead and then everything worked as it should.

In summary, check the file permissions on your mysql config files are correct. Hope this helps someone.

How do I cancel form submission in submit button onclick event?

function btnClick() {
    return validData();
}

How do I script a "yes" response for installing programs?

You just need to put -y with the install command.

For example: yum install <package_to_install> -y

What does void do in java?

Void doesn't return anything; it tells the compiler the method doesn't have a return value.

How to print a dictionary's key?

Make sure to do

dictionary.keys()
# rather than
dictionary.keys

Icons missing in jQuery UI

You need downbload the jQueryUI, this contains de images that you need

enter link description here

Current time formatting with Javascript

_x000D_
_x000D_
d = Date.now();_x000D_
d = new Date(d);_x000D_
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");_x000D_
_x000D_
console.log(d);
_x000D_
_x000D_
_x000D_

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

I have 2 accounts on my windows machine and I was experiencing this problem with one of them. I did not want to use the sa account, I wanted to use Windows login. It was not immediately obvious to me that I needed to simply sign into the other account that I used to install SQL Server, and add the permissions for the new account from there

(SSMS > Security > Logins > Add a login there)

Easy way to get the full domain name you need to add there open cmd echo each one.

echo %userdomain%\%username%

Add a login for that user and give it all the permissons for master db and other databases you want. When I say "all permissions" make sure NOT to check of any of the "deny" permissions since that will do the opposite.

Rotate label text in seaborn factorplot

You can also use plt.setp as follows:

import matplotlib.pyplot as plt
import seaborn as sns

plot=sns.barplot(data=df,  x=" ", y=" ")
plt.setp(plot.get_xticklabels(), rotation=90)

to rotate the labels 90 degrees.

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

I just had this problem when trying to use data bind and declaring the layout tag. I know it is a bit late but for the sake of anyone encountering this problem, What I did to resolve the issue after so many attempts was that on your root layout when you are not using data bind say for example this

  <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">     </android.support.constraint.ConstraintLayout>

remove the

xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"

and just put it on your layout tag(that is if you are using data binding)

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

</layout>

and hopefully it will work. the android.enableAapt2=false didn't work for me so I have to remove everything and try to figure out why I get the error when I put layout tag and use data binding thus I came up with the solution. Hope it helps

Regex Email validation

STRING SEARCH USING REGEX METHOD IN C#

How to validate an Email by Regular Expression?

string EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
if (Regex.IsMatch(Email, EmailPattern, RegexOptions.IgnoreCase))
{
    Console.WriteLine("Email: {0} is valid.", Email);
}
else
{
    Console.WriteLine("Email: {0} is not valid.", Email);
}

Use Reference String.Regex() Method

Check if string contains only digits

If you want to even support for float values (Dot separated values) then you can use this expression :

var isNumber = /^\d+\.\d+$/.test(value);

Disable Copy or Paste action for text box?

Best way to do this is to add a data attribute to the field (textbox) where you want to avoid the cut,copy and paste.

Just create a method for the same which is as follows :-

function ignorePaste() {

$("[data-ignorepaste]").bind("cut copy paste", function (e) {
            e.preventDefault(); //prevent the default behaviour 
        });

};

Then once when you add the above code simply add the data attribute to the field where you want to ignore cut copy paste. in our case your add a data attribute to confirm email text box as below :-

Confirm Email: <input type="textbox" id= "confirmEmail" data-ignorepaste=""/>

Call the method ignorePaste()

So in this way you will be able to use this throughout the application, all you need to do is just add the data attribute where you want to ignore cut copy paste

https://jsfiddle.net/0ac6pkbf/21/

Kubernetes service external ip pending

If running on minikube, don't forget to mention namespace if you are not using default.

minikube service << service_name >> --url --namespace=<< namespace_name >>

how to convert java string to Date object

    try 
    {  
      String datestr="06/27/2007";
      DateFormat formatter; 
      Date date; 
      formatter = new SimpleDateFormat("MM/dd/yyyy");
      date = (Date)formatter.parse(datestr);  
    } 
    catch (Exception e)
    {}

month is MM, minutes is mm..

How to convert array values to lowercase in PHP?

You don't say if your array is multi-dimensional. If it is, array_map will not work alone. You need a callback method. For multi-dimensional arrays, try array_change_key_case.

// You can pass array_change_key_case a multi-dimensional array,
// or call a method that returns one
$my_array = array_change_key_case(aMethodThatReturnsMultiDimArray(), CASE_UPPER);

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

Many browsers have changed their security policies to no longer allow reading data directly from file shares or even local resources. You need to either place the files somewhere that your tomcat instance can serve them up and put a "regular" http url in the html you generate. This can be accomplished by either providing a servlet which reads and provides the file putting the file into a directory where tomcat will serve it up as "static" content.

How to get thread id from a thread pool?

Using Thread.currentThread():

private class MyTask implements Runnable {
    public void run() {
        long threadId = Thread.currentThread().getId();
        logger.debug("Thread # " + threadId + " is doing this task");
    }
}

What's the correct way to convert bytes to a hex string in Python 3?

it can been used the format specifier %x02 that format and output a hex value. For example:

>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
...     res += "%02x" % b
... 
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736

jquery append div inside div with id and manipulate

Why not go even simpler with either one of these options:

$("#box").html('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Or, if you want to append it to existing content:

$("#box").append('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

Note: I put the id="myid" right into the HTML string rather than using separate code to set it.

Both the .html() and .append() jQuery methods can take a string of HTML so there's no need to use a separate step for creating the objects.

ng serve not detecting file changes automatically

I had the same problem, using sudo ng serve seemed to "solve" the problem unsatisfactorily. Using sudo is not satisfactory IMO.

I checked my INotify count versus my default limit (8192) using: lsof | grep inotify | wc -l The value returned by the above command was way less than the limit. So the INotify solution didn't seem to apply to my problem.

I also checked permissions and ownership, both seemed ok, comparable to another project that worked.

Out of frustration I restarted VS Code. Basically I closed all instances, I had two running and re-opened both following which the problem went away.

I am leaning towards a possible bug somewhere. This is something to consider before turning your system inside out. Fortunately/Unfortunately this problem hasn't occurred again, I'll dig deeper if it does.

How to reduce a huge excel file

I stumbled upon an interesting reason for a gigantic .xlsx file. Original workbook had 20 sheets or so, was 20 MB I made a new workbook with 1 of the sheets, so it would be more manageable: still 11.5 MB Imagine my surprise to find that the single sheet in the new workbook had 1,041,776 (count 'em!) blank rows. Now it's 13.5 KB

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

That is an HTTP header. You would configure your webserver or webapp to send this header ideally. Perhaps in htaccess or PHP.

Alternatively you might be able to use

<head>...<meta http-equiv="Access-Control-Allow-Origin" content="*">...</head>

I do not know if that would work. Not all HTTP headers can be configured directly in the HTML.

This works as an alternative to many HTTP headers, but see @EricLaw's comment below. This particular header is different.

Caveat

This answer is strictly about how to set headers. I do not know anything about allowing cross domain requests.

About HTTP Headers

Every request and response has headers. The browser sends this to the webserver

GET /index.htm HTTP/1.1

Then the headers

Host: www.example.com
User-Agent: (Browser/OS name and version information)
.. Additional headers indicating supported compression types and content types and other info

Then the server sends a response

Content-type: text/html
Content-length: (number of bytes in file (optional))
Date: (server clock)
Server: (Webserver name and version information)

Additional headers can be configured for example Cache-Control, it all depends on your language (PHP, CGI, Java, htaccess) and webserver (Apache, etc).

conversion from string to json object android

Using Kotlin

    val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
    
try {
      val jsonObject = JSONObject(data)
      val infoObj = jsonObject.getJSONObject("ApiInfo")
    } catch (e: Exception) {
    }

Edit a text file on the console using Powershell

While risking you punching me, I guess you are stuck with the solution you mentioned. Have a look at this posting on SuperUser:

Which are the non-x text editors in Powershell?

Also, there is a nano version for windows:

Nano Editor

I'll duck and cover now, hopefully someone will have a more sufficient answer.

Android check null or empty string in Android

Checking for empty string if it is equal to null, length is zero or containing "null" string

public static boolean isEmptyString(String text) {
        return (text == null || text.trim().equals("null") || text.trim()
                .length() <= 0);
    }

How to clear cache of Eclipse Indigo

If you are asking about cache where eclipse stores your project and workspace information right click on your project(s) and choose refresh. Then go to project in the menu on top of the window and click "clean".

This typically does what you need.

If it does not try to remove project from the workspace (just press "delete" on the project and then say that you DO NOT want to remove the sources). Then open project again.

If this does not work too, do the same with the workspace. If this still does not work, perform fresh checkout of your project from source control and create new workspace.

Well, this should work.

installing requests module in python 2.7 windows

There are four options here:

  1. Get virtualenv set up. Each virtual environment you create will automatically have pip.

  2. Get pip set up globally.

  3. Learn how to install Python packages manually—in most cases it's as simple as download, unzip, python setup.py install, but not always.

  4. Use Christoph Gohlke's binary installers.

Drop all tables command

rm db/development.sqlite3

How to "properly" create a custom object in JavaScript?

You can also do it this way, using structures :

function createCounter () {
    var count = 0;

    return {
        increaseBy: function(nb) {
            count += nb;
        },
        reset: function {
            count = 0;
        }
    }
}

Then :

var counter1 = createCounter();
counter1.increaseBy(4);

TypeError: 'NoneType' object has no attribute '__getitem__'

BrenBarn is correct. The error means you tried to do something like None[5]. In the backtrace, it says self.imageDef=self.values[2], which means that your self.values is None.

You should go through all the functions that update self.values and make sure you account for all the corner cases.

React js onClick can't pass value to method

I think, .bind(this, arg1, arg2, ...) in React's map - is bad code, because it is slow! 10-50 of .bind(this) in single render method - very slow code.
I fix it like this:
Render method
<tbody onClick={this.handleClickRow}>
map of <tr data-id={listItem.id}>
Handler
var id = $(ev.target).closest('tr').data().id

Full code below:

_x000D_
_x000D_
class MyGrid extends React.Component {_x000D_
  // In real, I get this from props setted by connect in Redux_x000D_
  state = {_x000D_
    list: [_x000D_
      {id:1, name:'Mike'},_x000D_
      {id:2, name:'Bob'},_x000D_
      {id:3, name:'Fred'}_x000D_
    ],_x000D_
    selectedItemId: 3_x000D_
  }_x000D_
  _x000D_
  render () {_x000D_
    const { list, selectedItemId }  = this.state_x000D_
    const { handleClickRow } = this_x000D_
_x000D_
    return (_x000D_
      <table>_x000D_
        <tbody onClick={handleClickRow}>_x000D_
          {list.map(listItem =>(_x000D_
            <tr key={listItem.id} data-id={listItem.id} className={selectedItemId===listItem.id ? 'selected' : ''}>_x000D_
              <td>{listItem.id}</td>_x000D_
              <td>{listItem.name}</td>_x000D_
            </tr>_x000D_
          ))}_x000D_
        </tbody>_x000D_
      </table>_x000D_
    )_x000D_
  }_x000D_
  _x000D_
  handleClickRow = (ev) => {_x000D_
    const target = ev.target_x000D_
    // You can use what you want to find TR with ID, I use jQuery_x000D_
    const dataset = $(target).closest('tr').data()_x000D_
    if (!dataset || !dataset.id) return_x000D_
    this.setState({selectedItemId:+dataset.id})_x000D_
    alert(dataset.id) // Have fun!_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<MyGrid/>, document.getElementById("react-dom"))
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.selected td {_x000D_
  background-color: rgba(0, 0, 255, 0.3);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="react-dom"></div>
_x000D_
_x000D_
_x000D_

CSS Transition doesn't work with top, bottom, left, right

Are there properties that aren't 'transitional'?

Answer: Yes.

If the property is not listed here it is not 'transitional'.

Reference: Animatable CSS Properties

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

How do I remove accents from characters in a PHP string?

You could use urlencode. Does not quite do what you want (remove accents), but will give you a url usable string

$output = urlencode ($input);

In Perl I could use a translate regex, but I cannot think of the PHP equivalent

$input =~ tr/áâàå/aaaa/;

etc...

you could do this using preg_replace

$patterns[0] = '/[á|â|à|å|ä]/';
$patterns[1] = '/[ð|é|ê|è|ë]/';
$patterns[2] = '/[í|î|ì|ï]/';
$patterns[3] = '/[ó|ô|ò|ø|õ|ö]/';
$patterns[4] = '/[ú|û|ù|ü]/';
$patterns[5] = '/æ/';
$patterns[6] = '/ç/';
$patterns[7] = '/ß/';
$replacements[0] = 'a';
$replacements[1] = 'e';
$replacements[2] = 'i';
$replacements[3] = 'o';
$replacements[4] = 'u';
$replacements[5] = 'ae';
$replacements[6] = 'c';
$replacements[7] = 'ss';

$output = preg_replace($patterns, $replacements, $input);

(Please note this was typed from a foggy beer ridden Friday after noon memory, so may not be 100% correct)

or you could make a hash table and do a replacement based off of that.

Fastest way to copy a file in Node.js

Mike's solution, but with promises:

const FileSystem = require('fs');

exports.copyFile = function copyFile(source, target) {
    return new Promise((resolve,reject) => {
        const rd = FileSystem.createReadStream(source);
        rd.on('error', err => reject(err));
        const wr = FileSystem.createWriteStream(target);
        wr.on('error', err => reject(err));
        wr.on('close', () => resolve());
        rd.pipe(wr);
    });
};

What is the difference between vmalloc and kmalloc?

You only need to worry about using physically contiguous memory if the buffer will be accessed by a DMA device on a physically addressed bus (like PCI). The trouble is that many system calls have no way to know whether their buffer will eventually be passed to a DMA device: once you pass the buffer to another kernel subsystem, you really cannot know where it is going to go. Even if the kernel does not use the buffer for DMA today, a future development might do so.

vmalloc is often slower than kmalloc, because it may have to remap the buffer space into a virtually contiguous range. kmalloc never remaps, though if not called with GFP_ATOMIC kmalloc can block.

kmalloc is limited in the size of buffer it can provide: 128 KBytes*). If you need a really big buffer, you have to use vmalloc or some other mechanism like reserving high memory at boot.

*) This was true of earlier kernels. On recent kernels (I tested this on 2.6.33.2), max size of a single kmalloc is up to 4 MB! (I wrote a fairly detailed post on this.) — kaiwan

For a system call you don't need to pass GFP_ATOMIC to kmalloc(), you can use GFP_KERNEL. You're not an interrupt handler: the application code enters the kernel context by means of a trap, it is not an interrupt.

How do I find the difference between two values without knowing which is larger?

If you plan to use the signed distance calculation snippet posted by phi (like I did) and your b might have value 0, you probably want to fix the code as described below:

import math

def distance(a, b):
    if (a == b):
        return 0
    elif (a < 0) and (b < 0) or (a > 0) and (b >= 0): # fix: b >= 0 to cover case b == 0
        if (a < b):
            return (abs(abs(a) - abs(b)))
        else:
            return -(abs(abs(a) - abs(b)))
    else:
        return math.copysign((abs(a) + abs(b)),b)

The original snippet does not work correctly regarding sign when a > 0 and b == 0.

How to quickly and conveniently disable all console.log statements in my code?

Ive been using the following to deal with he problem:-

var debug = 1;
var logger = function(a,b){ if ( debug == 1 ) console.log(a, b || "");};

Set debug to 1 to enable debugging. Then use the logger function when outputting debug text. It's also set up to accept two parameters.

So, instead of

console.log("my","log");

use

logger("my","log");

How to save image in database using C#

This is a method that uses a FileUpload control in asp.net:

byte[] buffer = new byte[fu.FileContent.Length];
Stream s = fu.FileContent;
s.Read(buffer, 0, buffer.Length);
//Then save 'buffer' to the varbinary column in your db where you want to store the image.

check if file exists on remote host with ssh

Test if a file exists:

HOST="example.com"
FILE="/path/to/file"

if ssh $HOST "test -e $FILE"; then
    echo "File exists."
else
    echo "File does not exist."
fi

And the opposite, test if a file does not exist:

HOST="example.com"
FILE="/path/to/file"

if ! ssh $HOST "test -e $FILE"; then
    echo "File does not exist."
else
    echo "File exists."
fi

HTML/CSS--Creating a banner/header

Remove the position: absolute; attribute in the style

How to increase space between dotted border dots

IF you're only targeting modern browsers, AND you can have your border on a separate element from your content, then you can use the CSS scale transform to get a larger dot or dash:

border: 1px dashed black;
border-radius: 10px;
-webkit-transform: scale(8);
transform: scale(8);

It takes a lot of positional tweaking to get it to line up, but it works. By changing the thickness of the border, the starting size and the scale factor, you can get to just about thickness-length ratio you want. Only thing you can't touch is dash-to-gap ratio.

Sending email with PHP from an SMTP server

In cases where you are hosting a Wordpress site on Linux and have server access you can save some headaches by installing msmtp which allows you to send via smtp from the standard php mail() function. msmtp is a simpler alternative to postfix which requires a bit more configuration.

Here are the steps:

Install msmtp

sudo apt-get install msmtp-mta ca-certificates

Create a new configuration file:

sudo nano /etc/msmtprc

...with the following configuration information:

# Set defaults.    
defaults

# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <[email protected]>
password <password>
from <[email protected]>
syslog LOG_MAIL

You need to replace the configuration data represented by everything within "<" and ">" (inclusive, remove these). For host/username/password, use your normal credentials for sending mail through your mail provider.

Tell PHP to use it

sudo nano /etc/php5/apache2/php.ini

Add this single line:

sendmail_path = /usr/bin/msmtp -t

Complete documention can be found here:

https://marlam.de/msmtp/

Chaining multiple filter() in Django, is this a bug?

Sometimes you don't want to join multiple filters together like this:

def your_dynamic_query_generator(self, event: Event):
    qs \
    .filter(shiftregistrations__event=event) \
    .filter(shiftregistrations__shifts=False)

And the following code would actually not return the correct thing.

def your_dynamic_query_generator(self, event: Event):
    return Q(shiftregistrations__event=event) & Q(shiftregistrations__shifts=False)

What you can do now is to use an annotation count-filter.

In this case we count all shifts which belongs to a certain event.

qs: EventQuerySet = qs.annotate(
    num_shifts=Count('shiftregistrations__shifts', filter=Q(shiftregistrations__event=event))
)

Afterwards you can filter by annotation.

def your_dynamic_query_generator(self):
    return Q(num_shifts=0)

This solution is also cheaper on large querysets.

Hope this helps.

Multiple arguments to function called by pthread_create()?

The args of print_the_arguments is arguments, so you should use:

struct arg_struct *args = (struct arg_struct *)arguments. 

"Multiple definition", "first defined here" errors

You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123();

#endif

commands.c

#include "commands.h"

void f123()
{
    /* code */
}

Math.random() versus Random.nextInt(int)

According to https://forums.oracle.com/forums/thread.jspa?messageID=6594485&#6594485 Random.nextInt(n) is both more efficient and less biased than Math.random() * n