Programs & Examples On #Yii

Use for questions about any version of Yii, an open-source MVC framework for writing web 2.0 applications in PHP5+

Only on Firefox "Loading failed for the <script> with source"

I ran in the same situation and the script was correctly loading in safe mode. However, disabling all the Add-ons and other Firefox security features didn't help. One thing I tried, and this was the solution in my case, was to temporary disable the cache from the developer window for this particular request. After I saw this was the cause, I wiped out the cache for that site and everything started word normally.

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

In my case there was problem in URL. I've use https://example.com - but they ensure 'www.' - so when i switched to https://www.example.com everything was ok. The proper header was sent 'Host: www.example.com'.

You can try make a request in firefox brwoser, persist it and copy as cURL - that how I've found it.

Get current URL/URI without some of $_GET variables

Yii 1

Most of the other answers are wrong. The poster is asking for the url WITHOUT (some) $_GET-parameters.

Here is a complete breakdown (creating url for the currently active controller, modules or not):

// without $_GET-parameters
Yii::app()->controller->createUrl(Yii::app()->controller->action->id);

// with $_GET-parameters, HAVING ONLY supplied keys
Yii::app()->controller->createUrl(Yii::app()->controller->action->id,
    array_intersect_key($_GET, array_flip(['id']))); // include 'id'

// with all $_GET-parameters, EXCEPT supplied keys
Yii::app()->controller->createUrl(Yii::app()->controller->action->id,
    array_diff_key($_GET, array_flip(['lg']))); // exclude 'lg'

// with ALL $_GET-parameters (as mensioned in other answers)
Yii::app()->controller->createUrl(Yii::app()->controller->action->id, $_GET);
Yii::app()->request->url;

When you don't have the same active controller, you have to specify the full path like this:

Yii::app()->createUrl('/controller/action');
Yii::app()->createUrl('/module/controller/action');

Check out the Yii guide for building url's in general: http://www.yiiframework.com/doc/guide/1.1/en/topics.url#creating-urls

findAll() in yii

This is your safest way to do it:

$id =101;
//$user_id=25;
$criteria=new CDbCriteria;
$criteria->condition="email_id < :email_id";
//$criteria->addCondition("user_id=:user_id");
$criteria->params=array(
  ':email_id' => $id,
  //':user_id' => $user_id,
);
$comments=EmailArchive::model()->findAll($criteria);

Note that if you comment out the commented lines you get a way to add more filtering to your search.

After this it is recommend to check if there is any data returned like:

if (isset($comments)) { // We found some comments, we can sleep well tonight
  // do comments process or whatever
}

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get:

$.get(
    'index.php?r=admin/post/ajax',
    {"parentCatId":parentCatId},
    function(data){                     
        $.each(data, function(key, value){
            console.log(key + ":" + value)
        })
    },
    'json'
);

Yii2 data provider default sorting

I think there's proper solution. Configure the yii\data\Sort object:

 $dataProvider = new ActiveDataProvider([
     'query' => $query,
     'sort'=> ['defaultOrder' => ['topic_order' => SORT_ASC]],
 ]);

Official doc link

Include CSS,javascript file in Yii Framework

You can do so by adding

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/script');

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

It only appeared in my Chrome browser a few days ago too. I checked a few websites I developed in the past that haven't been changed and they also show the same error. So I'd suggest it's not down to your coding, rather a bug in the latest Chrome release.

Can a Windows batch file determine its own file name?

You can get the file name, but you can also get the full path, depending what you place between the '%~' and the '0'. Take your pick from

d -- drive
p -- path
n -- file name
x -- extension
f -- full path

E.g., from inside c:\tmp\foo.bat, %~nx0 gives you "foo.bat", whilst %~dpnx0 gives "c:\tmp\foo.bat". Note the pieces are always assembled in canonical order, so if you get cute and try %~xnpd0, you still get "c:\tmp\foo.bat"

How to find first element of array matching a boolean condition in JavaScript?

There is no built-in function in Javascript to perform this search.

If you are using jQuery you could do a jQuery.inArray(element,array).

Creating multiline strings in JavaScript

You have to use the concatenation operator '+'.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p id="demo"></p>
    <script>
        var str = "This "
                + "\n<br>is "
                + "\n<br>multiline "
                + "\n<br>string.";
        document.getElementById("demo").innerHTML = str;
     </script>
</body>
</html>

By using \n your source code will look like -

This 
 <br>is
 <br>multiline
 <br>string.

By using <br> your browser output will look like -

This
is
multiline
string.

Create dataframe from a matrix

You can use stack from the base package. But, you need first to coerce your matrix to a data.frame and to reorder the columns once the data is stacked.

mat <- as.data.frame(mat)
res <- data.frame(time= mat$time,stack(mat,select=-time))
res[,c(3,1,2)]

  ind time values
1 C_0  0.0    0.1
2 C_0  0.5    0.2
3 C_0  1.0    0.3
4 C_1  0.0    0.3
5 C_1  0.5    0.4
6 C_1  1.0    0.5

Note that stack is generally more efficient than the reshape2 package.

javascript: Disable Text Select

Just use this css method:

body{
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

You can find the same answer here: How to disable text selection highlighting using CSS?

How to cast Object to boolean?

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())

Indent List in HTML and CSS

It sounds like some of your styles are being reset.

By default in most browsers, uls and ols have margin and padding added to them.

You can override this (and many do) by adding a line to your css like so

ul, ol {  //THERE MAY BE OTHER ELEMENTS IN THE LIST
    margin:0;
    padding:0;
}

In this case, you would remove the element from this list or add a margin/padding back, like so

ul{
    margin:1em;
}

Example: http://jsfiddle.net/jasongennaro/vbMbQ/1/

Get output parameter value in ADO.NET

Not my code, but a good example i think

source: http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624

using System; 
using System.Data; 
using System.Data.SqlClient; 


class OutputParams 
{ 
    [STAThread] 
    static void Main(string[] args) 
    { 

    using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;")) 
    { 
        SqlCommand cmd = new SqlCommand("CustOrderOne", cn); 
        cmd.CommandType=CommandType.StoredProcedure ; 

        SqlParameter parm= new SqlParameter("@CustomerID",SqlDbType.NChar) ; 
        parm.Value="ALFKI"; 
        parm.Direction =ParameterDirection.Input ; 
        cmd.Parameters.Add(parm); 

        SqlParameter parm2= new SqlParameter("@ProductName",SqlDbType.VarChar); 
        parm2.Size=50; 
        parm2.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm2); 

        SqlParameter parm3=new SqlParameter("@Quantity",SqlDbType.Int); 
        parm3.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm3);

        cn.Open(); 
        cmd.ExecuteNonQuery(); 
        cn.Close(); 

        Console.WriteLine(cmd.Parameters["@ProductName"].Value); 
        Console.WriteLine(cmd.Parameters["@Quantity"].Value.ToString());
        Console.ReadLine(); 
    } 
} 

How do I create a multiline Python string with inline variables?

If anyone came here from python-graphql client looking for a solution to pass an object as variable here's what I used:

query = """
{{
  pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
    id
    txCount
    reserveUSD
    trackedReserveETH
    volumeUSD
  }}
}}
""".format(block=''.join(['{number: ', str(block), '}']))

 query = gql(query)

Make sure to escape all curly braces like I did: "{{", "}}"

Squash the first two commits in Git?

There is an easier way to do this. Let's assume you're on the master branch

Create a new orphaned branch which will remove all commit history:

$ git checkout --orphan new_branch

Add your initial commit message:

$ git commit -a

Get rid of the old unmerged master branch:

$ git branch -D master

Rename your current branch new_branch to master:

$ git branch -m master

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

i hope this code is work well,try this.

add css file.

.scrollbar {
    height: auto;
    max-height: 180px;
    overflow-x: hidden;
}

HTML code:

<div class="col-sm-2  scrollable-menu" role="menu">
    <div>
   <ul>
  <li><a class="active" href="#home">Tutorials</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>

    </ul>
   </div>
   </div>

HTML5 Dynamically create Canvas

Via Jquery:

$('<canvas/>', { id: 'mycanvas', height: 500, width: 200});

http://jsfiddle.net/8DEsJ/736/

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I was just having the same issue...

To resolve the problem (at least in my case) ensure you have included the lib folder in your bundle classpath:

Manifest-Version: 1.0
... 
Bundle-ClassPath: lib/gson-1.6.jar,
 .
...

Or if you want to include all jar's in the folder:

Bundle-ClassPath: lib/

You will still need to place the jar files on the java build path as shown above. Then your imported jar's should appear in the folder "Referenced Libraries"

Android: How to set password property in an edit text?

This is deprecated

In xml of EditText iclude this attribute: android:password="true"

Edit

android:inputType="textPassword"

Twitter Bootstrap Button Text Word Wrap

You can add these style's and it works just as expected.

.btn {
    white-space:normal !important; 
    word-wrap: break-word; 
    word-break: normal;
}

Set EditText cursor color

Wow I am real late to this party but it has had activity 17 days ago It would seam we need to consider posting what version of Android we are using for an answer so as of now this answer works with Android 2.1 and above Go to RES/VALUES/STYLES and add the lines of code below and your cursor will be black

    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <!--<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">-->
    <!-- Customize your theme here. -->
    <item name="colorControlActivated">@color/color_Black</item>
    <!--Sets COLOR for the Cursor in EditText  -->
</style>

You will need a this line of code in your RES/COLOR folder

<color name="color_Black">#000000</color>

Why post this late ? It might be nice to consider some form of categories for the many headed monster Android has become!

Get first element from a dictionary

Dictionary does not define order of items. If you just need an item use Keys or Values properties of dictionary to pick one.

IndexError: tuple index out of range ----- Python

This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

Use the following excellent npm package: to-arraybuffer.

Or, you can implement it yourself. If your buffer is called buf, do this:

buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)

How to change status bar color to match app in Lollipop? [Android]

Just add this in you styles.xml. The colorPrimary is for the action bar and the colorPrimaryDark is for the status bar.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:colorPrimary">@color/primary</item>
    <item name="android:colorPrimaryDark">@color/primary_dark</item>
</style>

This picture from developer android explains more about color pallete. You can read more on this link.

enter image description here

angular ng-repeat in reverse

This is what i used:

<alert ng-repeat="alert in alerts.slice().reverse()" type="alert.type" close="alerts.splice(index, 1)">{{$index + 1}}: {{alert.msg}}</alert>

Update:

My answer was OK for old version of Angular. Now, you should be using

ng-repeat="friend in friends | orderBy:'-'"

or

ng-repeat="friend in friends | orderBy:'+':true"

from https://stackoverflow.com/a/26635708/1782470

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

I dug deeper into this and found the best solutions are here.

http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python

In my case I solved "UnicodeEncodeError: 'charmap' codec can't encode character "

original code:

print("Process lines, file_name command_line %s\n"% command_line))

New code:

print("Process lines, file_name command_line %s\n"% command_line.encode('utf-8'))  

Exit while loop by user hitting ENTER key

If you want your user to press enter, then the raw_input() will return "", so compare the User with "":

User = raw_input('Press enter to exit...')
running = 1
while running == 1:
    Run your program
if User == "":
    break
else
    running == 1

How can I check if a string represents an int, without using try/except?

The proper RegEx solution would combine the ideas of Greg Hewgill and Nowell, but not use a global variable. You can accomplish this by attaching an attribute to the method. Also, I know that it is frowned upon to put imports in a method, but what I'm going for is a "lazy module" effect like http://peak.telecommunity.com/DevCenter/Importing#lazy-imports

edit: My favorite technique so far is to use exclusively methods of the String object.

#!/usr/bin/env python

# Uses exclusively methods of the String object
def isInteger(i):
    i = str(i)
    return i=='0' or (i if i.find('..') > -1 else i.lstrip('-+').rstrip('0').rstrip('.')).isdigit()

# Uses re module for regex
def isIntegre(i):
    import re
    if not hasattr(isIntegre, '_re'):
        print("I compile only once. Remove this line when you are confident in that.")
        isIntegre._re = re.compile(r"[-+]?\d+(\.0*)?$")
    return isIntegre._re.match(str(i)) is not None

