Programs & Examples On #Mathml

An application of XML for describing mathematical notation and mathematical content

Fatal error: Call to undefined function: ldap_connect()

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

    extension=php_ldap.dll

  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!

Detect Windows version in .net

Like R. Bemrose suggested, if you are doing Windows 7 specific features, you should look at the Windows® API Code Pack for Microsoft® .NET Framework.

It contains a CoreHelpers class that let you determine the OS you are currently on (XP and above only, its a requirement for .NET nowaday)

It also provide multiple helper methods. For example, suppose that you want to use the jump list of Windows 7, there is a class TaskbarManager that provide a property called IsPlatformSupported and it will return true if you are on Windows 7 and above.

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

How to give ASP.NET access to a private key in a certificate in the certificate store?

If you are trying to load a cert from a .pfx file in IIS the solution may be as simple as enabling this option for the Application Pool.

Right click on the App Pool and select Advanced Settings.

Then enable Load User Profile


enter image description here

Setting SMTP details for php mail () function

Try from your dedicated server to telnet to smtp.gmail.com on port 465. It might be blocked by your internet provider

How to pass a parameter like title, summary and image in a Facebook sharer URL

Looks like Facebook disabled passing parameters to the sharer.

We have changed the behavior of the sharer plugin to be consistent with other plugins and features on our platform.

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Here's the URL to the post: https://developers.facebook.com/x/bugs/357750474364812/

Creating a Plot Window of a Particular Size

A convenient function for saving plots is ggsave(), which can automatically guess the device type based on the file extension, and smooths over differences between devices. You save with a certain size and units like this:

ggsave("mtcars.png", width = 20, height = 20, units = "cm")

In R markdown, figure size can be specified by chunk:

```{r, fig.width=6, fig.height=4}  
plot(1:5)
```

How to read a file in other directory in python

Looks like you are trying to open a directory for reading as if it's a regular file. Many OSs won't let you do that. You don't need to anyway, because what you want (judging from your description) is

x_file = open(os.path.join(direct, "5_1.txt"), "r")  

or simply

x_file = open(direct+"/5_1.txt", "r")

pythonic way to do something N times without an index variable?

A slightly faster approach than looping on xrange(N) is:

import itertools

for _ in itertools.repeat(None, N):
    do_something()

Passing HTML input value as a JavaScript Function Parameter

do you use jquery? if then:

$('#xx').val();

or use original javascript(DOM)

document.getElementById('xx').value

or

xxxform.xx.value;

if you want to learn more, w3chool can help you a lot.

Getting datarow values into a string?

You can get a columns value by doing this

 rows["ColumnName"]

You will also have to cast to the appropriate type.

 output += (string)rows["ColumnName"]

Java optional parameters

Default arguments can not be used in Java. Where in C#, C++ and Python, we can use them..

In Java, we must have to use 2 methods (functions) instead of one with default parameters.

Example:

Stash(int size); 

Stash(int size, int initQuantity);

http://parvindersingh.webs.com/apps/forums/topics/show/8856498-java-how-to-set-default-parameters-values-like-c-

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

How to specify jdk path in eclipse.ini on windows 8 when path contains space

tl;dr

The -vm option must occur after the other Eclipse-specific options (such as -product, --launcher.*, etc), but before the -vmargs option, since everything after -vmargs is passed directly to the JVM. Add the -vm option on its own line and the path to your JDK executable on the following line; e.g.

-vm
C:\Program Files\Java\jdk1.8.0_161\bin\javaw.exe

Details

Notes

  • The path is on a new line below the -vm option
  • There is no need to escape any characters or use slashes (back-slashes are fine)
  • The path points to the bin directory, not to javaw.exe

Gotcha JAVA_HOME

When you don't specify a virtual machine in your eclipse.ini file, you may think that the JAVA_HOME environment variable is used, but this is not the case!
From FAQ_How_do_I_run_Eclipse#Find_the_JVM

Eclipse DOES NOT consult the JAVA_HOME environment variable.

Instead the Windows search path will be scanned.

Recommendation
You may think it is a good idea to use the search path, because it is flexible.
While this is true, it also has the downside that the search path may be altered by installing or updating programs.
Thus, I recommend to use the explicit setting in the eclipse.ini file.

Finding a VM

The reason why you should specify the bin directory and not the javaw.exe (as proposed by many other answers), is that the launcher can then dynamically choose which is the best way to start the JVM. See details of the launcher process for all details:

We look in that directory for: (1) a default.ee file, (2) a java launcher or (3) the jvm shared library.

Verfication

You can verify which VM is used by your running eclipse instance in the Configuration dialogue.
In eclipse Oxygen go to Help - About Eclipse - Installation Details - Configuration

You will see which VM path eclipse has chosen, e.g.:

eclipse.vm=C:\Program Files\Java\jdk1.8.0_161\bin\..\jre\bin\server\jvm.dll

Where to place the 'assets' folder in Android Studio?

In Android Studio, click on the app folder, then the src folder, and then the main folder. Inside the main folder you can add the assets folder.

What is thread safe or non-thread safe in PHP?

Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).

So basically, from bottom to top

Linux

Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx

PHP-FPM + APC

ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.

HTML5 Canvas: Zooming

Building on the suggestion of using drawImage you could also combine this with scale function.

So before you draw the image scale the context to the zoom level you want:

ctx.scale(2, 2) // Doubles size of anything draw to canvas.

I've created a small example here http://jsfiddle.net/mBzVR/4/ that uses drawImage and scale to zoom in on mousedown and out on mouseup.

How to upload files to server using Putty (ssh)

"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:

file.py will be uploaded into your HOME dir on remote server.

or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:

After connecting to the server pscp will ask for a password.

Execute raw SQL using Doctrine 2

In your model create the raw SQL statement (example below is an example of a date interval I had to use but substitute your own. If you are doing a SELECT add ->fetchall() to the execute() call.

   $sql = "DELETE FROM tmp 
            WHERE lastedit + INTERVAL '5 minute' < NOW() ";

    $stmt = $this->getServiceLocator()
                 ->get('Doctrine\ORM\EntityManager')
                 ->getConnection()
                 ->prepare($sql);

    $stmt->execute();

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

Add CultureInfo.InvariantCulture as an argument:

using System.Globalization;

...

var dateTime = new DateTime(2016,8,16);
dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

Will return:

"16/08/2016"

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

Byte[] to InputStream or OutputStream

I do realize that my answer is way late for this question but I think the community would like a newer approach to this issue.

SQL Server JOIN missing NULL values

Dirty and quick hack:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 INNER JOIN Table2 ON Table1.Col1 = Table2.Col1
 AND ((Table1.Col2 = Table2.Col2) OR (Table1.Col2 IS NULL AND Table2.Col2 IS NULL))

Writing/outputting HTML strings unescaped

In ASP.NET MVC 3 You should do something like this:

// Say you have a bit of HTML like this in your controller:
ViewBag.Stuff = "<li>Menu</li>"
//  Then you can do this in your view:
@MvcHtmlString.Create(ViewBag.Stuff)

Difference between F5, Ctrl + F5 and click on refresh button?

CTRL+F5 Reloads the current page, ignoring cached content and generating the expected result.

How to enumerate an object's properties in Python?

I think it's worth showing the difference between the various options mentioned - often a picture is worth a thousand words.

>>> from pprint import pprint
>>> import inspect
>>>
>>> class a():
    x = 1               # static class member
    def __init__(self):
        self.y = 2      # static instance member
    @property
    def dyn_prop(self): # dynamic property
        print('DYNPROP WAS HERE')
        return 3
    def test(self):     # function member
        pass
    @classmethod
    def myclassmethod(cls): # class method; static methods behave the same
        pass

>>> i = a()
>>> pprint(i.__dict__)
{'y': 2}
>>> pprint(vars(i))
{'y': 2}
>>> pprint(dir(i))
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'dyn_prop',
 'myclassmethod',
 'test',
 'x',
 'y']
>>> pprint(inspect.getmembers(i))
DYNPROP WAS HERE
[('__class__', <class '__main__.a'>),
 ('__delattr__',
  <method-wrapper '__delattr__' of a object at 0x000001CB891BC7F0>),
 ('__dict__', {'y': 2}),
 ('__dir__', <built-in method __dir__ of a object at 0x000001CB891BC7F0>),
 ('__doc__', None),
 ('__eq__', <method-wrapper '__eq__' of a object at 0x000001CB891BC7F0>),
 ('__format__', <built-in method __format__ of a object at 0x000001CB891BC7F0>),
 ('__ge__', <method-wrapper '__ge__' of a object at 0x000001CB891BC7F0>),
 ('__getattribute__',
  <method-wrapper '__getattribute__' of a object at 0x000001CB891BC7F0>),
 ('__gt__', <method-wrapper '__gt__' of a object at 0x000001CB891BC7F0>),
 ('__hash__', <method-wrapper '__hash__' of a object at 0x000001CB891BC7F0>),
 ('__init__',
  <bound method a.__init__ of <__main__.a object at 0x000001CB891BC7F0>>),
 ('__init_subclass__',
  <built-in method __init_subclass__ of type object at 0x000001CB87CA6A70>),
 ('__le__', <method-wrapper '__le__' of a object at 0x000001CB891BC7F0>),
 ('__lt__', <method-wrapper '__lt__' of a object at 0x000001CB891BC7F0>),
 ('__module__', '__main__'),
 ('__ne__', <method-wrapper '__ne__' of a object at 0x000001CB891BC7F0>),
 ('__new__', <built-in method __new__ of type object at 0x00007FFCA630AB50>),
 ('__reduce__', <built-in method __reduce__ of a object at 0x000001CB891BC7F0>),
 ('__reduce_ex__',
  <built-in method __reduce_ex__ of a object at 0x000001CB891BC7F0>),
 ('__repr__', <method-wrapper '__repr__' of a object at 0x000001CB891BC7F0>),
 ('__setattr__',
  <method-wrapper '__setattr__' of a object at 0x000001CB891BC7F0>),
 ('__sizeof__', <built-in method __sizeof__ of a object at 0x000001CB891BC7F0>),
 ('__str__', <method-wrapper '__str__' of a object at 0x000001CB891BC7F0>),
 ('__subclasshook__',
  <built-in method __subclasshook__ of type object at 0x000001CB87CA6A70>),
 ('__weakref__', None),
 ('dyn_prop', 3),
 ('myclassmethod', <bound method a.myclassmethod of <class '__main__.a'>>),
 ('test', <bound method a.test of <__main__.a object at 0x000001CB891BC7F0>>),
 ('x', 1),
 ('y', 2)]

To summarize:

  • vars() and __dict__ only return instance-local properties;
  • dir() returns everything, but only as a list of string member names; dynamic properties are not called;
  • inspect.getmembers() returns everything, as a list of tuples (name, value); it actually runs dynamic properties, and accepts an optional predicate argument that can filter out members by value.

So my common-sense approach is typically to use dir() on the command line, and getmembers() in programs, unless specific performance considerations apply.

