Programs & Examples On #Wxglade

How to install grunt and how to build script with it

Some time we need to set PATH variable for WINDOWS

%USERPROFILE%\AppData\Roaming\npm

After that test with where grunt

Note: Do not forget to close the command prompt window and reopen it.

How to copy multiple files in one layer using a Dockerfile?

simple

COPY README.md  package.json gulpfile.js __BUILD_NUMBER ./

from the doc

If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.

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

Here is a regex_subst() function. Examples:

=regex_subst("watermellon", "[aeiou]", "")
---> wtrmlln
=regex_subst("watermellon", "[^aeiou]", "")
---> aeeo

Here is the simplified code (simpler for me, anyway). I couldn't figure out how to build a suitable output pattern using the above to work like my examples:

Function regex_subst( _
     strInput As String _
   , matchPattern As String _
   , Optional ByVal replacePattern As String = "" _
) As Variant
    Dim inputRegexObj As New VBScript_RegExp_55.RegExp

    With inputRegexObj
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = matchPattern
    End With

    regex_subst = inputRegexObj.Replace(strInput, replacePattern)
End Function

Setting width of spreadsheet cell using PHPExcel

Tha is because getColumnDimensionByColumn receives the column index (an integer starting from 0), not a string.

The same goes for setCellValueByColumnAndRow

How to extract svg as file from web page

Unless I am misunderstanding you, this could be as easy as inspecting (F12) the icon on the page to reveal its .svg source file path, going to that path directly (Example), and then viewing the page source code with Control+u. Then just save that code.

Pandas merge two dataframes with different columns

I think in this case concat is what you want:

In [12]:

pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
   attr_1  attr_2  attr_3  id  quantity
0       0       1     NaN   1        20
1       1       1     NaN   2        23
2       1       1     NaN   3        19
3       0       0     NaN   4        19
4       1     NaN       0   5         8
5       0     NaN       1   6        13
6       1     NaN       1   7        20
7       1     NaN       1   8        25

by passing axis=0 here you are stacking the df's on top of each other which I believe is what you want then producing NaN value where they are absent from their respective dfs.

Error while trying to retrieve text for error ORA-01019

I have the same issue. My solution was delete one of the oracle path in environment variable. I also changed the inventory.xml and point to the oracle home version which is in my environment path variable.

Python unittest passing arguments

So the doctors here that are saying "You say that hurts? Then don't do that!" are probably right. But if you really want to, here's one way of passing arguments to a unittest test:

import sys
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username : {}'.format(self.USERNAME))
        print('password : {}'.format(self.PASSWORD))


if __name__ == "__main__":
    if len(sys.argv) > 1:
        MyTest.USERNAME = sys.argv.pop()
        MyTest.PASSWORD = sys.argv.pop()
    unittest.main()

that will let you run with:

python mytests.py ausername apassword

You need the argv.pops so your command line params don't mess with unittest's own...

[update] The other thing you might want to look into is using environment variables:

import os
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username : {}'.format(self.USERNAME))
        print('password : {}'.format(self.PASSWORD))


if __name__ == "__main__":
    MyTest.USERNAME = os.environ.get('TEST_USERNAME', MyTest.USERNAME)            
    MyTest.PASSWORD = os.environ.get('TEST_PASSWORD', MyTest.PASSWORD)
    unittest.main()

That will let you run with:

TEST_USERNAME=ausername TEST_PASSWORD=apassword python mytests.py

and it has the advantage that you're not messing with unittest's own argument parsing. downside is it won't work quite like that on Windows...

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

In your config.xml file add this line:

<preference name="loadUrlTimeoutValue" value="700000" />

What’s the best RESTful method to return total number of items in an object?

As of "X-"-Prefix was deprecated. (see: https://tools.ietf.org/html/rfc6648)

We found the "Accept-Ranges" as being the best bet to map the pagination ranging: https://tools.ietf.org/html/rfc7233#section-2.3 As the "Range Units" may either be "bytes" or "token". Both do not represent a custom data type. (see: https://tools.ietf.org/html/rfc7233#section-4.2) Still, it is stated that

HTTP/1.1 implementations MAY ignore ranges specified using other units.

Which indicates: using custom Range Units is not against the protocol, but it MAY be ignored.

This way, we would have to set the Accept-Ranges to "members" or whatever ranged unit type, we'd expect. And in addition, also set the Content-Range to the current range. (see: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.12)

Either way, I would stick to the recommendation of RFC7233 (https://tools.ietf.org/html/rfc7233#page-8) to send a 206 instead of 200:

If all of the preconditions are true, the server supports the Range
header field for the target resource, and the specified range(s) are
valid and satisfiable (as defined in Section 2.1), the server SHOULD
send a 206 (Partial Content) response with a payload containing one
or more partial representations that correspond to the satisfiable
ranges requested, as defined in Section 4.

So, as a result, we would have the following HTTP header fields:

For Partial Content:

206 Partial Content
Accept-Ranges: members
Content-Range: members 0-20/100

For full Content:

200 OK
Accept-Ranges: members
Content-Range: members 0-20/20

Memory address of variables in Java

Like Sunil said, this is not memory address.This is just the hashcode

To get the same @ content, you can:

If hashCode is not overridden in that class:

"@" + Integer.toHexString(obj.hashCode())

If hashCode is overridden, you get the original value with:

"@" + Integer.toHexString(System.identityHashCode(obj)) 

This is often confused with memory address because if you don't override hashCode(), the memory address is used to calculate the hash.

MD5 hashing in Android

I have made a simple Library in Kotlin.

Add at Root build.gradle

allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

at App build.gradle

implementation 'com.github.1AboveAll:Hasher:-SNAPSHOT'

Usage

In Kotlin

val ob = Hasher()

Then Use hash() method

ob.hash("String_You_Want_To_Encode",Hasher.MD5)

ob.hash("String_You_Want_To_Encode",Hasher.SHA_1)

It will return MD5 and SHA-1 Respectively.

More about the Library

https://github.com/ihimanshurawat/Hasher

Send file using POST from a Python script

You may also want to have a look at httplib2, with examples. I find using httplib2 is more concise than using the built-in HTTP modules.

Listing available com ports with Python

Please, try this code:

import serial
ports = serial.tools.list_ports.comports(include_links=False)
for port in ports :
    print(port.device)

first of all, you need to import package for serial port communication, so:

import serial

then you create the list of all the serial ports currently available:

ports = serial.tools.list_ports.comports(include_links=False)

and then, walking along whole list, you can for example print port names:

for port in ports :
    print(port.device)

This is just an example how to get the list of ports and print their names, but there some other options you can do with this data. Just try print different variants after

port.

How can I overwrite file contents with new content in PHP?

MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]

$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);

Warning for those using file_put_contents

It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time

How to retrieve images from MySQL database and display in an html tag

You can't. You need to create another php script to return the image data, e.g. getImage.php. Change catalog.php to:

<body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>

Then getImage.php is

<?php

  $id = $_GET['id'];
  // do some validation here to ensure id is safe

  $link = mysql_connect("localhost", "root", "");
  mysql_select_db("dvddb");
  $sql = "SELECT dvdimage FROM dvd WHERE id=$id";
  $result = mysql_query("$sql");
  $row = mysql_fetch_assoc($result);
  mysql_close($link);

  header("Content-type: image/jpeg");
  echo $row['dvdimage'];
?>

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Pretty-Printing JSON with PHP

This solution makes 'really pretty' JSON. Not exactly what the OP was asking for, but it lets you visualise the JSON better.

/**
 * takes an object parameter and returns the pretty json format.
 * this is a space saving version that uses 2 spaces instead of the regular 4
 *
 * @param $in
 *
 * @return string
 */
function pretty_json ($in): string
{
  return preg_replace_callback('/^ +/m',
    function (array $matches): string
    {
      return str_repeat(' ', strlen($matches[0]) / 2);
    }, json_encode($in, JSON_PRETTY_PRINT | JSON_HEX_APOS)
  );
}

/**
 * takes a JSON string an adds colours to the keys/values
 * if the string is not JSON then it is returned unaltered.
 *
 * @param string $in
 *
 * @return string
 */

function markup_json (string $in): string
{
  $string  = 'green';
  $number  = 'darkorange';
  $null    = 'magenta';
  $key     = 'red';
  $pattern = '/("(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/';
  return preg_replace_callback($pattern,
      function (array $matches) use ($string, $number, $null, $key): string
      {
        $match  = $matches[0];
        $colour = $number;
        if (preg_match('/^"/', $match))
        {
          $colour = preg_match('/:$/', $match)
            ? $key
            : $string;
        }
        elseif ($match === 'null')
        {
          $colour = $null;
        }
        return "<span style='color:{$colour}'>{$match}</span>";
      }, str_replace(['<', '>', '&'], ['&lt;', '&gt;', '&amp;'], $in)
   ) ?? $in;
}

public function test_pretty_json_object ()
{
  $ob       = new \stdClass();
  $ob->test = 'unit-tester';
  $json     = pretty_json($ob);
  $expected = <<<JSON
{
  "test": "unit-tester"
}
JSON;
  $this->assertEquals($expected, $json);
}

public function test_pretty_json_str ()
{
  $ob   = 'unit-tester';
  $json = pretty_json($ob);
  $this->assertEquals("\"$ob\"", $json);
}

public function test_markup_json ()
{
  $json = <<<JSON
[{"name":"abc","id":123,"warnings":[],"errors":null},{"name":"abc"}]
JSON;
  $expected = <<<STR
[
  {
    <span style='color:red'>"name":</span> <span style='color:green'>"abc"</span>,
    <span style='color:red'>"id":</span> <span style='color:darkorange'>123</span>,
    <span style='color:red'>"warnings":</span> [],
    <span style='color:red'>"errors":</span> <span style='color:magenta'>null</span>
  },
  {
    <span style='color:red'>"name":</span> <span style='color:green'>"abc"</span>
  }
]
STR;

  $output = markup_json(pretty_json(json_decode($json)));
  $this->assertEquals($expected,$output);
}

}

How to find rows in one table that have no corresponding row in another table

You can also use exists, since sometimes it's faster than left join. You'd have to benchmark them to figure out which one you want to use.

select
    id
from
    tableA a
where
    not exists
    (select 1 from tableB b where b.id = a.id)

To show that exists can be more efficient than a left join, here's the execution plans of these queries in SQL Server 2008:

left join - total subtree cost: 1.09724:

left join

exists - total subtree cost: 1.07421:

exists

Random number between 0 and 1 in python

random.randrange(0,2) this works!

Javascript decoding html entities

There is a jQuery solution in this thread. Try something like this:

var decoded = $("<div/>").html('your string').text();

This sets the innerHTML of a new <div> element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Returning value that was passed into a method

Even more useful, if you have multiple parameters you can access any/all of them with:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
     .Returns((string a, string b, string c) => string.Concat(a,b,c));

You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.

How can I quickly sum all numbers in a file?

I prefer to use GNU datamash for such tasks because it's more succinct and legible than perl or awk. For example

datamash sum 1 < myfile

where 1 denotes the first column of data.

How to put a UserControl into Visual Studio toolBox

In my case, I couldn't see any of the controls in the project. Only when right clicking on toolBox and selecting "Show All" I saw them, but yet they were disabled...

Changing Project type from Windows application to ClassLibrary made the fix.

Writing files in Node.js

There are a lot of details in the File System API. The most common way is:

const fs = require('fs');

fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
}); 

// Or
fs.writeFileSync('/tmp/test-sync', 'Hey there!');

Setting Android Theme background color

Open res -> values -> styles.xml and to your <style> add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>. Example:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@drawable/background</item>
    </style>