# When executed directly run Unit Tests
if __name__ == '__main__':
    for obj in [
                # integers
                0, 1, -1, 1.0, -1.0,
                '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0',
                # non-integers
                1.1, -1.1, '1.1', '-1.1', '+1.1',
                '1.1.1', '1.1.0', '1.0.1', '1.0.0',
                '1.0.', '1..0', '1..',
                '0.0.', '0..0', '0..',
                'one', object(), (1,2,3), [1,2,3], {'one':'two'}
            ]:
        # Notice the integre uses 're' (intended to be humorous)
        integer = ('an integer' if isInteger(obj) else 'NOT an integer')
        integre = ('an integre' if isIntegre(obj) else 'NOT an integre')
        # Make strings look like strings in the output
        if isinstance(obj, str):
            obj = ("'%s'" % (obj,))
        print("%30s is %14s is %14s" % (obj, integer, integre))

And for the less adventurous members of the class, here is the output:

I compile only once. Remove this line when you are confident in that.
                             0 is     an integer is     an integre
                             1 is     an integer is     an integre
                            -1 is     an integer is     an integre
                           1.0 is     an integer is     an integre
                          -1.0 is     an integer is     an integre
                           '0' is     an integer is     an integre
                          '0.' is     an integer is     an integre
                         '0.0' is     an integer is     an integre
                           '1' is     an integer is     an integre
                          '-1' is     an integer is     an integre
                          '+1' is     an integer is     an integre
                         '1.0' is     an integer is     an integre
                        '-1.0' is     an integer is     an integre
                        '+1.0' is     an integer is     an integre
                           1.1 is NOT an integer is NOT an integre
                          -1.1 is NOT an integer is NOT an integre
                         '1.1' is NOT an integer is NOT an integre
                        '-1.1' is NOT an integer is NOT an integre
                        '+1.1' is NOT an integer is NOT an integre
                       '1.1.1' is NOT an integer is NOT an integre
                       '1.1.0' is NOT an integer is NOT an integre
                       '1.0.1' is NOT an integer is NOT an integre
                       '1.0.0' is NOT an integer is NOT an integre
                        '1.0.' is NOT an integer is NOT an integre
                        '1..0' is NOT an integer is NOT an integre
                         '1..' is NOT an integer is NOT an integre
                        '0.0.' is NOT an integer is NOT an integre
                        '0..0' is NOT an integer is NOT an integre
                         '0..' is NOT an integer is NOT an integre
                         'one' is NOT an integer is NOT an integre
<object object at 0x103b7d0a0> is NOT an integer is NOT an integre
                     (1, 2, 3) is NOT an integer is NOT an integre
                     [1, 2, 3] is NOT an integer is NOT an integre
                {'one': 'two'} is NOT an integer is NOT an integre

Npm install failed with "cannot run in wd"

!~~ For Docker ~~!

@Alexander Mills answer - just to make it easier to find:

RUN npm set unsafe-perm true

How do I use Docker environment variable in ENTRYPOINT array?

You're using the exec form of ENTRYPOINT. Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, ENTRYPOINT [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: ENTRYPOINT [ "sh", "-c", "echo $HOME" ].
When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.(from Dockerfile reference)

In your case, I would use shell form

ENTRYPOINT ./greeting --message "Hello, $ADDRESSEE\!"

Test if something is not undefined in JavaScript

Check if condition == null; It will resolve the problem

Variable name as a string in Javascript

Probably pop would be better than indexing with [0], for safety (variable might be null).

const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${variable}'`);

// returns "Variable myFirstName with value 'John'"

How do I automatically play a Youtube video (IFrame API) muted?

You can select the video player and then set its volume:

var mp = iframe.getElementById('movie_player');
mp.setVolume(0);

Source: http://userscripts.org/scripts/review/49366

How to enable bulk permission in SQL Server

SQL Server may also return this error if the service account does not have permission to read the file being imported. Ensure that the service account has read access to the file location. For example:

icacls D:\ImportFiles /Grant "NT Service\MSSQLServer":(OI)(CI)R

#define macro for debug printing in C?

Here's the version I use:

#ifdef NDEBUG
#define Dprintf(FORMAT, ...) ((void)0)
#define Dputs(MSG) ((void)0)
#else
#define Dprintf(FORMAT, ...) \
    fprintf(stderr, "%s() in %s, line %i: " FORMAT "\n", \
        __func__, __FILE__, __LINE__, __VA_ARGS__)
#define Dputs(MSG) Dprintf("%s", MSG)
#endif

How can I get a list of locally installed Python modules?

Warning: Adam Matan discourages this use in pip > 10.0. Also, read @sinoroc's comment below

This was inspired by Adam Matan's answer (the accepted one):

import tabulate
try:
  from pip import get_installed_distributions
except:
  from pip._internal.utils.misc import get_installed_distributions

tabpackages = []
for _, package in sorted([('%s %s' % (i.location, i.key), i) for i in get_installed_distributions()]):
  tabpackages.append([package.location, package.key, package.version])

print(tabulate.tabulate(tabpackages))

which then prints out a table in the form of

19:33 pi@rpi-v3 [iot-wifi-2] ~/python$ python installed_packages.py
-------------------------------------------  --------------  ------
/home/pi/.local/lib/python2.7/site-packages  enum-compat     0.0.2
/home/pi/.local/lib/python2.7/site-packages  enum34          1.1.6
/home/pi/.local/lib/python2.7/site-packages  pexpect         4.2.1
/home/pi/.local/lib/python2.7/site-packages  ptyprocess      0.5.2
/home/pi/.local/lib/python2.7/site-packages  pygatt          3.2.0
/home/pi/.local/lib/python2.7/site-packages  pyserial        3.4
/usr/local/lib/python2.7/dist-packages       bluepy          1.1.1
/usr/local/lib/python2.7/dist-packages       click           6.7
/usr/local/lib/python2.7/dist-packages       click-datetime  0.2
/usr/local/lib/python2.7/dist-packages       construct       2.8.21
/usr/local/lib/python2.7/dist-packages       pyaudio         0.2.11
/usr/local/lib/python2.7/dist-packages       tabulate        0.8.2
-------------------------------------------  --------------  ------

which lets you then easily discern which packages you installed with and without sudo.


A note aside: I've noticed that when I install a packet once via sudo and once without, one takes precedence so that the other one isn't being listed (only one location is shown). I believe that only the one in the local directory is then listed. This could be improved.

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

Remove certain characters from a string

UPDATE yourtable 
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern') 
WHERE 1

How to draw vectors (physical 2D/3D vectors) in MATLAB?

            % draw simple vector from pt a to pt b
            % wtr : with respect to
            scale=0;%for drawin  vectors with true scale
            a = [10 20 30];% wrt origine O(0,0,0)
            b = [10 10 20];% wrt origine O(0,0,0)

            starts=a;% a now is the origine of my vector to draw (from a to b) so we made a translation from point O to point  a = to vector a 
            c = b-a;% c is the new coordinates of b wrt origine a 
            ends=c;%
            plot3(a(1),a(2),a(3),'*b')
            hold on
            plot3(b(1),b(2),b(3),'*g')

             quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3),scale);% Use scale = 0 to plot the vectors without the automatic scaling.
            % axis equal
            hold off

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

If you used this to secure your server: http://www.thonky.com/how-to/prevent-base-64-decode-hack/

And then got the error: Code Igniter needs mysql_pconnect() in order to run.

I figured it out once I realized all the Code Igniter websites on the server were broken, so it wasn't a localized connection issue.

SQL Server format decimal places with commas

SQL (or to be more precise, the RDBMS) is not meant to be the right choice for formatting the output. The database should deliver raw data which then should be formatted (or more general: processed) in the destination application.

However, depending on the specific system you use, you may write a UDF (user defined function) to achive what you want. But please bear in mind that you then are in fact returning a varchar, which you will not be able to further process (e.g. summarize).

Insert into ... values ( SELECT ... FROM ... )

Here's how to insert from multiple tables. This particular example is where you have a mapping table in a many to many scenario:

insert into StudentCourseMap (StudentId, CourseId) 
SELECT  Student.Id, Course.Id FROM Student, Course 
WHERE Student.Name = 'Paddy Murphy' AND Course.Name = 'Basket weaving for beginners'

(I realise matching on the student name might return more than one value but you get the idea. Matching on something other than an Id is necessary when the Id is an Identity column and is unknown.)

How to get current moment in ISO 8601 format with date, hour, and minute?

private static String getCurrentDateIso()
{
    // Returns the current date with the same format as Javascript's new Date().toJSON(), ISO 8601
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return dateFormat.format(new Date());
}

Styling HTML email for Gmail

Gmail started basic support for style tags in the head area. Found nothing official yet but you can easily try it yourself.
It seems to ignore class and id selectors but basic element selectors work.

<!doctype html>
<html>
  <head>
    <style type="text/css">
      p{font-family:Tahoma,sans-serif;font-size:12px;margin:0}  
    </style>
  </head>
  <body>
    <p>Email content here</p>
  </body>
</html>

it will create a style tag in its own head area limited to the div containing the mail body

<style>div.m14623dcb877eef15 p{font-family:Tahoma,sans-serif;font-size:12px;margin:0}</style>

Changing CSS for last <li>

I've done this with pure CSS (probably because I come from the future - 3 years later than everyone else :P )

Supposing we have a list:

<ul id="nav">
  <li><span>Category 1</span></li>
  <li><span>Category 2</span></li>
  <li><span>Category 3</span></li>
</ul>

Then we can easily make the text of the last item red with:

ul#nav li:last-child span {
   color: Red;
}

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

I'll try to explain it visually:

_x000D_
_x000D_
/**_x000D_
 * explaining margins_x000D_
 */_x000D_