Note that, to keep things cleaner, I did not include __slots__ - if present, it was explicitly put there to be queried, and should be used directly. I also did not cover metaclasses, which can get a bit hairy (most people will never use them anyway).

Creating files in C++

Here is my solution:

#include <fstream>

int main()
{
    std::ofstream ("Hello.txt");
    return 0;
}

File (Hello.txt) is created even without ofstream name, and this is the difference from Mr. Boiethios answer.

How do I Set Background image in Flutter?

To set a background image without shrinking after adding the child, use this code.

  body: Container(
    constraints: BoxConstraints.expand(),
      decoration: BoxDecoration(
        image: DecorationImage(
            image: AssetImage("assets/aaa.jpg"),
        fit: BoxFit.cover,
        )
      ),

    //You can use any widget
    child: Column(
      children: <Widget>[],
    ),
    ),

SSL cert "err_cert_authority_invalid" on mobile chrome only

I just spent the morning dealing with this. The problem wasn't that I had a certificate missing. It was that I had an extra.

I started out with my ssl.conf containing my server key and three files provided by my SSL certificate authority:

#   Server Certificate:
SSLCertificateFile /etc/pki/tls/certs/myserver.cer

#   Server Private Key:
SSLCertificateKeyFile /etc/pki/tls/private/myserver.key

#   Server Certificate Chain:
SSLCertificateChainFile /etc/pki/tls/certs/AddTrustExternalCARoot.pem

#   Certificate Authority (CA):
SSLCACertificateFile /etc/pki/tls/certs/InCommonServerCA.pem

It worked fine on desktops, but Chrome on Android gave me err_cert_authority_invalid

A lot of headaches, searching and poor documentation later, I figured out that it was the Server Certificate Chain:

SSLCertificateChainFile /etc/pki/tls/certs/AddTrustExternalCARoot.pem

That was creating a second certificate chain which was incomplete. I commented out that line, leaving me with

#   Server Certificate:
SSLCertificateFile /etc/pki/tls/certs/myserver.cer

#   Server Private Key:
SSLCertificateKeyFile /etc/pki/tls/private/myserver.key

#   Certificate Authority (CA):
SSLCACertificateFile /etc/pki/tls/certs/InCommonServerCA.pem

and now it's working on Android again. This was on Linux running Apache 2.2.

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

/usr/local/ssl/openssl.cnf

A path like this means the program has been compiled with either Cygwin or MSYS. If you must use this openssl then you will need an interpreter that understands those paths, like Bash, which is provided by Cygwin or MSYS.

Another option would be to download or compile a Windows Native version of openssl. Using that the program would instead require a path like

C:\Users\Steven\ssl\openssl.cnf

which would be better suited for the Command Prompt.

:touch CSS pseudo-class or something similar?

There is no such thing as :touch in the W3C specifications, http://www.w3.org/TR/CSS2/selector.html#pseudo-class-selectors

:active should work, I would think.

Order on the :active/:hover pseudo class is important for it to function correctly.

Here is a quote from that above link

Interactive user agents sometimes change the rendering in response to user actions. CSS provides three pseudo-classes for common cases:

  • The :hover pseudo-class applies while the user designates an element (with some pointing device), but does not activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not supporting interactive media do not have to support this pseudo-class. Some conforming user agents supporting interactive media may not be able to support this pseudo-class (e.g., a pen device).
  • The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.
  • The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).

Create a HTML table where each TR is a FORM

If you need form inside tr and inputs in every td, you can add form in td tag, and add attribute 'form' that contains id of form tag to outside inputs. Something like this:

<tr>
  <td>
    <form id='f1'>
      <input type="text">
    </form>
  </td>
  <td>
    <input form='f1' type="text">
  </td>
</tr>

Insert Data Into Tables Linked by Foreign Key

Not with a regular statement, no.

What you can do is wrap the functionality in a PL/pgsql function (or another language, but PL/pgsql seems to be the most appropriate for this), and then just call that function. That means it'll still be a single statement to your app.

Biggest differences of Thrift vs Protocol Buffers?

Protocol Buffers seems to have a more compact representation, but that's only an impression I get from reading the Thrift whitepaper. In their own words:

We decided against some extreme storage optimizations (i.e. packing small integers into ASCII or using a 7-bit continuation format) for the sake of simplicity and clarity in the code. These alterations can easily be made if and when we encounter a performance-critical use case that demands them.

Also, it may just be my impression, but Protocol Buffers seems to have some thicker abstractions around struct versioning. Thrift does have some versioning support, but it takes a bit of effort to make it happen.

Python/Json:Expecting property name enclosed in double quotes

Quite simply, that string is not valid JSON. As the error says, JSON documents need to use double quotes.

You need to fix the source of the data.

Create the perfect JPA entity

My 2 cents addition to the answers here are:

  1. With reference to Field or Property access (away from performance considerations) both are legitimately accessed by means of getters and setters, thus, my model logic can set/get them in the same manner. The difference comes to play when the persistence runtime provider (Hibernate, EclipseLink or else) needs to persist/set some record in Table A which has a foreign key referring to some column in Table B. In case of a Property access type, the persistence runtime system uses my coded setter method to assign the cell in Table B column a new value. In case of a Field access type, the persistence runtime system sets the cell in Table B column directly. This difference is not of importance in the context of a uni-directional relationship, yet it is a MUST to use my own coded setter method (Property access type) for a bi-directional relationship provided the setter method is well designed to account for consistency. Consistency is a critical issue for bi-directional relationships refer to this link for a simple example for a well-designed setter.

  2. With reference to Equals/hashCode: It is impossible to use the Eclipse auto-generated Equals/hashCode methods for entities participating in a bi-directional relationship, otherwise they will have a circular reference resulting in a stackoverflow Exception. Once you try a bidirectional relationship (say OneToOne) and auto-generate Equals() or hashCode() or even toString() you will get caught in this stackoverflow exception.

How to fix apt-get: command not found on AWS EC2?

Check with "uname -a" and/or "lsb_release -a" to see which version of Linux you are actually running on your AWS instance. The default Amazon AMI image uses YUM for its package manager.

Can an ASP.NET MVC controller return an Image?

Yes you can return Image

public ActionResult GetImage(string imageFileName)
{
    var path = Path.Combine(Server.MapPath("/Images"), imageFileName + ".jpg"); 
    return base.File(path, "image/jpeg");
}

(Please don't forget to mark this as answer)

How to apply multiple transforms in CSS?

You can apply more than one transform like this:

li:nth-of-type(2){
    transform : translate(-20px, 0px) rotate(15deg);
}

PHP display current server path

echo $_SERVER["DOCUMENT_ROOT"];

'DOCUMENT_ROOT' The document root directory under which the current script is executing, as defined in the server's configuration file.

http://php.net/manual/en/reserved.variables.server.php

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

Unable to create Genymotion Virtual Device

I followed following steps

  1. I removed everything under {~/.Genymobile/Genymotion/ova} folder (with only doing this step it works sometimes)
  2. removed everything under {~/.Genymobile/Genymotion/bin} folder

After which I downloaded the fresh copy and it worked like magic.

Hope this helps.

Bootstrap dropdown menu not working (not dropping down when clicked)

Adding this script to my code fixed the dropdown menu.

<script>
    $(document).ready(function () {
        $('.dropdown-toggle').dropdown();
    });
</script>

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

Tried npm install mongoose --msvs_version=2012, if you have multiple Visual installed, it worked for me

import httplib ImportError: No module named httplib

I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:

apt-get install -y --no-install-recommends python

And I should not have included the --no-install-recommends flag:

apt-get install -y python

git ignore exception

Git ignores folders if you write:

/js

but it can't add exceptions if you do: !/js/jquery or !/js/jquery/ or !/js/jquery/*

You must write:

/js/* 

and only then you can except subfolders like this

!/js/jquery

How to run Visual Studio post-build events for debug build only

Like any project setting, the buildevents can be configured per Configuration. Just select the configuration you want to change in the dropdown of the Property Pages dialog and edit the post build step.

Deactivate or remove the scrollbar on HTML

If you really need it...

html { overflow-y: hidden; }

How to check if ZooKeeper is running or up from command prompt?

echo stat | nc localhost 2181 | grep Mode
echo srvr | nc localhost 2181 | grep Mode #(From 3.3.0 onwards)

Above will work in whichever modes Zookeeper is running (standalone or embedded).

Another way

If zookeeper is running in standalone mode, its a JVM process. so -

jps | grep Quorum

will display list of jvm processes; something like this for zookeeper with process ID

HQuorumPeer

Is recursion ever faster than looping?

Functional programming is more about "what" rather than "how".

The language implementors will find a way to optimize how the code works underneath, if we don't try to make it more optimized than it needs to be. Recursion can also be optimized within the languages that support tail call optimization.

What matters more from a programmer standpoint is readability and maintainability rather than optimization in the first place. Again, "premature optimization is root of all evil".

Getting "type or namespace name could not be found" but everything seems ok?

I got this error trying to make a build with a Visual Studio Team Services build running on my local machine as an agent.

It worked in my regular workspace just fine and I was able to open the SLN file within the agent folder locally and everything compiled ok.

The DLL in question was stored within the project as Lib/MyDLL.DLL and references with this in the csproj file:

<Reference Include="MYDLL, Version=2009.0.0.0, Culture=neutral, PublicKeyToken=b734e31dca085caa">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>Lib\MYDLL.dll</HintPath>
</Reference>

It turned out it literally just wasn't finding the file despite the hint path. I think maybe msbuild was looking relative to the SLN file instead of the project file.

In any case if the message you get is Could not resolve this reference. Could not locate the assembly then make sure that the DLL is in an accessible location to msbuild.

I kind of cheated and found a message that said Considered "Reference\bin\xxx.dll" and just copied the dlls into there instead.

PHP check if url parameter exists

Here is the PHP code to check if 'id' parameter exists in the URL or not:

if(isset($_GET['id']))
{
   $slide = $_GET['id'] // Getting parameter value inside PHP variable
}

I hope it will help you.

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

How to scroll table's "tbody" independent of "thead"?

The missing part is:

thead, tbody {
    display: block;
}

Demo

Convert a list to a string in C#

The .ToString() method for reference types usually resolves back to System.Object.ToString() unless you override it in a derived type (possibly using extension methods for the built-in types). The default behavior for this method is to output the name of the type on which it's called. So what you're seeing is expected behavior.

You could try something like string.Join(", ", myList.ToArray()); to achieve this. It's an extra step, but it could be put in an extension method on System.Collections.Generic.List<T> to make it a bit easier. Something like this:

public static class GenericListExtensions
{
    public static string ToString<T>(this IList<T> list)
    {
        return string.Join(", ", list);
    }
}

(Note that this is free-hand and untested code. I don't have a compiler handy at the moment. So you'll want to experiment with it a little.)

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

After lots of struggle I found here you go:

  1. open folder -> xampp
  2. then open -> phpmyadmin
  3. finally open -> config.inc
$cfg['blowfish_secret'] = ''; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */
  1. Put SHA256 inside single quotations like this one

830bbca930d5e417ae4249931838e2c70ca0365044268fa0ede75e33aff677de

$cfg['blowfish_secret'] = '830bbca930d5e417ae4249931838e2c70ca0365044268fa0ede75e33aff677de
';

I found this when I was downloading updated version of phpmyadmin. I wish this solution help you. enter image description here

Placing border inside of div and not on its edge

Set box-sizing property to border-box:

_x000D_
_x000D_
div {_x000D_
    box-sizing: border-box;_x000D_
    -moz-box-sizing: border-box;_x000D_
    -webkit-box-sizing: border-box;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    border: 20px solid #f00;_x000D_
    background: #00f;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div + div {_x000D_
    border: 10px solid red;_x000D_
}
_x000D_
<div>Hello!</div>_x000D_
<div>Hello!</div>
_x000D_
_x000D_
_x000D_

It works on IE8 & above.

How does the modulus operator work?

Basically modulus Operator gives you remainder simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2

for same thing C++ has modulus operator ('%')

Basic code for explanation

#include <iostream>
using namespace std;


int main()
{
    int num = 11;
    cout << "remainder is " << (num % 3) << endl;

    return 0;
}

Which will display

remainder is 2

How can I kill all sessions connecting to my oracle database?

Try trigger on logon

Insted of trying disconnect users you should not allow them to connect.

There is and example of such trigger.

CREATE OR REPLACE TRIGGER rds_logon_trigger
AFTER LOGON ON DATABASE
BEGIN
  IF SYS_CONTEXT('USERENV','IP_ADDRESS') not in ('192.168.2.121','192.168.2.123','192.168.2.233') THEN
    RAISE_APPLICATION_ERROR(-20003,'You are not allowed to connect to the database');
  END IF;

  IF (to_number(to_char(sysdate,'HH24'))< 6) and (to_number(to_char(sysdate,'HH24')) >18) THEN
    RAISE_APPLICATION_ERROR(-20005,'Logon only allowed during business hours');
  END IF;

END;

What is the difference between 'typedef' and 'using' in C++11?

Both keywords are equivalent, but there are a few caveats. One is that declaring a function pointer with using T = int (*)(int, int); is clearer than with typedef int (*T)(int, int);. Second is that template alias form is not possible with typedef. Third is that exposing C API would require typedef in public headers.

How to view Plugin Manager in Notepad++

My system was 32 bit. I removed and re-installed Notepad++. After that from below got PluginManager_v1.4.12_UNI.zip and extracted it.

https://github.com/bruderstein/nppPluginManager/releases

I created a folder called PluginManager at C:\Program Files (x86)\Notepad++\plugins\ and copied PluginManager.dll into it. I restarted my notepad++ and now I see Plugin Manager.

enter image description here

Align div right in Bootstrap 3

Add offset8 to your class, for example:

<div class="offset8">aligns to the right</div>

Transparent background in JPEG image

JPG doesn't support transparency

failed to push some refs to [email protected]

I'm the only person working on my app and only work on it from my desktop, so the possibility that I managed to get the heroku repository above dev didn't make sense. BUT! I recently had a Heroku support rep look into my heroku account for a cache issue involving gem installs and he had changed something that caused heroku to return the same error as the one listed above. A git pull heroku master was all it took. Then I found the reps minor change and reverted it myself.

How do I install a plugin for vim?

I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.

Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).