</resources>

There is a <item name ="android:colorBackground">@color/black</item> also, that will affect not only your main window background but all the component in your app. Read about customize theme here.

If you want version specific styles:

If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:

res/values/styles.xml        # themes for all versions
res/values-v21/styles.xml    # themes for API level 21+ only

Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.

Read more here(doc in theme).

what does this mean ? image/png;base64?

They serve the actual image inside CSS so there will be less HTTP requests per page.

Where to get this Java.exe file for a SQL Developer installation

you should browse to where java installed, then go to bin directory which contains the java.exe file.

example - C:\Program Files\Java\jdk1.6.0_03\bin\java.exe

but you should run your SQL Developer as Administrator

How do I set a fixed background image for a PHP file?

Your question doesn't have anything to do with PHP... just CSS.

Your CSS is correct, but your browser won't typically be able to open what you have put in for a URL. At a minimum, you'll need a file: path. It would be best to reference the file by its relative path.

Unable to connect to any of the specified mysql hosts. C# MySQL

use SqlConnectionStringBuilder to simplify the connection

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Initial Catalog"] = "Server";
builder["Data Source"] = "db";
builder["integrated Security"] = true;
string connexionString = builder.ConnectionString;
SqlConnection connexion = new SqlConnection(connexionString);
try { connexion.Open(); return true; }
catch { return false; }

Plotting multiple lines, in different colors, with pandas dataframe

You can use this code to get your desire output

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'color': ['red','red','red','blue','blue','blue'], 'x': [0,1,2,3,4,5],'y': [0,1,2,9,16,25]})
print df

  color  x   y
0   red  0   0
1   red  1   1
2   red  2   2
3  blue  3   9
4  blue  4  16
5  blue  5  25

To plot graph

a = df.iloc[[i for i in xrange(0,len(df)) if df['x'][i]==df['y'][i]]].plot(x='x',y='y',color = 'red')
df.iloc[[i for i in xrange(0,len(df)) if df['y'][i]== df['x'][i]**2]].plot(x='x',y='y',color = 'blue',ax=a)

plt.show()

Output The output result will look like this

Upper memory limit?

Not only are you reading the whole of each file into memory, but also you laboriously replicate the information in a table called list_of_lines.

You have a secondary problem: your choices of variable names severely obfuscate what you are doing.

Here is your script rewritten with the readlines() caper removed and with meaningful names:

file_A1_B1 = open("A1_B1_100000.txt", "r")
file_A2_B2 = open("A2_B2_100000.txt", "r")
file_A1_B2 = open("A1_B2_100000.txt", "r")
file_A2_B1 = open("A2_B1_100000.txt", "r")
file_write = open ("average_generations.txt", "w")
mutation_average = open("mutation_average", "w") # not used
files = [file_A2_B2,file_A2_B2,file_A1_B2,file_A2_B1]
for afile in files:
    table = []
    for aline in afile:
        values = aline.split('\t')
        values.remove('\n') # why?
        table.append(values)
    row_count = len(table)
    row0length = len(table[0])
    print_counter = 4
    for column_index in range(row0length):
        column_total = 0
        for row_index in range(row_count):
            number = float(table[row_index][column_index])
            column_total = column_total + number
        column_average = column_total/row_count
        print column_average
        if print_counter == 4:
            file_write.write(str(column_average)+'\n')
            print_counter = 0
        print_counter +=1
file_write.write('\n')

It rapidly becomes apparent that (1) you are calculating column averages (2) the obfuscation led some others to think you were calculating row averages.

As you are calculating column averages, no output is required until the end of each file, and the amount of extra memory actually required is proportional to the number of columns.

Here is a revised version of the outer loop code:

for afile in files:
    for row_count, aline in enumerate(afile, start=1):
        values = aline.split('\t')
        values.remove('\n') # why?
        fvalues = map(float, values)
        if row_count == 1:
            row0length = len(fvalues)
            column_index_range = range(row0length)
            column_totals = fvalues
        else:
            assert len(fvalues) == row0length
            for column_index in column_index_range:
                column_totals[column_index] += fvalues[column_index]
    print_counter = 4
    for column_index in column_index_range:
        column_average = column_totals[column_index] / row_count
        print column_average
        if print_counter == 4:
            file_write.write(str(column_average)+'\n')
            print_counter = 0
        print_counter +=1

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

What is new in .NET Framework 4.5 & What's new and expected in .NET Framework 4.5:

  • Support for Windows Runtime
  • Support for Metro Style Applications
  • Support for Async Programming
  • Garbage Collector Improvements
  • Faster ASP.NET Startup
  • Better Data Access Support
  • WebSockets Support
  • Workflow Support - BCL Support

differences in ASP.NET in these frameworks

Compare What's New in ASP.NET 4 and Visual Web Developer and What's New in ASP.NET 4.5 and Visual Studio 11 Beta:

Asp.net 4.0

  • Web.config File Refactoring
  • Extensible Output Caching
  • Auto-Start Web Applications
  • Permanently Redirecting a Page
  • Shrinking Session State
  • Expanding the Range of Allowable URLs
  • Extensible Request Validation
  • Object Caching and Object Caching Extensibility
  • Extensible HTML, URL, and HTTP Header Encoding
  • Performance Monitoring for Individual Applications in a Single Worker Process
  • Multi-Targeting
  • etc

And for Asp.net 4.5 there is also a long list of improvements:

  • Asynchronously Reading and Writing HTTP Requests and Responses
  • Improvements to HttpRequest handling
  • Asynchronously flushing a response
  • Support for await and Task-Based Asynchronous Modules and Handlers

differences in C# also in these frameworks

Go Through C# 4.0 - New C# Features in the .NET Framework and What's New for Visual C# in Visual Studio 11 Beta.

Edit:
The languages documentation for C# and VB breaking changes:

VB: Visual Basic Breaking Changes in Visual Studio 2012

C#: Visual C# Breaking Changes in Visual Studio 2012

Hope this help you get what are you looking for..

Laravel 5.4 redirection to custom url after login

you can add method in LoginController add line use App\User; on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }} on view admin and user

protected function authenticated(Request $request, $user){

$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');

if ($a==0) {
    return redirect('admin');

}else{
    return redirect('user');

}}

How to convert an OrderedDict into a regular dict in python3

If you are looking for a recursive version without using the json module:

def ordereddict_to_dict(value):
    for k, v in value.items():
        if isinstance(v, dict):
            value[k] = ordereddict_to_dict(v)
    return dict(value)

How to change MySQL data directory?

Under SuSE 13.1, this works fine to move the mysql data directory elsewhere, e.g. to /home/example_user/ , and to give it a more informative name:

In /var/lib/ :

# mv -T mysql /home/example_user/mysql_datadir
# ln -s /home/example_user/mysql_datadir ./mysql

I restarted mysql:

# systemctl restart mysql.service

but suspect that even that wasn't necessary.

How to get all selected values from <select multiple=multiple>?

$('#select-meal-type :selected') will contain an array of all of the selected items.

$('#select-meal-type option:selected').each(function() {
    alert($(this).val());
});

?

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

In JUnit 4:

  • For the Class Under Test, initialize in a @Before method, to catch failures.
  • For other classes, initialize in the declaration...
    • ...for brevity, and to mark fields final, exactly as stated in the question,
    • ...unless it is complex initialization that could fail, in which case use @Before, to catch failures.
  • For global state (esp. slow initialization, like a database), use @BeforeClass, but be careful of dependencies between tests.
  • Initialization of an object used in a single test should of course be done in the test method itself.

Initializing in a @Before method or test method allows you to get better error reporting on failures. This is especially useful for instantiating the Class Under Test (which you might break), but is also useful for calling external systems, like filesystem access ("file not found") or connecting to a database ("connection refused").

It is acceptable to have a simple standard and always use @Before (clear errors but verbose) or always initialize in declaration (concise but gives confusing errors), since complex coding rules are hard to follow, and this isn't a big deal.

Initializing in setUp is a relic of JUnit 3, where all test instances were initialized eagerly, which causes problems (speed, memory, resource exhaustion) if you do expensive initialization. Thus best practice was to do expensive initialization in setUp, which was only run when the test was executed. This no longer applies, so it is much less necessary to use setUp.

This summarizes several other replies that bury the lede, notably by Craig P. Motlin (question itself and self-answer), Moss Collum (class under test), and dsaff.

How to validate email id in angularJs using ng-pattern

There is nice example how to deal with this kind of problem modyfing built-in validators angulardocs. I have only added more strict validation pattern.

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;

  return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, elm, attrs, ctrl) {
      // only apply the validator if ngModel is present and Angular has added the email validator
      if (ctrl && ctrl.$validators.email) {

        // this will overwrite the default Angular email validator
        ctrl.$validators.email = function(modelValue) {
          return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
        };
      }
    }
  };
});

And simply add

<input type='email' validate-email name='email' id='email' ng-model='email' required>  

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

it worked for me by neutralizing the '\' by f = open('F:\\file.csv')

How can I get a first element from a sorted list?

If you just want to get the minimum of a list, instead of sorting it and then getting the first element (O(N log N)), you can use do it in linear time using min:

<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)

That looks gnarly at first, but looking at your previous questions, you have a List<String>. In short: min works on it.

For the long answer: all that super and extends stuff in the generic type constraints is what Josh Bloch calls the PECS principle (usually presented next to a picture of Arnold -- I'M NOT KIDDING!)

Producer Extends, Consumer Super

It essentially makes generics more powerful, since the constraints are more flexible while still preserving type safety (see: what is the difference between ‘super’ and ‘extends’ in Java Generics)

WRONGTYPE Operation against a key holding the wrong kind of value php

Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.

Here are the commands to retrieve key value:

  • if value is of type string -> GET <key>
  • if value is of type hash -> HGETALL <key>
  • if value is of type lists -> lrange <key> <start> <end>
  • if value is of type sets -> smembers <key>
  • if value is of type sorted sets -> ZRANGEBYSCORE <key> <min> <max>

Use the TYPE command to check the type of value a key is mapping to:

  • type <key>

Angular 2 Dropdown Options Default Value

You Can approach this way:

<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>

or this way:

  <option *ngFor="let workout of workouts" [attr.value]="workout.name" [attr.selected]="workout.name == 'leg' ? true : null">{{workout.name}}</option>

or you can set default value this way:

<option [value]="null">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>

or

<option [value]="0">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

These two things don't match:

driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby://localhost:1527/poll database;create=true"

If you are using the EmbeddedDriver, your URL should not contain network syntax.

Conversely, if you are using network syntax, you need to use the ClientDriver.

http://db.apache.org/derby/docs/10.8/getstart/rgsquck35368.html

When is null or undefined used in JavaScript?

The DOM methods getElementById(), nextSibling(), childNodes[n], parentNode() and so on return null (defined but having no value) when the call does not return a node object.

The property is defined, but the object it refers to does not exist.

This is one of the few times you may not want to test for equality-

if(x!==undefined) will be true for a null value

but if(x!= undefined) will be true (only) for values that are not either undefined or null.

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

If you don't have the API enabled, but have an API key, you won't get that error if you run an API from the browser (such as when displaying a map) or pass the request to the curl command. You only get that error if you call an API within code. In Python, it doesn't matter if you use urllib, pycurl, construct the curl command and pass it to subprocess.check_output(), or send the request using jQuery.get(); you still get that error. I wonder how Google knows the difference.

npm check and update package if needed

To really update just one package install NCU and then run it just for that package. This will bump to the real latest.

npm install -g npm-check-updates

ncu -f your-intended-package-name -u

$location / switching between html5 and hashbang mode / link rewriting

Fur future readers, if you are using Angular 1.6, you also need to change the hashPrefix:

appModule.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('');
}]);