_x000D_
body {_x000D_
  padding: 3em 15%_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  width: 50%;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  position: relative;_x000D_
  background: lemonchiffon;_x000D_
}_x000D_
_x000D_
.parent:before,_x000D_
.parent:after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
}_x000D_
_x000D_
.parent:before {_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 50%;_x000D_
  border-left: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.parent:after {_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 50%;_x000D_
  border-top: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background: rgba(200, 198, 133, .5);_x000D_
}_x000D_
_x000D_
ul {_x000D_
  padding: 5% 20px;_x000D_
}_x000D_
_x000D_
.set1 .child {_x000D_
  margin: 0;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.set2 .child {_x000D_
  margin-left: 75px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.set3 .child {_x000D_
  margin-left: -75px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
_x000D_
/* position absolute */_x000D_
_x000D_
.set4 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
.set5 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-left: 75px;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
.set6 .child {_x000D_
  top: 50%; /* level from which margin-top starts _x000D_
 - downwards, in the case of a positive margin_x000D_
 - upwards, in the case of a negative margin _x000D_
 */_x000D_
  left: 50%; /* level from which margin-left starts _x000D_
 - towards right, in the case of a positive margin_x000D_
 - towards left, in the case of a negative margin _x000D_
 */_x000D_
  margin: -75px;_x000D_
  position: absolute;_x000D_
}
_x000D_
<!-- content to be placed inside <body>…</body> -->_x000D_
<h2><code>position: relative;</code></h2>_x000D_
<h3>Set 1</h3>_x000D_
<div class="parent set 1">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set1 .child {_x000D_
  margin: 0;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 2</h3>_x000D_
<div class="parent set2">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set2 .child {_x000D_
  margin-left: 75px;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 3</h3>_x000D_
<div class="parent set3">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set3 .child {_x000D_
  margin-left: -75px;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h2><code>position: absolute;</code></h2>_x000D_
_x000D_
<h3>Set 4</h3>_x000D_
<div class="parent set4">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set4 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 5</h3>_x000D_
<div class="parent set5">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set5 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-left: 75px;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 6</h3>_x000D_
<div class="parent set6">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set6 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: -75px;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I've gotten this error when running a scalar function using a table value, but the Select statement in my scalar function RETURN clause was missing the "FROM table" portion. :facepalms:

Why use pip over easy_install?

From Ian Bicking's own introduction to pip:

pip was originally written to improve on easy_install in the following ways

  • All packages are downloaded before installation. Partially-completed installation doesn’t occur as a result.
  • Care is taken to present useful output on the console.
  • The reasons for actions are kept track of. For instance, if a package is being installed, pip keeps track of why that package was required.
  • Error messages should be useful.
  • The code is relatively concise and cohesive, making it easier to use programmatically.
  • Packages don’t have to be installed as egg archives, they can be installed flat (while keeping the egg metadata).
  • Native support for other version control systems (Git, Mercurial and Bazaar)
  • Uninstallation of packages.
  • Simple to define fixed sets of requirements and reliably reproduce a set of packages.

Is there a Google Sheets formula to put the name of the sheet into a cell?

I got this to finally work in a semi-automatic fashion without the use of scripts... but it does take up 3 cells to pull it off. Borrowing from a bit from previous answers, I start with a cell that has nothing more than =NOW() it in to show the time. For example, we'll put this into cell A1...

=NOW()

This function updates automatically every minute. In the next cell, put a pointer formula using the sheets own name to point to the previous cell. For example, we'll put this in A2...

='Sheet Name'!A1

Cell formatting aside, cell A1 and A2 should at this point display the same content... namely the current time.

And, the last cell is the part I'm borrowing from previous solutions using a regex expression to pull the fomula from the second cell and then strip out the name of the sheet from said formula. For example, we'll put this into cell A3...

=REGEXREPLACE(FORMULATEXT(A2),"='?([^']+)'?!.*","$1")

At this point, the resultant value displayed in A3 should be the name of the sheet.

From my experience, as soon as the name of the sheet is changed, the formula in A2 is immediately updated. However that's not enough to trigger A3 to update. But, every minute when cell A1 recalculates the time, the result of the formula in cell A2 is subsequently updated and then that in turn triggers A3 to update with the new sheet name. It's not a compact solution... but it does seem to work.

Add property to an array of objects

I came up against this problem too, and in trying to solve it I kept crashing the chrome tab that was running my app. It looks like the spread operator for objects was the culprit.

With a little help from adrianolsk’s comment and sidonaldson's answer above, I used Object.assign() the output of the spread operator from babel, like so:

this.options.map(option => {
  // New properties to be added
  const newPropsObj = {
    newkey1:value1,
    newkey2:value2
  };

  // Assign new properties and return
  return Object.assign(option, newPropsObj);
});

PowerShell try/catch/finally

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

Case insensitive 'in'

I needed this for a dictionary instead of list, Jochen solution was the most elegant for that case so I modded it a bit:

class CaseInsensitiveDict(dict):
    ''' requests special dicts are case insensitive when using the in operator,
     this implements a similar behaviour'''
    def __contains__(self, name): # implements `in`
        return name.casefold() in (n.casefold() for n in self.keys())

now you can convert a dictionary like so USERNAMESDICT = CaseInsensitiveDict(USERNAMESDICT) and use if 'MICHAEL89' in USERNAMESDICT:

android.app.Application cannot be cast to android.app.Activity

In my case, when I'm in an activity that extends from AppCompatActivity, it did not work(Activity) getApplicationContext (), I just putthis in its place.

Get Hard disk serial Number

Use "vol" shell command and parse serial from it's output, like this. Works at least in Win7

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CheckHD
{
        class HDSerial
        {
            const string MY_SERIAL = "F845-BB23";
            public static bool CheckSerial()
            {
                string res = ExecuteCommandSync("vol");
                const string search = "Number is";
                int startI = res.IndexOf(search, StringComparison.InvariantCultureIgnoreCase);

                if (startI > 0)
                {
                    string currentDiskID = res.Substring(startI + search.Length).Trim();
                    if (currentDiskID.Equals(MY_SERIAL))
                        return true;
                }
                return false;
            }

            public static string ExecuteCommandSync(object command)
            {
                try
                {
                    // create the ProcessStartInfo using "cmd" as the program to be run,
                    // and "/c " as the parameters.
                    // Incidentally, /c tells cmd that we want it to execute the command that follows,
                    // and then exit.
                    System.Diagnostics.ProcessStartInfo procStartInfo =
                        new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

                    // The following commands are needed to redirect the standard output.
                    // This means that it will be redirected to the Process.StandardOutput StreamReader.
                    procStartInfo.RedirectStandardOutput = true;
                    procStartInfo.UseShellExecute = false;
                    // Do not create the black window.
                    procStartInfo.CreateNoWindow = true;
                    // Now we create a process, assign its ProcessStartInfo and start it
                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    proc.StartInfo = procStartInfo;
                    proc.Start();
                    // Get the output into a string
                    string result = proc.StandardOutput.ReadToEnd();
                    // Display the command output.
                    return result;
                }
                catch (Exception)
                {
                    // Log the exception
                    return null;
                }
            }
        }
    }

How to use a PHP class from another file?

In this case, it appears that you've already included the file somewhere. But for class files, you should really "include" them using require_once to avoid that sort of thing; it won't include the file if it already has been. (And you should usually use require[_once], not include[_once], the difference being that require will cause a fatal error if the file doesn't exist, instead of just issuing a warning.)

What is the meaning of @_ in Perl?

@ is used for an array.

In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function:

sub Average{

    # Get total number of arguments passed.
    $n = scalar(@_);
    $sum = 0;

    foreach $item (@_){

        # foreach is like for loop... It will access every
        # array element by an iterator
        $sum += $item;
    }

    $average = $sum / $n;

    print "Average for the given numbers: $average\n";
}

Function call

Average(10, 20, 30);

If you observe the above code, see the foreach $item(@_) line... Here it passes the input parameter.

':app:lintVitalRelease' error when generating signed apk

Go to build.gradle(Module:app)

lintOptions {
    checkReleaseBuilds false
    // Or, if you prefer, you can continue to check for errors in release builds,
    // but continue the build even when errors are found:
    abortOnError false
}

How can I make space between two buttons in same div?

Put them inside btn-toolbar or some other container, not btn-group. btn-group joins them together. More info on Bootstrap documentation.

Edit: The original question was for Bootstrap 2.x, but the same is still valid for Bootstrap 3 and Bootstrap 4.

In Bootstrap 4 you will need to add appropriate margin to your groups using utility classes, such as mx-2.

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

how to get the selected index of a drop down

the actual index is available as a property of the select element.

var sel = document.getElementById('CCards');
alert(sel.selectedIndex);

you can use the index to get to the selection option, where you can pull the text and value.

var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);

How do I compare a value to a backslash?

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):
    do_stuff()

Shell script variable not empty (-z option)

I think this is the syntax you are looking for:

if [ -z != $errorstatus ] 
then
commands
else
commands
fi

Android Studio - Importing external Library/Jar

you export the project from Eclipse and then import the project from Android Studio, this should solve your problem, open a eclipse project without importing it from Android Studio you can cause problems, look at: (Excuse my language, I speak Spanish.) http://developer.android.com/intl/es/sdk/installing/migrate.html

How do I ALTER a PostgreSQL table and make a column unique?

I figured it out from the PostgreSQL docs, the exact syntax is:

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.

AssertContains on strings in jUnit

Use hamcrest Matcher containsString()

// Hamcrest assertion
assertThat(person.getName(), containsString("myName"));

// Error Message
java.lang.AssertionError:
Expected: a string containing "myName"
     got: "some other name"

You can optional add an even more detail error message.

// Hamcrest assertion with custom error message
assertThat("my error message", person.getName(), containsString("myName"));

// Error Message
java.lang.AssertionError: my error message
Expected: a string containing "myName"
     got: "some other name"

Posted my answer to a duplicate question here

In JPA 2, using a CriteriaQuery, how to count results

With Spring Data Jpa, we can use this method:

    /*
     * (non-Javadoc)
     * @see org.springframework.data.jpa.repository.JpaSpecificationExecutor#count(org.springframework.data.jpa.domain.Specification)
     */
    @Override
    public long count(@Nullable Specification<T> spec) {
        return executeCountQuery(getCountQuery(spec, getDomainClass()));
    }

When to use HashMap over LinkedList or ArrayList and vice-versa

I will put here some real case examples and scenarios when to use one or another, it might be of help for somebody else:

HashMap

When you have to use cache in your application. Redis and membase are some type of extended HashMap. (Doesn't matter the order of the elements, you need quick ( O(1) ) read access (a value), using a key).

LinkedList

When the order is important (they are ordered as they were added to the LinkedList), the number of elements are unknown (don't waste memory allocation) and you require quick insertion time ( O(1) ). A list of to-do items that can be listed sequentially as they are added is a good example.

How to create the pom.xml for a Java project with Eclipse

The easiest way would be to create a new (simple) Maven project using the "new project" wizard. You can then migrate your source into the Maven folder structure + the auto generated POM file.

How to Sign an Already Compiled Apk

create a key using

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

then sign the apk using :

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name

check here for more info

There is already an object named in the database

I was facing the same issue. I tried below solution : 1. deleted create table code from Up() and related code from Down() method 2. Run update-database command in Package Manager Consol

this solved my problem

export html table to csv

Using just jQuery, vanilla Javascript, and the table2CSV library:

export-to-html-table-as-csv-file-using-jquery

Put this code into a script to be loaded in the head section:

 $(document).ready(function () {
    $('table').each(function () {
        var $table = $(this);

        var $button = $("<button type='button'>");
        $button.text("Export to spreadsheet");
        $button.insertAfter($table);

        $button.click(function () {
            var csv = $table.table2CSV({
                delivery: 'value'
            });
            window.location.href = 'data:text/csv;charset=UTF-8,' 
            + encodeURIComponent(csv);
        });
    });
})

Notes:

Requires jQuery and table2CSV: Add script references to both libraries before the script above.

The table selector is used as an example, and can be adjusted to suit your needs.

It only works in browsers with full Data URI support: Firefox, Chrome and Opera, not in IE, which only supports Data URIs for embedding binary image data into a page.

For full browser compatibility you would have to use a slightly different approach that requires a server side script to echo the CSV.

Inserting created_at data with Laravel

In my case, I wanted to unit test that users weren't able to verify their email addresses after 1 hour had passed, so I didn't want to do any of the other answers since they would also persist when not unit testing, so I ended up just manually updating the row after insert:

// Create new user
$user = factory(User::class)->create();

// Add an email verification token to the 
// email_verification_tokens table
$token = $user->generateNewEmailVerificationToken();

// Get the time 61 minutes ago
$created_at = (new Carbon())->subMinutes(61);

// Do the update
\DB::update(
    'UPDATE email_verification_tokens SET created_at = ?',
    [$created_at]
);

Note: For anything other than unit testing, I would look at the other answers here.

Google maps Marker Label with multiple characters

A much simpler solution to this problem that allows letters, numbers and words as the label is the following code. More specifically, the line of code starting with "icon:". Any string or variable could be substituted for 'k'.

for (i = 0; i < locations.length; i++) 
      { 
      k = i + 1;
      marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),     
      map: map,
      icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + k + '|FF0000|000000'
});

--- the locations array holds the lat and long and k is the row number for the address I was mapping. In other words if I had a 100 addresses to map my marker labels would be 1 to 100.

Multiple linear regression in Python

Use scipy.optimize.curve_fit. And not only for linear fit.

from scipy.optimize import curve_fit
import scipy

def fn(x, a, b, c):
    return a + b*x[0] + c*x[1]

# y(x0,x1) data:
#    x0=0 1 2
# ___________
# x1=0 |0 1 2
# x1=1 |1 2 3
# x1=2 |2 3 4

x = scipy.array([[0,1,2,0,1,2,0,1,2,],[0,0,0,1,1,1,2,2,2]])
y = scipy.array([0,1,2,1,2,3,2,3,4])
popt, pcov = curve_fit(fn, x, y)
print popt

How to sort in mongoose?

As of October 2020, to fix your issue you should add .exec() to the call. don't forget that if you want to use this data outside of the call you should run something like this inside of an async function.

let post = await callQuery();

async function callQuery() {
      return Post.find().sort(['updatedAt', 1].exec();
}

Returning binary file from controller in ASP.NET Web API

For anyone having the problem of the API being called more than once while downloading a fairly large file using the method in the accepted answer, please set response buffering to true System.Web.HttpContext.Current.Response.Buffer = true;

This makes sure that the entire binary content is buffered on the server side before it is sent to the client. Otherwise you will see multiple request being sent to the controller and if you do not handle it properly, the file will become corrupt.

How to make a round button?

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
    android:color="#ffffff"
    />
</shape>

Set that on your XML drawable resources, and simple use and image button with an round image, using your drawable as background.

How can I throw a general exception in Java?

You could use IllegalArgumentException:

public void speedDown(int decrement)
{
    if(speed - decrement < 0){
        throw new IllegalArgumentException("Final speed can not be less than zero");
    }else{
        speed -= decrement;
    }
}

lexical or preprocessor issue file not found occurs while archiving?

I know this is old, but I'm gonna chime in anyway because it may be useful to someone. If you can still see the file in Finder, then click on the file in your project and delete it, selecting "remove references" and not "move to trash".

Once the reference is removed, drag and drop the file from finder into your project again and it should sort itself out.

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

As you need access to your hostname variable in every component, and to change it to localhost while in development mode, or to production hostname when in production mode, you can define this variable in the prototype.

Like this:

Vue.prototype.$hostname = 'http://localhost:3000'

And $hostname will be available in all Vue instances:

new Vue({
  beforeCreate: function () {
    console.log(this.$hostname)
  }
})

In my case, to automatically change from development to production, I've defined the $hostname prototype according to a Vue production tip variable in the file where I instantiated the Vue.

Like this:

Vue.config.productionTip = false
Vue.prototype.$hostname = (Vue.config.productionTip) ? 'https://hostname' : 'http://localhost:3000'

An example can be found in the docs: Documentation on Adding Instance Properties

More about production tip config can be found here:

Vue documentation for production tip

How to switch text case in visual studio code

Now an uppercase and lowercase switch can be done simultaneously in the selected strings via a regular expression replacement (regex, CtrlH + AltR), according to v1.47.3 June 2020 release:

Replacing different text cases in one selection

This is done through 4 "Single character" character classes (Perl documentation), namely, for the matched group following it:

  • \l <=> [[:lower:]]: first character becomes lowercase
  • \u <=> [[:upper:]]: first character becomes uppercase
  • \L <=> [^[:lower:]]: all characters become lowercase
  • \U <=> [^[:upper:]]: all characters become uppercase

$0 matches all selected groups, while $1 matches the 1st group, $2 the 2nd one, etc.

Hit the Match Case button at the left of the search bar (or AltC) and, borrowing some examples from an old Sublime Text answer, now this is possible:

  1. Capitalize words
  • Find: (\s)([a-z]) (\s matches spaces and new lines, i.e. " venuS" => " VenuS")
  • Replace: $1\u$2
  1. Uncapitalize words
  • Find: (\s)([A-Z])
  • Replace: $1\l$2
  1. Remove a single camel case (e.g. cAmelCAse => camelcAse => camelcase)
  • Find: ([a-z])([A-Z])
  • Replace: $1\l$2
  1. Lowercase all from an uppercase letter within words (e.g. LowerCASe => Lowercase)
  • Find: (\w)([A-Z]+)
  • Replace: $1\L$2
  • Alternate Replace: \L$0
  1. Uppercase all from a lowercase letter within words (e.g. upperCASe => uPPERCASE)
  • Find: (\w)([A-Z]+)
  • Replace: $1\U$2
  1. Uppercase previous (e.g. upperCase => UPPERCase)
  • Find: (\w+)([A-Z])
  • Replace: \U$1$2
  1. Lowercase previous (e.g. LOWERCase => lowerCase)
  • Find: (\w+)([A-Z])
  • Replace: \L$1$2
  1. Uppercase the rest (e.g. upperCase => upperCASE)
  • Find: ([A-Z])(\w+)
  • Replace: $1\U$2
  1. Lowercase the rest (e.g. lOWERCASE => lOwercase)
  • Find: ([A-Z])(\w+)
  • Replace: $1\L$2
  1. Shift-right-uppercase (e.g. Case => cAse => caSe => casE)
  • Find: ([a-z\s])([A-Z])(\w)
  • Replace: $1\l$2\u$3
  1. Shift-left-uppercase (e.g. CasE => CaSe => CAse => Case)
  • Find: (\w)([A-Z])([a-z\s])
  • Replace: \u$1\l$2$3

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

Answers by ‘smartnut007’, ‘Bill Karwin’, and ‘sqlvogel’ are excellent. Yet let me put an interesting perspective to it.

Well, we have prime and non-prime keys.

When we focus on how non-primes depend on primes, we see two cases:

Non-primes can be dependent or not.

  • When dependent: we see they must depend on a full candidate key. This is 2NF.
  • When not dependent: there can be no-dependency or transitive dependency

    • Not even transitive dependency: Not sure what normalization theory addresses this.
    • When transitively dependent: It is deemed undesirable. This is 3NF.

What about dependencies among primes?

Now you see, we’re not addressing the dependency relationship among primes by either 2nd or 3rd NF. Further such dependency, if any, is not desirable and thus we’ve a single rule to address that. This is BCNF.

Referring to the example from Bill Karwin's post here, you’ll notice that both ‘Topping’, and ‘Topping Type’ are prime keys and have a dependency. Had they been non-primes with dependency, then 3NF would have kicked in.

Note:

The definition of BCNF is very generic and without differentiating attributes between prime and non-prime. Yet, the above way of thinking helps to understand how some anomaly is percolated even after 2nd and 3rd NF.

Advanced Topic: Mapping generic BCNF to 2NF & 3NF

Now that we know BCNF provides a generic definition without reference to any prime/non-prime attribues, let's see how BCNF and 2/3 NF's are related.

First, BCNF requires (other than the trivial case) that for each functional dependency X -> Y (FD), X should be super-key. If you just consider any FD, then we've three cases - (1) Both X and Y non-prime, (2) Both prime and (3) X prime and Y non-prime, discarding the (nonsensical) case X non-prime and Y prime.

For case (1), 3NF takes care of.

For case (3), 2NF takes care of.

For case (2), we find the use of BCNF

Send Email to multiple Recipients with MailMessage?

As suggested by Adam Miller in the comments, I'll add another solution.

The MailMessage(String from, String to) constructor accepts a comma separated list of addresses. So if you happen to have already a comma (',') separated list, the usage is as simple as:

MailMessage Msg = new MailMessage(fromMail, addresses);

In this particular case, we can replace the ';' for ',' and still make use of the constructor.

MailMessage Msg = new MailMessage(fromMail, addresses.replace(";", ","));

Whether you prefer this or the accepted answer it's up to you. Arguably the loop makes the intent clearer, but this is shorter and not obscure. But should you already have a comma separated list, I think this is the way to go.

no suitable HttpMessageConverter found for response type

In addition to all the answers, if you happen to receive in response text/html while you've expected something else (i.e. application/json), it may suggest that an error occurred on the server side (say 404) and the error page was returned instead of your data.

So it happened in my case. Hope it will save somebody's time.

tomcat - CATALINA_BASE and CATALINA_HOME variables

Pointing CATALINA_BASE to a different directory from CATALINA_HOME allows you to separate the configuration directory from the binaries directory.

By default, CATALINA_BASE (configurations) and CATALINA_HOME (binaries) point to the same folder, but separating the configurations from the binaries can help you to run multiple instances of Tomcat side by side without duplicating the binaries.

It is also useful when you want to update the binaries, without modifying, or needing to backup/restore your configuration files for Tomcat.

Update 2018

There is an easier way to set CATALINA_BASE now with the makebase utility. I have posted a tutorial that covers this subject at http://blog.rasia.io/blog/how-to-easily-setup-lucee-in-tomcat.html along with a video tutorial at https://youtu.be/nuugoG5c-7M

Original answer continued below

To take advantage of this feature, simply create the config directory and point to it with the CATALINA_BASE environment variable. You will have to put some files in that directory:

  • Copy the conf directory from the original Tomcat installation directory, including its contents, and ensure that Tomcat has read permissions to it. Edit the configuration files according to your needs.
  • Create a logs directory if conf/logging.properties points to ${catalina.base}/logs, and ensure that Tomcat has read/write permissions to it.
  • Create a temp directory if you are not overriding the default of $CATALINA_TMPDIR which points to ${CATALINA_BASE}/temp, and ensure that Tomcat has write permissions to it.
  • Create a work directory which defaults to ${CATALINA_BASE}/work, and ensure that Tomcat has write permissions to it.

Working Soap client example

The response of acdcjunior it was awesome, I just expand his explanation with the next code, where you can see how iterate over the XML elements.

public class SOAPClientSAAJ {

public static void main(String args[]) throws Exception {
    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Send SOAP Message to SOAP Server
    String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
    SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);



    SOAPPart soapPart=soapResponse.getSOAPPart();
    // SOAP Envelope
    SOAPEnvelope envelope=soapPart.getEnvelope();
    SOAPBody soapBody = envelope.getBody();

    @SuppressWarnings("unchecked")
    Iterator<Node> itr=soapBody.getChildElements();
    while (itr.hasNext()) {

        Node node=(Node)itr.next();
        if (node.getNodeType()==Node.ELEMENT_NODE) {
            System.out.println("reading Node.ELEMENT_NODE");
            Element ele=(Element)node;
            System.out.println("Body childs : "+ele.getLocalName());

            switch (ele.getNodeName()) {

          case "VerifyEmailResponse":
             NodeList statusNodeList = ele.getChildNodes();

             for(int i=0;i<statusNodeList.getLength();i++){
               Element emailResult = (Element) statusNodeList.item(i);
               System.out.println("VerifyEmailResponse childs : "+emailResult.getLocalName());
                switch (emailResult.getNodeName()) {

                case "VerifyEmailResult":
                    NodeList emailResultList = emailResult.getChildNodes();

                    for(int j=0;j<emailResultList.getLength();j++){
                      Element emailResponse = (Element) emailResultList.item(j);
                      System.out.println("VerifyEmailResult childs : "+emailResponse.getLocalName());
                       switch (emailResponse.getNodeName()) {
                       case "ResponseText":
                           System.out.println(emailResponse.getTextContent());
                           break;
                        case "ResponseCode":
                          System.out.println(emailResponse.getTextContent());
                           break;
                        case "LastMailServer":
                          System.out.println(emailResponse.getTextContent());
                          break;
                        case "GoodEmail":
                          System.out.println(emailResponse.getTextContent());
                       default:
                          break;
                       }
                    }
                    break;
                default:
                   break;
                }
             }


             break;


          default:
             break;
          }

        } else if (node.getNodeType()==Node.TEXT_NODE) {
            System.out.println("reading Node.TEXT_NODE");
            //do nothing here most likely, as the response nearly never has mixed content type
            //this is just for your reference
        }
    }
    // print SOAP Response
    System.out.println("Response SOAP Message:");
    soapResponse.writeTo(System.out);

    soapConnection.close();
}

private static SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String serverURI = "http://ws.cdyne.com/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", serverURI);

    /*
    Constructed SOAP Request Message:
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
        <SOAP-ENV:Header/>
        <SOAP-ENV:Body>
            <example:VerifyEmail>
                <example:email>[email protected]</example:email>
                <example:LicenseKey>123</example:LicenseKey>
            </example:VerifyEmail>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
     */

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
    soapBodyElem1.addTextNode("[email protected]");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
    soapBodyElem2.addTextNode("123");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.println("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    System.out.println("");
    System.out.println("------");

    return soapMessage;
}

}

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

How to use count and group by at the same select statement

I know this is an old post, in SQL Server:

select  isnull(town,'TOTAL') Town, count(*) cnt
from    user
group by town WITH ROLLUP

Town         cnt
Copenhagen   58
NewYork      58
Athens       58
TOTAL        174

How to create empty text file from a batch file?

type NUL > EmptyFile.txt

After reading the previous two posts, this blend of the two is what I came up with. It seems a little cleaner. There is no need to worry about redirecting the "1 file(s) copied." message to NUL, like the previous post does, and it looks nice next to the ECHO OutputLineFromLoop >> Emptyfile.txt that will usually follow in a batch file.

What's the difference between process.cwd() vs __dirname?

Knowing the scope of each can make things easier to remember.

process is node's global object, and .cwd() returns where node is running.

__dirname is module's property, and represents the file path of the module. In node, one module resides in one file.

Similarly, __filename is another module's property, which holds the file name of the module.

Return JSON with error status code MVC

And if your needs aren't as complex as Sarath's you can get away with something even simpler:

[MyError]
public JsonResult Error(string objectToUpdate)
{
   throw new Exception("ERROR!");
}

public class MyErrorAttribute : FilterAttribute, IExceptionFilter
{
   public virtual void OnException(ExceptionContext filterContext)
   {
      if (filterContext == null)
      {
         throw new ArgumentNullException("filterContext");
      }
      if (filterContext.Exception != null)
      {
         filterContext.ExceptionHandled = true;
         filterContext.HttpContext.Response.Clear();
         filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
         filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
         filterContext.Result = new JsonResult() { Data = filterContext.Exception.Message };
      }
   }
}

SELECT * FROM X WHERE id IN (...) with Dapper ORM

Also make sure you do not wrap parentheses around your query string like so:

SELECT Name from [USER] WHERE [UserId] in (@ids)

I had this cause a SQL Syntax error using Dapper 1.50.2, fixed by removing parentheses

SELECT Name from [USER] WHERE [UserId] in @ids

Good examples of python-memcache (memcached) being used in Python?

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

Yes. Run ssh-add on the client machine. Then repeat command ssh-copy-id [email protected]

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

Convert DateTime to String PHP

echo date_format($date,"Y/m/d H:i:s");

Using the passwd command from within a shell script

I stumbled upon the same problem and for some reason the --stdin option was not available on the version of passwd I was using (shipped in Ubuntu 14.04).

If any of you happen to experience the same issue, you can work it around as I did, by using the chpasswd command like this:

echo "<user>:<password>" | chpasswd

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

When setting the curl options for CURLOPT_CAINFO please remember to use single quotes, using double quotes will only cause another error. So your option should look like:

curl_setopt ($ch, CURLOPT_CAINFO, 'c:\wamp\www\mywebfolder\cacert.pem');

Additionally, in your php.ini file setting should be written as:(notice my double quotes)

curl.cainfo = "C:\wamp\www\mywebfolder"

I put it directly below the line that says this: extension=php_curl.dll

(For organizing purposes only, you could put it anywhere within your php.ini, i just put it close to another curl reference so when I search using keyword curl I caan find both curl references in one area.)

Validation of radio button group using jQuery validation plugin

You can also use this:

<fieldset>
<input type="radio" name="myoptions[]" value="blue"> Blue<br />
<input type="radio" name="myoptions[]" value="red"> Red<br />
<input type="radio" name="myoptions[]" value="green"> Green<br />
<label for="myoptions[]" class="error" style="display:none;">Please choose one.</label>
</fieldset>

and simply add this rule

rules: {
 'myoptions[]':{ required:true }
}

Mention how to add rules.

How to convert file to base64 in JavaScript?

Try the solution using the FileReader class:

function getBase64(file) {
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}

var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file); // prints the base64 string

Notice that .files[0] is a File type, which is a sublcass of Blob. Thus it can be used with FileReader.
See the complete working example.

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

1) Tried creating a new branch and pushing. Worked for a couple of times but faced the same error again.

2)Just ran these two statements before pushing the code. All I did was to cancel the proxy.

$ git config --global --unset http.proxy
$ git config --global --unset https.proxy

3) Faced the issue again after couple of weeks. I have updated homebrew and it got fixed

How to check String in response body with mockMvc

Spring security's @WithMockUser and hamcrest's containsString matcher makes for a simple and elegant solution:

@Test
@WithMockUser(roles = "USER")
public void loginWithRoleUserThenExpectUserSpecificContent() throws Exception {
    mockMvc.perform(get("/index"))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("This content is only shown to users.")));
}