How to force a list to be vertical using html css

I would add this to the LI's CSS

.list-item
{
    float: left;
    clear: left;
}

Call web service in excel

In Microsoft Excel Office 2007 try installing "Web Service Reference Tool" plugin. And use the WSDL and add the web-services. And use following code in module to fetch the necessary data from the web-service.

Sub Demo()
    Dim XDoc As MSXML2.DOMDocument
    Dim xEmpDetails As MSXML2.IXMLDOMNode
    Dim xParent As MSXML2.IXMLDOMNode
    Dim xChild As MSXML2.IXMLDOMNode
    Dim query As String
    Dim Col, Row As Integer
    Dim objWS As New clsws_GlobalWeather

    Set XDoc = New MSXML2.DOMDocument
    XDoc.async = False
    XDoc.validateOnParse = False
    query = objWS.wsm_GetCitiesByCountry("india")

    If Not XDoc.LoadXML(query) Then  'strXML is the string with XML'
        Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
    End If
    XDoc.LoadXML (query)

    Set xEmpDetails = XDoc.DocumentElement
    Set xParent = xEmpDetails.FirstChild
    Worksheets("Sheet3").Cells(1, 1).Value = "Country"
    Worksheets("Sheet3").Cells(1, 1).Interior.Color = RGB(65, 105, 225)
    Worksheets("Sheet3").Cells(1, 2).Value = "City"
    Worksheets("Sheet3").Cells(1, 2).Interior.Color = RGB(65, 105, 225)
    Row = 2
    Col = 1
    For Each xParent In xEmpDetails.ChildNodes
        For Each xChild In xParent.ChildNodes
            Worksheets("Sheet3").Cells(Row, Col).Value = xChild.Text
            Col = Col + 1
        Next xChild
        Row = Row + 1
        Col = 1
    Next xParent
End Sub

CodeIgniter: Load controller within controller

With the following code you can load the controller classes and execute the methods.

This code was written for codeigniter 2.1

First add a new file MY_Loader.php in your application/core directory. Add the following code to your newly created MY_Loader.php file:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// written by AJ  [email protected]

class MY_Loader extends CI_Loader 
{
    protected $_my_controller_paths     = array();  

    protected $_my_controllers          = array();


    public function __construct()
    {
        parent::__construct();

        $this->_my_controller_paths = array(APPPATH);
    }

    public function controller($controller, $name = '', $db_conn = FALSE)
    {
        if (is_array($controller))
        {
            foreach ($controller as $babe)
            {
                $this->controller($babe);
            }
            return;
        }

        if ($controller == '')
        {
            return;
        }

        $path = '';

        // Is the controller in a sub-folder? If so, parse out the filename and path.
        if (($last_slash = strrpos($controller, '/')) !== FALSE)
        {
            // The path is in front of the last slash
            $path = substr($controller, 0, $last_slash + 1);

            // And the controller name behind it
            $controller = substr($controller, $last_slash + 1);
        }

        if ($name == '')
        {
            $name = $controller;
        }

        if (in_array($name, $this->_my_controllers, TRUE))
        {
            return;
        }

        $CI =& get_instance();
        if (isset($CI->$name))
        {
            show_error('The controller name you are loading is the name of a resource that is already being used: '.$name);
        }

        $controller = strtolower($controller);

        foreach ($this->_my_controller_paths as $mod_path)
        {
            if ( ! file_exists($mod_path.'controllers/'.$path.$controller.'.php'))
            {
                continue;
            }

            if ($db_conn !== FALSE AND ! class_exists('CI_DB'))
            {
                if ($db_conn === TRUE)
                {
                    $db_conn = '';
                }

                $CI->load->database($db_conn, FALSE, TRUE);
            }

            if ( ! class_exists('CI_Controller'))
            {
                load_class('Controller', 'core');
            }

            require_once($mod_path.'controllers/'.$path.$controller.'.php');

            $controller = ucfirst($controller);

            $CI->$name = new $controller();

            $this->_my_controllers[] = $name;
            return;
        }

        // couldn't find the controller
        show_error('Unable to locate the controller you have specified: '.$controller);
    }

}

Now you can load all the controllers in your application/controllers directory. for example:

load the controller class Invoice and execute the function test()

$this->load->controller('invoice','invoice_controller');

$this->invoice_controller->test();

or when the class is within a dir

$this->load->controller('/dir/invoice','invoice_controller');

$this->invoice_controller->test();

It just works the same like loading a model

How do you Change a Package's Log Level using Log4j?

I just encountered the issue and couldn't figure out what was going wrong even after reading all the above and everything out there. What I did was

  1. Set root logger level to WARN
  2. Set package log level to DEBUG

Each logging implementation has it's own way of setting it via properties or via code(lot of help available on this)

Irrespective of all the above I would not get the logs in my console or my log file. What I had overlooked was the below...


enter image description here


All I was doing with the above jugglery was controlling only the production of the logs(at root/package/class etc), left of the red line in above image. But I was not changing the way displaying/consumption of the logs of the same, right of the red line in above image. Handler(Consumption) is usually defaulted at INFO, therefore your precious debug statements wouldn't come through. Consumption/displaying is controlled by setting the log levels for the Handlers(ConsoleHandler/FileHandler etc..) So I went ahead and set the log levels of all my handlers to finest and everything worked.

This point was not made clear in a precise manner in any place.

I hope someone scratching their head, thinking why the properties are not working will find this bit helpful.

get DATEDIFF excluding weekends using sql server

I found when i used this there was a problem when d1 fell on saturday. Below is what i used to correct this.

declare @d1 datetime, @d2 datetime
select @d1 = '11/19/2011' ,  @d2 = '11/28/2011'

select datediff(dd, @d1, @d2) +case when datepart(dw, @d1) = 7 then 1 else 0 end - (datediff(wk, @d1, @d2) * 2) -
 case when datepart(dw, @d1) = 1 then 1 else 0 end +
 case when datepart(dw, @d2) = 1 then 1 else 0 end

How to find the Vagrant IP?

Open a terminal, cd to the path of your Vagrantfile and write this

(Linux)

vagrant ssh -c "hostname -I | cut -d' ' -f2" 2>/dev/null

(OS X)

vagrant ssh -c "hostname -I | cut -d' ' -f2" 2>/dev/null | pbcopy

The command for Linux also works for windows. I have no way to test, sorry.

source: https://coderwall.com/p/etzdmq/get-vagrant-box-guest-ip-from-host

Switch on Enum in Java

You actually can switch on enums, but you can't switch on Strings until Java 7. You might consider using polymorphic method dispatch with Java enums rather than an explicit switch. Note that enums are objects in Java, not just symbols for ints like they are in C/C++. You can have a method on an enum type, then instead of writing a switch, just call the method - one line of code: done!

enum MyEnum {
    SOME_ENUM_CONSTANT {
        @Override
        public void method() {
            System.out.println("first enum constant behavior!");
        }
    },
    ANOTHER_ENUM_CONSTANT {
        @Override
        public void method() {
            System.out.println("second enum constant behavior!");
        }
    }; // note the semi-colon after the final constant, not just a comma!
    public abstract void method(); // could also be in an interface that MyEnum implements
}

void aMethodSomewhere(final MyEnum e) {
    doSomeStuff();
    e.method(); // here is where the switch would be, now it's one line of code!
    doSomeOtherStuff();
}

Is there a limit on an Excel worksheet's name length?

My solution was to use a short nickname (less than 31 characters) and then write the entire name in cell 0.

SELECT FOR UPDATE with SQL Server

I'm assuming you don't want any other session to be able to read the row while this specific query is running...

Wrapping your SELECT in a transaction while using WITH (XLOCK,READPAST) locking hint will get the results you want. Just make sure those other concurrent reads are NOT using WITH (NOLOCK). READPAST allows other sessions to perform the same SELECT but on other rows.