Don't forget to set the base in your HTML <head>:

<head>
    <base href="/">
    ...
</head>

More info about the changelog here.

How do I split a string by a multi-character delimiter in C#?

You can use the Regex.Split method, something like this:

Regex regex = new Regex(@"\bis\b");
string[] substrings = regex.Split("This is a sentence");

foreach (string match in substrings)
{
   Console.WriteLine("'{0}'", match);
}

Edit: This satisfies the example you gave. Note that an ordinary String.Split will also split on the "is" at the end of the word "This", hence why I used the Regex method and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Split will probably suffice.

Oracle query to fetch column names

You can use the below query to get a list of table names which uses the specific column in DB2:

SELECT TBNAME                
FROM SYSIBM.SYSCOLUMNS       
WHERE NAME LIKE '%COLUMN_NAME'; 

Note : Here replace the COLUMN_NAME with the column name that you are searching for.

Format a Go string without printing?

1. Simple strings

For "simple" strings (typically what fits into a line) the simplest solution is using fmt.Sprintf() and friends (fmt.Sprint(), fmt.Sprintln()). These are analogous to the functions without the starter S letter, but these Sxxx() variants return the result as a string instead of printing them to the standard output.

For example:

s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)

The variable s will be initialized with the value:

Hi, my name is Bob and I'm 23 years old.

Tip: If you just want to concatenate values of different types, you may not automatically need to use Sprintf() (which requires a format string) as Sprint() does exactly this. See this example:

i := 23
s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"

For concatenating only strings, you may also use strings.Join() where you can specify a custom separator string (to be placed between the strings to join).

Try these on the Go Playground.

2. Complex strings (documents)

If the string you're trying to create is more complex (e.g. a multi-line email message), fmt.Sprintf() becomes less readable and less efficient (especially if you have to do this many times).

For this the standard library provides the packages text/template and html/template. These packages implement data-driven templates for generating textual output. html/template is for generating HTML output safe against code injection. It provides the same interface as package text/template and should be used instead of text/template whenever the output is HTML.

Using the template packages basically requires you to provide a static template in the form of a string value (which may be originating from a file in which case you only provide the file name) which may contain static text, and actions which are processed and executed when the engine processes the template and generates the output.

You may provide parameters which are included/substituted in the static template and which may control the output generation process. Typical form of such parameters are structs and map values which may be nested.

Example:

For example let's say you want to generate email messages that look like this:

Hi [name]!

Your account is ready, your user name is: [user-name]

You have the following roles assigned:
[role#1], [role#2], ... [role#n]

To generate email message bodies like this, you could use the following static template:

const emailTmpl = `Hi {{.Name}}!

Your account is ready, your user name is: {{.UserName}}

You have the following roles assigned:
{{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}}
`

And provide data like this for executing it:

data := map[string]interface{}{
    "Name":     "Bob",
    "UserName": "bob92",
    "Roles":    []string{"dbteam", "uiteam", "tester"},
}

Normally output of templates are written to an io.Writer, so if you want the result as a string, create and write to a bytes.Buffer (which implements io.Writer). Executing the template and getting the result as string:

t := template.Must(template.New("email").Parse(emailTmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, data); err != nil {
    panic(err)
}
s := buf.String()

This will result in the expected output:

Hi Bob!

Your account is ready, your user name is: bob92

You have the following roles assigned:
dbteam, uiteam, tester

Try it on the Go Playground.

Also note that since Go 1.10, a newer, faster, more specialized alternative is available to bytes.Buffer which is: strings.Builder. Usage is very similar:

builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
    panic(err)
}
s := builder.String()

Try this one on the Go Playground.

Note: you may also display the result of a template execution if you provide os.Stdout as the target (which also implements io.Writer):

t := template.Must(template.New("email").Parse(emailTmpl))
if err := t.Execute(os.Stdout, data); err != nil {
    panic(err)
}

This will write the result directly to os.Stdout. Try this on the Go Playground.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Partly cherry-picking a commit with Git

Use git format-patch to slice out the part of the commit you care about and git am to apply it to another branch

git format-patch <sha> -- path/to/file
git checkout other-branch
git am *.patch

Strange PostgreSQL "value too long for type character varying(500)"

By specifying the column as VARCHAR(500) you've set an explicit 500 character limit. You might not have done this yourself explicitly, but Django has done it for you somewhere. Telling you where is hard when you haven't shown your model, the full error text, or the query that produced the error.

If you don't want one, use an unqualified VARCHAR, or use the TEXT type.

varchar and text are limited in length only by the system limits on column size - about 1GB - and by your memory. However, adding a length-qualifier to varchar sets a smaller limit manually. All of the following are largely equivalent:

column_name VARCHAR(500)

column_name VARCHAR CHECK (length(column_name) <= 500) 

column_name TEXT CHECK (length(column_name) <= 500) 

The only differences are in how database metadata is reported and which SQLSTATE is raised when the constraint is violated.

The length constraint is not generally obeyed in prepared statement parameters, function calls, etc, as shown:

regress=> \x
Expanded display is on.
regress=> PREPARE t2(varchar(500)) AS SELECT $1;
PREPARE
regress=> EXECUTE t2( repeat('x',601) );
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
?column? | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

and in explicit casts it result in truncation:

regress=> SELECT repeat('x',501)::varchar(1);
-[ RECORD 1 ]
repeat | x

so I think you are using a VARCHAR(500) column, and you're looking at the wrong table or wrong instance of the database.

How do you attach and detach from Docker's process?

I think this should depend on the situation.Take the following container as an example:

# docker run -it -d ubuntu
91262536f7c9a3060641448120bda7af5ca812b0beb8f3c9fe72811a61db07fc
# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
91262536f7c9        ubuntu              "/bin/bash"         5 seconds ago       Up 4 seconds                            serene_goldstine

(1) Use "docker attach" to attach the container:

Since "docker attach" will not allocate a new tty, but reuse the original running tty, so if you run exit command, it will cause the running container exit:

# docker attach 91262536f7c9
exit
exit
# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
91262536f7c9        ubuntu              "/bin/bash"         39 minutes ago      Exited (0) 3 seconds ago                       serene_goldstine

So unless you really want to make running container exit, you should use Ctrl+p + Ctrl+q.

(2) Use "docker exec"

Since "docker exec" will allocate a new tty, so I think you should use exit instead of Ctrl+p + Ctrl+q.

The following is executing Ctrl+p + Ctrl+q to quit the container:

# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  18160  1908 ?        Ss+  04:03   0:00 /bin/bash
root        15  0.0  0.0  18164  1892 ?        Ss   04:03   0:00 bash
root        28  0.0  0.0  15564  1148 ?        R+   04:03   0:00 ps -aux
root@91262536f7c9:/# echo $$
15

Then login container again, you will see the bash process in preavious docker exec command is still alive (PID is 15):

# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  18160  1908 ?        Ss+  04:03   0:00 /bin/bash
root        15  0.0  0.0  18164  1892 ?        Ss+  04:03   0:00 bash
root        29  0.0  0.0  18164  1888 ?        Ss   04:04   0:00 bash
root        42  0.0  0.0  15564  1148 ?        R+   04:04   0:00 ps -aux
root@91262536f7c9:/# echo $$
29

How to detect if a string contains special characters?

Assuming SQL Server:

e.g. if you class special characters as anything NOT alphanumeric:

DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'

IF (@MyString LIKE '%[^a-zA-Z0-9]%')
    PRINT 'Contains "special" characters'
ELSE
    PRINT 'Does not contain "special" characters'

Just add to other characters you don't class as special, inside the square brackets

Hive: Filtering Data between Specified Dates when Date is a String

Just like SQL, Hive supports BETWEEN operator for more concise statement:

SELECT *
  FROM your_table
  WHERE your_date_column BETWEEN '2010-09-01' AND '2013-08-31';

How to set space between listView Items in Android

For my application, i have done this way

 <ListView
    android:id="@+id/staff_jobassigned_listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@null"
    android:dividerHeight="10dp">

</ListView>

just set the divider to null and providing height to the divider did for me.

Example :

android:divider="@null"

or

android:divider="@android:color/transparent"

and this is result

enter image description here

Wait some seconds without blocking UI execution

If you do not want to block things and also not want to use multi threading, here is the solution for you: https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx

The UI Thread is not blocked and the timer waits for 2 seconds before doing something.

Here is the code coming from the link above:

        // Create a timer with a two second interval.
    aTimer = new System.Timers.Timer(2000);
    // Hook up the Elapsed event for the timer. 
    aTimer.Elapsed += OnTimedEvent;
    aTimer.Enabled = true;

    Console.WriteLine("Press the Enter key to exit the program... ");
    Console.ReadLine();
    Console.WriteLine("Terminating the application...");

Convert Mongoose docs to json

Late answer but you can also try this when defining your schema.

/**
 * toJSON implementation
 */
schema.options.toJSON = {
    transform: function(doc, ret, options) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.__v;
        return ret;
    }
};

Note that ret is the JSON'ed object, and it's not an instance of the mongoose model. You'll operate on it right on object hashes, without getters/setters.

And then:

Model
    .findById(modelId)
    .exec(function (dbErr, modelDoc){
         if(dbErr) return handleErr(dbErr);

         return res.send(modelDoc.toJSON(), 200);
     });

Edit: Feb 2015

Because I didn't provide a solution to the missing toJSON (or toObject) method(s) I will explain the difference between my usage example and OP's usage example.

OP:

UserModel
    .find({}) // will get all users
    .exec(function(err, users) {
        // supposing that we don't have an error
        // and we had users in our collection,
        // the users variable here is an array
        // of mongoose instances;

        // wrong usage (from OP's example)
        // return res.end(users.toJSON()); // has no method toJSON

        // correct usage
        // to apply the toJSON transformation on instances, you have to
        // iterate through the users array

        var transformedUsers = users.map(function(user) {
            return user.toJSON();
        });

        // finish the request
        res.end(transformedUsers);
    });

My Example:

UserModel
    .findById(someId) // will get a single user
    .exec(function(err, user) {
        // handle the error, if any
        if(err) return handleError(err);

        if(null !== user) {
            // user might be null if no user matched
            // the given id (someId)

            // the toJSON method is available here,
            // since the user variable here is a 
            // mongoose model instance
            return res.end(user.toJSON());
        }
    });

How to Multi-thread an Operation Within a Loop in Python

First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.

This is not true if your operation "takes forever to return" because it's IO-bound—that is, waiting on the network or disk copies or the like. I'll come back to that later.


Next, the way to process 5 or 10 or 100 items at once is to create a pool of 5 or 10 or 100 workers, and put the items into a queue that the workers service. Fortunately, the stdlib multiprocessing and concurrent.futures libraries both wraps up most of the details for you.

The former is more powerful and flexible for traditional programming; the latter is simpler if you need to compose future-waiting; for trivial cases, it really doesn't matter which you choose. (In this case, the most obvious implementation with each takes 3 lines with futures, 4 lines with multiprocessing.)

If you're using 2.6-2.7 or 3.0-3.1, futures isn't built in, but you can install it from PyPI (pip install futures).


Finally, it's usually a lot simpler to parallelize things if you can turn the entire loop iteration into a function call (something you could, e.g., pass to map), so let's do that first:

def try_my_operation(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

Putting it all together:

executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_my_operation, item) for item in items]
concurrent.futures.wait(futures)

If you have lots of relatively small jobs, the overhead of multiprocessing might swamp the gains. The way to solve that is to batch up the work into larger jobs. For example (using grouper from the itertools recipes, which you can copy and paste into your code, or get from the more-itertools project on PyPI):