More examples on github

Count items in a folder with PowerShell

If you need to speed up the process (for example counting 30k or more files) then I would go with something like this..

$filepath = "c:\MyFolder"
$filetype = "*.txt"
$file_count = [System.IO.Directory]::GetFiles("$filepath", "$filetype").Count

What does "zend_mm_heap corrupted" mean

I was getting this same error under PHP 5.5 and increasing the output buffering didn't help. I wasn't running APC either so that wasn't the issue. I finally tracked it down to opcache, I simply had to disable it from the cli. There was a specific setting for this:

opcache.enable_cli=0

Once switched the zend_mm_heap corrupted error went away.

Route.get() requires callback functions but got a "object Undefined"

I had the same error. The problem was in the export and import of the modules.

Example of my solution:

Controller (File: posts.js)

exports.getPosts = (req, res) => {
    res.json({
        posts: [
            { tittle: 'First posts' },
            { tittle: 'Second posts' },
        ]
    });
};

Router (File: posts.js)

const express = require('express');
const { getPosts } = require('../controllers/posts');

const routerPosts = express.Router();
routerPosts.get('/', getPosts);

exports.routerPosts = routerPosts;

Main (File: app.js)

const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
const { routerPosts } = require('./routes/posts');

const app = express();
const port = process.env.PORT || 3000;