BEGIN TRAN
  SELECT *
  FROM <tablename> WITH (XLOCK,READPAST) 
  WHERE RowId = @SomeId

  -- Do SOMETHING

  UPDATE <tablename>
  SET <column>=@somevalue
  WHERE RowId=@SomeId
COMMIT

Fit image to table cell [Pure HTML]

It's all about display: block :)

Updated:

Ok so you have the table, tr and td tags:

<table>
  <tr>
    <td>
      <!-- your image goes here -->
    </td>
  </tr>
</table>

Lets say your table or td (whatever define your width) has property width: 360px;. Now, when you try to replace the html comment with the actual image and set that image property for example width: 100%; which should fully fill out the td cell you will face the problem.

The problem is that your table cell (td) isn't properly filled with the image. You'll notice the space at the bottom of the cell which your image doesn't cover (it's like 5px of padding).

How to solve this in a simpliest way?

You are working with the tables, right? You just need to add the display property to your image so that it has the following:

img {
  width: 100%;
  display: block;
}

CSS filter: make color image with transparency white

You can use

filter: brightness(0) invert(1);

_x000D_
_x000D_
html {_x000D_
  background: red;_x000D_
}_x000D_
p {_x000D_
  float: left;_x000D_
  max-width: 50%;_x000D_
  text-align: center;_x000D_
}_x000D_
img {_x000D_
  display: block;_x000D_
  max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
  -webkit-filter: brightness(0) invert(1);_x000D_
  filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
  Original:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
  Filter:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
_x000D_
_x000D_

First, brightness(0) makes all image black, except transparent parts, which remain transparent.

Then, invert(1) makes the black parts white.

How can I enable CORS on Django REST Framework

Well, I don't know guys but:

using here python 3.6 and django 2.2

Renaming MIDDLEWARE_CLASSES to MIDDLEWARE in settings.py worked.

How do you build a Singleton in Dart?

Modified @Seth Ladd answer for who's prefer Swift style of singleton like .shared:

class Auth {
  // singleton
  static final Auth _singleton = Auth._internal();
  factory Auth() => _singleton;
  Auth._internal();
  static Auth get shared => _singleton;

  // variables
  String username;
  String password;
}

Sample:

Auth.shared.username = 'abc';

Calling a Function defined inside another function in Javascript

You are not calling the function inner, just defining it.

function outer() { 
    function inner() {
        alert("hi");
    }

    inner(); //Call the inner function

}

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

Converting between datetime and Pandas Timestamp objects

Pandas Timestamp to datetime.datetime:

pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()

datetime.datetime to Timestamp

pd.Timestamp(datetime(2014, 1, 23))

How to check for palindrome using Python logic

#compare 1st half with reversed second half
# i.e. 'abba' -> 'ab' == 'ba'[::-1]

def is_palindrome( s ):
   return True if len( s ) < 2 else s[ :len( s ) // 2 ] == s[ -( len( s ) // 2 ):][::-1]

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

A simple plot for sine and cosine curves with a legend.

Used matplotlib.pyplot

import math
import matplotlib.pyplot as plt
x=[]
for i in range(-314,314):
    x.append(i/100)
ysin=[math.sin(i) for i in x]
ycos=[math.cos(i) for i in x]
plt.plot(x,ysin,label='sin(x)')  #specify label for the corresponding curve
plt.plot(x,ycos,label='cos(x)')
plt.xticks([-3.14,-1.57,0,1.57,3.14],['-$\pi$','-$\pi$/2',0,'$\pi$/2','$\pi$'])
plt.legend()
plt.show()

Sin and Cosine plots (click to view image)

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

mToolbar.setNavigationIcon(R.mipmap.ic_launcher);
mToolbar.setOverflowIcon(ContextCompat.getDrawable(this, R.drawable.ic_menu));

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

After reading several suggestions here and combining the ideas, for me following changes in /etc/ImageMagick-6/policy.xml were necessary:

<policy domain="coder" rights="read|write" pattern="PDF" />

... rights="none" did not help. ...pattern="LABEL" was not neccessary. Although I do not work with big png files (only ~1 Mb) some changes in memory limits were also necessary:

<policy domain="resource" name="memory" value="2GiB"/>

(instead of 256Mib), and

<policy domain="resource" name="area" value="2GB"/>

(instead of 128 MB)

Android: Go back to previous activity

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

This will get you to a previous activity keeping its stack and clearing all activities after it from the stack.

For example, if stack was A->B->C->D and you start B with this flag, stack will be A->B

Java OCR implementation

There are a variety of OCR libraries out there. However, my experience is that the major commercial implementations, ABBYY, Omnipage, and ReadIris, far outdo the open-source or other minor implementations. These commercial libraries are not primarily designed to work with Java, though of course it is possible.

Of course, if your interest is to learn the code, the open-source implementations will do the trick.

How do I call a specific Java method on a click/submit event of a specific button in JSP?

Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.

You only need to make sure that the button inputs have type="submit" as in <input type="submit"> and <button type="submit"> and not type="button", which only renders a "dead" button purely for onclick stuff and all.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
    <input type="submit" name="button2" value="Button 2" />
    <input type="submit" name="button3" value="Button 3" />
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();

        if (request.getParameter("button1") != null) {
            myClass.method1();
        } else if (request.getParameter("button2") != null) {
            myClass.method2();
        } else if (request.getParameter("button3") != null) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

Alternatively, use <button type="submit"> instead of <input type="submit">, then you can give them all the same name, but an unique value. The value of the <button> won't be used as label, you can just specify that yourself as child.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <button type="submit" name="button" value="button1">Button 1</button>
    <button type="submit" name="button" value="button2">Button 2</button>
    <button type="submit" name="button" value="button3">Button 3</button>
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();
        String button = request.getParameter("button");

        if ("button1".equals(button)) {
            myClass.method1();
        } else if ("button2".equals(button)) {
            myClass.method2();
        } else if ("button3".equals(button)) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

See also:

Converting Select results into Insert script - SQL Server

It's possible to do via Visual Studio SQL Server Object Explorer.

You can click "View Data" from context menu for necessary table, filter results and save result as script.

Auto select file in Solution Explorer from its open tab

I don't know if you can do it on-demand, but you can enable the option "Track Active Item in Solution Explorer" (Tools->Options->Projects and Solutions->General) which will always select the active tab item in the solution explorer.

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

Might be a pasting problem, but as far as I can see from your code, you're missing the single quotes around the HTML part you're echo-ing.

If not, could you post the code correctly and tell us what line is causing the error?

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

Then apart from these 4, we have

foldByKey which is same as reduceByKey but with a user defined Zero Value.

AggregateByKey takes 3 parameters as input and uses 2 functions for merging(one for merging on same partitions and another to merge values across partition. The first parameter is ZeroValue)

whereas

ReduceBykey takes 1 parameter only which is a function for merging.

CombineByKey takes 3 parameter and all 3 are functions. Similar to aggregateBykey except it can have a function for ZeroValue.

GroupByKey takes no parameter and groups everything. Also, it is an overhead for data transfer across partitions.

Brackets.io: Is there a way to auto indent / format <html>

You can install an indentator package.

Click on File > Extension Manager....

Look for the search field and type: Indentator > Install

Once Indentator is installed, you can use Ctrl + Alt + I

How do I share variables between different .c files?

  1. Try to avoid globals. If you must use a global, see the other answers.
  2. Pass it as an argument to a function.

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

Create an interface to define the 'indexer' interface

Then create your object with that index.

Note: this will still have same issues other answers have described with respect to enforcing the type of each item - but that's often exactly what you want.

You can make the generic type parameter whatever you need : ObjectIndexer< Dog | Cat>

// this should be global somewhere, or you may already be 
// using a library that provides such a type
export interface ObjectIndexer<T> {
  [id: string]: T;
}

interface ISomeObject extends ObjectIndexer<string>
{
    firstKey:   string;
    secondKey:  string;
    thirdKey:   string;
}

let someObject: ISomeObject = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   'thirdValue'
};

let key: string = 'secondKey';

let secondValue: string = someObject[key];

Typescript Playground


You can even use this in a generic constraint when defining a generic type:

export class SmartFormGroup<T extends IndexableObject<any>> extends FormGroup

Then T inside the class can be indexed :-)

Running script upon login mac

Follow this:

  • start Automator.app
  • select Application
  • click Show library in the toolbar (if hidden)
  • add Run shell script (from the Actions/Utilities)
  • copy & paste your script into the window
  • test it
  • save somewhere (for example you can make an Applications folder in your HOME, you will get an your_name.app)

  • go to System Preferences -> Accounts -> Login items

  • add this app
  • test & done ;)

EDIT:

I've recently earned a "Good answer" badge for this answer. While my solution is simple and working, the cleanest way to run any program or shell script at login time is described in @trisweb's answer, unless, you want interactivity.

With automator solution you can do things like next: automator screenshot login application

so, asking to run a script or quit the app, asking passwords, running other automator workflows at login time, conditionally run applications at login time and so on...

Close Bootstrap Modal

Using modal.hide would only hide the modal. If you are using overlay underneath the modal, it would still be there. use click call to actually close the modal and remove the overlay.

$("#modalID .close").click()

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

Simple bubble sort c#

public static int[] BubbleSort(int[] arr)
{
   int length = arr.Length();

   while (length > 0)
   {
      int newLength = 0;
      for (int i = 1; i < length; i++)
      {
         if (arr[i - 1] > arr[i])
         {
            Swap(ref arr[i - 1], ref arr[i]); 
            newLength = i;   
         }   
      }
      length = newLength;
   }
}

public static void Swap(ref int x, ref int y)
{
   int temp = y;
   y = x;
   x = temp;
}

Oracle database: How to read a BLOB?

If the content is not too large, you can also use

SELECT CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) FROM <table>;

or

SELECT DUMP ( CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) ) FROM <table>;

This will show you the HEX values.

Adding attribute in jQuery

You can do this with jQuery's .attr function, which will set attributes. Removing them is done via the .removeAttr function.

//.attr()
$("element").attr("id", "newId");
$("element").attr("disabled", true);

//.removeAttr()
$("element").removeAttr("id");
$("element").removeAttr("disabled");

How to hide Bootstrap previous modal when you opening new one?

You hide Bootstrap modals with:

$('#modal').modal('hide');

Saying $().hide() makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.

How do I get the opposite (negation) of a Boolean in Python?

You can just compare the boolean array. For example

X = [True, False, True]

then

Y = X == False

would give you

Y = [False, True, False]

Iterate two Lists or Arrays with one ForEach statement in C#

If you don't want to wait for .NET 4.0, you could implement your own Zip method. The following works with .NET 2.0. You can adjust the implementation depending on how you want to handle the case where the two enumerations (or lists) have different lengths; this one continues to the end of the longer enumeration, returning the default values for missing items from the shorter enumeration.