def try_multiple_operations(items):
    for item in items:
        try:
            api.my_operation(item)
        except:
            print('error with item')

executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_multiple_operations, group) 
           for group in grouper(5, items)]
concurrent.futures.wait(futures)

Finally, what if your code is IO bound? Then threads are just as good as processes, and with less overhead (and fewer limitations, but those limitations usually won't affect you in cases like this). Sometimes that "less overhead" is enough to mean you don't need batching with threads, but you do with processes, which is a nice win.

So, how do you use threads instead of processes? Just change ProcessPoolExecutor to ThreadPoolExecutor.

If you're not sure whether your code is CPU-bound or IO-bound, just try it both ways.


Can I do this for multiple functions in my python script? For example, if I had another for loop elsewhere in the code that I wanted to parallelize. Is it possible to do two multi threaded functions in the same script?

Yes. In fact, there are two different ways to do it.

First, you can share the same (thread or process) executor and use it from multiple places with no problem. The whole point of tasks and futures is that they're self-contained; you don't care where they run, just that you queue them up and eventually get the answer back.

Alternatively, you can have two executors in the same program with no problem. This has a performance cost—if you're using both executors at the same time, you'll end up trying to run (for example) 16 busy threads on 8 cores, which means there's going to be some context switching. But sometimes it's worth doing because, say, the two executors are rarely busy at the same time, and it makes your code a lot simpler. Or maybe one executor is running very large tasks that can take a while to complete, and the other is running very small tasks that need to complete as quickly as possible, because responsiveness is more important than throughput for part of your program.

If you don't know which is appropriate for your program, usually it's the first.

JavaScript onclick redirect

Change the onclick from

onclick="javascript:SubmitFrm()"

to

onclick="SubmitFrm()"

Pass parameters in setInterval function

You can use a library called underscore js. It gives a nice wrapper on the bind method and is a much cleaner syntax as well. Letting you execute the function in the specified scope.

http://underscorejs.org/#bind

_.bind(function, scope, *arguments)

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

In Chrome (v.56 is what I'm using but I AFAIK this applies generally) you can set title=" " (a single space) and the automatic title text will be overridden and nothing displayed. (If you try to make it just an empty string, though, it will treat it as if it isn't set and add that automatic tooltip text you've been getting).

I haven't tested this in other browsers, because I found it whilst making a Google Chrome Extension. I'm sure once I port things to other browsers, though, I'll see if it works in them (if even necessary), too.

Python: IndexError: list index out of range

I think you mean to put the rolling of the random a,b,c, etc within the loop:

a = None # initialise
while not (a in winning_numbers):
    # keep rolling an a until you get one not in winning_numbers
    a = random.randint(1,30)
    winning_numbers.append(a)

Otherwise, a will be generated just once, and if it is in winning_numbers already, it won't be added. Since the generation of a is outside the while (in your code), if a is already in winning_numbers then too bad, it won't be re-rolled, and you'll have one less winning number.

That could be what causes your error in if guess[i] == winning_numbers[i]. (Your winning_numbers isn't always of length 5).

What processes are using which ports on unix?

netstat -ln | awk '/^(tcp|udp)/ { split($4, a, /:/); print $1, a[2]}' | sort -u

gives you the active tcp/udp ports. Then you can use the ports with fuser -n tcp or fuser -n udp, as root, and supposing that fuser is GNU fuser or has similar options.

If you need more help, let me know.

What is the difference between an int and a long in C++?

It is implementation dependent.

For example, under Windows they are the same, but for example on Alpha systems a long was 64 bits whereas an int was 32 bits. This article covers the rules for the Intel C++ compiler on variable platforms. To summarize:

  OS           arch           size
Windows       IA-32        4 bytes
Windows       Intel 64     4 bytes
Windows       IA-64        4 bytes
Linux         IA-32        4 bytes
Linux         Intel 64     8 bytes
Linux         IA-64        8 bytes
Mac OS X      IA-32        4 bytes
Mac OS X      Intel 64     8 bytes  

No resource identifier found for attribute '...' in package 'com.app....'

this helps for me:

on your build.gradle:

implementation 'com.android.support:design:28.0.0'

How to compare data between two table in different databases using Sql Server 2008?

Another solution (non T-SQL): you can use tablediff utility. For example if you want to compare two tables (Localitate) from two different servers (ROBUH01 & ROBUH02) you can use this shell command:

C:\Program Files\Microsoft SQL Server\100\COM>tablediff -sourceserver ROBUH01 -s
ourcedatabase SIM01 -sourceschema dbo -sourcetable Localitate -destinationserver
 ROBUH02 -destinationschema dbo -destinationdatabase SIM02 -destinationtable Lo
calitate

Results:

Microsoft (R) SQL Server Replication Diff Tool Copyright (c) 2008 Microsoft Corporation User-specified agent parameter values: 
-sourceserver ROBUH01 
-sourcedatabase SIM01 
-sourceschema dbo 
-sourcetable Localitate 
-destinationserver ROBUH02 
-destinationschema dbo 
-destinationdatabase SIM02 
-destinationtable Localitate 

Table [SIM01].[dbo].[Localitate] on ROBUH01 and Table [SIM02].[dbo].[Localitate ] on ROBUH02 have 10 differences. 

Err Id Dest. 
Only 21433 Dest. 
Only 21434 Dest. 
Only 21435 Dest. 
Only 21436 Dest. 
Only 21437 Dest. 
Only 21438 Dest. 
Only 21439 Dest. 
Only 21441 Dest. 
Only 21442 Dest. 
Only 21443 
The requested operation took 9,9472657 seconds.
------------------------------------------------------------------------

how to align text vertically center in android

In relative layout you need specify textview height:

android:layout_height="100dp"

Or specify lines attribute:

android:lines="3"

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

How to get DATE from DATETIME Column in SQL?

use the following

select sum(transaction_amount) from TransactionMaste
where Card_No = '123' and transaction_date = CONVERT(VARCHAR(10),GETDATE(),111)

or the following

select sum(transaction_amount) from TransactionMaste
where Card_No = '123' and transaction_date = CONVERT(VARCHAR(10), GETDATE(), 120)

Contain an image within a div?

object-fit, behaves like background-size, solving the issue of scaling images up and down to fit.

The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

snapshot of an image rendered with all the object-fit options

.cover img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    overflow: hidden;
}

Browser Support

There's no IE support, and support in Edge begins at v16, only for img element: https://caniuse.com/#search=object-fit

The bfred-it/object-fit-images polyfill works very well for me in IE11, tested on Browserstack: demo.


Alternative without polyfill using an image in SVG

For Edge pre v16, and ie9, ie10, ie11:

You can crop and scale any image using CSS object-fit and object-position. However, these properties are only supported in the latest version of MS Edge as well as all other modern browsers.

If you need to crop and scale an image in Internet Explorer and provide support back to IE9, you can do that by wrapping the image in an <svg>, and using the viewBox and preserveAspectRatio attributes to do what object-fit and object-position do.

http://www.sarasoueidan.com/blog/svg-object-fit/#summary-recap

(The author explains the technique thoroughly, and duplicating the detail here would be impractical.)

call a static method inside a class?

This is a very late response, but adds some detail on the previous answers

When it comes to calling static methods in PHP from another static method on the same class, it is important to differentiate between self and the class name.

Take for instance this code:

class static_test_class {
    public static function test() {
        echo "Original class\n";
    }

    public static function run($use_self) {
        if($use_self) {
            self::test();
        } else {
            $class = get_called_class();
            $class::test(); 
        }
    }
}

class extended_static_test_class extends static_test_class {
    public static function test() {
        echo "Extended class\n";
    }
}

extended_static_test_class::run(true);
extended_static_test_class::run(false);

The output of this code is:

Original class

Extended class

This is because self refers to the class the code is in, rather than the class of the code it is being called from.

If you want to use a method defined on a class which inherits the original class, you need to use something like:

$class = get_called_class();
$class::function_name(); 

Getting the last argument passed to a shell script

#! /bin/sh

next=$1
while [ -n "${next}" ] ; do
  last=$next
  shift
  next=$1
done

echo $last

CSS float right not working correctly

Verry Easy, change order of element:

Origin

<div style="">

    My Text

    <button type="button" style="float: right; margin:5px;">
       My Button
    </button>

</div>

Change to:

<div style=""> 

    <button type="button" style="float: right; margin:5px;">
       My Button
     </button>

   My Text

</div>

Convert timestamp to date in Oracle SQL

If the datatype is timestamp then the visible format is irrelevant.

You should avoid converting the data to date or use of to_char. Instead compare the timestamp data to timestamp values using TO_TIMESTAMP()

WHERE start_ts >= TO_TIMESTAMP('2016-05-13', 'YYYY-MM-DD')
   AND start_ts < TO_TIMESTAMP('2016-05-14', 'YYYY-MM-DD')

Finding duplicate values in MySQL

to get all the data that contains duplication i used this:

SELECT * FROM TableName INNER JOIN(
  SELECT DupliactedData FROM TableName GROUP BY DupliactedData HAVING COUNT(DupliactedData) > 1 order by DupliactedData)
  temp ON TableName.DupliactedData = temp.DupliactedData;

TableName = the table you are working with.

DupliactedData = the duplicated data you are looking for.

Arrays vs Vectors: Introductory Similarities and Differences

I'll add that arrays are very low-level constructs in C++ and you should try to stay away from them as much as possible when "learning the ropes" -- even Bjarne Stroustrup recommends this (he's the designer of C++).

Vectors come very close to the same performance as arrays, but with a great many conveniences and safety features. You'll probably start using arrays when interfacing with API's that deal with raw arrays, or when building your own collections.

Latest jQuery version on Google's CDN

Here's an updated link.

There are updated now and then, just keep checking for the latest version.

Console output in a Qt GUI app?

In your .pro add

CONFIG          += console

Excel formula to remove space between words in a cell

Suppose the data is in the B column, write in the C column the formula:

=SUBSTITUTE(B1," ","")

Copy&Paste the formula in the whole C column.

edit: using commas or semicolons as parameters separator depends on your regional settings (I have to use the semicolons). This is weird I think. Thanks to @tocallaghan and @pablete for pointing this out.

How to get pandas.DataFrame columns containing specific dtype

To get the column names from pandas dataframe in python3- Here I am creating a data frame from a fileName.csv file

>>> import pandas as pd
>>> df = pd.read_csv('fileName.csv')
>>> columnNames = list(df.head(0)) 
>>> print(columnNames)

How to unlock android phone through ADB

if the device is locked with black screen run the following:

  1. adb shell input keyevent 26 - this will turn screen on
  2. adb shell input keyevent 82 - this will unlock and ask for pin
  3. adb shell input text xxxx && adb shell input keyevent 66 - this will input your pin and press enter, unlocking device to home screen

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.

Including one C source file in another?

is it ok? yes, it will compile

is it recommended? no - .c files compile to .obj files, which are linked together after compilation (by the linker) into the executable (or library), so there is no need to include one .c file in another. What you probably want to do instead is to make a .h file that lists the functions/variables available in the other .c file, and include the .h file

Simplest way to throw an error/exception with a custom message in Swift 2?

Simplest solution without extra extensions, enums, classes and etc.:

NSException(name:NSExceptionName(rawValue: "name"), reason:"reason", userInfo:nil).raise()

Searching word in vim?

like this:

/\<word\>

\< means beginning of a word, and \> means the end of a word,

Adding @Roe's comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*' to search forward in the file or '#' to search backwards.

How to run multiple sites on one apache instance

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

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

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

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

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

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

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

NameVirtualHost *:80

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

Now your vhost definitions:

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

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

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

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

Getting the screen resolution using PHP

I found using CSS inside my html inside my php did the trick for me.

<?php             
    echo '<h2 media="screen and (max-width: 480px)">'; 
    echo 'My headline';
    echo '</h2>'; 

    echo '<h1 media="screen and (min-width: 481px)">'; 
    echo 'My headline';
    echo '</h1>'; 

    ?>

This will output a smaller sized headline if the screen is 480px or less. So no need to pass any vars using JS or similar.

Finding the average of an array using JS

It can simply be done with a single reduce operation as follows;

_x000D_
_x000D_
var avg = [1,2,3,4].reduce((p,c,_,a) => p + c/a.length,0);_x000D_
console.log(avg)
_x000D_
_x000D_
_x000D_

Table Naming Dilemma: Singular vs. Plural Names

There are different papers on both sites, I think that you only need to choose your side. Personally I prefer Plurar for tables naming, and of course singular for column naming.

I like how you can read this:

SELECT CustomerName FROM Customers WHERE CustomerID = 100;

Really we have OOP, and is great, but most people keep using Relational Databases, no Object Databases. There is no need to follow the OOP concepts for Relational Databases.

Another example, you have a table Teams, that keep TeamID, TeamColor but also PlayerID, and will have same teamID and TeamColor for certain amount of PlayerID...

To Which team the player belongs?

SELECT * FROM Teams WHERE PlayerID = X

All Players from X Team?

SELECT * FROM Players INNER JOIN Teams ON Players.PlayerID = Teams.PlayerID WHERE Teams.TeamID = X

All this sound good to you?

Anyways, also take a look to naming conventions used by W3Schools:

http://www.w3schools.com/sql/sql_join_inner.asp

Dynamically create Bootstrap alerts box through JavaScript

I found that AlertifyJS is a better alternative and have a Bootstrap theme.

alertify.alert('Alert Title', 'Alert Message!', function(){ alertify.success('Ok'); });

Also have a 4 components: Alert, Confirm, Prompt and Notifier.

Exmaple: JSFiddle

How to move the cursor word by word in the OS X Terminal

If you happen to be a Vim user, you could try bash's vim mode. Run this or put it in your ~/.bashrc file:

set -o vi

By default you're in insert mode; hit escape and you can move around just like you can in normal-mode Vim, so movement by word is w or b, and the usual movement keys also work.

Should Jquery code go in header or footer?

Put Scripts at the Bottom

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.

An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

EDIT: Firefox does support the DEFER attribute since version 3.6.

Sources:

how to merge 200 csv files in Python

Quite easy to combine all files in a directory and merge them

import glob
import csv


# Open result file
with open('output.txt','wb') as fout:
    wout = csv.writer(fout,delimiter=',') 
    interesting_files = glob.glob("*.csv") 
    h = True
    for filename in interesting_files: 
        print 'Processing',filename 
        # Open and process file
        with open(filename,'rb') as fin:
            if h:
                h = False
            else:
                fin.next()#skip header
            for line in csv.reader(fin,delimiter=','):
                wout.writerow(line)

Compiling an application for use in highly radioactive environments

Writing code for radioactive environments is not really any different than writing code for any mission-critical application.

In addition to what has already been mentioned, here are some miscellaneous tips:

  • Use everyday "bread & butter" safety measures that should be present on any semi-professional embedded system: internal watchdog, internal low-voltage detect, internal clock monitor. These things shouldn't even need to be mentioned in the year 2016 and they are standard on pretty much every modern microcontroller.

  • If you have a safety and/or automotive-oriented MCU, it will have certain watchdog features, such as a given time window, inside which you need to refresh the watchdog. This is preferred if you have a mission-critical real-time system.

  • In general, use a MCU suitable for these kind of systems, and not some generic mainstream fluff you received in a packet of corn flakes. Almost every MCU manufacturer nowadays have specialized MCUs designed for safety applications (TI, Freescale, Renesas, ST, Infineon etc etc). These have lots of built-in safety features, including lock-step cores: meaning that there are 2 CPU cores executing the same code, and they must agree with each other.

  • IMPORTANT: You must ensure the integrity of internal MCU registers. All control & status registers of hardware peripherals that are writeable may be located in RAM memory, and are therefore vulnerable.

    To protect yourself against register corruptions, preferably pick a microcontroller with built-in "write-once" features of registers. In addition, you need to store default values of all hardware registers in NVM and copy-down those values to your registers at regular intervals. You can ensure the integrity of important variables in the same manner.

    Note: always use defensive programming. Meaning that you have to setup all registers in the MCU and not just the ones used by the application. You don't want some random hardware peripheral to suddenly wake up.

  • There are all kinds of methods to check for errors in RAM or NVM: checksums, "walking patterns", software ECC etc etc. The best solution nowadays is to not use any of these, but to use a MCU with built-in ECC and similar checks. Because doing this in software is complex, and the error check in itself could therefore introduce bugs and unexpected problems.

  • Use redundancy. You could store both volatile and non-volatile memory in two identical "mirror" segments, that must always be equivalent. Each segment could have a CRC checksum attached.

  • Avoid using external memories outside the MCU.

  • Implement a default interrupt service routine / default exception handler for all possible interrupts/exceptions. Even the ones you are not using. The default routine should do nothing except shutting off its own interrupt source.

  • Understand and embrace the concept of defensive programming. This means that your program needs to handle all possible cases, even those that cannot occur in theory. Examples.

    High quality mission-critical firmware detects as many errors as possible, and then handles or ignores them in a safe manner.

  • Never write programs that rely on poorly-specified behavior. It is likely that such behavior might change drastically with unexpected hardware changes caused by radiation or EMI. The best way to ensure that your program is free from such crap is to use a coding standard like MISRA, together with a static analyser tool. This will also help with defensive programming and with weeding out bugs (why would you not want to detect bugs in any kind of application?).

  • IMPORTANT: Don't implement any reliance of the default values of static storage duration variables. That is, don't trust the default contents of the .data or .bss. There could be any amount of time between the point of initialization to the point where the variable is actually used, there could have been plenty of time for the RAM to get corrupted. Instead, write the program so that all such variables are set from NVM in run-time, just before the time when such a variable is used for the first time.

    In practice this means that if a variable is declared at file scope or as static, you should never use = to initialize it (or you could, but it is pointless, because you cannot rely on the value anyhow). Always set it in run-time, just before use. If it is possible to repeatedly update such variables from NVM, then do so.

    Similarly in C++, don't rely on constructors for static storage duration variables. Have the constructor(s) call a public "set-up" routine, which you can also call later on in run-time, straight from the caller application.

    If possible, remove the "copy-down" start-up code that initializes .data and .bss (and calls C++ constructors) entirely, so that you get linker errors if you write code relying on such. Many compilers have the option to skip this, usually called "minimal/fast start-up" or similar.

    This means that any external libraries have to be checked so that they don't contain any such reliance.

  • Implement and define a safe state for the program, to where you will revert in case of critical errors.

  • Implementing an error report/error log system is always helpful.

nginx 502 bad gateway

You can make nginx ignore client aborts using:

location / {
  proxy_ignore_client_abort on;
}

Center align a column in twitter bootstrap

With bootstrap 3 the best way to go about achieving what you want is ...with offsetting columns. Please see these examples for more detail:
http://getbootstrap.com/css/#grid-offsetting

In short, and without seeing your divs here's an example what might help, without using any custom classes. Just note how the "col-6" is used and how half of that is 3 ...so the "offset-3" is used. Splitting equally will allow the centered spacing you're going for:

<div class="container">
<div class="col-sm-6 col-sm-offset-3">
your centered, floating column
</div></div>

In C can a long printf statement be broken up into multiple lines?

If you want to break a string literal onto multiple lines, you can concatenate multiple strings together, one on each line, like so:

printf("name: %s\t"
"args: %s\t"
"value %d\t"
"arraysize %d\n", 
sp->name, 
sp->args, 
sp->value, 
sp->arraysize);

Using ng-click vs bind within link function of Angular Directive

I think it is fine because I've seen many people doing this way.

If you are just defining the event handler within the directive, you do not have to define it on the scope, though. Following would be fine.

myApp.directive('clickme', function() {
  return function(scope, element, attrs) {
    var clickingCallback = function() {
      alert('clicked!')
    };
    element.bind('click', clickingCallback);
  }
});

What order are the Junit @Before/@After called?

Yes, this behaviour is guaranteed:

@Before:

The @Before methods of superclasses will be run before those of the current class, unless they are overridden in the current class. No other ordering is defined.

@After:

The @After methods declared in superclasses will be run after those of the current class, unless they are overridden in the current class.

Xampp-mysql - "Table doesn't exist in engine" #1932

  • Copy the content of backups folder into data folder. This worked for me.
  • After this you have to reconfigure innodb files of your existent databases

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

Pandas DataFrame Groupby two columns and get counts

You can just use the built-in function count follow by the groupby function

df.groupby(['col5','col2']).count()

How to browse for a file in java swing library?

I ended up using this quick piece of code that did exactly what I needed:

final JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);