dotenv.config();

// Middleware
app.use(morgan('dev'));

app.use('/', routerPosts);

app.listen(port, () => {
    console.log(`A NodeJS API is listining on port: ${port}`);
});

Running the application (chrome output)

// 20200409002022
// http://localhost:3000/

{
  "posts": [
    {
      "tittle": "First posts"
    },
    {
      "tittle": "Second posts"
    }
  ]
}

Console Log

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ npm run dev

> [email protected] dev /home/jmendoza/IdeaProjects/NodeJS-API-Course/Basic-Node-API
> nodemon app.js

[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
GET / 304 5.093 ms - -
GET / 304 0.714 ms - -
GET / 304 0.653 ms - -
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
GET / 200 4.427 ms - 62
GET / 304 0.783 ms - -
GET / 304 0.642 ms - -

Node Version

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Node-API$ node -v
v13.12.0

NPM Version

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Node-API$ npm -v
6.14.4

How to convert java.lang.Object to ArrayList?

Rather Cast It to an Object Array.

Object obj2 = from some source . . ;
Object[] objects=(Object[])obj2;

Why is using "for...in" for array iteration a bad idea?

There are three reasons why you shouldn't use for..in to iterate over array elements:

  • for..in will loop over all own and inherited properties of the array object which aren't DontEnum; that means if someone adds properties to the specific array object (there are valid reasons for this - I've done so myself) or changed Array.prototype (which is considered bad practice in code which is supposed to work well with other scripts), these properties will be iterated over as well; inherited properties can be excluded by checking hasOwnProperty(), but that won't help you with properties set in the array object itself

  • for..in isn't guaranteed to preserve element ordering

  • it's slow because you have to walk all properties of the array object and its whole prototype chain and will still only get the property's name, ie to get the value, an additional lookup will be required

Mongoose and multiple database in single node.js project

A bit optimized(for me atleast) solution. write this to a file db.js and require this to wherever required and call it with a function call and you are good to go.

   const MongoClient = require('mongodb').MongoClient;
    async function getConnections(url,db){
        return new Promise((resolve,reject)=>{
            MongoClient.connect(url, { useUnifiedTopology: true },function(err, client) {
                if(err) { console.error(err) 
                    resolve(false);
                }
                else{
                    resolve(client.db(db));
                }
            })
        });
    }

    module.exports = async function(){
        let dbs      = [];
        dbs['db1']     = await getConnections('mongodb://localhost:27017/','db1');
        dbs['db2']     = await getConnections('mongodb://localhost:27017/','db2');
        return dbs;
    };

Python foreach equivalent

The foreach construct is unfortunately not intrinsic to collections but instead external to them. The result is two-fold:

  • it can not be chained
  • it requires two lines in idiomatic python.

Python does not support a true foreach on collections directly. An example would be

myList.foreach( a => print(a)).map( lambda x:  x*2)

But python does not support it. Partial fixes to this and other missing functionals features in python are provided by various third party libraries including one that I helped author: see https://pypi.org/project/infixpy/

High CPU Utilization in java application - why?

Flame graphs can be helpful in identifying the execution paths that are consuming the most CPU time.

In short, the following are the steps to generate flame graphs

yum -y install perf

wget https://github.com/jvm-profiling-tools/async-profiler/releases/download/v1.8.3/async-profiler-1.8.3-linux-x64.tar.gz

tar -xvf async-profiler-1.8.3-linux-x64.tar.gz
chmod -R 777 async-profiler-1.8.3-linux-x64
cd async-profiler-1.8.3-linux-x64

echo 1 > /proc/sys/kernel/perf_event_paranoid
echo 0 > /proc/sys/kernel/kptr_restrict

JAVA_PID=`pgrep java`

./profiler.sh -d 30 $JAVA_PID -f flame-graph.svg

flame-graph.svg can be opened using browsers as well, and in short, the width of the element in stack trace specifies the number of thread dumps that contain the execution flow relatively.

There are few other approaches to generating them

  • By introducing -XX:+PreserveFramePointer as the JVM options as described here
  • Using async-profiler with -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints as described here

But using async-profiler without providing any options though not very accurate, can be leveraged with no changes to the running Java process with low CPU overhead to the process.

Their wiki provides details on how to leverage it. And more about flame graphs can be found here

Adding calculated column(s) to a dataframe in pandas

The exact code will vary for each of the columns you want to do, but it's likely you'll want to use the map and apply functions. In some cases you can just compute using the existing columns directly, since the columns are Pandas Series objects, which also work as Numpy arrays, which automatically work element-wise for usual mathematical operations.

>>> d
    A   B  C
0  11  13  5
1   6   7  4
2   8   3  6
3   4   8  7
4   0   1  7
>>> (d.A + d.B) / d.C
0    4.800000
1    3.250000
2    1.833333
3    1.714286
4    0.142857
>>> d.A > d.C
0     True
1     True
2     True
3    False
4    False

If you need to use operations like max and min within a row, you can use apply with axis=1 to apply any function you like to each row. Here's an example that computes min(A, B)-C, which seems to be like your "lower wick":

>>> d.apply(lambda row: min([row['A'], row['B']])-row['C'], axis=1)
0    6
1    2
2   -3
3   -3
4   -7

Hopefully that gives you some idea of how to proceed.

Edit: to compare rows against neighboring rows, the simplest approach is to slice the columns you want to compare, leaving off the beginning/end, and then compare the resulting slices. For instance, this will tell you for which rows the element in column A is less than the next row's element in column C:

d['A'][:-1] < d['C'][1:]

and this does it the other way, telling you which rows have A less than the preceding row's C:

d['A'][1:] < d['C'][:-1]

Doing ['A"][:-1] slices off the last element of column A, and doing ['C'][1:] slices off the first element of column C, so when you line these two up and compare them, you're comparing each element in A with the C from the following row.

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Ruby can't find any root certificates to trust.

Take a look at this blog post for a solution: "Ruby 1.9 and the SSL error".

The solution is to install the curl-ca-bundle port which contains the same root certificates used by Firefox:

sudo port install curl-ca-bundle

and tell your https object to use it:

https.ca_file = '/opt/local/share/curl/curl-ca-bundle.crt'

Note that if you want your code to run on Ubuntu, you need to set the ca_path attribute instead, with the default certificates location /etc/ssl/certs.

Git, fatal: The remote end hung up unexpectedly

PLESK Nginx and GIT I was getting this error on plesk git and while pushing a large repo with (who knows what) it gave me this error with HTTP code 413 and i looked into following Server was Plesk and it had nginx running as well as apache2 so i looked into logs and found the error in nginx logs

Followed this link to allow plesk to rebuild configuration with larger file upload.

I skipped the php part for git

After that git push worked without any errors.

How do I authenticate a WebClient request?

Public Function getWeb(ByRef sURL As String) As String
    Dim myWebClient As New System.Net.WebClient()

    Try
        Dim myCredentialCache As New System.Net.CredentialCache()
        Dim myURI As New Uri(sURL)
        myCredentialCache.Add(myURI, "ntlm", System.Net.CredentialCache.DefaultNetworkCredentials)
        myWebClient.Encoding = System.Text.Encoding.UTF8
        myWebClient.Credentials = myCredentialCache
        Return myWebClient.DownloadString(myURI)
    Catch ex As Exception
        Return "Exception " & ex.ToString()
    End Try
End Function

fitting data with numpy

Unfortunately, np.polynomial.polynomial.polyfit returns the coefficients in the opposite order of that for np.polyfit and np.polyval (or, as you used np.poly1d). To illustrate:

In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]: 
array([  84.29340848, -100.53595376,   44.83281408,   -8.85931101,
          0.65459882])

In [41]: np.polyfit(x, y, 4)
Out[41]: 
array([   0.65459882,   -8.859311  ,   44.83281407, -100.53595375,
         84.29340846])

In general: np.polynomial.polynomial.polyfit returns coefficients [A, B, C] to A + Bx + Cx^2 + ..., while np.polyfit returns: ... + Ax^2 + Bx + C.

So if you want to use this combination of functions, you must reverse the order of coefficients, as in:

ffit = np.polyval(coefs[::-1], x_new)

However, the documentation states clearly to avoid np.polyfit, np.polyval, and np.poly1d, and instead to use only the new(er) package.

You're safest to use only the polynomial package:

import numpy.polynomial.polynomial as poly

coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)

Or, to create the polynomial function:

ffit = poly.Polynomial(coefs)    # instead of np.poly1d
plt.plot(x_new, ffit(x_new))

fit and data plot

Find non-ASCII characters in varchar columns using SQL Server

This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:

declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
    begin
    set @str = @str + '|' + char(@i)
    set @i = @i + 1
    end

select  col1
from    YourTable
where   col1 like '%[^' + @str + ']%' escape '|'

Windows batch script launch program and exit console

start "" ExeToExecute

method does not work for me in the case of Xilinx xsdk, because as pointed out by @jeb in the comments below it is actaully a bat file.

so what does not work de-facto is

start "" BatToExecute

I am trying to open xsdk like that and it opens a separate cmd that needs to be closed and xsdk can run on its own

Before launching xsdk I run (source) the Env / Paths (with settings64.bat) so that xsdk.bat command gets recognized (simply as xsdk, withoitu the .bat)

what works with .bat

call BatToExecute

Is 'bool' a basic datatype in C++?

bool is a fundamental datatype in C++. Converting true to an integer type will yield 1, and converting false will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like

enum bool {
    false, true
};

So did the Windows API. Starting with C99, we have _Bool as a basic data type. Including stdbool.h will typedef #define that to bool and provide the constants true and false. They didn't make bool a basic data-type (and thus a keyword) because of compatibility issues with existing code.

How do I increase the RAM and set up host-only networking in Vagrant?

I could not get any of these answers to work. Here's what I ended up putting at the very top of my Vagrantfile, before the Vagrant::Config.run do block:

Vagrant.configure("2") do |config|
  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end
end

I noticed that the shortcut accessor style, "vb.memory = 1024", didn't seem to work.

How do I remove a substring from the end of a string in Python?

Because this is a very popular question i add another, now available, solution. With python 3.9 (https://docs.python.org/3.9/whatsnew/3.9.html) the function removesuffix() will be added (and removeprefix()) and this function is exactly what was questioned here.

url = 'abcdc.com'
print(url.removesuffix('.com'))

output:

'abcdc'

PEP 616 (https://www.python.org/dev/peps/pep-0616/) shows how it will behave (it is not the real implementation):

def removeprefix(self: str, prefix: str, /) -> str:
    if self.startswith(prefix):
        return self[len(prefix):]
    else:
        return self[:]

and what benefits it has against self-implemented solutions:

  1. Less fragile: The code will not depend on the user to count the length of a literal.

  2. More performant: The code does not require a call to the Python built-in len function nor to the more expensive str.replace() method.

  3. More descriptive: The methods give a higher-level API for code readability as opposed to the traditional method of string slicing.

Using an authorization header with Fetch in React Native

It turns out, I was using the fetch method incorrectly.

fetch expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.

I was wrapping the intended object within a second object, which did not get me any desired result.

Here's how it looks on a high level:

fetch('API_ENDPOINT', OBJECT)  
  .then(function(res) {
    return res.json();
   })
  .then(function(resJson) {
    return resJson;
   })

I structured my object as such:

var obj = {  
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Origin': '',
    'Host': 'api.producthunt.com'
  },
  body: JSON.stringify({
    'client_id': '(API KEY)',
    'client_secret': '(API SECRET)',
    'grant_type': 'client_credentials'
  })

How do I include negative decimal numbers in this regular expression?

This will allow a - or + character only when followed by a number:

 ^([+-](?=\.?\d))?(\d+)?(\.\d+)?$

SQL Server copy all rows from one table into another i.e duplicate table

Don't have sql server around to test but I think it's just:

insert into newtable select * from oldtable;

How to select lines between two marker patterns which may occur multiple times with awk/sed

From the previous response's links, the one that did it for me, running ksh on Solaris, was this:

sed '1,/firstmatch/d;/secondmatch/,$d'
  • 1,/firstmatch/d: from line 1 until the first time you find firstmatch, delete.
  • /secondmatch/,$d: from the first occurrance of secondmatch until the end of file, delete.
  • Semicolon separates the two commands, which are executed in sequence.

How can I get a resource content from a static context?

Another solution:

If you have a static subclass in a non-static outer class, you can access the resources from within the subclass via static variables in the outer class, which you initialise on creation of the outer class. Like

public class Outerclass {

    static String resource1

    public onCreate() {
        resource1 = getString(R.string.text);
    }

    public static class Innerclass {

        public StringGetter (int num) {
            return resource1; 
        }
    }
}

I used it for the getPageTitle(int position) Function of the static FragmentPagerAdapter within my FragmentActivity which is useful because of I8N.

Copy or rsync command

It's not really a question of what's more efficient.

The commands 'rsync', and 'cp' are not equivalent and achieve different goals.

1- rsync can preserve the time of creation of existing files. (using -a option)
2- rsync will run multiprocess and transfer using either local sockets or network sockets. (i.e. fork itself into multiple processes)
3- The multiprocessing, and threading will increase your throughput when copying large number of small files, and even with multiple larger files.

So bottom line is rsync is for large data, and cp is for smaller local copying. (MB to small GB range). When you start getting into multiple GB or in the TB range, go with rsync. And of course network copies, rsync all the way.

How to pass arguments and redirect stdin from a file to program run in gdb?

Pass the arguments to the run command from within gdb.

$ gdb ./a.out
(gdb) r < t
Starting program: /dir/a.out < t

How to set Java classpath in Linux?

Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.

Continue For loop

You're thinking of a continue statement like Java's or Python's, but VBA has no such native statement, and you can't use VBA's Next like that.

You could achieve something like what you're trying to do using a GoTo statement instead, but really, GoTo should be reserved for cases where the alternatives are contrived and impractical.

In your case with a single "continue" condition, there's a really simple, clean, and readable alternative:

    If Not InStr(sname, "Configuration item") Then
        '// other code to copy paste and do various stuff
    End If

Use JSTL forEach loop's varStatus as an ID

You can try this. similar result

 <c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
    <div id="divIDNo${theCount.count}"></div>
 </c:forEach>

Using Jquery AJAX function with datatype HTML

Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.

Ajax call:

$.ajax({
  type : 'POST',
  url : 'post.php',
  dataType : 'html',
  data: {
      email : $('#email').val()
  },
  success : function(data){
      $('#waiting').hide(500);
      $('#message').removeClass().addClass((data == '') ? 'error' : 'success')
     .html(data).show(500);
      if (data == '') {
          $('#message').html("Format your email correcly");
          $('#demoForm').show(500);
      }
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
      $('#waiting').hide(500);
      $('#message').removeClass().addClass('error')
      .text('There was an error.').show(500);
      $('#demoForm').show(500);
  }

});

post.php

<?php
sleep(1);

function processEmail($email) {
    if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
        // your logic here (ex: add into database)
        return true;
    }
    return false;
}

if (processEmail($_POST['email'])) {
    echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}

How do I add a custom script to my package.json file that runs a javascript file?

Custom Scripts

npm run-script <custom_script_name>

or

npm run <custom_script_name>

In your example, you would want to run npm run-script script1 or npm run script1.

See https://docs.npmjs.com/cli/run-script

Lifecycle Scripts

Node also allows you to run custom scripts for certain lifecycle events, like after npm install is run. These can be found here.

For example:

"scripts": {
    "postinstall": "electron-rebuild",
},

This would run electron-rebuild after a npm install command.

How to refresh Gridview after pressed a button in asp.net

All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :

protected void bLoanButton_Click(object sender, EventArgs e)
{

//your same code
........

GridView1.DataBind();


}

regards

How to start an application without waiting in a batch file?

If your exe takes arguments,

start MyApp.exe -arg1 -arg2

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

This is based on KoZm0kNoT's answer. I modified it to work across drives.

@echo off
pushd "%~d0"
pushd "%~dp0"
powershell.exe -sta -c "& {.\%~n0.ps1 %*}"
popd
popd

The two pushd/popds are necessary in case the user's cwd is on a different drive. Without the outer set, the cwd on the drive with the script will get lost.

Sort JavaScript object by key

The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6 / ES2015 spec has been published.


See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:

All methods that iterate over property keys do so in the same order:

  1. First all Array indices, sorted numerically.
  2. Then all string keys (that are not indices), in the order in which they were created.
  3. Then all symbols, in the order in which they were created.

So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.

Here’s how you can sort an object by its keys/properties, alphabetically:

_x000D_
_x000D_
const unordered = {
  'b': 'foo',
  'c': 'bar',
  'a': 'baz'
};

console.log(JSON.stringify(unordered));
// ? '{"b":"foo","c":"bar","a":"baz"}'

const ordered = Object.keys(unordered).sort().reduce(
  (obj, key) => { 
    obj[key] = unordered[key]; 
    return obj;
  }, 
  {}
);

console.log(JSON.stringify(ordered));
// ? '{"a":"baz","b":"foo","c":"bar"}'
_x000D_
_x000D_
_x000D_

Use var instead of const for compatibility with ES5 engines.

How to Change Margin of TextView

TextView does not support setMargins. Android docs say:

Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information.

Where should I put <script> tags in HTML markup?

You can place most of <script> references at the end of <body>,
But If there are active components on your page which are using external scripts,
then their dependency (js files) should come before that (ideally in head tag).

How to strip HTML tags from a string in SQL Server?

Patrick Honorez code needs a slight change.

It returns incomplete results for html that contains &lt; or &gt;

This is because the code below the section

-- Remove anything between tags

will in fact replace the < > to nothing. The fix is to the apply the below two lines at the end:

set @HTMLText = replace(@htmlText, '&lt;' collate Latin1_General_CS_AS, '<'  collate Latin1_General_CS_AS)
set @HTMLText = replace(@htmlText, '&gt;' collate Latin1_General_CS_AS, '>'  collate Latin1_General_CS_AS)

Preserve line breaks in angularjs

Just use the css style "white-space: pre-wrap" and you should be good to go. I've had the same issue where I need to handle error messages for which the line breaks and white spaces are really particular. I just added this inline where I was binding the data and it works like Charm!

How to get everything after last slash in a URL?

url ='http://www.test.com/page/TEST2'.split('/')[4]
print url

Output: TEST2.

Find all table names with column name?

You could do this:

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;

Reference:

Getting Image from API in Angular 4/5+?

There is no need to use angular http, you can get with js native functions

_x000D_
_x000D_
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
     // on the first then you will return blob from response_x000D_
    return await fetch(url).then(r => r.blob())_x000D_
    .then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
         _x000D_
        return new File([blob], fileName+'.'+   blob.type.split('/')[1]) ;_x000D_
    });_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
    // with file reader you will transform the file in a data url file;_x000D_
    var reader = new FileReader();_x000D_
    reader.readAsDataURL(file);_x000D_
    reader.onloadend = () => {_x000D_
    _x000D_
    // just putting the data url to img element_x000D_
        document.querySelector('#image').src = reader.result ;_x000D_
    }_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
_x000D_
_x000D_

How to capture a backspace on the onkeydown event

In your function check for the keycode 8 (backspace) or 46 (delete)

Keycode information
Keycode list

Select row with most recent date per user

Already solved, but just for the record, another approach would be to create two views...

CREATE TABLE lms_attendance
(id int, user int, time int, io varchar(3));

CREATE VIEW latest_all AS
SELECT la.user, max(la.time) time
FROM lms_attendance la 
GROUP BY la.user;

CREATE VIEW latest_io AS
SELECT la.* 
FROM lms_attendance la
JOIN latest_all lall 
    ON lall.user = la.user
    AND lall.time = la.time;

INSERT INTO lms_attendance 
VALUES
(1, 9, 1370931202, 'out'),
(2, 9, 1370931664, 'out'),
(3, 6, 1370932128, 'out'),
(4, 12, 1370932128, 'out'),
(5, 12, 1370933037, 'in');

SELECT * FROM latest_io;

Click here to see it in action at SQL Fiddle

slf4j: how to log formatted message, object array, exception

As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.

So, writing (in SLF4J version 1.7.x and later)

 logger.error("one two three: {} {} {}", "a", "b", 
              "c", new Exception("something went wrong"));

or writing (in SLF4J version 1.6.x)

 logger.error("one two three: {} {} {}", new Object[] {"a", "b", 
              "c", new Exception("something went wrong")});

will yield

one two three: a b c
java.lang.Exception: something went wrong
    at Example.main(Example.java:13)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at ...

The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.

sudo: npm: command not found

WARNING (edit)