static IEnumerable<KeyValuePair<T, U>> Zip<T, U>(IEnumerable<T> first, IEnumerable<U> second)
{
    IEnumerator<T> firstEnumerator = first.GetEnumerator();
    IEnumerator<U> secondEnumerator = second.GetEnumerator();

    while (firstEnumerator.MoveNext())
    {
        if (secondEnumerator.MoveNext())
        {
            yield return new KeyValuePair<T, U>(firstEnumerator.Current, secondEnumerator.Current);
        }
        else
        {
            yield return new KeyValuePair<T, U>(firstEnumerator.Current, default(U));
        }
    }
    while (secondEnumerator.MoveNext())
    {
        yield return new KeyValuePair<T, U>(default(T), secondEnumerator.Current);
    }
}

static void Test()
{
    IList<string> names = new string[] { "one", "two", "three" };
    IList<int> ids = new int[] { 1, 2, 3, 4 };

    foreach (KeyValuePair<string, int> keyValuePair in ParallelEnumerate(names, ids))
    {
        Console.WriteLine(keyValuePair.Key ?? "<null>" + " - " + keyValuePair.Value.ToString());
    }
}

Returning a pointer to a vector element in c++

I'm not sure if returning the address of the thing pointed by the iterator is needed. All you need is the pointer itself. You will see STL's iterator class itself implementing the use of _Ptr for this purpose. So, just do:

return iterator._Ptr;

What is "Connect Timeout" in sql server connection string?

Maximum time between connection request and a timeout error. When the client tries to make a connection, if the timeout wait limit is reached, it will stop trying and raise an error.

How can I set selected option selected in vue.js 2?

Handling the errors

You are binding properties to nothing. :required in

<select class="form-control" v-model="selected" :required @change="changeLocation">

and :selected in

<option :selected>Choose Province</option>

If you set the code like so, your errors should be gone:

<template>
  <select class="form-control" v-model="selected" :required @change="changeLocation">
    <option>Choose Province</option>
    <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
 </select>
</template>

Getting the select tags to have a default value

  1. you would now need to have a data property called selected so that v-model works. So,

    {
      data () {
        return {
          selected: "Choose Province"
        }
      }
    }
    
  2. If that seems like too much work, you can also do it like:

    <template>
      <select class="form-control" :required="true" @change="changeLocation">
       <option :selected="true">Choose Province</option>
       <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
      </select>
    </template>
    

When to use which method?

  1. You can use the v-model approach if your default value depends on some data property.

  2. You can go for the second method if your default selected value happens to be the first option.

  3. You can also handle it programmatically by doing so:

    <select class="form-control" :required="true">
      <option 
       v-for="option in options" 
       v-bind:value="option.id"
       :selected="option == '<the default value you want>'"
      >{{ option }}</option>
    </select>
    

Are HTTPS URLs encrypted?

Entire request and response is encrypted, including URL.

Note that when you use a HTTP Proxy, it knows the address (domain) of the target server, but doesn't know the requested path on this server (i.e. request and response are always encrypted).

Hashing a string with Sha256

This work for me in .NET Core 3.1.
But not in .NET 5 preview 7.

using System;
using System.Security.Cryptography;
using System.Text;

namespace PortalAplicaciones.Shared.Models
{
    public class Encriptar
    {
        public static string EncriptaPassWord(string Password)
        {
            try
            {
                SHA256Managed hasher = new SHA256Managed();

                byte[] pwdBytes = new UTF8Encoding().GetBytes(Password);
                byte[] keyBytes = hasher.ComputeHash(pwdBytes);

                hasher.Dispose();
                return Convert.ToBase64String(keyBytes);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }  
    }
}
 

Bash command to sum a column of numbers

Use a for loop to iterate over your file …

sum=0; for x in `cat <your-file>`; do let sum+=x; done; echo $sum

How to detect orientation change?

In Objective C

-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator

In swift

func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)

Override this method to detect the orientation change.

Using getopts to process long and short command line options

I wanted something without external dependencies, with strict bash support (-u), and I needed it to work on even the older bash versions. This handles various types of params:

  • short bools (-h)
  • short options (-i "image.jpg")
  • long bools (--help)
  • equals options (--file="filename.ext")
  • space options (--file "filename.ext")
  • concatinated bools (-hvm)

Just insert the following at the top of your script:

# Check if a list of params contains a specific param
# usage: if _param_variant "h|?|help p|path f|file long-thing t|test-thing" "file" ; then ...
# the global variable $key is updated to the long notation (last entry in the pipe delineated list, if applicable)
_param_variant() {
  for param in $1 ; do
    local variants=${param//\|/ }
    for variant in $variants ; do
      if [[ "$variant" = "$2" ]] ; then
        # Update the key to match the long version
        local arr=(${param//\|/ })
        let last=${#arr[@]}-1
        key="${arr[$last]}"
        return 0
      fi
    done
  done
  return 1
}

# Get input parameters in short or long notation, with no dependencies beyond bash
# usage:
#     # First, set your defaults
#     param_help=false
#     param_path="."
#     param_file=false
#     param_image=false
#     param_image_lossy=true
#     # Define allowed parameters
#     allowed_params="h|?|help p|path f|file i|image image-lossy"
#     # Get parameters from the arguments provided
#     _get_params $*
#
# Parameters will be converted into safe variable names like:
#     param_help,
#     param_path,
#     param_file,
#     param_image,
#     param_image_lossy
#
# Parameters without a value like "-h" or "--help" will be treated as
# boolean, and will be set as param_help=true
#
# Parameters can accept values in the various typical ways:
#     -i "path/goes/here"
#     --image "path/goes/here"
#     --image="path/goes/here"
#     --image=path/goes/here
# These would all result in effectively the same thing:
#     param_image="path/goes/here"
#
# Concatinated short parameters (boolean) are also supported
#     -vhm is the same as -v -h -m
_get_params(){

  local param_pair
  local key
  local value
  local shift_count

  while : ; do
    # Ensure we have a valid param. Allows this to work even in -u mode.
    if [[ $# == 0 || -z $1 ]] ; then
      break
    fi

    # Split the argument if it contains "="
    param_pair=(${1//=/ })
    # Remove preceeding dashes
    key="${param_pair[0]#--}"

    # Check for concatinated boolean short parameters.
    local nodash="${key#-}"
    local breakout=false
    if [[ "$nodash" != "$key" && ${#nodash} -gt 1 ]]; then
      # Extrapolate multiple boolean keys in single dash notation. ie. "-vmh" should translate to: "-v -m -h"
      local short_param_count=${#nodash}
      let new_arg_count=$#+$short_param_count-1
      local new_args=""
      # $str_pos is the current position in the short param string $nodash
      for (( str_pos=0; str_pos<new_arg_count; str_pos++ )); do
        # The first character becomes the current key
        if [ $str_pos -eq 0 ] ; then
          key="${nodash:$str_pos:1}"
          breakout=true
        fi
        # $arg_pos is the current position in the constructed arguments list
        let arg_pos=$str_pos+1
        if [ $arg_pos -gt $short_param_count ] ; then
          # handle other arguments
          let orignal_arg_number=$arg_pos-$short_param_count+1
          local new_arg="${!orignal_arg_number}"
        else
          # break out our one argument into new ones
          local new_arg="-${nodash:$str_pos:1}"
        fi
        new_args="$new_args \"$new_arg\""
      done
      # remove the preceding space and set the new arguments
      eval set -- "${new_args# }"
    fi
    if ! $breakout ; then
      key="$nodash"
    fi

    # By default we expect to shift one argument at a time
    shift_count=1
    if [ "${#param_pair[@]}" -gt "1" ] ; then
      # This is a param with equals notation
      value="${param_pair[1]}"
    else
      # This is either a boolean param and there is no value,
      # or the value is the next command line argument
      # Assume the value is a boolean true, unless the next argument is found to be a value.
      value=true
      if [[ $# -gt 1 && -n "$2" ]]; then
        local nodash="${2#-}"
        if [ "$nodash" = "$2" ]; then
          # The next argument has NO preceding dash so it is a value
          value="$2"
          shift_count=2
        fi
      fi
    fi

    # Check that the param being passed is one of the allowed params
    if _param_variant "$allowed_params" "$key" ; then
      # --key-name will now become param_key_name
      eval param_${key//-/_}="$value"
    else
      printf 'WARNING: Unknown option (ignored): %s\n' "$1" >&2
    fi
    shift $shift_count
  done
}

And use it like so:

# Assign defaults for parameters
param_help=false
param_path=$(pwd)
param_file=false
param_image=true
param_image_lossy=true
param_image_lossy_quality=85

# Define the params we will allow
allowed_params="h|?|help p|path f|file i|image image-lossy image-lossy-quality"

# Get the params from arguments provided
_get_params $*

Getting all request parameters in Symfony 2

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

c++ array - expression must have a constant value

C++ doesn't allow non-constant values for the size of an array. That's just the way it was designed.

C99 allows the size of an array to be a variable, but I'm not sure it is allowed for two dimensions. Some C++ compilers (gcc) will allow this as an extension, but you may need to turn on a compiler option to allow it.

And I almost missed it - you need to declare a variable name, not just the array dimensions.

HTML form with side by side input fields

Put style="float:left" on each of your divs:

<div style="float:left;">...........

Example:

<div style="float:left;">
  <label for="username">First Name</label>
  <input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>

<div style="float:left;">
  <label for="name">Last Name</label>
  <input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>

To put an element on new line, put this div below it:

<div style="clear:both;">&nbsp;</div>

Of course, you can also create classes in the CSS file:

.left{
  float:left;
}

.clear{
  clear:both;
}

And then your html should look like this:

<div class="left">
  <label for="username">First Name</label>
  <input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>

<div class="left">
  <label for="name">Last Name</label>
  <input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>

To put an element on new line, put this div below it:

<div class="clear">&nbsp;</div>

More Info:

How to delete items from a dictionary while iterating over it?

Iterate over a copy instead, such as the one returned by items():

for k, v in list(mydict.items()):

Failed to load ApplicationContext for JUnit test of Spring controller

If you are using Maven, add the below config in your pom.xml:

<build>
    <testResources>
                <testResource>
                    <directory>src/main/webapp</directory>
                </testResource>
    </testResources>
</build>

With this config, you will be able to access xml files in WEB-INF folder. From Maven POM Reference: The testResources element block contains testResource elements. Their definitions are similar to resource elements, but are naturally used during test phases.

Linq with group by having count

Below solution may help you.

var unmanagedDownloadcountwithfilter = from count in unmanagedDownloadCount.Where(d =>d.downloaddate >= startDate && d.downloaddate <= endDate)
group count by count.unmanagedassetregistryid into grouped
where grouped.Count() > request.Download
select new
{
   UnmanagedAssetRegistryID = grouped.Key,
   Count = grouped.Count()
};

Location of the android sdk has not been setup in the preferences in mac os?

i was facing the same problem. the solution is...Copy the link http://dl-ssl.google.com/android/eclipse/ then in eclipse go to

Help > Install New Software > Add(work with) > past the link on locations > ok > select all > next

this will solve your problem.

Detect and exclude outliers in Pandas data frame

Deleting and dropping outliers I believe is wrong statistically. It makes the data different from original data. Also makes data unequally shaped and hence best way is to reduce or avoid the effect of outliers by log transform the data. This worked for me:

np.log(data.iloc[:, :])

What Language is Used To Develop Using Unity

Unity3d supports C#, Boo and JavaScript. The framework translates this into its intermediate format and later to the desired platform (IOS/Android/Linux/Windows)

Keep in mind, C# Scripts are compiled first, followed by JS and Boo Hence if you want a C# script to interact with a JS, you ll have to keep the JS in the Standard Assets Folder.

Difference between a SOAP message and a WSDL?

A WSDL (Web Service Definition Language) is a meta-data file that describes the web service.

Things like operation name, parameters etc.

The soap messages are the actual payloads

overlay two images in android to set an imageview

ok just so you know there is a program out there that's called DroidDraw. It can help you draw objects and try them one on top of the other. I tried your solution but I had animation under the smaller image so that didn't work. But then I tried to place one image in a relative layout that's suppose to be under first and then on top of that I drew the other image that is suppose to overlay and everything worked great. So RelativeLayout, DroidDraw and you are good to go :) Simple, no any kind of jiggery pockery :) and here is a bit of code for ya:

The logo is going to be on top of shazam background image.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="@+id/widget39"
android:layout_width="219px"
android:layout_height="225px"
android:src="@drawable/shazam_bkgd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
<ImageView
android:id="@+id/widget37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/shazam_logo"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
</RelativeLayout>

How to get every first element in 2 dimensional list

If you have access to numpy,

import numpy as np
a_transposed = a.T
# Get first row
print(a_transposed[0])

The benefit of this method is that if you want the "second" element in a 2d list, all you have to do now is a_transposed[1]. The a_transposed object is already computed, so you do not need to recalculate.

Description

Finding the first element in a 2-D list can be rephrased as find the first column in the 2d list. Because your data structure is a list of rows, an easy way of sampling the value at the first index in every row is just by transposing the matrix and sampling the first list.

cURL error 60: SSL certificate: unable to get local issuer certificate

I had this problem appear out-of-the-blue one day, when a Guzzle(5) script was attempting to connect to a host over SSL. Sure, I could disable the VERIFY option in Guzzle/Curl, but that's clearly not the correct way to go.

I tried everything listed here and in similar threads, then eventually went to terminal with openssl to test against the domain with which I was trying to connect:

openssl s_client -connect example.com:443 

... and received first few lines indicating:

CONNECTED(00000003)
depth=0 CN = example.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 CN = example.com
verify error:num=21:unable to verify the first certificate
verify return:1 

... while everything worked fine when trying other destinations (ie: google.com, etc)

This prompted me to contact the domain I had been trying to connect to, and indeed, they had a problem on THEIR END that had crept up. It was resolved and my script went back to working.

So... if you're pulling your hair out, give openssl a shot and see if there's anything up with the response from the location you are attempting to connect. Maybe the issue isn't so 'local' after all sometimes.

jQuery: Clearing Form Inputs

You may try

$("#addRunner input").each(function(){ ... });

Inputs are no selectors, so you do not need the : Haven't tested it with your code. Just a fast guess!

Does a valid XML file require an XML declaration?

Xml declaration is optional so your xml is well-formed without it. But it is recommended to use it so that wrong assumptions are not made by the parsers, specifically about the encoding used.

How to synchronize or lock upon variables in Java?

From Java 1.5 it's always a good Idea to consider java.util.concurrent package. They are the state of the art locking mechanism in java right now. The synchronize mechanism is more heavyweight that the java.util.concurrent classes.

The example would look something like this:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Sample {

    private final Lock lock = new ReentrantLock();

    private String message = null;

    public void newmsg(String msg) {
        lock.lock();
        try {
            message = msg;
        } finally {
            lock.unlock();
        }
    }

    public String getmsg() {
        lock.lock();
        try {
            String temp = message;
            message = null;
            return temp;
        } finally {
            lock.unlock();
        }
    }
}

How to set HTTP headers (for cache-control)?

OWASP recommends the following,

Whenever possible ensure the cache-control HTTP header is set with no-cache, no-store, must-revalidate, private; and that the pragma HTTP header is set with no-cache.

<IfModule mod_headers.c>
    Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
    Header set Pragma "no-cache"
</IfModule>

How to get a single value from FormGroup

Yes, you can.

this.formGroup.get('name of you control').value

How do I query for all dates greater than a certain date in SQL Server?

Try enclosing your date into a character string.

 select * 
 from dbo.March2010 A
 where A.Date >= '2010-04-01';

Mongoose query where value is not null

Hello guys I am stucked with this. I've a Document Profile who has a reference to User,and I've tried to list the profiles where user ref is not null (because I already filtered by rol during the population), but after googleing a few hours I cannot figure out how to get this. I have this query:

const profiles = await Profile.find({ user: {$exists: true,  $ne: null }})
                            .select("-gallery")
                            .sort( {_id: -1} )
                            .skip( skip )
                            .limit(10)
                            .select(exclude)
                            .populate({
                                path: 'user',
                                match: { role: {$eq: customer}},
                                select: '-password -verified -_id -__v'
                              })

                            .exec();

And I get this result, how can I remove from the results the user:null colletions? . I meant, I dont want to get the profile when user is null (the role does not match).
{
    "code": 200,
    "profiles": [
        {
            "description": null,
            "province": "West Midlands",
            "country": "UK",
            "postal_code": "83000",
            "user": null
        },
        {
            "description": null,

            "province": "Madrid",
            "country": "Spain",
            "postal_code": "43000",
            "user": {
                "role": "customer",
                "name": "pedrita",
                "email": "[email protected]",
                "created_at": "2020-06-05T11:05:36.450Z"
            }
        }
    ],
    "page": 1
}

Thanks in advance.

How to change the default port of mysql from 3306 to 3360

On newer (for example 8.0.0) the simplest solution is (good choice for a scripted start-up for example):

mysqld --port=23306

Get/pick an image from Android's built-in Gallery app programmatically

To display images and videos try this:

    Intent intent = new Intent();
    intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, 1);
    startActivityForResult(Intent.createChooser(intent,"Wybierz plik"), SELECT_FILE);

CodeIgniter: Create new helper?

Create a file with the name of your helper in /application/helpers and add it to the autoload config file/load it manually.

E.g. place a file called user_helper.php in /application/helpers with this content:

<?php
  function pre($var)
  {
    echo '<pre>';
    if(is_array($var)) {
      print_r($var);
    } else {
      var_dump($var);
    }
    echo '</pre>';
  }
?> 

Now you can either load the helper via $this->load->helper(‘user’); or add it to application/config/autoload.php config.

Cannot ping AWS EC2 instance

By default EC2 is secured by AWS Security Group (A service found in EC2 and VPC). Security Group by default are disallowing Any ICMP request which includes the ping. To allow it:

Goto: AWS EC2 Instance Locate: The Security Group bind to that instance (It's possible to have multiple security group) Check: Inbound Rules for Protocol (ICMP) Port (0 - 65535) if it's not present you can add it and allow it on your specified source IP or Another Security Group.

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

C# Public Enums in Classes

You need to define the enum outside of the class.

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
     // ...

That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.

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

To make it more interesting and to hopefully enable less hair pulling for someone else. Using python, built dictionary for a device which we can use curl to configure.

Problem: {"timezone":"+5"} //throws an error " 5"

Solution: {"timezone":"%2B"+"5"} //Works

So, in a nutshell:

var = {"timezone":"%2B"+"5"}
json = JSONEncoder().encode(var)
subprocess.call(["curl",ipaddress,"-XPUT","-d","data="+json])

Thanks to this post!

Textarea to resize based on content length

Use this function:

function adjustHeight(el){
    el.style.height = (el.scrollHeight > el.clientHeight) ? (el.scrollHeight)+"px" : "60px";
}

Use this html:

<textarea onkeyup="adjustHeight(this)"></textarea>

And finally use this css:

textarea {
min-height: 60px;
overflow-y: auto;
word-wrap:break-word
}

The solution simply is letting the scrollbar appears to detect that height needs to be adjusted, and whenever the scrollbar appears in your text area, it adjusts the height just as much as to hide the scrollbar again.

Failed to install *.apk on device 'emulator-5554': EOF

When it happened to me, I solved it by closing the emulator and running the project again.

Microsoft SQL Server 2005 service fails to start

I'd try just installing the tools and database services to start with. leave analysis, Rs etc and see if you get further. I do remeber having issues with failed installs so be sure to go into add/remove programs and remove all the pieces that the uninstaller is leaving behind

shell init issue when click tab, what's wrong with getcwd?

By chance, is this occurring on a directory using OverlayFS (or some other special file system type)?

I just had this issue where my cross-compiled version of bash would use an internal implementation of getcwd which has issues with OverlayFS. I found information about this here:

It seems that this can be traced to an internal implementation of getcwd() in bash. When cross-compiled, it can't check for getcwd() use of malloc, so it is cautious and sets GETCWD_BROKEN and uses an internal implementation of getcwd(). This internal implementation doesn't seem to work well with OverlayFS.

http://permalink.gmane.org/gmane.linux.embedded.yocto.general/25204

You can configure and rebuild bash with bash_cv_getcwd_malloc=yes (if you're actually building bash and your C library does malloc a getcwd call).

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

How do I position one image on top of another in HTML?

You can absolutely position pseudo elements relative to their parent element.

This gives you two extra layers to play with for every element - so positioning one image on top of another becomes easy - with minimal and semantic markup (no empty divs etc).

markup:

<div class="overlap"></div>

css:

.overlap
{
    width: 100px;
    height: 100px;
    position: relative;
    background-color: blue;
}
.overlap:after
{
    content: '';
    position: absolute;
    width: 20px;
    height: 20px;
    top: 5px;
    left: 5px;
    background-color: red;
}

Here's a LIVE DEMO

'react-scripts' is not recognized as an internal or external command

Faced the same problem, although I am using yarn.

The following worked for me:

yarn install 
yarn start

How to make a select with array contains value clause in psql

Try

SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]

Django: multiple models in one template using forms

I currently have a workaround functional (it passes my unit tests). It is a good solution to my opinion when you only want to add a limited number of fields from other models.

Am I missing something here ?

class UserProfileForm(ModelForm):
    def __init__(self, instance=None, *args, **kwargs):
        # Add these fields from the user object
        _fields = ('first_name', 'last_name', 'email',)
        # Retrieve initial (current) data from the user object
        _initial = model_to_dict(instance.user, _fields) if instance is not None else {}
        # Pass the initial data to the base
        super(UserProfileForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
        # Retrieve the fields from the user model and update the fields with it
        self.fields.update(fields_for_model(User, _fields))

    class Meta:
        model = UserProfile
        exclude = ('user',)

    def save(self, *args, **kwargs):
        u = self.instance.user
        u.first_name = self.cleaned_data['first_name']
        u.last_name = self.cleaned_data['last_name']
        u.email = self.cleaned_data['email']
        u.save()
        profile = super(UserProfileForm, self).save(*args,**kwargs)
        return profile

How to insert an item into an array at a specific index (JavaScript)?

Taking profit of reduce method as following:

function insert(arr, val, index) {
    return index >= arr.length 
        ? arr.concat(val)
        : arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}

So at this way we can return a new array (will be a cool functional way - more much better than use push or splice) with the element inserted at index, and if the index is greater than the length of the array it will be inserted at the end.

How can I correctly format currency using jquery?

Try regexp currency with jQuery (no plugin):

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('#test').click(function() {_x000D_
    TESTCURRENCY = $('#value').val().toString().match(/(?=[\s\d])(?:\s\.|\d+(?:[.]\d+)*)/gmi);_x000D_
    if (TESTCURRENCY.length <= 1) {_x000D_
      $('#valueshow').val(_x000D_
        parseFloat(TESTCURRENCY.toString().match(/^\d+(?:\.\d{0,2})?/))_x000D_
      );_x000D_
    } else {_x000D_
      $('#valueshow').val('Invalid a value!');_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="text" value="12345.67890" id="value">_x000D_
<input type="button" id="test" value="CLICK">_x000D_
<input type="text" value="" id="valueshow">
_x000D_
_x000D_
_x000D_

Edit: New check a value to valid/invalid

import module from string variable

Apart from using the importlib one can also use exec method to import a module from a string variable.

Here I am showing an example of importing the combinations method from itertools package using the exec method:

MODULES = [
    ['itertools','combinations'],
]

for ITEM in MODULES:
    import_str = "from {0} import {1}".format(ITEM[0],', '.join(str(i) for i in ITEM[1:]))
    exec(import_str)

ar = list(combinations([1, 2, 3, 4], 2))
for elements in ar:
    print(elements)

Output:

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

How to replace all double quotes to single quotes using jquery?

You can also use replaceAll(search, replaceWith) [MDN].

Then, make sure you have a string by wrapping one type of quotes by a different type:

 'a "b" c'.replaceAll('"', "'")
 // result: "a 'b' c"
    
 'a "b" c'.replaceAll(`"`, `'`)
 // result: "a 'b' c"

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

Sql Server string to date conversion

For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

ASP.NET MVC Dropdown List From SelectList

Just try this in razor

@{
    var selectList = new SelectList(
        new List<SelectListItem>
        {
            new SelectListItem {Text = "Google", Value = "Google"},
            new SelectListItem {Text = "Other", Value = "Other"},
        }, "Value", "Text");
}

and then

@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })

or

@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })

See :hover state in Chrome Developer Tools

I was debugging a menu hover state with Chrome and did this to be able to see the hover state code:

In the Elements panel click over Toggle Element state button and select :hover.

In the Scripts panel go to Event Listeners Breakpoints in the right bottom section and select Mouse -> mouseup.

Now inspect the Menu and select the box you want. When you release the mouse button it should stop and show you the selected element hover state in the Elements panel (look at the Styles section).

How to get the nvidia driver version from the command line?

Windows version:

cd \Program Files\NVIDIA Corporation\NVSMI

nvidia-smi

Make DateTimePicker work as TimePicker only in WinForms

...or alternatively if you only want to show a portion of the time value use "Custom":

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Custom;
timePicker.CustomFormat = "HH:mm"; // Only use hours and minutes
timePicker.ShowUpDown = true;

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

I prefer using the value returned by System.currentTimeMillis() for all kinds of calculations and only use Calendar or Date if I need to really display a value that is read by humans. This will also prevent 99% of your daylight-saving-time bugs. :)

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

If your file has only one main function that you want to call/expose, then you can also just start the file with:

Param($Param1)

You can then call it e.g. as follows:

.\MyFunctions.ps1 -Param1 'value1'

This makes it much more convenient if you want to easily call just that function without having to import the function.

wamp server mysql user id and password

Simply goto MySql Console.

If using Wamp:

  1. Click on Wamp icon just beside o'clock.
  2. In MySql section click on MySql Console.
  3. Press enter (means no password) twice.
  4. mysql commands preview like this : mysql>
  5. SET PASSWORD FOR 'root'@'localhost' = PASSWORD('secret');

That's it. This set your root password to secret

In order to set user privilege to default one:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');

Works like a charm!

kill a process in bash

It is not clear to me what you mean by "escape an executable which is running", but ctrl-z will put a process into the background and return control to the command line. You can then use the fg command to bring the program back into the foreground.

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

  1. Delete early created devices.
  2. Close Android studio.
  3. Open: Control panel -> System & security -> System -> Advanced system settings -> Environment variables.
  4. Create New variable "ANDROID_SDK_HOME" and set new path(in my case it was F:\Coding2019\Android\AVDdevices). Push 'ok'.
  5. Open Android Studio.
  6. Create new device. After creating in drop-down menu click "View Details" to see new path of new AVD.

Jquery get form field value

An alternative approach, without searching for the field html:

var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
  return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;

Collection was modified; enumeration operation may not execute

This way should cover a situation of concurrency when the function is called again while is still executing (and items need used only once):

 while (list.Count > 0)
 {
    string Item = list[0];
    list.RemoveAt(0);
 
    // do here what you need to do with item
 
 } 
 

If the function get called while is still executing items will not reiterate from the first again as they get deleted as soon as they get used. Should not affect performance much for small lists.

How to read an entire file to a string using C#?

A benchmark comparison of File.ReadAllLines vs StreamReader ReadLine from C# file handling

File Read Comparison

Results. StreamReader is much faster for large files with 10,000+ lines, but the difference for smaller files is negligible. As always, plan for varying sizes of files, and use File.ReadAllLines only when performance isn't critical.


StreamReader approach

As the File.ReadAllText approach has been suggested by others, you can also try the quicker (I have not tested quantitatively the performance impact, but it appears to be faster than File.ReadAllText (see comparison below)). The difference in performance will be visible only in case of larger files though.

string readContents;
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
     readContents = streamReader.ReadToEnd();
}


Comparison of File.Readxxx() vs StreamReader.Readxxx()

Viewing the indicative code through ILSpy I have found the following about File.ReadAllLines, File.ReadAllText.

  • File.ReadAllText - Uses StreamReader.ReadToEnd internally
  • File.ReadAllLines - Also uses StreamReader.ReadLine internally with the additionally overhead of creating the List<string> to return as the read lines and looping till the end of file.


So both the methods are an additional layer of convenience built on top of StreamReader. This is evident by the indicative body of the method.

File.ReadAllText() implementation as decompiled by ILSpy

public static string ReadAllText(string path)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    if (path.Length == 0)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    }
    return File.InternalReadAllText(path, Encoding.UTF8);
}   

private static string InternalReadAllText(string path, Encoding encoding)
{
    string result;
    using (StreamReader streamReader = new StreamReader(path, encoding))
    {
        result = streamReader.ReadToEnd();
    }
    return result;
}

Replacing some characters in a string with another character

echo "$string" | tr xyz _

would replace each occurrence of x, y, or z with _, giving A__BC___DEF__LMN in your example.

echo "$string" | sed -r 's/[xyz]+/_/g'

would replace repeating occurrences of x, y, or z with a single _, giving A_BC_DEF_LMN in your example.

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

Regex match digits, comma and semicolon?

You almost have it, you just left out 0 and forgot the quantifier.

word.matches("^[0-9,;]+$")

How to find the mime type of a file in python?

Python bindings to libmagic

All the different answers on this topic are very confusing, so I’m hoping to give a bit more clarity with this overview of the different bindings of libmagic. Previously mammadori gave a short answer listing the available option.

libmagic

When determining a files mime-type, the tool of choice is simply called file and its back-end is called libmagic. (See the Project home page.) The project is developed in a private cvs-repository, but there is a read-only git mirror on github.

Now this tool, which you will need if you want to use any of the libmagic bindings with python, already comes with its own python bindings called file-magic. There is not much dedicated documentation for them, but you can always have a look at the man page of the c-library: man libmagic. The basic usage is described in the readme file:

import magic

detected = magic.detect_from_filename('magic.py')
print 'Detected MIME type: {}'.format(detected.mime_type)
print 'Detected encoding: {}'.format(detected.encoding)
print 'Detected file type name: {}'.format(detected.name)

Apart from this, you can also use the library by creating a Magic object using magic.open(flags) as shown in the example file.

Both toivotuo and ewr2san use these file-magic bindings included in the file tool. They mistakenly assume, they are using the python-magic package. This seems to indicate, that if both file and python-magic are installed, the python module magic refers to the former one.

python-magic

This is the library that Simon Zimmermann talks about in his answer and which is also employed by Claude COULOMBE as well as Gringo Suave.

filemagic

Note: This project was last updated in 2013!

Due to being based on the same c-api, this library has some similarity with file-magic included in libmagic. It is only mentioned by mammadori and no other answer employs it.

Eclipse CDT: Symbol 'cout' could not be resolved

I had the same issue using Eclipse CDT (Kepler) on Windows with Cygwin installed. After pointing the project properties at every Cygwin include I could think of, it still couldn't find cout.

The final missing piece turned out to be C:cygwin64\lib\gcc\x86_64-pc-cygwin\4.8.2\install-tool\include.

To sum up:

  • Right click on the project
  • Choose Properties
  • Navigate to C/C++ General > Paths and Symbols > Includes tab
  • Click Add...
  • Click File system...
  • Browse to the location of your Cygwin lib\gcc\x86_64-pc-cygwin\4.8.2\install-tool\include
  • Click OK

Here is what my project includes ended up looking like when it was all said and done: enter image description here

Making Python loggers output all messages to stdout in addition to log file

Here's an extremely simple example:

import logging
l = logging.getLogger("test")

# Add a file logger
f = logging.FileHandler("test.log")
l.addHandler(f)

# Add a stream logger
s = logging.StreamHandler()
l.addHandler(s)

# Send a test message to both -- critical will always log
l.critical("test msg")

The output will show "test msg" on stdout and also in the file.

This compilation unit is not on the build path of a Java project

Add this to .project file

 <?xml version="1.0" encoding="UTF-8"?>
        <projectDescription>
            <name>framework</name>
            <comment></comment>
            <projects>
            </projects>
            <buildSpec>
                <buildCommand>
                    <name>org.eclipse.wst.common.project.facet.core.builder</name>
                    <arguments>
                    </arguments>
                </buildCommand>
                <buildCommand>
                    <name>org.eclipse.jdt.core.javabuilder</name>
                    <arguments>
                    </arguments>
                </buildCommand>
                <buildCommand>
                    <name>org.eclipse.m2e.core.maven2Builder</name>
                    <arguments>
                    </arguments>
                </buildCommand>
                <buildCommand>
                    <name>org.eclipse.wst.validation.validationbuilder</name>
                    <arguments>
                    </arguments>
                </buildCommand>
            </buildSpec>
            <natures>
                <nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
                <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
                <nature>org.eclipse.jdt.core.javanature</nature>
                <nature>org.eclipse.m2e.core.maven2Nature</nature>
                <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
            </natures>
        </projectDescription>

./xx.py: line 1: import: command not found

I've experienced the same problem and now I just found my solution to this issue.

#!/usr/bin/python

import sys
import os

os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))

This is the code[1] for my case. When I tried this script I received error message like :

import: command not found

I found people talks about the shebang. As you see there is the shebang in my python code above. I tried these and those trials but didn't find a good solution.

I finally tried to type the shebang my self.

#!/usr/bin/python

and removed the copied one.

And my problem solved!!!

I copied the code from the internet[1].

And I guess there had been some unseeable(?) unseen special characters in the original copied shebang statement.

I use vim, sometimes I experience similar problems.. Especially when I copied some code snippet from the internet this kind of problems happen.. Web pages have some virus special characters!! I doubt. :-)

Journeyer

PS) I copied the code in Windows 7 - host OS - into the Windows clipboard and pasted it into my vim in Ubuntu - guest OS. VM is Oracle Virtual Machine.

[1] http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy

How to add shortcut keys for java code in eclipse

Type "Sysout" and then Ctrl+Space. It expands to

System.out.println();

Optimistic vs. Pessimistic locking

One use case for optimistic locking is to have your application use the database to allow one of your threads / hosts to 'claim' a task. This is a technique that has come in handy for me on a regular basis.

The best example I can think of is for a task queue implemented using a database, with multiple threads claiming tasks concurrently. If a task has status 'Available', 'Claimed', 'Completed', a db query can say something like "Set status='Claimed' where status='Available'. If multiple threads try to change the status in this way, all but the first thread will fail because of dirty data.

Note that this is a use case involving only optimistic locking. So as an alternative to saying "Optimistic locking is used when you don't expect many collisions", it can also be used where you expect collisions but want exactly one transaction to succeed.

How to make a pure css based dropdown menu?

_x000D_
_x000D_
html, body {_x000D_
    font-family: Arial, Helvetica, sans-serif;_x000D_
}_x000D_
_x000D_
/* define a fixed width for the entire menu */_x000D_
.navigation {_x000D_
  width: 150px;_x000D_
}_x000D_
_x000D_
/* reset our lists to remove bullet points and padding */_x000D_
.mainmenu, .submenu {_x000D_
  list-style: none;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
/* make ALL links (main and submenu) have padding and background color */_x000D_
.mainmenu a {_x000D_
  display: block;_x000D_
  background-color: #CCC;_x000D_
  text-decoration: none;_x000D_
  padding: 10px;_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
/* add hover behaviour */_x000D_
.mainmenu a:hover {_x000D_
    background-color: #C5C5C5;_x000D_
}_x000D_
_x000D_
_x000D_
/* when hovering over a .mainmenu item,_x000D_
  display the submenu inside it._x000D_
  we're changing the submenu's max-height from 0 to 200px;_x000D_
*/_x000D_
_x000D_
.mainmenu li:hover .submenu {_x000D_
  display: block;_x000D_
  max-height: 200px;_x000D_
}_x000D_
_x000D_
/*_x000D_
  we now overwrite the background-color for .submenu links only._x000D_
  CSS reads down the page, so code at the bottom will overwrite the code at the top._x000D_
*/_x000D_
_x000D_
.submenu a {_x000D_
  background-color: #999;_x000D_
}_x000D_
_x000D_
/* hover behaviour for links inside .submenu */_x000D_
.submenu a:hover {_x000D_
  background-color: #666;_x000D_
}_x000D_
_x000D_
/* this is the initial state of all submenus._x000D_
  we set it to max-height: 0, and hide the overflowed content._x000D_
*/_x000D_
.submenu {_x000D_
  overflow: hidden;_x000D_
  max-height: 0;_x000D_
  -webkit-transition: all 0.5s ease-out;_x000D_
}
_x000D_
<html>_x000D_
<body>_x000D_
<head>_x000D_
<link rel="stylesheet" type="css/text" href="nav.css">_x000D_
</head>_x000D_
</body>_x000D_
<nav class="navigation">_x000D_
  <ul class="mainmenu">_x000D_
    <li><a href="">Home</a></li>_x000D_
    <li><a href="">About</a></li>_x000D_
    <li><a href="">Products</a>_x000D_
      <ul class="submenu">_x000D_
        <li><a href="">Tops</a></li>_x000D_
        <li><a href="">Bottoms</a></li>_x000D_
        <li><a href="">Footwear</a></li>_x000D_
      </ul>_x000D_
    </li>_x000D_
    <li><a href="">Contact us</a></li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

WampServer orange icon

Wamp server default disk is "C:\" if you install it to another disk for ex G:\: go to

  1. g:\wamp\bin\apache\apache2.4.9\bin\

2 .call cmd

3 .execute httpd.exe -t

you will see errors

enter image description here

  1. go to g:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-autoindex.conf

  2. change in line 23 to :

Alias /icons/ "g:/Apache24/icons/"

<Directory "g:/Apache24/icons">
    Options Indexes MultiViews
    AllowOverride None
    Require all granted
</Directory>
  1. Restart All services. Done. Resolved

How do I make XAML DataGridColumns fill the entire DataGrid?

Another spin on the same theme:

protected void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
    dataGrid.Width = e.NewSize.Width - (e.NewSize.Width * .1);

    foreach (var column in dataGrid.Columns)
    {
       column.Width = dataGrid.Width / dataGrid.Columns.Count;
    }
 }

Find (and kill) process locking port 3000 on Mac

A one-liner to extract the PID of the process using port 3000 and kill it.

lsof -ti:3000 | xargs kill

The -t flag removes everything but the PID from the lsof output, making it easy to kill it.

Logout button php

Instead of a button, put a link and navigate it to another page

<a href="logout.php">Logout</a>

Then in logout.php page, use

session_start();
session_destroy();
header('Location: login.php');
exit;

How to compare two Carbon Timestamps?

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

protected $dates = ['edited_at'];

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

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

Usage:

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

VirtualBox error "Failed to open a session for the virtual machine"

For MAC users

After some research, this worked for me:

  • Quit VirtualBox
  • Right click "Applications" folder
  • Click on "Get Info"
  • Change "Everyone" Permission to "Read Only"
  • Open VirtualBox, and now it should work.

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!

You can actually export the data to an excel file or SQL.

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

Does uninstalling a package with "pip" also remove the dependent packages?

I have found the solution even though it might be a little difficult for some to carry out.

1st step (for python3 and linux):
pip3 install pip-autoremove
2nd step:
cd /home/usernamegoeshere/.local/bin/
3rd step:
gedit /home/usernamegoeshere/.local/lib/python3.8/site-packages/pip_autoremove.py
and change all pip(s) to pip3 4th step: ./pip-autoremove packagenamegoeshere

At least, this was what worked for me ...

How to randomize (shuffle) a JavaScript array?

Using sort method and Math method :

var arr =  ["HORSE", "TIGER", "DOG", "CAT"];
function shuffleArray(arr){
  return arr.sort( () => Math.floor(Math.random() * Math.floor(3)) - 1)  
}

// every time it gives random sequence
shuffleArr(arr);
// ["DOG", "CAT", "TIGER", "HORSE"]
// ["HORSE", "TIGER", "CAT", "DOG"]
// ["TIGER", "HORSE", "CAT", "DOG"]

Sort hash by key, return hash in Ruby

No, it is not (Ruby 1.9.x)

require 'benchmark'

h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
many = 100_000

Benchmark.bm do |b|
  GC.start

  b.report("hash sort") do
    many.times do
      Hash[h.sort]
    end
  end

  GC.start

  b.report("keys sort") do
    many.times do
      nh = {}
      h.keys.sort.each do |k|
        nh[k] = h[k]
      end
    end
  end
end

       user     system      total        real
hash sort  0.400000   0.000000   0.400000 (  0.405588)
keys sort  0.250000   0.010000   0.260000 (  0.260303)

For big hashes difference will grow up to 10x and more

How to convert String object to Boolean Object?

This is how I did it:

"1##true".contains( string )

For my case is mostly either 1 or true. I use hashes as dividers.

How to change the foreign key referential action? (behavior)

I had a bunch of FKs to alter, so I wrote something to make the statements for me. Figured I'd share:

SELECT

CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
    '` DROP FOREIGN KEY `' ,rc.CONSTRAINT_NAME,'`;')
, CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
    '` ADD CONSTRAINT `' ,rc.CONSTRAINT_NAME ,'` FOREIGN KEY (`',kcu.COLUMN_NAME,
    '`) REFERENCES `',kcu.REFERENCED_TABLE_NAME,'` (`',kcu.REFERENCED_COLUMN_NAME,'`) ON DELETE CASCADE;')

FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
LEFT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
    ON kcu.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA
    AND kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
WHERE DELETE_RULE = 'NO ACTION'
AND rc.CONSTRAINT_SCHEMA = 'foo'

What is *.o file?

A file ending in .o is an object file. The compiler creates an object file for each source file, before linking them together, into the final executable.

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

Kotlin version:

Use these extensions with infix functions that simplify later calls

infix fun View.below(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

infix fun View.leftOf(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.LEFT_OF, view.id)
}

infix fun View.alightParentRightIs(aligned: Boolean) {
    val layoutParams = this.layoutParams as? RelativeLayout.LayoutParams
    if (aligned) {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
    } else {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0)
    }
    this.layoutParams = layoutParams
}

Then use them as infix functions calls:

view1 below view2
view1 leftOf view2
view1 alightParentRightIs true

Or you can use them as normal functions:

view1.below(view2)
view1.leftOf(view2)
view1.alightParentRightIs(true)

Disabling right click on images using jquery

This should work

$(function(){
     $('body').on('contextmenu', 'img', function(e){ 
         return false; 
     });
 });

Angular.js: How does $eval work and why is it different from vanilla eval?

From the test,

it('should allow passing locals to the expression', inject(function($rootScope) {
  expect($rootScope.$eval('a+1', {a: 2})).toBe(3);

  $rootScope.$eval(function(scope, locals) {
    scope.c = locals.b + 4;
  }, {b: 3});
  expect($rootScope.c).toBe(7);
}));

We also can pass locals for evaluation expression.

How do I find where JDK is installed on my windows machine?

#!/bin/bash

if [[ $(which ${JAVA_HOME}/bin/java) ]]; then
    exe="${JAVA_HOME}/bin/java"
elif [[ $(which java) ]]; then
    exe="java"
else 
    echo "Java environment is not detected."
    exit 1
fi

${exe} -version

For windows:

@echo off
if "%JAVA_HOME%" == "" goto nojavahome

echo Using JAVA_HOME            :   %JAVA_HOME%

"%JAVA_HOME%/bin/java.exe" -version
goto exit

:nojavahome
echo The JAVA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program.
goto exit

:exit

This link might help to explain how to find java executable from bash: http://srcode.org/2014/05/07/detect-java-executable/