try {
    // Open an input stream
    Scanner reader = new Scanner(fc.getSelectedFile());
}

How to edit binary file on Unix systems

Bless is a high quality, full featured hex editor.

It is written in mono/Gtk# and its primary platform is GNU/Linux. However it should be able to run without problems on every platform that mono and Gtk# run. Main Features Bless currently provides the following features:

  • Efficient editing of large data files and block devices.
  • Multilevel undo - redo operations.
  • Customizable data views.
  • Fast data rendering on screen.
  • Multiple tabs.
  • Fast find and replace operations.
  • A data conversion table.
  • Advanced copy/paste capabilities.
  • Highlighting of selection pattern matches in the file.
  • Plugin based architecture.
  • Export of data to text and html (others with plugins).
  • Bitwise operations on data.
  • A comprehensive user manual.

copied from http://home.gna.org/bless/

How to serve an image using nodejs

It is too late but helps someone, I'm using node version v7.9.0 and express version 4.15.0

if your directory structure is something like this:

your-project
   uploads
   package.json
   server.js

server.js code:

var express         = require('express');
var app             = express();
app.use(express.static(__dirname + '/uploads'));// you can access image 
 //using this url: http://localhost:7000/abc.jpg
//make sure `abc.jpg` is present in `uploads` dir.

//Or you can change the directory for hiding real directory name:

`app.use('/images', express.static(__dirname+'/uploads/'));// you can access image using this url: http://localhost:7000/images/abc.jpg


app.listen(7000);

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

I sympathise with the question - I too found (find?) the choice bewildering, so I set out scientifically to see which data structure is the fastest (I did the test using VB, but I imagine C# would be the same, since both languages do the same thing at the CLR level). You can see some benchmarking results conducted by me here (there's also some discussion of which data type is best to use in which circumstances).

How to import csv file in PHP?

From the PHP manual:

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

How to get a list of sub-folders and their files, ordered by folder-names

Hej man, why are you using this ?

dir /s/b/o:gn > f.txt (wrong one)

Don't you know what is that 'g' in '/o' ??

Check this out: http://www.computerhope.com/dirhlp.htm or dir /? for dir help

You should be using this instead:

dir /s/b/o:n > f.txt (right one)

make sounds (beep) with c++

alternatively in c or c++ after including stdio.h

char d=(char)(7);
printf("%c\n",d);

(char)7 is called the bell character.

How to create a hash or dictionary object in JavaScript

Don't use an array if you want named keys, use a plain object.

var a = {};
a["key1"] = "value1";
a["key2"] = "value2";

Then:

if ("key1" in a) {
   // something
} else {
   // something else 
}

Prevent form redirect OR refresh on submit?

In the opening tag of your form, set an action attribute like so:

<form id="contactForm" action="#">

How to convert Blob to File in JavaScript

For me to work I had to explicitly provide the type although it is contained in the blob by doing so:

const file = new File([blob], 'untitled', { type: blob.type })

Forbidden :You don't have permission to access /phpmyadmin on this server

Find your IP address and replace where ever you see 127.0.0.1 with your workstation IP address you get from the link above.

. . .
Require ip your_workstation_IP_address
. . .
Allow from your_workstation_IP_address
. . .
Require ip your_workstation_IP_address
. . .
Allow from your_workstation_IP_address
. . .

and in the end don't forget to restart the server

sudo systemctl restart httpd.service

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT [UserID] FROM [User] u LEFT JOIN (
SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) t on t.TailUser=u.USerID

Upgrading PHP in XAMPP for Windows?

Take a backup of your htdocs and data folder (subfolder of MySQL folder), reinstall upgraded version and replace those folders.

Note: In case you have changed config files like PHP (php.ini), Apache (httpd.conf) or any other, please take back up of those files as well and replace them with newly installed version.

How can I setup & run PhantomJS on Ubuntu?

Install from package manager:

sudo apt-get install phantomjs

How to get object size in memory?

OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.

First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?

I had previously touched this subject in this article:

Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.

Changing cursor to waiting in javascript/jquery

In your jQuery use:

$("body").css("cursor", "progress");

and then back to normal again

$("body").css("cursor", "default");

Git reset single file in feature branch to be the same as in master

If you want to revert the file to its state in master:

git checkout origin/master [filename]

Hibernate: "Field 'id' doesn't have a default value"

Maybe that is the problem with the table schema. drop the table and rerun the application.

Set database from SINGLE USER mode to MULTI USER

You couldn't do that becouse database in single mode. Above all right but you should know that: when you opened the sql management studio it doesn't know any user on the database but when you click the database it consider you the single user and your command not working. Just do that: Close management studio and re open it. new query window without selecting any database write the command script.

USE [master];
GO
ALTER DATABASE [tuncayoto] SET MULTI_USER WITH NO_WAIT;
GO 

make f5 wolla everything ok !

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

Replacing instances of a character in a string

Turn the string into a list; then you can change the characters individually. Then you can put it back together with .join:

s = 'a;b;c;d'
slist = list(s)
for i, c in enumerate(slist):
    if slist[i] == ';' and 0 <= i <= 3: # only replaces semicolons in the first part of the text
        slist[i] = ':'
s = ''.join(slist)
print s # prints a:b:c;d

Expected response code 220 but got code "", with message "" in Laravel

This problem can generally occur when you do not enable two step verification for the gmail account (which can be done here) you are using to send an email. So first, enable two step verification, you can find plenty of resources for enabling two step verification. After you enable it, then you have to create an app password. And use the app password in your .env file. When you are done with it, your .env file will look something like.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<<your email address>>
MAIL_PASSWORD=<<app password>>
MAIL_ENCRYPTION=tls

and your mail.php

<?php

return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => env('MAIL_PORT', 587),
    'from' => ['address' => '<<your email>>', 'name' => '<<any name>>'],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => false,

];

After doing so, run php artisan config:cache and php artisan config:clear, then check, email should work.

Differences between cookies and sessions?

Sessions are server-side files that contain user information, while Cookies are client-side files that contain user information. Sessions have a unique identifier that maps them to specific users. This identifier can be passed in the URL or saved into a session cookie.

Most modern sites use the second approach, saving the identifier in a Cookie instead of passing it in a URL (which poses a security risk). You are probably using this approach without knowing it, and by deleting the cookies you effectively erase their matching sessions as you remove the unique session identifier contained in the cookies.

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

In my case, I was passsing all models 'Users' to column and it wasn't mapped correctly, so I just passed 'Users.Name' and it fixed it.

var data = db.ApplicationTranceLogs 
             .Include(q=>q.Users)
             .Include(q => q.LookupItems) 
             .Select(q => new { Id = q.Id, FormatDate = q.Date.ToString("yyyy/MM/dd"), ***Users = q.Users,*** ProcessType = q.ProcessType, CoreProcessId = q.CoreProcessId, Data = q.Data }) 
             .ToList();

var data = db.ApplicationTranceLogs 
             .Include(q=>q.Users).Include(q => q.LookupItems) 
             .Select(q => new { Id = q.Id, FormatDate = q.Date.ToString("yyyy/MM/dd"), ***Users = q.Users.Name***, ProcessType = q.ProcessType, CoreProcessId = q.CoreProcessId, Data = q.Data }) 
             .ToList();

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

No Such Element Exception?

Another situation which issues the same problem, map.entrySet().iterator().next()

If there is no element in the Map object, then the above code will return NoSuchElementException. Make sure to call hasNext() first.

TypeError: $(...).on is not a function

The problem may be if you are using older version of jQuery. Because older versions of jQuery have 'live' method instead of 'on'

Hide Command Window of .BAT file that Executes Another .EXE File

Create a .vbs file with this code:

CreateObject("Wscript.Shell").Run "your_batch.bat",0,True

This .vbs will run your_batch.bat hidden.

Works fine for me.

Serializing PHP object to JSON

Try using this, this worked fine for me.

json_encode(unserialize(serialize($array)));

Android appcompat v7:23

First you need to download the latest support repository (17 by the time I write this) from internal SDK manager of Android Studio or from the stand alone SDK manager. Then you can add compile 'com.android.support:appcompat-v7:23.0.0' or any other support library you want to your build.gradle file. (Don't forget the last .0)

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

You can get the raw data by calling ReadAsStringAsAsync on the Request.Content property.

string result = await Request.Content.ReadAsStringAsync();

There are various overloads if you want it in a byte or in a stream. Since these are async-methods you need to make sure your controller is async:

public async Task<IHttpActionResult> GetSomething()
{
    var rawMessage = await Request.Content.ReadAsStringAsync();
    // ...
    return Ok();
}

EDIT: if you're receiving an empty string from this method, it means something else has already read it. When it does that, it leaves the pointer at the end. An alternative method of doing this is as follows:

public IHttpActionResult GetSomething()
{
    var reader = new StreamReader(Request.Body);
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var rawMessage = reader.ReadToEnd();

    return Ok();
}

In this case, your endpoint doesn't need to be async (unless you have other async-methods)

Blocks and yields in Ruby

Yield can be used as nameless block to return a value in the method. Consider the following code:

Def Up(anarg)
  yield(anarg)
end

You can create a method "Up" which is assigned one argument. You can now assign this argument to yield which will call and execute an associated block. You can assign the block after the parameter list.

Up("Here is a string"){|x| x.reverse!; puts(x)}

When the Up method calls yield, with an argument, it is passed to the block variable to process the request.

RegEx match open tags except XHTML self-contained tags

I used a open source tool called HTMLParser before. It's designed to parse HTML in various ways and serves the purpose quite well. It can parse HTML as different treenode and you can easily use its API to get attributes out of the node. Check it out and see if this can help you.

How to use a class from one C# project with another C# project

To provide another much simpler solution:-

  1. Within the project, right click and select "Add -> Existing"
  2. Navigate to the class file in the adjacent project.
  3. The Add button is also a dropdown, click the dropdown and select

"Add as link"

Thats it.

How to return an array from a function?

It is not possible to return an array from a C++ function. 8.3.5[dcl.fct]/6:

Functions shall not have a return type of type array or function[...]

Most commonly chosen alternatives are to return a value of class type where that class contains an array, e.g.

struct ArrayHolder
{
    int array[10];
};

ArrayHolder test();

Or to return a pointer to the first element of a statically or dynamically allocated array, the documentation must indicate to the user whether he needs to (and if so how he should) deallocate the array that the returned pointer points to.

E.g.

int* test2()
{
    return new int[10];
}

int* test3()
{
    static int array[10];
    return array;
}

While it is possible to return a reference or a pointer to an array, it's exceedingly rare as it is a more complex syntax with no practical advantage over any of the above methods.

int (&test4())[10]
{
        static int array[10];
        return array;
}

int (*test5())[10]
{
        static int array[10];
        return &array;
}

How to fix "set SameSite cookie to none" warning?

I ended up fixing our Ubuntu 18.04 / Apache 2.4.29 / PHP 7.2 install for Chrome 80 by installing mod_headers:

a2enmod headers

Adding the following directive to our Apache VirtualHost configurations:

Header edit Set-Cookie ^(.*)$ "$1; Secure; SameSite=None"

And restarting Apache:

service apache2 restart

In reviewing the docs (http://www.balkangreenfoundation.org/manual/en/mod/mod_headers.html) I noticed the "always" condition has certain situations where it does not work from the same pool of response headers. Thus not using "always" is what worked for me with PHP but the docs suggest that if you want to cover all your bases you could add the directive both with and without "always". I have not tested that.

Converting stream of int's to char's in java

Most answers here propose shortcuts, which can bring you in big problems if you have no idea what you are doing. If you want to take shortcuts, then you have to know exactly what encoding your data is in.

UTF-16

Whenever java talks about characters in its documentation, it talks about 16-bit characters.

You can use a DataInputStream, which has convenient methods. For efficiency, wrap it in a BufferedReader.

// e.g. for sockets
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
char character = readChar(); // no need to cast

The thing is that each readChar() will actually perform 2 read's and combine them to one 16-bit character.

US-ASCII

US-ASCII reserves 8 bits to encode 1 character. The ASCII table only describes 128 possible characters though, so 1 bit is always unused.

You can simply perform a cast in this case.

int input = stream.read();
if (input < 0) throw new EOFException();
char character = (char) input;

Extended ASCII

UTF-8, Latin-1, ANSI and many other encodings use all 8-bits. The first 7-bit follow the ASCII table and are identical to the ones of the US-ASCII encoding. However, the 8th bit offers characters that are different in all these encodings. So, here things get interesting.

If you are a cowboy, and you think that the 8th bit does not matter (i.e. you don't care about characters like "à, é, ç, è, ô ...) then you can get away with a simple cast.

However, if you want to do this professionally, you should really ALWAYS specify a charset whenever you import/export text (e.g. sockets, files ...).

Always use charsets

Let's get serious. All the above options are cheap tricks. If you want to write flexible software you need to support a configurable charset to import/export your data. Here's a generic solution:

Read your data using a byte[] buffer and to convert that to a String using a charset parameter.

byte[] buffer = new byte[1024];
int nrOfBytes = stream.read(buffer);
String result = new String(buffer, nrOfBytes, charset);

You can also use an InputStreamReader which can be instantiated with a charset parameter.

Just one more golden rule: don't ever directly cast a byte to a character. That's always a mistake.

How do I tell matplotlib that I am done with a plot?

If you're using Matplotlib interactively, for example in a web application, (e.g. ipython) you maybe looking for

plt.show()

instead of plt.close() or plt.clf().

Cannot add a project to a Tomcat server in Eclipse

If you are able to see the project in Eclipse project explorer but unable to see the project while adding the project to the web server, follow project properties -> Project Facets, make sure Dynamic Web Module & Java were ticked.

AngularJS: ng-model not binding to ng-checked for checkboxes

You can use ng-value-true to tell angular that your ng-model is a string.

I could only get ng-true-value working if I added the extra quotes like so (as shown in the official Angular docs - https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D)

ng-true-value="'1'"

VMware Workstation and Device/Credential Guard are not compatible

I also struggled a lot with this issue. The answers in this thread were helpful but were not enough to resolve my error. You will need to disable Hyper-V and Device guard like the other answers have suggested. More info on that can be found in here.

I am including the changes needed to be done in addition to the answers provided above. The link that finally helped me was this.

My answer is going to summarize only the difference between the rest of the answers (i.e. Disabling Hyper-V and Device guard) and the following steps :

  1. If you used Group Policy, disable the Group Policy setting that you used to enable Windows Defender Credential Guard (Computer Configuration -> Administrative Templates -> System -> Device Guard -> Turn on Virtualization Based Security).
  2. Delete the following registry settings:

    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\LsaCfgFlags HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\DeviceGuard\EnableVirtualizationBasedSecurity HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\DeviceGuard\RequirePlatformSecurityFeatures

    Important : If you manually remove these registry settings, make sure to delete them all. If you don't remove them all, the device might go into BitLocker recovery.

  3. Delete the Windows Defender Credential Guard EFI variables by using bcdedit. From an elevated command prompt(start in admin mode), type the following commands:

     mountvol X: /s
    
     copy %WINDIR%\System32\SecConfig.efi X:\EFI\Microsoft\Boot\SecConfig.efi /Y
    
     bcdedit /create {0cb3b571-2f2e-4343-a879-d86a476d7215} /d "DebugTool" /application osloader
    
     bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} path "\EFI\Microsoft\Boot\SecConfig.efi"
    
     bcdedit /set {bootmgr} bootsequence {0cb3b571-2f2e-4343-a879-d86a476d7215}
    
     bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} loadoptions DISABLE-LSA-ISO
    
     bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} device partition=X:
    
     mountvol X: /d
    
  4. Restart the PC.

  5. Accept the prompt to disable Windows Defender Credential Guard.

  6. Alternatively, you can disable the virtualization-based security features to turn off Windows Defender Credential Guard.

How to implement onBackPressed() in Fragments?

   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
    {
       if ((keyCode == KeyEvent.KEYCODE_BACK))
  {
           finish();
    }
       return super.onKeyDown(keyCode, event);
    }

Just Comment Any Key down related method now addToBackStack will work . thanks

cmd line rename file with date and time

problem in %time:~0,2% can't set to 24 hrs format, ended with space(1-9), instead of 0(1-9)

go around with:

set HR=%time:~0,2%

set HR=%Hr: =0% (replace space with 0 if any <has a space in between : =0>)

then replace %time:~0,2% with %HR%

good luck

How do I connect to this localhost from another computer on the same network?

On Mac OS X:

  1. In terminal, run ifconfig | grep 192. to get the internal IP of your machine on it's current network. It may be something like 192.168.1.140

  2. Start a server. For example, node server.js may start a server on some port.

  3. On your phone, visit 192.168.1.140:3000 or whatever port your server is running on.

Return anonymous type results?

Just select dogs, then use dog.Breed.BreedName, this should work fine.

If you have a lot of dogs, use DataLoadOptions.LoadWith to reduce the number of db calls.

Convert string to symbol-able in ruby

Rails got ActiveSupport::CoreExtensions::String::Inflections module that provides such methods. They're all worth looking at. For your example:

'Book Author Title'.parameterize.underscore.to_sym # :book_author_title

convert php date to mysql format

function my_date_parse($date)
{
        if (!preg_match('/^(\d+)\.(\d+)\.(\d+)$/', $date, $m))
                return false;

        $day = $m[1];
        $month = $m[2];
        $year = $m[3];

        if (!checkdate($month, $day, $year))
                return false;

        return "$year-$month-$day";
}

Hashset vs Treeset

1.HashSet allows null object.

2.TreeSet will not allow null object. If you try to add null value it will throw a NullPointerException.

3.HashSet is much faster than TreeSet.

e.g.

 TreeSet<String> ts = new TreeSet<String>();
 ts.add(null); // throws NullPointerException

 HashSet<String> hs = new HashSet<String>();
 hs.add(null); // runs fine

How to redirect to a 404 in Rails?

routes.rb
  get '*unmatched_route', to: 'main#not_found'

main_controller.rb
  def not_found
    render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
  end

How to write dynamic variable in Ansible playbook

I am sure there is a smarter way for doing what you want but this should work:

- name         : Test var
  hosts        : all
  gather_facts : no
  vars:
    myvariable : false
  tasks:
    - name: param1
      set_fact:
        myvariable: "{{param1}}"
      when: param1 is defined

    - name: param2
      set_fact:
        myvariable: "{{ param2 if not myvariable else myvariable + ',' + param2 }}"
      when: param2 is defined

    - name: param3
      set_fact:
        myvariable: "{{ param3 if not myvariable else myvariable + ',' + param3 }}"
      when: param3 is defined

    - name: default
      set_fact:
        myvariable: "default"
      when: not myvariable

    - debug:
       var=myvariable

Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible

Align div right in Bootstrap 3

The class pull-right is still there in Bootstrap 3 See the 'helper classes' here

pull-right is defined by

.pull-right {
  float: right !important;
}

without more info on styles and content, it's difficult to say.

It definitely pulls right in this JSBIN when the page is wider than 990px - which is when the col-md styling kicks in, Bootstrap 3 being mobile first and all.

Bootstrap 4

Note that for Bootstrap 4 .pull-right has been replaced with .float-right https://www.geeksforgeeks.org/pull-left-and-pull-right-classes-in-bootstrap-4/#:~:text=pull%2Dright%20classes%20have%20been,based%20on%20the%20Bootstrap%20Grid.

VBA Convert String to Date

I used this code:

ws.Range("A:A").FormulaR1C1 = "=DATEVALUE(RC[1])"

column A will be mm/dd/yyyy

RC[1] is column B, the TEXT string, eg, 01/30/12, THIS IS NOT DATE TYPE

Automating running command on Linux from Windows using PuTTY

There could be security issues with common methods for auto-login. One of the most easiest ways is documented below:

And as for the part the executes the command In putty UI, Connection>SSH> there's a field for remote command.

4.17 The SSH panel

The SSH panel allows you to configure options that only apply to SSH sessions.

4.17.1 Executing a specific command on the server

In SSH, you don't have to run a general shell session on the server. Instead, you can choose to run a single specific command (such as a mail user agent, for example). If you want to do this, enter the command in the "Remote command" box. http://the.earth.li/~sgtatham/putty/0.53/htmldoc/Chapter4.html

in short, your answers might just as well be similar to the text below:

C# Switch-case string starting with

This is now possible with C# 7.0's pattern matching. For example:

var myString = "abcDEF";

switch(myString)
{
    case string x when x.StartsWith("abc"):
        //Do something here
        break;
}

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

How to quit android application programmatically

First of all, this approach requires min Api 16.

I will divide this solution to 3 parts to solve this problem more widely.

1. If you want to quit application in an Activity use this code snippet:

if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
    finishAffinity();
} else if(Build.VERSION.SDK_INT>=21){
    finishAndRemoveTask();
}

2. If you want to quit the application in a non Activity class which has access to Activity then use this code snippet:

if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
    getActivity().finishAffinity();
} else if(Build.VERSION.SDK_INT>=21){
    getActivity().finishAndRemoveTask();
}

3. If you want to quit the application in a non Activity class and cannot access to Activity such as Service I recommend you to use BroadcastReceiver. You can add this approach to all of your Activities in your project.

Create LocalBroadcastManager and BroadcastReceiver instance variables. You can replace getPackageName()+".closeapp" if you want to.

LocalBroadcastManager mLocalBroadcastManager;
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(getPackageName()+".closeapp")){
            if(Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT<21){
                finishAffinity();
            } else if(Build.VERSION.SDK_INT>=21){
                finishAndRemoveTask();
            }
        }
    }
};

Add these to onCreate() method of Activity.

mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(getPackageName()+".closeapp");
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, mIntentFilter);

Also, don't forget to call unregister receiver at onDestroy() method of Activity

mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);

For quit application, you must send broadcast using LocalBroadcastManager which I use in my PlayService class which extends Service.

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(PlayService.this);
localBroadcastManager.sendBroadcast(new Intent(getPackageName() + ".closeapp"));

Setting up SSL on a local xampp/apache server

I did most of the suggested stuff here, still didnt work. Tried this and it worked: Open your XAMPP Control Panel, locate the Config button for the Apache module. Click on the Config button and Select PHP (php.ini). Open with any text editor and remove the semi-column before php_openssl. Save and Restart Apache. That should do!

Capitalize words in string

Ivo's answer is good, but I prefer to not match on \w because there's no need to capitalize 0-9 and A-Z. We can ignore those and only match on a-z.

'your string'.replace(/\b[a-z]/g, match => match.toUpperCase())
// => 'Your String'

It's the same output, but I think clearer in terms of self-documenting code.

Cannot declare instance members in a static class in C#

It says what it means:

make your class non-static:

public class employee
{
  NameValueCollection appSetting = ConfigurationManager.AppSettings;    
}

or the member static:

public static class employee
{
  static NameValueCollection appSetting = ConfigurationManager.AppSettings;    
}

How to get Activity's content view?

You can get the view Back if you put an ID to your Layout.

<RelativeLayout
    android:id="@+id/my_relative_layout_id"

And call it from findViewById ...

How to refresh materialized view in oracle

Try using the below syntax:

Common Syntax:

begin
dbms_mview.refresh('mview_name');
end;

Example:

begin
dbms_mview.refresh('inv_trans');
end;

Hope the above helps.

RESTful URL design for search

RESTful does not recommend using verbs in URL's /cars/search is not restful. The right way to filter/search/paginate your API's is through Query Parameters. However there might be cases when you have to break the norm. For example, if you are searching across multiple resources, then you have to use something like /search?q=query

You can go through http://saipraveenblog.wordpress.com/2014/09/29/rest-api-best-practices/ to understand the best practices for designing RESTful API's

sendmail: how to configure sendmail on ubuntu?

When you typed in sudo sendmailconfig, you should have been prompted to configure sendmail.

For reference, the files that are updated during configuration are located at the following (in case you want to update them manually):

/etc/mail/sendmail.conf
/etc/cron.d/sendmail
/etc/mail/sendmail.mc

You can test sendmail to see if it is properly configured and setup by typing the following into the command line:

$ echo "My test email being sent from sendmail" | /usr/sbin/sendmail [email protected]

The following will allow you to add smtp relay to sendmail:

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

Add the following lines to sendmail.mc, but before the MAILERDEFINITIONS. Make sure you update your smtp server.

define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/auth/client-info.db')dnl

Invoke creation sendmail.cf (alternatively run make -C /etc/mail):

m4 sendmail.mc > sendmail.cf

Restart the sendmail daemon:

service sendmail restart

R dates "origin" must be supplied

My R use 1970-01-01:

>as.Date(15103, origin="1970-01-01")
[1] "2011-05-09"

and this matches the calculation from

>as.numeric(as.Date(15103, origin="1970-01-01"))

How to include scripts located inside the node_modules folder?

To use multiple files from node_modules in html, the best way I've found is to put them to an array and then loop on them to make them visible for web clients, for example to use filepond modules from node_modules:

const filePondModules = ['filepond-plugin-file-encode', 'filepond-plugin-image-preview', 'filepond-plugin-image-resize', 'filepond']
filePondModules.forEach(currentModule => {
    let module_dir = require.resolve(currentModule)
                           .match(/.*\/node_modules\/[^/]+\//)[0];
    app.use('/' + currentModule, express.static(module_dir + 'dist/'));
})

And then in the html (or layout) file, just call them like this :

    <link rel="stylesheet" href="/filepond/filepond.css">
    <link rel="stylesheet" href="/filepond-plugin-image-preview/filepond-plugin-image-preview.css">
...
    <script src="/filepond-plugin-image-preview/filepond-plugin-image-preview.js" ></script>
    <script src="/filepond-plugin-file-encode/filepond-plugin-file-encode.js"></script>
    <script src="/filepond-plugin-image-resize/filepond-plugin-image-resize.js"></script>
    <script src="/filepond/filepond.js"></script>

MySQL ORDER BY rand(), name ASC

Use a subquery:

SELECT * FROM 
(
    SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name 

The inner query selects 20 users at random and the outer query orders the selected users by name.

How can I specify system properties in Tomcat configuration on startup?

This question is addressed in the Apache wiki.

Question: "Can I set Java system properties differently for each webapp?"

Answer: No. If you can edit Tomcat's startup scripts (or better create a setenv.sh file), you can add "-D" options to Java. But there is no way in Java to have different values of system properties for different classes in the same JVM. There are some other methods available, like using ServletContext.getContextPath() to get the context name of your web application and locate some resources accordingly, or to define elements in WEB-INF/web.xml file of your web application and then set the values for them in Tomcat context file (META-INF/context.xml). See http://tomcat.apache.org/tomcat-7.0-doc/config/context.html .

http://wiki.apache.org/tomcat/HowTo#Can_I_set_Java_system_properties_differently_for_each_webapp.3F

What's the difference between IFrame and Frame?

Inline frame is just one "box" and you can place it anywhere on your site. Frames are a bunch of 'boxes' put together to make one site with many pages.

Find indices of elements equal to zero in a NumPy array

numpy.where() is my favorite.

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.where(x == 0)[0]
array([1, 3, 5])

Detect if an element is visible with jQuery

You're looking for:

.is(':visible')

Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code
}

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.


Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {
    $('#testElement').fadeToggle('fast');
}

Reading InputStream as UTF-8

Solved my own problem. This line:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

needs to be:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

or since Java 7:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

Setting background colour of Android layout element

You can use android:background="#DC143C", or any other RGB values for your color. I have no problem using it this way, as stated here

How can I force division to be floating point? Division keeps rounding down to 0?

Add a dot (.) to indicate floating point numbers

>>> 4/3.
1.3333333333333333

sys.argv[1] meaning in script

To pass arguments to your python script while running a script via command line

python create_thumbnail.py test1.jpg test2.jpg

here, script name - create_thumbnail.py, argument 1 - test1.jpg, argument 2 - test2.jpg

With in the create_thumbnail.py script i use

sys.argv[1:]

which give me the list of arguments i passed in command line as ['test1.jpg', 'test2.jpg']

How do I vertically align text in a paragraph?

Alternative solution which scales for multi-line text:

Set vertical and horizontal padding to be (height - line-height) / 2

p.event_desc {
    font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
    line-height: 14px;
    padding: 10.5px 0;
    margin: 0px;
}

PHP - Fatal error: Unsupported operand types

I had a similar error with the following code:-

foreach($myvar as $key => $value){
    $query = "SELECT stuff
            FROM table
            WHERE col1 = '$criteria1'
            AND col2 = '$criteria2'";

    $result = mysql_query($query) or die('Could not execute query - '.mysql_error(). __FILE__. __LINE__. $query);               
    $point_values = mysql_fetch_assoc($result);
    $top_five_actions[$key] += $point_values; //<--- Problem Line       
}

It turned out that my $point_values variable was occasionally returning false which caused the problem so I fixed it by wrapping it in mysql_num_rows check:-

if(mysql_num_rows($result) > 0) {
        $point_values = mysql_fetch_assoc($result);
        $top_five_actions[$key] += $point_values;
}

Not sure if this helps though?

Cheers

Jquery change <p> text programmatically

It seems you have the click event wrapped around a custom event name "pageinit", are you sure you're triggered the event before you click the button?

something like this:

$("#gender").trigger("pageinit");

How to create an empty array in Swift?

var myArr1 = [AnyObject]()

can store any object

var myArr2 = [String]()

can store only string

How to edit a JavaScript alert box title?

There's quite a nice 'hack' here - https://stackoverflow.com/a/14565029 where you use an iframe with an empty src to generate the alert / confirm message - it doesn't work on Android (for security's sake) - but may suit your scenario.

How to find the type of an object in Go?

If we have this variables:

var counter int = 5
var message string  = "Hello"
var factor float32 = 4.2
var enabled bool = false

1: fmt.Printf %T format : to use this feature you should import "fmt"

fmt.Printf("%T \n",factor )   // factor type: float32

2: reflect.TypeOf function : to use this feature you should import "reflect"

fmt.Println(reflect.TypeOf(enabled)) // enabled type:  bool

3: reflect.ValueOf(X).Kind() : to use this feature you should import "reflect"

fmt.Println(reflect.ValueOf(counter).Kind()) // counter type:  int

How to Set JPanel's Width and Height?

please, something went xxx*x, and that's not true at all, check that

JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]

code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )

EDIT: forget setDefaultCloseOperation()

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class FrameSize {

    private JFrame frm = new JFrame();
    private JPanel pnl = new JPanel();
    private JButton btn = new JButton("Get ScreenSize for JComponents");

    public FrameSize() {
        btn.setPreferredSize(new Dimension(400, 40));
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("JButton Size - " + btn.getSize());
                System.out.println("JPanel Size - " + pnl.getSize());
                System.out.println("JFrame Size - " + frm.getSize());
            }
        });
        pnl.setPreferredSize(new Dimension(640, 480));
        pnl.add(btn, BorderLayout.SOUTH);
        frm.add(pnl, BorderLayout.CENTER);
        frm.setLocation(150, 100);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
        frm.setResizable(false);
        frm.pack();
        frm.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FrameSize fS = new FrameSize();
            }
        });
    }
}

Decode HTML entities in Python string?

I had a similar encoding issue. I used the normalize() method. I was getting a Unicode error using the pandas .to_html() method when exporting my data frame to an .html file in another directory. I ended up doing this and it worked...

    import unicodedata 

The dataframe object can be whatever you like, let's call it table...

    table = pd.DataFrame(data,columns=['Name','Team','OVR / POT'])
    table.index+= 1

encode table data so that we can export it to out .html file in templates folder(this can be whatever location you wish :))

     #this is where the magic happens
     html_data=unicodedata.normalize('NFKD',table.to_html()).encode('ascii','ignore')

export normalized string to html file

    file = open("templates/home.html","w") 

    file.write(html_data) 

    file.close() 

Reference: unicodedata documentation

R Markdown - changing font size and font type in html output

I would definitely use html markers to achieve this. Just surround your text with <p></p> or <font></font> and add the desired attributes. See the following example:

<p style="font-family: times, serif; font-size:11pt; font-style:italic">
    Why did we use these specific parameters during the calculation of the fingerprints?
</p>

This will produce the following output

Font Output

compared to

Default Output

This would work with Jupyter Notebook as well as Typora, but I'm not sure if it is universal.

Lastly, be aware that the html marker overrides the font styling used by Markdown.

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

It's a pity that both of the answers analyze the problem but didn't give a direct answer. Let's see the code.

Z = np.array([1.0, 1.0, 1.0, 1.0])  

def func(TempLake, Z):
    A = TempLake
    B = Z
    return A * B
Nlayers = Z.size
N = 3
TempLake = np.zeros((N+1, Nlayers))
kOUT = np.zeros(N + 1)

for i in xrange(N):
    # store the i-th result of
    # function "func" in i-th item in kOUT
    kOUT[i] = func(TempLake[i], Z)

The error shows that you set the ith item of kOUT(dtype:int) into an array. Here every item in kOUT is an int, can't directly assign to another datatype. Hence you should declare the data type of kOUT when you create it. For example, like:

Change the statement below:

kOUT = np.zeros(N + 1)

into:

kOUT = np.zeros(N + 1, dtype=object)

or:

kOUT = np.zeros((N + 1, N + 1))

All code:

import numpy as np
Z = np.array([1.0, 1.0, 1.0, 1.0])

def func(TempLake, Z):
    A = TempLake
    B = Z
    return A * B

Nlayers = Z.size
N = 3
TempLake = np.zeros((N + 1, Nlayers))

kOUT = np.zeros(N + 1, dtype=object)
for i in xrange(N):
    kOUT[i] = func(TempLake[i], Z)

Hope it can help you.

Problem in running .net framework 4.0 website on iis 7.0

In our case the solution to this problem did not involve the "ISAPI and CGI Restrictions" settings. The error started occuring after operations staff had upgraded the server to .NET 4.5 by accident, then downgraded to .NET 4.0 again. This caused some of the IIS websites to forget their respective correct application pools, and it caused some of the application pools to switch from .NET Framework 4.0 to 2.0. Changing these settings back fixed the problem.

How can I use std::maps with user-defined types as key?

I'd like to expand a little bit on Pavel Minaev's answer, which you should read before reading my answer. Both solutions presented by Pavel won't compile if the member to be compared (such as id in the question's code) is private. In this case, VS2013 throws the following error for me:

error C2248: 'Class1::id' : cannot access private member declared in class 'Class1'

As mentioned by SkyWalker in the comments on Pavel's answer, using a friend declaration helps. If you wonder about the correct syntax, here it is:

class Class1
{
public:
    Class1(int id) : id(id) {}

private:
    int id;
    friend struct Class1Compare;      // Use this for Pavel's first solution.
    friend struct std::less<Class1>;  // Use this for Pavel's second solution.
};

Code on Ideone

However, if you have an access function for your private member, for example getId() for id, as follows:

class Class1
{
public:
    Class1(int id) : id(id) {}
    int getId() const { return id; }

private:
    int id;
};

then you can use it instead of a friend declaration (i.e. you compare lhs.getId() < rhs.getId()). Since C++11, you can also use a lambda expression for Pavel's first solution instead of defining a comparator function object class. Putting everything together, the code could be writtem as follows:

auto comp = [](const Class1& lhs, const Class1& rhs){ return lhs.getId() < rhs.getId(); };
std::map<Class1, int, decltype(comp)> c2int(comp);

Code on Ideone

range() for floats

A simpler library-less version

Aw, heck -- I'll toss in a simple library-less version. Feel free to improve on it[*]:

def frange(start=0, stop=1, jump=0.1):
    nsteps = int((stop-start)/jump)
    dy = stop-start
    # f(i) goes from start to stop as i goes from 0 to nsteps
    return [start + float(i)*dy/nsteps for i in range(nsteps)]

The core idea is that nsteps is the number of steps to get you from start to stop and range(nsteps) always emits integers so there's no loss of accuracy. The final step is to map [0..nsteps] linearly onto [start..stop].

edit

If, like alancalvitti you'd like the series to have exact rational representation, you can always use Fractions:

from fractions import Fraction

def rrange(start=0, stop=1, jump=0.1):
    nsteps = int((stop-start)/jump)
    return [Fraction(i, nsteps) for i in range(nsteps)]

[*] In particular, frange() returns a list, not a generator. But it sufficed for my needs.

Python BeautifulSoup extract text between element

Use .children instead:

from bs4 import NavigableString, Comment
print ''.join(unicode(child) for child in hit.children 
    if isinstance(child, NavigableString) and not isinstance(child, Comment))

Yes, this is a bit of a dance.

Output:

>>> for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
...     print ''.join(unicode(child) for child in hit.children 
...         if isinstance(child, NavigableString) and not isinstance(child, Comment))
... 




      THIS IS MY TEXT

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

I am using ASP.NET with IIS and it turns out I just needed to add the MIME-type to IIS: '.woff2' / 'application/font-woff'

Java: how to add image to Jlabel?

(If you are using NetBeans IDE) Just create a folder in your project but out side of src folder. Named the folder Images. And then put the image into the Images folder and write code below.

// Import ImageIcon     
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);

Now run your program.