Doing a chmod 777 is a fairly radical solution. Try these first, one at a time, and stop when one works:

  • $ sudo chmod -R 777 /usr/local/lib/node_modules/npm
  • $ sudo chmod -R 777 /usr/local/lib/node_modules
  • $ sudo chmod g+w /usr/local/lib
  • $ sudo chmod g+rwx /usr/local/lib

$ brew postinstall node is the only install part where I would get a problem

Permission denied - /usr/local/lib/node_modules/npm/.github

So I

// !! READ EDIT ABOVE BEFORE RUNNING THIS CODE !!
$ sudo chmod -R 777 /usr/local/lib
$ brew postinstall node

and viola, npm is now linked

$ npm -v
3.10.10

Extra

If you used -R 777 on lib my recommendation would be to set nested files and directories to a default setting:

  • $ find /usr/local/lib -type f -print -exec chmod 644 {} \;
  • $ find /usr/local/lib -type d -print -exec chmod 755 {} \;
  • $ chmod /usr/local/lib 755

How to convert Set to Array?

via https://speakerdeck.com/anguscroll/es6-uncensored by Angus Croll

It turns out, we can use spread operator:

var myArr = [...mySet];

Or, alternatively, use Array.from:

var myArr = Array.from(mySet);

$(form).ajaxSubmit is not a function

Try:

$(document).ready(function() {
    $('#contact-form').validate({submitHandler: function(form) {
         var data = $('#contact-form').serialize();   
         $.post(
              'url_request',
               {data: data},
               function(response){
                  console.log(response);
               }
          );
         }
    });
});

ssl_error_rx_record_too_long and Apache SSL

In my case the problem was that https was unable to start correctly because Listen 443 was in "IfDefine SSL" derective, but my apache didnt start with -DSSL option. The fix was to change my apachectl script in:

$HTTPD -k $ARGV

to:

$HTTPD -k $ARGV -DSSL

Hope that helps somebody.

How to create and write to a txt file using VBA

Dim SaveVar As Object

Sub Main()

    Console.WriteLine("Enter Text")

    Console.WriteLine("")

    SaveVar = Console.ReadLine

    My.Computer.FileSystem.WriteAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt", "Text: " & SaveVar & ", ", True)

    Console.WriteLine("")

    Console.WriteLine("File Saved")

    Console.WriteLine("")

    Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt"))
    Console.ReadLine()

End Sub()

Stopping Excel Macro executution when pressing Esc won't work

Just Keep pressing ESC key. It will stop the VBA. This methods works when you get infinite MsgBox s

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

Add the following dependency in your pom.xml file and if you are using IntelliJ then add the same jars to WEB-INF->lib folder.... path is Project Structure -> Atrifacts -> Select jar from Available Elements pane and double click. It will add to respective folder

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>3.0.1.RELEASE</version>
</dependency>

How to sort with lambda in Python

Use

a = sorted(a, key=lambda x: x.modified, reverse=True)
#             ^^^^

On Python 2.x, the sorted function takes its arguments in this order:

sorted(iterable, cmp=None, key=None, reverse=False)

so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.

Print Pdf in C#

Looks like the usual suspects like pdfsharp and migradoc are not able to do that (pdfsharp only if you have Acrobat (Reader) installed).

I found here

https://vishalsbsinha.wordpress.com/2014/05/06/how-to-programmatically-c-net-print-a-pdf-file-directly-to-the-printer/

code ready for copy/paste. It uses the default printer and from what I can see it doesn't even use any libraries, directly sending the pdf bytes to the printer. So I assume the printer also needs to support it, on one 10 year old printer I tested this it worked flawlessly.

Most other approaches - without commercial libraries or applications - require you to draw yourself in the printing device context. Doable but will take a while to figure it out and make it work across printers.

Align button to the right

try to put your script and link on the head like this:

<html>
  <head>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"> 
     </script>
  </head>
  <body>
     <div class="row">
        <h3 class="one">Text</h3>
        <button class="btn btn-secondary pull-right">Button</button>
     </div>
  </body>
</html>

How to add line break for UILabel?

For those of you who want an easy solution, do the following in the text Label input box in Interface Builder:

Make sure your number of lines is set to 0.

Alt + Enter

(Alt is your option key)

Cheers!

Multi-dimensional arrays in Bash

Independent of the shell being used (sh, ksh, bash, ...) the following approach works pretty well for n-dimensional arrays (the sample covers a 2-dimensional array).

In the sample the line-separator (1st dimension) is the space character. For introducing a field separator (2nd dimension) the standard unix tool tr is used. Additional separators for additional dimensions can be used in the same way.

Of course the performance of this approach is not very well, but if performance is not a criteria this approach is quite generic and can solve many problems:

array2d="1.1:1.2:1.3 2.1:2.2 3.1:3.2:3.3:3.4"

function process2ndDimension {
    for dimension2 in $*
    do
        echo -n $dimension2 "   "
    done
    echo
}

function process1stDimension {
    for dimension1 in $array2d
    do
        process2ndDimension `echo $dimension1 | tr : " "`
    done
}

process1stDimension

The output of that sample looks like this:

1.1     1.2     1.3     
2.1     2.2     
3.1     3.2     3.3     3.4 

How do I get a list of all the duplicate items using pandas in python?

With Pandas version 0.17, you can set 'keep = False' in the duplicated function to get all the duplicate items.

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(['a','b','c','d','a','b'])

In [3]: df
Out[3]: 
       0
    0  a
    1  b
    2  c
    3  d
    4  a
    5  b

In [4]: df[df.duplicated(keep=False)]
Out[4]: 
       0
    0  a
    1  b
    4  a
    5  b

Swift: print() vs println() vs NSLog()

There's another method called dump() which can also be used for logging:

func dump<T>(T, name: String?, indent: Int, maxDepth: Int, maxItems: Int)

Dumps an object’s contents using its mirror to standard output.

From Swift Standard Library Functions

Prevent form submission on Enter key press

A much simpler and effective way from my perspective should be :

function onPress_ENTER()
{
        var keyPressed = event.keyCode || event.which;

        //if ENTER is pressed
        if(keyPressed==13)
        {
            alert('enter pressed');
            keyPressed=null;
        }
        else
        {
            return false;
        }
}

Add borders to cells in POI generated Excel File

To create a border in Apache POI you should...

1: Create a style

final XSSFCellStyle style = workbook.createCellStyle();

2: Then you have to create the border

style.setBorderBottom( new XSSFColor(new Color(235,235,235));

?3: Then you have to set the color of that border

style.setBottomBorderColor( new XSSFColor(new Color(235,235,235));

4: Then apply the style to a cell

cell.setCellStyle(style);

How to initialize java.util.date to empty

IMO, you cannot create an empty Date(java.util). You can create a Date object with null value and can put a null check.

 Date date = new Date(); // Today's date and current time
 Date date2 = new Date(0); // Default date and time
 Date date3 = null; //Date object with null as value.
 if(null != date3) {
    // do your work.
 }

Mapping object to dictionary and vice versa

Convert the Dictionary to JSON string first with Newtonsoft.

var json = JsonConvert.SerializeObject(advancedSettingsDictionary, Newtonsoft.Json.Formatting.Indented);

Then deserialize the JSON string to your object

var myobject = JsonConvert.DeserializeObject<AOCAdvancedSettings>(json);

Java 8 List<V> into Map<K, V>

You can create a Stream of the indices using an IntStream and then convert them to a Map :

Map<Integer,Item> map = 
IntStream.range(0,items.size())
         .boxed()
         .collect(Collectors.toMap (i -> i, i -> items.get(i)));

How do you turn a Mongoose document into a plain object?

In some cases as @JohnnyHK suggested, you would want to get the Object as a Plain Javascript. as described in this Mongoose Documentation there is another alternative to query the data directly as object:

const docs = await Model.find().lean();

In addition if someone might want to conditionally turn to an object,it is also possible as an option argument, see find() docs at the third parameter:

const toObject = true;
const docs = await Model.find({},null,{lean:toObject});

its available on the fonctions: find(), findOne(), findById(), findOneAndUpdate(), and findByIdAndUpdate().

Change NULL values in Datetime format to empty string

Select isnull(date_column_name,cast('1900-01-01' as DATE)) from table name

Javascript how to split newline

you don't need to pass any regular expression there. this works just fine..

 (function($) {
      $(document).ready(function() {
        $('#data').click(function(e) {
          e.preventDefault();
          $.each($("#keywords").val().split("\n"), function(e, element) {
            alert(element);
          });
        });
      });
    })(jQuery);

Detect if user is scrolling

this works:

window.onscroll = function (e) {  
// called when the window is scrolled.  
} 

edit:

you said this is a function in a TimeInterval..
Try doing it like so:

userHasScrolled = false;
window.onscroll = function (e)
{
    userHasScrolled = true;
}

then inside your Interval insert this:

if(userHasScrolled)
{
//do your code here
userHasScrolled = false;
}

Is Java a Compiled or an Interpreted programming language ?

The terms "interpreted language" or "compiled language" don't make sense, because any programming language can be interpreted and/or compiled.

As for the existing implementations of Java, most involve a compilation step to bytecode, so they involve compilation. The runtime also can load bytecode dynamically, so some form of a bytecode interpreter is always needed. That interpreter may or may not in turn use compilation to native code internally.

These days partial just-in-time compilation is used for many languages which were once considered "interpreted", for example JavaScript.

one line if statement in php

Something like this?

($var > 2 ? echo "greater" : echo "smaller")

How to convert integer into date object python?

Here is what I believe answers the question (Python 3, with type hints):

from datetime import date


def int2date(argdate: int) -> date:
    """
    If you have date as an integer, use this method to obtain a datetime.date object.

    Parameters
    ----------
    argdate : int
      Date as a regular integer value (example: 20160618)

    Returns
    -------
    dateandtime.date
      A date object which corresponds to the given value `argdate`.
    """
    year = int(argdate / 10000)
    month = int((argdate % 10000) / 100)
    day = int(argdate % 100)

    return date(year, month, day)


print(int2date(20160618))

The code above produces the expected 2016-06-18.

How to find all trigger associated with a table with SQL Server?

you can open your trigger with sp_helptext yourtriggername

How to execute a Windows command on a remote PC?

You can use native win command:

WMIC /node:ComputerName process call create “cmd.exe /c start.exe”

The WMIC is part of wbem win folder: C:\Windows\System32\wbem

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

This question has MANY answers, and I think mine would suit another question better, but the answers to that question are locked. It points to this thread.

What solved it for me was appending &createDatabaseIfNotExist=true to the spring.datasource.url string in application.properties.

This was very tricky because it manifested itself in a couple of different, weird, seemingly unrelated errors, and when I tried to fix what it complained about it simply would pop another error up, or the error was impossible to fix. It complained about not being able to load JDBC, saying it wasn't in the classpath, but I added it to the classpath in some 30 different ways and was already facedesking.

How to delete specific rows and columns from a matrix in a smarter way?

> S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
[,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    1    2    3    4
[3,]    3    2    1    2    3
[4,]    4    3    2    1    2
[5,]    5    4    3    2    1
> S<-S[,-2]
> S
[,1] [,2] [,3] [,4]
[1,]    1    3    4    5
[2,]    2    2    3    4
[3,]    3    1    2    3
[4,]    4    2    1    2
[5,]    5    3    2    1

Just use the command S <- S[,-2] to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,].

Font awesome is not showing icon

It's something to do with v5, some of the icons don't work with older versions.

This link worked for me!

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">

Fill remaining vertical space - only CSS

If you can add an extra couple of divs so your html looks like this:

<div id="wrapper">
    <div id="first" class="row">
        <div class="cell"></div>
    </div>
    <div id="second" class="row">
        <div class="cell"></div>
    </div>
</div>

You can make use of the display:table properties:

#wrapper
{
   width:300px;
   height:100%;
   display:table;
}

.row 
{
   display:table-row;
}

.cell 
{
   display:table-cell;
}

#first .cell
{
   height:200px;
   background-color:#F5DEB3;
}

#second .cell
{
   background-color:#9ACD32;
}

Example

Fast way to concatenate strings in nodeJS/JavaScript

You asked about performance. See this perf test comparing 'concat', '+' and 'join' - in short the + operator wins by far.

How do I check if a string contains a specific word?

Using strstr() or stristr() if your search should be case insensitive would be another option.

how to download file in react js

You can define a component and use it wherever.

import React from 'react';
import PropTypes from 'prop-types';


export const DownloadLink = ({ to, children, ...rest }) => {

  return (
    <a
      {...rest}
      href={to}
      download
    >
      {children}
    </a>
  );
};


DownloadLink.propTypes = {
  to: PropTypes.string,
  children: PropTypes.any,
};

export default DownloadLink;

Regular expression containing one word or another

You can use a single group for seconds/minutes. The following expression may suit your needs:

([0-9]+)\s*(seconds|minutes)

Online demo

HTML.HiddenFor value set

The @ symbol when specifying HtmlAttributes is used when the "thing" you are trying to set is a keyword c#. So for instance the word class, you cannot specify class, you must use @class.

Stop Visual Studio from launching a new browser window when starting debug?

There seems to be one case in which none of the above but the following helps. I'm developing a project for Windows Azure cloud platform and I have a web role. There is indeed a radio button Don't open page in Project -> {Project name} properties... as was pointed out by Pawel Krakowiak, but it has no effect in my case whatsoever. However, there is the main cloud project in solution explorer and there is the Roles folder under it. If I right click my web role in this folder and choose Properties, I get another set of settings and on the Configuration tab there is the Launch browser for flag, after unchecking it a new browser window is not opened on application start up.

Passing arguments to angularjs filters

From what I understand you can't pass an arguments to a filter function (when using the 'filter' filter). What you would have to do is to write a custom filter, sth like this:

.filter('weDontLike', function(){

return function(items, name){

    var arrayToReturn = [];        
    for (var i=0; i<items.length; i++){
        if (items[i].name != name) {
            arrayToReturn.push(items[i]);
        }
    }

    return arrayToReturn;
};

Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/myr4a/1/

The other simple alternative, without writing custom filters is to store a name to filter out in a scope and then write:

$scope.weDontLike = function(item) {
  return item.name != $scope.name;
};

How do I declare a global variable in VBA?

The question is really about scope, as the other guy put it.

In short, consider this "module":

Public Var1 As variant     'Var1 can be used in all
                           'modules, class modules and userforms of 
                           'thisworkbook and will preserve any values
                           'assigned to it until either the workbook
                           'is closed or the project is reset.

Dim Var2 As Variant        'Var2 and Var3 can be used anywhere on the
Private Var3 As Variant    ''current module and will preserve any values
                           ''they're assigned until either the workbook
                           ''is closed or the project is reset.

Sub MySub()                'Var4 can only be used within the procedure MySub
    Dim Var4 as Variant    ''and will only store values until the procedure 
End Sub                    ''ends.

Sub MyOtherSub()           'You can even declare another Var4 within a
    Dim Var4 as Variant    ''different procedure without generating an
End Sub                    ''error (only possible confusion). 

You can check out this MSDN reference for more on variable declaration and this other Stack Overflow Question for more on how variables go out of scope.

Two other quick things:

  1. Be organized when using workbook level variables, so your code doesn't get confusing. Prefer Functions (with proper data types) or passing arguments ByRef.
  2. If you want a variable to preserve its value between calls, you can use the Static statement.

Function to clear the console in R and RStudio

If you are using the default R console CTRL + L

RStudio - CTRL + L

How to consume a SOAP web service in Java

As some sugested you can use apache or jax-ws. You can also use tools that generate code from WSDL such as ws-import but in my opinion the best way to consume web service is to create a dynamic client and invoke only operations you want not everything from wsdl. You can do this by creating a dynamic client: Sample code:

String endpointUrl = ...;

QName serviceName = new QName("http://com/ibm/was/wssample/echo/",
 "EchoService");
QName portName = new QName("http://com/ibm/was/wssample/echo/",
 "EchoServicePort");

/** Create a service and add at least one port to it. **/ 
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointUrl);

/** Create a Dispatch instance from a service.**/ 
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, 
SOAPMessage.class, Service.Mode.MESSAGE);

/** Create SOAPMessage request. **/
// compose a request message
MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);

// Create a message.  This example works with the SOAPPART.
SOAPMessage request = mf.createMessage();
SOAPPart part = request.getSOAPPart();

// Obtain the SOAPEnvelope and header and body elements.
SOAPEnvelope env = part.getEnvelope();
SOAPHeader header = env.getHeader();
SOAPBody body = env.getBody();

// Construct the message payload.
SOAPElement operation = body.addChildElement("invoke", "ns1",
 "http://com/ibm/was/wssample/echo/");
SOAPElement value = operation.addChildElement("arg0");
value.addTextNode("ping");
request.saveChanges();

/** Invoke the service endpoint. **/
SOAPMessage response = dispatch.invoke(request);

/** Process the response. **/

How do you run your own code alongside Tkinter's event loop?

This is the first working version of what will be a GPS reader and data presenter. tkinter is a very fragile thing with way too few error messages. It does not put stuff up and does not tell why much of the time. Very difficult coming from a good WYSIWYG form developer. Anyway, this runs a small routine 10 times a second and presents the information on a form. Took a while to make it happen. When I tried a timer value of 0, the form never came up. My head now hurts! 10 or more times per second is good enough for me. I hope it helps someone else. Mike Morrow

import tkinter as tk
import time

def GetDateTime():
  # Get current date and time in ISO8601
  # https://en.wikipedia.org/wiki/ISO_8601 
  # https://xkcd.com/1179/
  return (time.strftime("%Y%m%d", time.gmtime()),
          time.strftime("%H%M%S", time.gmtime()),
          time.strftime("%Y%m%d", time.localtime()),
          time.strftime("%H%M%S", time.localtime()))

class Application(tk.Frame):

  def __init__(self, master):

    fontsize = 12
    textwidth = 9

    tk.Frame.__init__(self, master)
    self.pack()

    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             text='Local Time').grid(row=0, column=0)
    self.LocalDate = tk.StringVar()
    self.LocalDate.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             textvariable=self.LocalDate).grid(row=0, column=1)

    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             text='Local Date').grid(row=1, column=0)
    self.LocalTime = tk.StringVar()
    self.LocalTime.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
             textvariable=self.LocalTime).grid(row=1, column=1)

    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             text='GMT Time').grid(row=2, column=0)
    self.nowGdate = tk.StringVar()
    self.nowGdate.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             textvariable=self.nowGdate).grid(row=2, column=1)

    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             text='GMT Date').grid(row=3, column=0)
    self.nowGtime = tk.StringVar()
    self.nowGtime.set('waiting...')
    tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
             textvariable=self.nowGtime).grid(row=3, column=1)

    tk.Button(self, text='Exit', width = 10, bg = '#FF8080', command=root.destroy).grid(row=4, columnspan=2)

    self.gettime()
  pass

  def gettime(self):
    gdt, gtm, ldt, ltm = GetDateTime()
    gdt = gdt[0:4] + '/' + gdt[4:6] + '/' + gdt[6:8]
    gtm = gtm[0:2] + ':' + gtm[2:4] + ':' + gtm[4:6] + ' Z'  
    ldt = ldt[0:4] + '/' + ldt[4:6] + '/' + ldt[6:8]
    ltm = ltm[0:2] + ':' + ltm[2:4] + ':' + ltm[4:6]  
    self.nowGtime.set(gdt)
    self.nowGdate.set(gtm)
    self.LocalTime.set(ldt)
    self.LocalDate.set(ltm)

    self.after(100, self.gettime)
   #print (ltm)  # Prove it is running this and the external code, too.
  pass

root = tk.Tk()
root.wm_title('Temp Converter')
app = Application(master=root)

w = 200 # width for the Tk root
h = 125 # height for the Tk root

# get display screen width and height
ws = root.winfo_screenwidth()  # width of the screen
hs = root.winfo_screenheight() # height of the screen

# calculate x and y coordinates for positioning the Tk root window

#centered
#x = (ws/2) - (w/2)
#y = (hs/2) - (h/2)

#right bottom corner (misfires in Win10 putting it too low. OK in Ubuntu)
x = ws - w
y = hs - h - 35  # -35 fixes it, more or less, for Win10

#set the dimensions of the screen and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

root.mainloop()

How to properly create composite primary keys - MYSQL

Aside from personal design preferences, there are cases where one wants to make use of composite primary keys. Tables may have two or more fields that provide a unique combination, and not necessarily by way of foreign keys.

As an example, each US state has a set of unique Congressional districts. While many states may individually have a CD-5, there will never be more than one CD-5 in any of the 50 states, and vice versa. Therefore, creating an autonumber field for Massachusetts CD-5 would be redundant.

If the database drives a dynamic web page, writing code to query on a two-field combination could be much simpler than extracting/resubmitting an autonumbered key.

So while I'm not answering the original question, I certainly appreciate Adam's direct answer.

Upload folder with subfolders using S3 and the AWS console

You can drag and drop those folders. Drag and drop functionality is supported only for the Chrome and Firefox browsers. Please refer this link https://docs.aws.amazon.com/AmazonS3/latest/user-guide/upload-objects.html

jquery how to catch enter key and change event to tab

I took the best of the above and added the ability to work with any input, outside of forms, etc. Also it properly loops back to start now if you reach the last input. And in the event of only one input it blurs then refocuses the single input to trigger any external blur/focus handlers.

$('input,select').keydown( function(e) {
  var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
  if(key == 13) {
    e.preventDefault();
    var inputs = $('#content').find(':input:visible');
    var nextinput = 0;
    if (inputs.index(this) < (inputs.length-1)) {
      nextinput = inputs.index(this)+1;
    }
    if (inputs.length==1) {
      $(this).blur().focus();
    } else {
      inputs.eq(nextinput).focus();
    }
  }
});

6 digits regular expression

You could try

^[0-9]{1,6}$

it should work.

How to stick a footer to bottom in css?

This worked for me:

.footer
{
  width: 100%;
  bottom: 0;
  clear: both;
}

Priority queue in .Net

Use a Java to C# translator on the Java implementation (java.util.PriorityQueue) in the Java Collections framework, or more intelligently use the algorithm and core code and plug it into a C# class of your own making that adheres to the C# Collections framework API for Queues, or at least Collections.

Disable HttpClient logging

The following 2 lines solved my problem completely:

Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.ERROR);
Logger.getLogger("httpclient").setLevel(Level.ERROR);

SVG Positioning

As mentioned in the other comment, the transform attribute on the g element is what you want. Use transform="translate(x,y)" to move the g around and things within the g will move in relation to the g.

convert htaccess to nginx

You can easily make a Php script to parse your old htaccess, I am using this one for PRestashop rules :

$content = $_POST['content'];

    $lines   = explode(PHP_EOL, $content);
    $results = '';

    foreach($lines as $line)
    {
        $items = explode(' ', $line);

        $q = str_replace("^", "^/", $items[1]);

        if (substr($q, strlen($q) - 1) !== '$') $q .= '$';

        $buffer = 'rewrite "'.$q.'" "'.$items[2].'" last;';

        $results .= $buffer.PHP_EOL;
    }

    die($results);

css rotate a pseudo :after or :before content:""

.process-list:after{
    content: "\2191";
    position: absolute;
    top:50%;
    right:-8px;
    background-color: #ea1f41;
    width:35px;
    height: 35px;
    border:2px solid #ffffff;
    border-radius: 5px;
    color: #ffffff;
    z-index: 10000;
    -webkit-transform: rotate(50deg) translateY(-50%);
    -moz-transform: rotate(50deg) translateY(-50%);
    -ms-transform: rotate(50deg) translateY(-50%);
    -o-transform: rotate(50deg) translateY(-50%);
    transform: rotate(50deg) translateY(-50%);
}

you can check this code . i hope you will easily understand.

PHP cURL, extract an XML response

Just add header('Content-type: application/xml'); before your echo of the XML response and you will see an XML page.

Git - How to use .netrc file on Windows to save user and password

I am posting a way to use _netrc to download materials from the site www.course.com.

If someone is going to use the coursera-dl to download the open-class materials on www.coursera.com, and on the Windows OS someone wants to use a file like ".netrc" which is in like-Unix OS to add the option -n instead of -U <username> -P <password> for convenience. He/she can do it like this:

  1. Check the home path on Windows OS: setx HOME %USERPROFILE%(refer to VonC's answer). It will save the HOME environment variable as C:\Users\"username".

  2. Locate into the directory C:\Users\"username" and create a file name _netrc.NOTE: there is NOT any suffix. the content is like: machine coursera-dl login <user> password <pass>

  3. Use a command like coursera-dl -n --path PATH <course name> to download the class materials. More coursera-dl options details for this page.