Programs & Examples On #Configurationmanager

In the .Net framework, ConfigurationManager is a built-in object that provides access to configuration files.

SCCM 2012 application install "Failed" in client Software Center

The execmgr.log will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log and some clients will have outdated appenforce or no ppenforce.log files. execmgr.log also shows required hidden uninstall actions as well.

You may want to save the blog link. I still reference it from time to time.

How to get the values of a ConfigurationSection of type NameValueSectionHandler

Suffered from exact issue. Problem was because of NameValueSectionHandler in .config file. You should use AppSettingsSection instead:

<configuration>

 <configSections>
    <section  name="DEV" type="System.Configuration.AppSettingsSection" />
    <section  name="TEST" type="System.Configuration.AppSettingsSection" />
 </configSections>

 <TEST>
    <add key="key" value="value1" />
 </TEST>

 <DEV>
    <add key="key" value="value2" />
 </DEV>

</configuration>

then in C# code:

AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");

btw NameValueSectionHandler is not supported any more in 2.0.

AppSettings get value from .config file

See I did what I thought was the obvious thing was:

string filePath = ConfigurationManager.AppSettings.GetValues("ClientsFilePath").ToString();

While that compiles it always returns null.

This however (from above) works:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

How to check if an appSettings key exists?

Using the new c# syntax with TryParse worked well for me:

  // TimeOut
  if (int.TryParse(ConfigurationManager.AppSettings["timeOut"], out int timeOut))
  {
     this.timeOut = timeOut;
  }

How to find path of active app.config file?

Strictly speaking, there is no single configuration file. Excluding ASP.NET1 there can be three configuration files using the inbuilt (System.Configuration) support. In addition to the machine config: app.exe.config, user roaming, and user local.

To get the "global" configuration (exe.config):

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                    .FilePath

Use different ConfigurationUserLevel values for per-use roaming and non-roaming configuration files.


1 Which has a completely different model where the content of a child folders (IIS-virtual or file system) web.config can (depending on the setting) add to or override the parent's web.config.

ConfigurationManager.AppSettings - How to modify and save?

Prefer <appSettings> to <customUserSetting> section. It is much easier to read AND write with (Web)ConfigurationManager. ConfigurationSection, ConfigurationElement and ConfigurationElementCollection require you to derive custom classes and implement custom ConfigurationProperty properties. Way too much for mere everyday mortals IMO.

Here is an example of reading and writing to web.config:

using System.Web.Configuration;
using System.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
string oldValue = config.AppSettings.Settings["SomeKey"].Value;
config.AppSettings.Settings["SomeKey"].Value = "NewValue";
config.Save(ConfigurationSaveMode.Modified);

Before:

<appSettings>
  <add key="SomeKey" value="oldValue" />
</appSettings>

After:

<appSettings>
  <add key="SomeKey" value="newValue" />
</appSettings>

How to run a shell script in OS X by double-clicking?

No need to use third-party apps such as Platypus.

Just create an Apple Script with Script Editor and use the command do shell script "shell commands" for direct command calls or executable shell script files, keep the editable script file safe somewhere then export it to create an Application script. the app script is launch-able by double click or selection in bar folder.

Should I use 'border: none' or 'border: 0'?

Both are valid. It's your choice.

I prefer border:0 because it's shorter; I find that easier to read. You may find none more legible. We live in a world of very capable CSS post-processors so I'd recommend you use whatever you prefer and then run it through a "compressor". There's no holy war worth fighting here but Webpack?LESS?PostCSS?PurgeCSS is a good 2020 stack.

That all said, if you're hand-writing all your production CSS, I maintain —despite the grumbling in the comments— it does not hurt to be bandwidth conscious. Using border:0 will save an infinitesimal amount of bandwidth on its own, but if you make every byte count, you will make your website faster.


The CSS2 specs are here. These are extended in CSS3 but not in any way relevant to this.

'border'
    Value:      [ <border-width> || <border-style> || <'border-top-color'> ] | inherit
    Initial:    see individual properties
    Applies to:     all elements
    Inherited:      no
    Percentages:    N/A
    Media:      visual
    Computed value:     see individual properties 

You can use any combination of width, style and colour.
Here, 0 sets the width, none the style. They have the same rendering result: nothing is shown.

do <something> N times (declarative syntax)

If you can't use Underscorejs, you can implement it yourself. By attaching new methods to the Number and String prototypes, you could do it like this (using ES6 arrow functions):

// With String
"5".times( (i) => console.log("number "+i) );

// With number variable
var five = 5;
five.times( (i) => console.log("number "+i) );

// With number literal (parentheses required)
(5).times( (i) => console.log("number "+i) );

You simply have to create a function expression (of whatever name) and assign it to whatever property name (on the prototypes) you would like to access it as:

var timesFunction = function(callback) {
  if (typeof callback !== "function" ) {
    throw new TypeError("Callback is not a function");
  } else if( isNaN(parseInt(Number(this.valueOf()))) ) {
    throw new TypeError("Object is not a valid number");
  }
  for (var i = 0; i < Number(this.valueOf()); i++) {
    callback(i);
  }
};

String.prototype.times = timesFunction;
Number.prototype.times = timesFunction;

Difference between Dictionary and Hashtable

Lets give an example that would explain the difference between hashtable and dictionary.

Here is a method that implements hashtable

public void MethodHashTable()
{
    Hashtable objHashTable = new Hashtable();
    objHashTable.Add(1, 100);    // int
    objHashTable.Add(2.99, 200); // float
    objHashTable.Add('A', 300);  // char
    objHashTable.Add("4", 400);  // string

    lblDisplay1.Text = objHashTable[1].ToString();
    lblDisplay2.Text = objHashTable[2.99].ToString();
    lblDisplay3.Text = objHashTable['A'].ToString();
    lblDisplay4.Text = objHashTable["4"].ToString();


    // ----------- Not Possible for HashTable ----------
    //foreach (KeyValuePair<string, int> pair in objHashTable)
    //{
    //    lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
    //}
}

The following is for dictionary

  public void MethodDictionary()
  {
    Dictionary<string, int> dictionary = new Dictionary<string, int>();
    dictionary.Add("cat", 2);
    dictionary.Add("dog", 1);
    dictionary.Add("llama", 0);
    dictionary.Add("iguana", -1);

    //dictionary.Add(1, -2); // Compilation Error

    foreach (KeyValuePair<string, int> pair in dictionary)
    {
        lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
    }
  }

How can I add a PHP page to WordPress?

Apart from creating a custom template file and assigning that template to a page (like in the example in the accepted answer), there is also a way with the template naming convention that WordPress uses for loading templates (template hierarchy).

Create a new page and use the slug of that page for the template filename (create a template file named page-{slug}.php). WordPress will automatically load the template that fits to this rule.

How to use Python's "easy_install" on Windows ... it's not so easy

For one thing, it says you already have that module installed. If you need to upgrade it, you should do something like this:

easy_install -U packageName

Of course, easy_install doesn't work very well if the package has some C headers that need to be compiled and you don't have the right version of Visual Studio installed. You might try using pip or distribute instead of easy_install and see if they work better.

Forking vs. Branching in GitHub

It has to do with the general workflow of Git. You're unlikely to be able to push directly to the main project's repository. I'm not sure if GitHub project's repository support branch-based access control, as you wouldn't want to grant anyone the permission to push to the master branch for example.

The general pattern is as follows:

  • Fork the original project's repository to have your own GitHub copy, to which you'll then be allowed to push changes.
  • Clone your GitHub repository onto your local machine
  • Optionally, add the original repository as an additional remote repository on your local repository. You'll then be able to fetch changes published in that repository directly.
  • Make your modifications and your own commits locally.
  • Push your changes to your GitHub repository (as you generally won't have the write permissions on the project's repository directly).
  • Contact the project's maintainers and ask them to fetch your changes and review/merge, and let them push back to the project's repository (if you and them want to).

Without this, it's quite unusual for public projects to let anyone push their own commits directly.

Is a Python dictionary an example of a hash table?

Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.

That's why you can't use something 'not hashable' as a dict key, like a list:

>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable

You can read more about hash tables or check how it has been implemented in python and why it is implemented that way.

How to write a full path in a batch file having a folder name with space?

start "" AcroRd32.exe /A "page=207" "C:\Users\abc\Desktop\abc xyz def\abc def xyz 2015.pdf"

You may try this, I did it finally, it works!

How do I read / convert an InputStream into a String in Java?

Here's more-or-less sampath's answer, cleaned up a bit and represented as a function:

String streamToString(InputStream in) throws IOException {
  StringBuilder out = new StringBuilder();
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  for(String line = br.readLine(); line != null; line = br.readLine()) 
    out.append(line);
  br.close();
  return out.toString();
}

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

Use file_put_contents()

file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo

Alternatively, if you're stuck with fopen() you can use the w or w+ modes:

'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

jQuery: how to change title of document during .ready()?

<script type="text/javascript">
$(document).ready(function() {

    $(this).attr("title", "sometitle");

});
</script>

Passing null arguments to C# methods

Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?

e.g.

private void Example(int? arg1, int? arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}

convert float into varchar in SQL server without scientific notation

I have another solution since the STR() function would result some blank spaces, so I use the FORMAT() function as folowing example:

SELECT ':' + STR(1000.2324422), ':' + FORMAT(1000.2324422,'##.#######'), ':' + FORMAT(1000.2324422,'##')

The result of above code would be:

:      1000 :1000.2324422   :1000

How to pass json POST data to Web API method as an object?

Make sure that your WebAPI service is expecting a strongly typed object with a structure that matches the JSON that you are passing. And make sure that you stringify the JSON that you are POSTing.

Here is my JavaScript (using AngluarJS):

$scope.updateUserActivity = function (_objuserActivity) {
        $http
        ({
            method: 'post',
            url: 'your url here',
            headers: { 'Content-Type': 'application/json'},
            data: JSON.stringify(_objuserActivity)
        })
        .then(function (response)
        {
            alert("success");
        })
        .catch(function (response)
        {
            alert("failure");
        })
        .finally(function ()
        {
        });

And here is my WebAPI Controller:

[HttpPost]
[AcceptVerbs("POST")]
public string POSTMe([FromBody]Models.UserActivity _activity)
{
    return "hello";
}

Maven: How to rename the war file for the project?

You can use the following in the web module that produces the war:

<build>
  <finalName>bird</finalName>
 . . .
</build>

This leads to a file called bird.war to be created when goal "war:war" is used.

How can I pad a value with leading zeros?

ES6 makes this fairly trivial:

function pad (num, length, countSign = true) {
  num = num.toString()
  let negative = num.startsWith('-')
  let numLength = negative && !countSign ? num.length - 1 : num.length
  if (numLength >= length) {
    return num
  } else if (negative) {
    return '-' + '0'.repeat(length - numLength) + num.substr(1)
  } else {
    return '0'.repeat(length - numLength) + num
  }
}

pad(42, 4)          === '0042'
pad(12345, 4)       === '12345'
pad(-123, 4)        === '-100'
pad(-123, 4, false) === '-0100'

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

How to get row from R data.frame

x[r,]

where r is the row you're interested in. Try this, for example:

#Add your data
x <- structure(list(A = c(5,    3.5, 3.25, 4.25,  1.5 ), 
                    B = c(4.25, 4,   4,    4.5,   4.5 ),
                    C = c(4.5,  2.5, 4,    2.25,  3   )
               ),
               .Names    = c("A", "B", "C"),
               class     = "data.frame",
               row.names = c(NA, -5L)
     )

#The vector your result should match
y<-c(A=5, B=4.25, C=4.5)

#Test that the items in the row match the vector you wanted
x[1,]==y

This page (from this useful site) has good information on indexing like this.

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

You can use general compound drawable implementation, but if you need to define a size of drawable use this library:

https://github.com/a-tolstykh/textview-rich-drawable

Here is a small example of usage:

<com.tolstykh.textviewrichdrawable.TextViewRichDrawable
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some text"
        app:compoundDrawableHeight="24dp"
        app:compoundDrawableWidth="24dp" />

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

How to select date from datetime column?

Here are all formats

Say this is the column that contains the datetime value, table data.

+--------------------+
| date_created       |
+--------------------+
| 2018-06-02 15:50:30|
+--------------------+

mysql> select DATE(date_created) from data;
+--------------------+
| DATE(date_created) |
+--------------------+
| 2018-06-02         |
+--------------------+

mysql> select YEAR(date_created) from data;
+--------------------+
| YEAR(date_created) |
+--------------------+
|               2018 |
+--------------------+

mysql> select MONTH(date_created) from data;
+---------------------+
| MONTH(date_created) |
+---------------------+
|                   6 |
+---------------------+

mysql> select DAY(date_created) from data;
+-------------------+
| DAY(date_created) |
+-------------------+
|                 2 |
+-------------------+

mysql> select HOUR(date_created) from data;
+--------------------+
| HOUR(date_created) |
+--------------------+
|                 15 |
+--------------------+

mysql> select MINUTE(date_created) from data;
+----------------------+
| MINUTE(date_created) |
+----------------------+
|                   50 |
+----------------------+

mysql> select SECOND(date_created) from data;
+----------------------+
| SECOND(date_created) |
+----------------------+
|                   31 |
+----------------------+

Background position, margin-top?

If you mean you want the background image itself to be offset by 50 pixels from the top, like a background margin, then just switch out the top for 50px and you're set.

#thedivstatus {
    background-image: url("imagestatus.gif");
    background-position: right 50px;
    background-repeat: no-repeat;
}

redirect while passing arguments

I found that none of the answers here applied to my specific use case, so I thought I would share my solution.

I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:

/app/4903294/my-great-car?email=coolguy%40gmail.com to

/public/4903294/my-great-car?email=coolguy%40gmail.com

Here's the solution that worked for me.

return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))

Hope this helps someone!

What's the algorithm to calculate aspect ratio?

paxdiablo's answer is great, but there are a lot of common resolutions that have just a few more or less pixels in a given direction, and the greatest common divisor approach gives horrible results to them.

Take for example the well behaved resolution of 1360x765 which gives a nice 16:9 ratio using the gcd approach. According to Steam, this resolution is only used by 0.01% of it's users, while 1366x768 is used by a whoping 18.9%. Let's see what we get using the gcd approach:

1360x765 - 16:9 (0.01%)
1360x768 - 85:48 (2.41%)
1366x768 - 683:384 (18.9%)

We'd want to round up that 683:384 ratio to the closest, 16:9 ratio.

I wrote a python script that parses a text file with pasted numbers from the Steam Hardware survey page, and prints all resolutions and closest known ratios, as well as the prevalence of each ratio (which was my goal when I started this):

# Contents pasted from store.steampowered.com/hwsurvey, section 'Primary Display Resolution'
steam_file = './steam.txt'

# Taken from http://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Vector_Video_Standards4.svg/750px-Vector_Video_Standards4.svg.png
accepted_ratios = ['5:4', '4:3', '3:2', '8:5', '5:3', '16:9', '17:9']

#-------------------------------------------------------
def gcd(a, b):
    if b == 0: return a
    return gcd (b, a % b)

#-------------------------------------------------------
class ResData:

    #-------------------------------------------------------
    # Expected format: 1024 x 768 4.37% -0.21% (w x h prevalence% change%)
    def __init__(self, steam_line):
        tokens = steam_line.split(' ')
        self.width  = int(tokens[0])
        self.height = int(tokens[2])
        self.prevalence = float(tokens[3].replace('%', ''))

        # This part based on pixdiablo's gcd answer - http://stackoverflow.com/a/1186465/828681
        common = gcd(self.width, self.height)
        self.ratio = str(self.width / common) + ':' + str(self.height / common)
        self.ratio_error = 0

        # Special case: ratio is not well behaved
        if not self.ratio in accepted_ratios:
            lesser_error = 999
            lesser_index = -1
            my_ratio_normalized = float(self.width) / float(self.height)

            # Check how far from each known aspect this resolution is, and take one with the smaller error
            for i in range(len(accepted_ratios)):
                ratio = accepted_ratios[i].split(':')
                w = float(ratio[0])
                h = float(ratio[1])
                known_ratio_normalized = w / h
                distance = abs(my_ratio_normalized - known_ratio_normalized)
                if (distance < lesser_error):
                    lesser_index = i
                    lesser_error = distance
                    self.ratio_error = distance

            self.ratio = accepted_ratios[lesser_index]

    #-------------------------------------------------------
    def __str__(self):
        descr = str(self.width) + 'x' + str(self.height) + ' - ' + self.ratio + ' - ' + str(self.prevalence) + '%'
        if self.ratio_error > 0:
            descr += ' error: %.2f' % (self.ratio_error * 100) + '%'
        return descr

#-------------------------------------------------------
# Returns a list of ResData
def parse_steam_file(steam_file):
    result = []
    for line in file(steam_file):
        result.append(ResData(line))
    return result

#-------------------------------------------------------
ratios_prevalence = {}
data = parse_steam_file(steam_file)

print('Known Steam resolutions:')
for res in data:
    print(res)
    acc_prevalence = ratios_prevalence[res.ratio] if (res.ratio in ratios_prevalence) else 0
    ratios_prevalence[res.ratio] = acc_prevalence + res.prevalence

# Hack to fix 8:5, more known as 16:10
ratios_prevalence['16:10'] = ratios_prevalence['8:5']
del ratios_prevalence['8:5']

print('\nSteam screen ratio prevalences:')
sorted_ratios = sorted(ratios_prevalence.items(), key=lambda x: x[1], reverse=True)
for value in sorted_ratios:
    print(value[0] + ' -> ' + str(value[1]) + '%')

For the curious, these are the prevalence of screen ratios amongst Steam users (as of October 2012):

16:9 -> 58.9%
16:10 -> 24.0%
5:4 -> 9.57%
4:3 -> 6.38%
5:3 -> 0.84%
17:9 -> 0.11%

CSS scale down image to fit in containing div, without specifing original size

Several of these things did not work for me... however, this did. Might help someone else in the future. Here is the CSS:

    .img-area {
     display: block;
     padding: 0px 0 0 0px;
     text-indent: 0;
     width: 100%;
     background-size: 100% 95%;
     background-repeat: no-repeat;
     background-image: url("https://yourimage.png");

    }

How can I capitalize the first letter of each word in a string using JavaScript?

let str = "I'm a little tea pot";

str = str.toLowerCase();

and add css property text-transform: capitalize; to the respective element.

How to check if C string is empty

Since C-style strings are always terminated with the null character (\0), you can check whether the string is empty by writing

do {
   ...
} while (url[0] != '\0');

Alternatively, you could use the strcmp function, which is overkill but might be easier to read:

do {
   ...
} while (strcmp(url, ""));

Note that strcmp returns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is nonempty.

Hope this helps!

jQuery disable/enable submit button

you can also use something like this :

$(document).ready(function() {
    $('input[type="submit"]').attr('disabled', true);
    $('input[type="text"]').on('keyup',function() {
        if($(this).val() != '') {
            $('input[type="submit"]').attr('disabled' , false);
        }else{
            $('input[type="submit"]').attr('disabled' , true);
        }
    });
});

here is Live example

How can I convert radians to degrees with Python?

I also like to define my own functions that take and return arguments in degrees rather than radians. I am sure there some capitalization purest who don't like my names, but I just use a capital first letter for my custom functions. The definitions and testing code are below.

#Definitions for trig functions using degrees.
def Cos(a):
    return cos(radians(a))
def Sin(a):
    return sin(radians(a))
def Tan(a):
    return tan(radians(a))
def ArcTan(a):
    return degrees(arctan(a))
def ArcSin(a):
    return degrees(arcsin(a))
def ArcCos(a):
    return degrees(arccos(a))

#Testing Code
print(Cos(90))
print(Sin(90))
print(Tan(45))
print(ArcTan(1))
print(ArcSin(1))
print(ArcCos(0))

Note that I have imported math (or numpy) into the namespace with

from math import *

Also note, that my functions are in the namespace in which they were defined. For instance,

math.Cos(45)

does not exist.

Correct way to work with vector of arrays

There is no error in the following piece of code:

float arr[4];
arr[0] = 6.28;
arr[1] = 2.50;
arr[2] = 9.73;
arr[3] = 4.364;
std::vector<float*> vec = std::vector<float*>();
vec.push_back(arr);
float* ptr = vec.front();
for (int i = 0; i < 3; i++)
    printf("%g\n", ptr[i]);

OUTPUT IS:

6.28

2.5

9.73

4.364

IN CONCLUSION:

std::vector<double*>

is another possibility apart from

std::vector<std::array<double, 4>>

that James McNellis suggested.

Printing 1 to 1000 without loop or conditionals

stand c++ concept, pass on gcc, vc

[root@localhost ~]# cat 1.cpp
#include <stdio.h>
#include <stdlib.h>

int i = 1;
void print(int arg0)
{
    printf("%d ",i);
    *(&arg0 - 1) = (int)print;
    *(&arg0 - i/1000) = (int)exit;
    i++;
}
int main(void) {
    int a[1000];
    print(0);
    return 0;
}

Running it:

[root@localhost ~]# g++ 1.cpp -o 1
[root@localhost ~]# ./1

1 2 ... 1000

Why does modulus division (%) only work with integers?

The % operator gives you a REMAINDER(another name for modulus) of a number. For C/C++, this is only defined for integer operations. Python is a little broader and allows you to get the remainder of a floating point number for the remainder of how many times number can be divided into it:

>>> 4 % math.pi
0.85840734641020688
>>> 4 - math.pi
0.85840734641020688
>>> 

How do I analyze a program's core dump file with GDB when it has command-line parameters?

Simply type the command:

$ gdb <Binary> <codeDump>

Or

$ gdb <binary>

$ gdb) core <coreDump>

There isn't any need to provide any command line argument. The code dump generated due to an earlier exercise.

How to know if two arrays have the same values

I have another way based on the accepted answer.

function compareArrays(array1, array2) {

    if (
        !Array.isArray(array1)
        || !Array.isArray(array2)
        || array1.length !== array2.length
    ) return false;

    var first = array1.sort().map(value => (String(value))).join();
    var second = array2.sort().map(value => (String(value))).join();

    return first == second ? true : false;
}

How to get the top 10 values in postgresql?

(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 10)

UNION ALL

(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC    
LIMIT 10)

Invalid attempt to read when no data is present

You have to call DataReader.Read to fetch the result:

SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read()) 
{
    // read data for first record here
}

DataReader.Read() returns a bool indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:

while (dr.Read()) 
{
    // read data for each record here
}

What does it mean to have an index to scalar variable error? python

exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

Did you mean to say:

L = identity(len(l))
for i in xrange(len(l)):
    L[i][i] = exponent[i]

or even

L = diag(exponent)

?

How to fix height of TR?

Tables are iffy (at least, in IE) when it comes to fixing heights and not wrapping text. I think you'll find that the only solution is to put the text inside a div element, like so:

_x000D_
_x000D_
td.container > div {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    overflow:hidden;_x000D_
}_x000D_
td.container {_x000D_
    height: 20px;_x000D_
}
_x000D_
<table>_x000D_
    <tr>_x000D_
        <td class="container">_x000D_
            <div>This is a long line of text designed not to wrap _x000D_
                 when the container becomes too small.</div>_x000D_
        </td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This way, the div's height is that of the containing cell and the text cannot grow the div, keeping the cell/row the same height no matter what the window size is.

Select rows with same id but different value in another column

This ought to do it:

SELECT *
FROM YourTable
WHERE ARIDNR IN (
    SELECT ARIDNR
    FROM YourTable
    GROUP BY ARIDNR
    HAVING COUNT(*) > 1
)

The idea is to use the inner query to identify the records which have a ARIDNR value that occurs 1+ times in the data, then get all columns from the same table based on that set of values.

Plotting images side by side using matplotlib

One thing that I found quite helpful to use to print all images :

_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
    ax.imshow(img)
plt.show()

Finding a branch point with Git?

I believe I've found a way that deals with all the corner-cases mentioned here:

branch=branch_A
merge=$(git rev-list --min-parents=2 --grep="Merge.*$branch" --all | tail -1)
git merge-base $merge^1 $merge^2

Charles Bailey is quite right that solutions based on the order of ancestors have only limited value; at the end of the day you need some sort of record of "this commit came from branch X", but such record already exists; by default 'git merge' would use a commit message such as "Merge branch 'branch_A' into master", this tells you that all the commits from the second parent (commit^2) came from 'branch_A' and was merged to the first parent (commit^1), which is 'master'.

Armed with this information you can find the first merge of 'branch_A' (which is when 'branch_A' really came into existence), and find the merge-base, which would be the branch point :)

I've tried with the repositories of Mark Booth and Charles Bailey and the solution works; how couldn't it? The only way this wouldn't work is if you have manually changed the default commit message for merges so that the branch information is truly lost.

For usefulness:

[alias]
    branch-point = !sh -c 'merge=$(git rev-list --min-parents=2 --grep="Merge.*$1" --all | tail -1) && git merge-base $merge^1 $merge^2'

Then you can do 'git branch-point branch_A'.

Enjoy ;)

Best way to retrieve variable values from a text file?

If your data has a regular structure you can read a file in line by line and populate your favorite container. For example:

Let's say your data has 3 variables: x, y, i.

A file contains n of these data, each variable on its own line (3 lines per record). Here are two records:

384
198
0
255
444
2

Here's how you read your file data into a list. (Reading from text, so cast accordingly.)

data = []
try:
    with open(dataFilename, "r") as file:
        # read data until end of file
        x = file.readline()
        while x != "":
            x = int(x.strip())    # remove \n, cast as int

            y = file.readline()
            y = int(y.strip())

            i = file.readline()
            i = int(i.strip())

            data.append([x,y,i])

            x = file.readline()

except FileNotFoundError as e:
    print("File not found:", e)

return(data)

How to lowercase a pandas dataframe string column if it has missing values?

May be using List comprehension

import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan],columns=['Name']})
df['Name'] = [str(i).lower() for i in df['Name']] 

print(df)

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

It's possible to inject instance of ApplicationContext class by using SpringClassRule and SpringMethodRule rules. It might be very handy if you would like to use another non-Spring runners. Here's an example:

@ContextConfiguration(classes = BeanConfiguration.class)
public static class SpringRuleUsage {

    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private ApplicationContext context;

    @Test
    public void shouldInjectContext() {
    }
}

svn over HTTP proxy

If you can get SSH to it you can an SSH Port-forwarded SVN server.

Use SSHs -L ( or -R , I forget, it always confuses me ) to make an ssh tunnel so that

127.0.0.1:3690 is really connecting to remote:3690 over the ssh tunnel, and then you can use it via

svn co svn://127.0.0.1/....

Java error: Only a type can be imported. XYZ resolves to a package

If you spell the class name wrong or the class isn't on the classpath, the JSP processor will say it "resolves to a package" rather than that it doesn't exist. This was driving me crazy today as I kept not seeing a typo I'd made.

Difference between AutoPostBack=True and AutoPostBack=False?

The AutoPostBack property is used to set or return whether or not an automatic post back occurs when the user presses "ENTER" or "TAB" in the TextBox control.

If this property is set to TRUE the automatic post back is enabled, otherwise FALSE. Default is FALSE.

Could not find main class HelloWorld

Tell it where to look for you class: it's in ".", which is the current directory:

java -classpath . HelloWorld

No need to set JAVA_HOME or CLASSPATH in this case

How do I escape a single quote in SQL Server?

Double quotes option helped me

SET QUOTED_IDENTIFIER OFF;
insert into my_table values("hi, my name's tim.");
SET QUOTED_IDENTIFIER ON;

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

I have the same problem and try almost all these suggestions and another options but nothing works for my case.

So I had run verbose command: (mvn install -X) and saw the problem with Jacoco lib, and finally found this answer that works for me.

Change the Jacoco lib version in my pom file.

<groupId>org.jacoco</groupId>
     <artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.4</version>

Integer to hex string in C++

Use std::stringstream to convert integers into strings and its special manipulators to set the base. For example like that:

std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();

Java "user.dir" property - what exactly does it mean?

It's the directory where java was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run java.

So if you cd into /somedir, then run your program, user.dir will be /somedir.

A different property, user.home, refers to the user directory. As in /Users/myuser or /home/myuser or C:\Users\myuser.

See here for a list of system properties and their descriptions.

Java Program to test if a character is uppercase/lowercase/number/vowel

If it weren't a homework, you could use existing methods such as Character.isDigit(char), Character.isUpperCase(char) and Character.isLowerCase(char) which are a bit "smarter", because they don't operate only in ASCII, but also in various charsets.

static final char[] VOWELS = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };

static boolean isVowel(char ch) {
    for (char vowel : VOWELS) {
        if (vowel == ch) {
            return true;
        }
    }
    return false;
}

static boolean isDigit(char ch) {
    return ch >= '0' && ch <= '9';
}

static boolean isLowerCase(char ch) {
    return ch >= 'a' && ch <= 'z';
}

static boolean isUpperCase(char ch) {
    return ch >= 'A' && ch <= 'Z';
}

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

I didnt try Sumama Waheed's answer but what worked for me was replacing the bin/catalina.jar with a working jar (I disposed of an older tomcat) and after adding in NetBeans, I put the original catalina.jar again.

How to change sender name (not email address) when using the linux mail command for autosending mail?

It depends on what sender address you are talking about. The sender address visble in the recipients mailprogramm is extracted from the "From:" Header. which can probably easily be set from your program.

If you are talking about the SMTP envelope sender address, you can pass the -f argument to the sendmail binary. Depending on the server configuration you may not be allowed to do that with the apache user.

from the sendmail manpage :

   -f <address>
                 This  option  sets  the  address  of the envelope sender of a
                 locally-generated message (also known as  the  return  path).
                 The  option  can normally be used only by a trusted user, but
                 untrusted_set_sender can be set to allow untrusted  users  to
                 use it. [...]

Use Font Awesome Icon in Placeholder

If you can / want to use Bootstrap the solution would be input-groups:

<div class="input-group">
 <div class="input-group-prepend">
  <span class="input-group-text"><i class="fa fa-search"></i></span>
  </div>
 <input type="text" class="form-control" placeholder="-">
</div>

Looks about like this:input with text-prepend and search symbol

Embedding JavaScript engine into .NET

It's Possible now with ASP.Net MVC4 Razor View engine. the code will be this:

// c# class
public class A
{
    public string Hello(string msg)
    {
        return msg + " whatewer";
    }
}

// js snippet
<script type="text/javascript">
var a = new A();
console.log('@a.Hello('Call me')'); // i have a console.log implemented, don't worry, it's not a client-side code :)
</script>

and Razor isn't just for MVC4 or another web applications and you can use it in offline desktop applications.

Is there a way to create multiline comments in Python?

I would advise against using """ for multi line comments!

Here is a simple example to highlight what might be considered an unexpected behavior:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

Now have a look at the output:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.

If you want to comment multiple lines do so according to PEP 8 guidelines:

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

Output:

I am a string
clearly I am also a string

PHP - get base64 img string decode and save as jpg (resulting empty image )

AFAIK, You have to use image function imagecreatefromstring, imagejpeg to create the images.

$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);

Hope this will help.

PHP CODE WITH IMAGE DATA

$imageDataEncoded = base64_encode(file_get_contents('sample.png'));
$imageData = base64_decode($imageDataEncoded);
$source = imagecreatefromstring($imageData);
$angle = 90;
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageName = "hello1.png";
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);

So Following is the php part of your program .. NOTE the change with comment Change is here

    $uploadedPhotos = array('photo_1','photo_2','photo_3','photo_4');
     foreach ($uploadedPhotos as $file) {
      if($this->input->post($file)){                   
         $imageData = base64_decode($this->input->post($file)); // <-- **Change is here for variable name only**
         $photo = imagecreatefromstring($imageData); // <-- **Change is here**

        /* Set name of the photo for show in the form */
        $this->session->set_userdata('upload_'.$file,'ant');
        /*set time of the upload*/
        if(!$this->session->userdata('uploading_on_datetime')){
         $this->session->set_userdata('uploading_on_datetime',time());
        }
         $datetime_upload = $this->session->userdata('uploading_on_datetime',true);

        /* create temp dir with time and user id */
        $new_dir = 'temp/user_'.$this->session->userdata('user_id',true).'_on_'.$datetime_upload.'/';
        if(!is_dir($new_dir)){
        @mkdir($new_dir);
        }
        /* move uploaded file with new name */
        // @file_put_contents( $new_dir.$file.'.jpg',imagejpeg($photo));
        imagejpeg($photo,$new_dir.$file.'.jpg',100); // <-- **Change is here**

      }
    }

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Well, I'm late.


In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(???) channel in HSV color space. Take refer to wiki HSL_and_HSV first. Then I'll copy most idea from my answer in this Detect Colored Segment in an image.


Main steps:

  1. Read into BGR
  2. Convert the image from bgr to hsv space
  3. Threshold the S channel
  4. Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners.

This is my result:

enter image description here


The Python code(Python 3.5 + OpenCV 3.3):

#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST

import cv2
import numpy as np

##(1) read into  bgr-space
img = cv2.imread("test2.jpg")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)

##(4) find all the external contours on the threshed S
#_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

canvas  = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)

## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]

## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)

## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)

Related answers:

  1. How to detect colored patches in an image using OpenCV?
  2. Edge detection on colored background using OpenCV
  3. OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection
  4. How to use `cv2.findContours` in different OpenCV versions?

How to create SPF record for multiple IPs?

The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.

How to programmatically clear application data

This way added by Sebastiano was OK, but it's necessary, when you run tests from i.e. IntelliJ IDE to add:

 try {
    // clearing app data
    Runtime runtime = Runtime.getRuntime();
    runtime.exec("adb shell pm clear YOUR_APP_PACKAGE_GOES HERE");

}

instead of only "pm package..."

and more important: add it before driver.setCapability(App_package, package_name).

Python find elements in one list that are not in the other

You can use sets:

main_list = list(set(list_2) - set(list_1))

Output:

>>> list_1=["a", "b", "c", "d", "e"]
>>> list_2=["a", "f", "c", "m"]
>>> set(list_2) - set(list_1)
set(['m', 'f'])
>>> list(set(list_2) - set(list_1))
['m', 'f']

Per @JonClements' comment, here is a tidier version:

>>> list_1=["a", "b", "c", "d", "e"]
>>> list_2=["a", "f", "c", "m"]
>>> list(set(list_2).difference(list_1))
['m', 'f']

How to get a .csv file into R?

You mention that you will call on each vertical column so that you can perform calculations. I assume that you just want to examine each single variable. This can be done through the following.

df <- read.csv("myRandomFile.csv", header=TRUE)

df$ID

df$GRADES

df$GPA

Might be helpful just to assign the data to a variable.

var3 <- df$GPA

Mockito test a void method throws an exception

If you ever wondered how to do it using the new BDD style of Mockito:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));

Multiline TextBox multiple newline

I had the same problem. If I add one Environment.Newline I get one new line in the textbox. But if I add two Environment.Newline I get one new line. In my web app I use a whitespace modul that removes all unnecessary white spaces. If i disable this module I get two new lines in my textbox. Hope that helps.

C# Create New T()

Another way is to use reflection:

protected T GetObject<T>(Type[] signature, object[] args)
{
    return (T)typeof(T).GetConstructor(signature).Invoke(args);
}

How to get the selected value from RadioButtonList?

string radioListValue = RadioButtonList.Text;

How can I group by date time column without taking time into consideration

I believe you need to group by , in that day of the month of the year . so why not using TRUNK_DATE functions . The way it works is described below :

Group By DATE_TRUNC('day' , 'occurred_at_time')

Calculating time difference in Milliseconds

From Java 8 onward you can try the following:

import java.time.*;
import java.time.temporal.ChronoUnit;

Instant start_time = Instant.now();
// Your code
Instant stop_time = Instant.now();

System.out.println(Duration.between(start_time, stop_time).toMillis());

//or

System.out.println(ChronoUnit.MILLIS.between(start_time, stop_time));

Hide element by class in pure Javascript

Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });

Forked @http://jsfiddle.net/QVJXD/

Unable to install packages in latest version of RStudio and R Version.3.1.1

What worked for me:

Preferences-General-Default working directory-Browse Switch from global to local mirror

Working on a Mac. 10.10.3

Using getline() in C++

i think you are not pausing the program before it ended so the output you are putting after getting the inpus is not seeing on the screen right?

do:

getchar();

before the end of the program

The PowerShell -and conditional operator

Try like this:

if($user_sam -ne $NULL -and $user_case -ne $NULL)

Empty variables are $null and then different from "" ([string]::empty).

Convert `List<string>` to comma-separated string

That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.

(does it still work without the ToArray)?

How can you tell when a layout has been drawn?

An alternative to the usual methods is to hook into the drawing of the view.

OnPreDrawListener is called many times when displaying a view, so there is no specific iteration where your view has valid measured width or height. This requires that you continually verify (view.getMeasuredWidth() <= 0) or set a limit to the number of times you check for a measuredWidth greater than zero.

There is also a chance that the view will never be drawn, which may indicate other problems with your code.

final View view = [ACQUIRE REFERENCE]; // Must be declared final for inner class
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if (view.getMeasuredWidth() > 0) {     
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
            //Do something with width and height here!
        }
        return true; // Continue with the draw pass, as not to stop it
    }
});

Why is "throws Exception" necessary when calling a function?

In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:

enter image description here

In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.


From Java Tutorial:

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?

Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.

Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:

  • Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an ArithmeticException of division by zero occurs or an ArrayIndexOutOfBoundsException occurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.

  • Errors: Errors are situations from which usually the program cannot recover. For example, if a StackOverflowError occurs, our program cannot do much, such as increase the size of program's function calling stack. Or if an OutOfMemoryError occurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.

For detailed information see:

ADB No Devices Found

I tried almost all the suggestions in most of the answers (the most popular), nothing was helping. Finally, I found the reason in my case. I used a bad USB cable. I change to another original USB cable - and it immediately worked!!!.

I hope it helps someone else.

Convert string to nullable type (int, double, etc...)

Here's something based on accepted answer. I removed the try/catch to make sure all the exceptions are not swallowed and not dealt with. Also made sure that the return variable (in accepted answer) is never initialized twice for nothing.

public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
    if (!string.IsNullOrWhiteSpace(s))
    {
        TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));

        return (T)conv.ConvertFrom(s);
    }

    return default(Nullable<T>);
}

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }

What is the difference between children and childNodes in JavaScript?

Pick one depends on the method you are looking for!?

I will go with ParentNode.children:

As it provides namedItem method that allows me directly to get one of the children elements without looping through all children or avoiding to use getElementById etc.

e.g.

ParentNode.children.namedItem('ChildElement-ID'); // JS
ref.current.children.namedItem('ChildElement-ID'); // React
this.$refs.ref.children.namedItem('ChildElement-ID'); // Vue

I will go with Node.childNodes:

As it provides forEach method when I work with window.IntersectionObserver e.g.

nodeList.forEach((node) => { observer.observe(node) })
// IE11 does not support forEach on nodeList, but easy to be polyfilled.

On Chrome 83

Node.childNodes provides entries, forEach, item, keys, length and values

ParentNode.children provides item, length and namedItem

jQuery prevent change for select

None of the other answers worked for me, here is what eventually did.

I had to track the previous selected value of the select element and store it in the data-* attribute. Then I had to use the val() method for the select box that JQuery provides. Also, I had to make sure I was using the value attribute in my options when I populated the select box.

<body>
    <select id="sel">
        <option value="Apple">Apple</option>        <!-- Must use the value attribute on the options in order for this to work. -->
        <option value="Bannana">Bannana</option>
        <option value="Cherry">Cherry</option>
    </select>
</body>

<script src="https://code.jquery.com/jquery-3.5.1.js" type="text/javascript" language="javascript"></script>

<script>
    $(document).ready()
    {
        //
        // Register the necessary events.
        $("#sel").on("click", sel_TrackLastChange);
        $("#sel").on("keydown", sel_TrackLastChange);
        $("#sel").on("change", sel_Change);
        
        $("#sel").data("lastSelected", $("#sel").val());
    }
    
    //
    // Track the previously selected value when the user either clicks on or uses the keyboard to change
    // the option in the select box.  Store it in the select box's data-* attribute.
    function sel_TrackLastChange()
    {
        $("#sel").data("lastSelected", $("#sel").val());
    }
    
    //
    // When the option changes on the select box, ask the user if they want to change it.
    function sel_Change()
    {
        if(!confirm("Are you sure?"))
        {
            //
            // If the user does not want to change the selection then use JQuery's .val() method to change
            // the selection back to what it was  previously.
            $("#sel").val($("#sel").data("lastSelected"));
        }
    }
</script>

I hope this can help someone else who has the same problem as I did.

You need to use a Theme.AppCompat theme (or descendant) with this activity

NOTE: I had intended this as an answer, but further testing reveals it still fails when built using maven from the command line, so I've had to edit it to be a problem! :-(

In my case when I got this error I was already using a AppCompat Theme and the error didn't make much sense.

I was in the process of mavenizing my android build. I had already dependencies on the apklib and jar versions of app compat, thus:

    <!-- See https://github.com/mosabua/maven-android-sdk-deployer -->
        <dependency>
            <groupId>android.support</groupId>
            <artifactId>compatibility-v7-appcompat</artifactId>
            <version>${compatibility.version}</version>
            <type>apklib</type>
        </dependency>

        <dependency>
            <groupId>android.support</groupId>
            <artifactId>compatibility-v7-appcompat</artifactId>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>android.support</groupId>
            <artifactId>compatibility-v7</artifactId>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>android.support</groupId>
            <artifactId>compatibility-v4</artifactId>
        </dependency>

Now, when I import the maven project and build and run from IntelliJ it's fine.

But when I build and deploy and run from the command line with maven I still get this exception.

Failed to decode downloaded font

My case looked similar but the font was corrupted (and so impossible to decode). It was caused by configuration in maven. Adding nonFilteredFileExtension for font extensions within maven-resources-plugin helped me:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <configuration>
        <nonFilteredFileExtensions>
            <nonFilteredFileExtension>ttf</nonFilteredFileExtension>
            <nonFilteredFileExtension>otf</nonFilteredFileExtension>
            <nonFilteredFileExtension>woff</nonFilteredFileExtension>
            <nonFilteredFileExtension>woff2</nonFilteredFileExtension>
            <nonFilteredFileExtension>eot</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
    </configuration>
</plugin>

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

You just need to store the differences between the numbers in sequence, and use an encoding to compress these sequence numbers. We have 2^23 bits. We shall divide it into 6bit chunks, and let the last bit indicate whether the number extends to another 6 bits (5bits plus extending chunk).

Thus, 000010 is 1, and 000100 is 2. 000001100000 is 128. Now, we consider the worst cast in representing differences in sequence of a numbers up to 10,000,000. There can be 10,000,000/2^5 differences greater than 2^5, 10,000,000/2^10 differences greater than 2^10, and 10,000,000/2^15 differences greater than 2^15, etc.

So, we add how many bits it will take to represent our the sequence. We have 1,000,000*6 + roundup(10,000,000/2^5)*6+roundup(10,000,000/2^10)*6+roundup(10,000,000/2^15)*6+roundup(10,000,000/2^20)*4=7935479.

2^24 = 8388608. Since 8388608 > 7935479, we should easily have enough memory. We will probably need another little bit of memory to store the sum of where are when we insert new numbers. We then go through the sequence, and find where to insert our new number, decrease the next difference if necessary, and shift everything after it right.

Remove spaces from std::string in C++

  string str = "2C F4 32 3C B9 DE";
  str.erase(remove(str.begin(),str.end(),' '),str.end());
  cout << str << endl;

output: 2CF4323CB9DE

How can I tell Moq to return a Task?

You only need to add .Returns(Task.FromResult(0)); after the Callback.

Example:

mock.Setup(arg => arg.DoSomethingAsync())
    .Callback(() => { <my code here> })
    .Returns(Task.FromResult(0));

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

In my case it was because the file was minified with wrong scope. Use Array!

app.controller('StoreController', ['$http', function($http) {
    ...
}]);

Coffee syntax:

app.controller 'StoreController', Array '$http', ($http) ->
  ...

Append text to file from command line without using io redirection

If you don't mind using sed then,

$ cat test 
this is line 1
$ sed -i '$ a\this is line 2 without redirection' test 
$ cat test 
this is line 1
this is line 2 without redirection

As the documentation may be a bit long to go through, some explanations :

  • -i means an inplace transformation, so all changes will occur in the file you specify
  • $ is used to specify the last line
  • a means append a line after
  • \ is simply used as a delimiter

Shared folder between MacOSX and Windows on Virtual Box

You should map your virtual network drive in Windows.

  1. Open command prompt in Windows (VirtualBox)
  2. Execute: net use x: \\vboxsvr\<your_shared_folder_name>
  3. You should see new drive X: in My Computer

In your case execute net use x: \\vboxsvr\win7

Pretty git branch graphs

Gitg is a clone of Gitk and GitX for GNOME (it also works on KDE etc.) which shows a pretty colored graph.

It is actively developed (as of 2012). It lets you sort the commits (graph nodes) either chronologically or topologically, and hide commits that don't lead to a selected branch.

It works fine with large repositories and complex dependency graphs.

Sample screenshots, showing the linux-git and linux-2.6 repositories:

linux-git

linux-2.6

Remove the legend on a matplotlib figure

I made a legend by adding it to the figure, not to an axis (matplotlib 2.2.2). To remove it, I set the legends attribute of the figure to an empty list:

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ax1.plot(range(10), range(10, 20), label='line 1')
ax2.plot(range(10), range(30, 20, -1), label='line 2')

fig.legend()

fig.legends = []

plt.show()

Using Sockets to send and receive data

the easiest way to do this is to wrap your sockets in ObjectInput/OutputStreams and send serialized java objects. you can create classes which contain the relevant data, and then you don't need to worry about the nitty gritty details of handling binary protocols. just make sure that you flush your object streams after you write each object "message".

Spring Security exclude url patterns in security annotation configurartion

Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.

Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.

I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.

In addition I have a resource, /admin, which requires higher privledges than the rest of the site.

The following is working for me.

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/login**").permitAll()
        .antMatchers("/healthcheck**").permitAll()
        .antMatchers("/static/**").permitAll()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .and()
            .formLogin().loginPage("/login").failureUrl("/login?error")
                .usernameParameter("username").passwordParameter("password")
        .and()
            .logout().logoutSuccessUrl("/login?logout")
        .and()
            .exceptionHandling().accessDeniedPage("/403")
        .and()
            .csrf();

}

NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:

        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .antMatchers("/login**").permitAll()
        .antMatchers("/healthcheck**").permitAll()

Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:

        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")

Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)

Turn off auto formatting in Visual Studio

You might have had Power Tool installed.

In this case you can turn it off from 'Tools > Options > Productivity Power Tools > PowerCommands > General'

enter image description here

jQuery Datepicker localization

If you want to include some options besides regional localization, you have to use $.extend, like this:

$(function() {
   $('#Date').datepicker($.extend({
      showMonthAfterYear: false,
      dateFormat:'d MM, y'
    },
    $.datepicker.regional['fr']
  ));
});

How to find out mySQL server ip address from phpmyadmin

The SQL query SHOW VARIABLES WHERE Variable_name = 'hostname' will show you the hostname of the MySQL server which you can easily resolve to its IP address.

SHOW VARIABLES WHERE Variable_name = 'port' Will give you the port number.

You can find details about this in MySQL's manual: 12.4.5.41. SHOW VARIABLES Syntax and 5.1.4. Server System Variables

Closing Excel Application Process in C# after Data Access

        GetWindowThreadProcessId((IntPtr)app.Hwnd, out iProcessId);
        wb.Close(true,Missing.Value,Missing.Value);
        app.Quit();
        System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
        foreach (System.Diagnostics.Process p in process)
        {
            if (p.Id == iProcessId)
            {
                try
                {
                    p.Kill();
                }
                catch { }
            }
        }
}
[DllImport("user32.dll")]

private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

uint iProcessId = 0;

this GetWindowThreadProcessId finds the correct Process Id o excell .... After kills it.... Enjoy It!!!

Laravel 5.2 not reading env file

I ran into this same problem on my local, and I have tried all the answers here but to no avail. Only this worked for me, php artisan config:clear and restart server. Works like a charm!

Producing a new line in XSLT

You can try,

<xsl:text>&#xA;</xsl:text>

It will work.

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

The suggested causes are now proven to be mostly impossible. I'm running SSMS V17.9.2 against SS 2014 and still have the problem. Memory problems have existed with this tool since at least 2006 when I started using SSMS.

Yes, MS 'wants' to get rid of diagramming but users won't let them. I have a feeling they will never fix any of these issues because they want users to be so fed up with the tool that enough of them quit using it and they can abandon it entirely.

Restarting is still a workaround if you can stand doing so numerous times per day.

HTTP error 403 in Python 3 Web Scraping

This is probably because of mod_security or some similar server security feature which blocks known spider/bot user agents (urllib uses something like python urllib/3.3.0, it's easily detected). Try setting a known browser user agent with:

from urllib.request import Request, urlopen

req = Request('http://www.cmegroup.com/trading/products/#sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1', headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()

This works for me.

By the way, in your code you are missing the () after .read in the urlopen line, but I think that it's a typo.

TIP: since this is exercise, choose a different, non restrictive site. Maybe they are blocking urllib for some reason...

How can I use Helvetica Neue Condensed Bold in CSS?

In case anyone is still looking for Helvetica Neue Condensed Bold, you essentially have two options.

  1. fonts.com: License the real font as a webfont from fonts.com. Free (with a badge), $10/month for 250k pageviews and $100/month for 2.5M pageviews. You can download the font to your desktop with the most expensive plan (but if you're on a Mac you already have it).
  2. myfonts.com / fontspring.com: Buy a pretty close alternative like Nimbus Sans Novus D from MyFont ($160 for unlimited pageviews), or Franklin Gothic FS Demi Condensed, from fontspring.com (about $21.95, flat one time fee with unlimited pageviews). In both cases you also get to download the font for your desktop so you can use it in Photoshop for comps.

A very cheap compromise is to buy Franklin from fontspring and then use "HelveticaNeue-CondensedBold" as the preferred font in your CSS.

h2 {"HelveticaNeue-CondensedBold", "FranklinGothicFSDemiCondensed", Arial, sans-serif;}

Then if a Mac user loads your site they see Helvetica Neue, but if they're on another platform they see Franklin.

UPDATE: I discovered a much closer match to Helvetica Neue Condensed Bold is Nimbus Sans Novus D Condensed bold. In fact, it is also derived from Helvetica. You can get it at MyFonts.com for $20 (desktop) and $20 (web, 10k pageviews). Web with unlimited pageviews is $160. I have used this font throughout (i.e. NOT exploiting the Mac's built in "NimbusSansNovusDBoldCondensed" at all) because it leads to a design that is more uniform across browsers. Built in HN and Nimbus Sans are very similar in all respects but point size. Nimbus needs a few extra points to get an identical size match.

How to delete file from public folder in laravel 5.1

the easiest way for you to delete the image of the news is using the model event like below and the model delete the image if the news deleted

at first you should import this in top of the model class use Illuminate\Support\Facades\Storage after that in the model class News you should do this

public static function boot(){
    parent::boot();

    static::deleting(function ($news) {
          Storage::disk('public')->delete("{$news->image}");
    })
}

or you can delete the image in your controller with this command

Storage::disk('public')->delete("images/news/{$news->file_name}");

but you should know that the default disk is public but if you create folder in the public folder and put the image on that you should set the folder name before $news->file_name

Select multiple columns in data.table by their numeric indices

From v1.10.2 onwards, you can also use ..

dt <- data.table(a=1:2, b=2:3, c=3:4)

keep_cols = c("a", "c")

dt[, ..keep_cols]

For loop example in MySQL

Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below

CREATE TABLE `table1` (
    `col1` VARCHAR(50) NULL DEFAULT NULL
)

Now if you want to insert number from 1 to 50 in that table then use following stored procedure

DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      DECLARE a INT Default 1 ;
      simple_loop: LOOP         
         insert into table1 values(a);
         SET a=a+1;
         IF a=51 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

To call that stored procedure use

CALL `ABC`()

Enable CORS in Web API 2

CORS works absolutely fine in Microsoft.AspNet.WebApi.Cors version 5.2.2. The following steps configured CORS like a charm for me:

  1. Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2" // run from Package manager console
  2. In Global.asax, add the following line: BEFORE ANY MVC ROUTE REGISTRATIONS

    GlobalConfiguration.Configure(WebApiConfig.Register);
    
  3. In the WebApiConfig Register method, have the following code:

    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();
        config.MapHttpAttributeRoutes();
    }
    

In the web.config, the following handler must be the first one in the pipeline:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

In the controller derived from ApiController, add the EnableCorsAttribute:

[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
[RoutePrefix("")]
public class MyController : ApiController

That should set you up nicely!

(413) Request Entity Too Large | uploadReadAheadSize

Got a similar error on IIS Express with Visual Studio 2017.

HTTP Error 413.0 - Request Entity Too Large

The page was not displayed because the request entity is too large.

Most likely causes:

  • The Web server is refusing to service the request because the request entity is too large.

  • The Web server cannot service the request because it is trying to negotiate a client certificate but the request entity is too large.

  • The request URL or the physical mapping to the URL (i.e., the physical file system path to the URL's content) is too long.

Things you can try:

  • Verify that the request is valid.

  • If using client certificates, try:

    • Increasing system.webServer/serverRuntime@uploadReadAheadSize

    • Configure your SSL endpoint to negotiate client certificates as part of the initial SSL handshake. (netsh http add sslcert ... clientcertnegotiation=enable) .vs\config\applicationhost.config

Solve this by editing \.vs\config\applicationhost.config. Switch serverRuntime from Deny to Allow like this:

<section name="serverRuntime" overrideModeDefault="Allow" />

If this value is not edited, you will get an error like this when setting uploadReadAheadSize:

HTTP Error 500.19 - Internal Server Error

The requested page cannot be accessed because the related configuration data for the page is invalid.

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

Then edit Web.config with the following values:

<system.webServer>
  <serverRuntime uploadReadAheadSize="10485760" />
...

ssh-copy-id no identities found error

Generating ssh keys on the client solved it for me

$ ssh-keygen -t rsa

How do you print in Sublime Text 2

Sorry to say that there is no print function in sublimetext2, may be 3 will fix this?

Anyway there are a few plugins that are floating about, the most helpful for you might be print-to-HTML https://github.com/joelpt/sublimetext-print-to-html .

What does the ^ (XOR) operator do?

XOR is a binary operation, it stands for "exclusive or", that is to say the resulting bit evaluates to one if only exactly one of the bits is set.

This is its function table:

a | b | a ^ b
--|---|------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

This operation is performed between every two corresponding bits of a number.

Example: 7 ^ 10
In binary: 0111 ^ 1010

  0111
^ 1010
======
  1101 = 13

Properties: The operation is commutative, associative and self-inverse.

It is also the same as addition modulo 2.

How to "grep" out specific line ranges of a file

Put this in a file and make it executable:

#!/bin/bash
start=`grep -n $1 < $3 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[0]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
    echo "couldn't find start pattern!" 1>&2
    exit 1
fi
stop=`tail -n +$start < $3 | grep -n $2 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[1]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
    echo "couldn't find end pattern!" 1>&2
    exit 1
fi

stop=$(( $stop + $start - 1))

sed "$start,$stop!d" < $3

Execute the file with arguments (NOTE that the script does not handle spaces in arguments!):

  1. Starting grep pattern
  2. Stopping grep pattern
  3. File path

To use with your example, use arguments: 1234 5555 myfile.txt

Includes lines with starting and stopping pattern.

How to make a WPF window be on top of all other windows of my app (not system wide)?

The best way is set this two events to all of windows of your app:

GotKeyboardFocus
LostKeyboardFocus

in this way:

WiondowOfMyApp_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
    windowThatShouldBeTopMost.TopMost = true;
}

WiondowOfMyApp_LostKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
    windowThatShouldBeTopMost.TopMost = false;
}
  • and surely all of the windows that you wanted to be top, should be accessible from other windows of your app. in my case I have a base window and another some windows that should be top of my base window, so this was not bad to my base window has instance of each another windows.

Accessing dictionary value by index in python

If you really just want a random value from the available key range, use random.choice on the dictionary's values (converted to list form, if Python 3).

>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))

setting global sql_mode in mysql

If someone want to set it only for the current session then use the following command

set session sql_mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

How do I send a POST request as a JSON?

This works perfect for Python 3.5, if the URL contains Query String / Parameter value,

Request URL = https://bah2.com/ws/rest/v1/concept/
Parameter value = 21f6bb43-98a1-419d-8f0c-8133669e40ca

import requests

url = 'https://bahbah2.com/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca'
data = {"name": "Value"}
r = requests.post(url, auth=('username', 'password'), verify=False, json=data)
print(r.status_code)

How do I automatically set the $DISPLAY variable for my current session?

Here's something I've just knocked up. It inspects the environment of the last-launched "gnome-session" process (DISPLAY is set correctly when VNC launches a session/window manager). Replace "gnome-session" with the name of whatever process your VNC server launches on startup.

PID=`pgrep -n -u $USER gnome-session`
if [ -n "$PID" ]; then
    export DISPLAY=`awk 'BEGIN{FS="="; RS="\0"}  $1=="DISPLAY" {print $2; exit}' /proc/$PID/environ`
    echo "DISPLAY set to $DISPLAY"
else
    echo "Could not set DISPLAY"
fi
unset PID

You should just be able to drop that in your .bashrc file.

No suitable records were found verify your bundle identifier is correct

If after you confirm your Bundle ID's match across App Store Connect, Apple Developer Portal, and Xcode and you are still having issues try this:

Remove the Apple ID associated with the Bundle ID you're experiencing issues with from your Accounts list in Xcode (Menu Bar -> Xcode -> Preferences -> Accounts). Then, add the Apple ID back to the Accounts list in Xcode.

Javascript swap array elements

function moveElement(array, sourceIndex, destinationIndex) {
    return array.map(a => a.id === sourceIndex ? array.find(a => a.id === destinationIndex): a.id === destinationIndex ? array.find(a => a.id === sourceIndex) : a )
}
let arr = [
{id: "1",title: "abc1"},
{id: "2",title: "abc2"},
{id: "3",title: "abc3"},
{id: "4",title: "abc4"}];

moveElement(arr, "2","4");

"unmappable character for encoding" warning in Java

Gradle Steps

If you are using Gradle then you can find the line that applies the java plugin:

apply plugin: 'java'

Then set the encoding for the compile task to be UTF-8:

compileJava {options.encoding = "UTF-8"}   

If you have unit tests, then you probably want to compile those with UTF-8 too:

compileTestJava {options.encoding = "UTF-8"}

Overall Gradle Example

This means that the overall gradle code would look something like this:

apply plugin: 'java'
compileJava {options.encoding = "UTF-8"}
compileTestJava {options.encoding = "UTF-8"}

Static vs class functions/variables in Swift classes?

I tried mipadi's answer and comments on playground. And thought of sharing it. Here you go. I think mipadi's answer should be mark as accepted.

class A{
    class func classFunction(){
    }
    static func staticFunction(){
    }
    class func classFunctionToBeMakeFinalInImmediateSubclass(){
    }
}

class B: A {
    override class func classFunction(){

    }

    //Compile Error. Class method overrides a 'final' class method
    override static func staticFunction(){

    }

    //Lets avoid the function called 'classFunctionToBeMakeFinalInImmediateSubclass' being overriden by subclasses

    /* First way of doing it
    override static func classFunctionToBeMakeFinalInImmediateSubclass(){
    }
    */

    // Second way of doing the same
    override final class func classFunctionToBeMakeFinalInImmediateSubclass(){
    }

    //To use static or final class is choice of style.
    //As mipadi suggests I would use. static at super class. and final class to cut off further overrides by a subclass
}

class C: B{
    //Compile Error. Class method overrides a 'final' class method
    override static func classFunctionToBeMakeFinalInImmediateSubclass(){

    }
}

Unknown SSL protocol error in connection

In many cases it is linked to proxy problems. If so just config your git proxy

git config --global http.proxy HOST:PORT

How to choose the id generation strategy when using JPA and Hibernate

The API Doc are very clear on this.

All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations. The shortcut names for the built-in generators are as follows:

increment

generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

identity

supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence

uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.

seqhilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid

uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.

guid

uses a database-generated GUID string on MS SQL Server and MySQL.

native

selects identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified.

select

retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. It is usually used in conjunction with a primary key association.

sequence-identity

a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.

If you are building a simple application with not much concurrent users, you can go for increment, identity, hilo etc.. These are simple to configure and did not need much coding inside the db.

You should choose sequence or guid depending on your database. These are safe and better because the id generation will happen inside the database.

Update: Recently we had an an issue with idendity where primitive type (int) this was fixed by using warapper type (Integer) instead.

Parse HTML in Android

We all know that programming have endless possibilities.There are numbers of solutions available for a single problem so i think all of the above solutions are perfect and may be helpful for someone but for me this one save my day..

So Code goes like this

  private void getWebsite() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        final StringBuilder builder = new StringBuilder();

        try {
          Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
          String title = doc.title();
          Elements links = doc.select("a[href]");

          builder.append(title).append("\n");

          for (Element link : links) {
            builder.append("\n").append("Link : ").append(link.attr("href"))
            .append("\n").append("Text : ").append(link.text());
          }
        } catch (IOException e) {
          builder.append("Error : ").append(e.getMessage()).append("\n");
        }

        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            result.setText(builder.toString());
          }
        });
      }
    }).start();
  }

You just have to call the above function in onCreate Method of your MainActivity

I hope this one is also helpful for you guys.

Also read the original blog at Medium

Tainted canvases may not be exported

Check out CORS enabled image from MDN. Basically you must have a server hosting images with the appropriate Access-Control-Allow-Origin header.

_x000D_
_x000D_
<IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
        <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
            SetEnvIf Origin ":" IS_CORS
            Header set Access-Control-Allow-Origin "*" env=IS_CORS
        </FilesMatch>
    </IfModule>
</IfModule>
_x000D_
_x000D_
_x000D_

You will be able to save those images to DOM Storage as if they were served from your domain otherwise you will run into security issue.

_x000D_
_x000D_
var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    src = "http://example.com/image"; // insert image url here

img.crossOrigin = "Anonymous";

img.onload = function() {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage( img, 0, 0 );
    localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
}
img.src = src;
// make sure the load event fires for cached images too
if ( img.complete || img.complete === undefined ) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
}
_x000D_
_x000D_
_x000D_

Concrete Javascript Regex for Accented Characters (Diacritics)

The easier way to accept all accents is this:

[A-zÀ-ú] // accepts lowercase and uppercase characters
[A-zÀ-ÿ] // as above but including letters with an umlaut (includes [ ] ^ \ × ÷)
[A-Za-zÀ-ÿ] // as above but not including [ ] ^ \
[A-Za-zÀ-ÖØ-öø-ÿ] // as above but not including [ ] ^ \ × ÷

See https://unicode-table.com/en/ for characters listed in numeric order.

GDB: Listing all mapped memory regions for a crashed process

You can also use info files to list all the sections of all the binaries loaded in process binary.

Visual Studio 2017: Display method references

In previous posts I have read that this feature IS available on VS 2015 community if you FIRST install SQL Server express (free) and THEN install VS. I have tried it and it worked. I just had to reinstall Windows and am going thru the same procedure now and it did not work... so will try again :). I know it worked 6 months ago when I tried.

-Ed

Deleting rows with Python in a CSV file

You are very close; currently you compare the row[2] with integer 0, make the comparison with the string "0". When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:

row[2]!="0":

Also, you can use the with keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close statements:

import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != "0":
            writer.writerow(row)

Note that input is a Python builtin, so I've used another variable name instead.


Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0" would work, so you can either use strip(row[2]) != 0, or check against " 0".

The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:

$ cat test.py 
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != " 0":
            writer.writerow(row)
$ cat first.csv 
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py 
$ cat first_edit.csv 
6.5, 5.4, 1, 320

How to beautify JSON in Python?

Try underscore-cli:

cat myfile.json | underscore print --color

It's a pretty nifty tool that can elegantly do a lot of manipulation of structured data, execute js snippets, fill templates, etc. It's ridiculously well documented, polished, and ready for serious use. And I wrote it. :)

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

I was having the same issue when accessing a published ASP.NET Web Api. In my case, I realized that when I was about to publish the Web Api, I had not indicated a connection string inside the Databases section:

After using the three dot button, the connection string will be displayed on the text field to the left

So I generated it using the three dot button, and after publishing, it worked.

What is weird, is that for a long time I am pretty sure that there was no connection string in that configuration but it still worked.

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

bootstrap initially collapsed element

You need to remove "in" from "collapse in"

How to apply a CSS class on hover to dynamically generated submit buttons?

Add the below code

input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;
}

If you need only for these button then you can add id name

#paginate input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;
}

DEMO

sorting dictionary python 3

I'm not sure whether this could help, but I had a similar problem and I managed to solve it, by defining an apposite function:

def sor_dic_key(diction):
    lista = []
    diction2 = {}
    for x in diction:
        lista.append([x, diction[x]])
    lista.sort(key=lambda x: x[0])
    for l in lista:
        diction2[l[0]] = l[1]
    return diction2

This function returns another dictionary with the same keys and relative values, but sorted by its keys. Similarly, I defined a function that could sort a dictionary by its values. I just needed to use x[1] instead of x[0] in the lambda function. I find this second function mostly useless, but one never can tell!

How to configure robots.txt to allow everything?

I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.

As per the official documentation, there are four ways, you can allow complete access for robots to access your site.

Clean:

Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt looks like this.

User-agent: *
Disallow:

The hack:

Create a /robots.txt file with no content in it. Which will default to allow all for all type of Bots.

I don't care way:

Do not create a /robots.txt altogether. Which should yield the exact same results as the above two.

The ugly:

From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots know that these pages are not supposed to be indexed.

<META NAME="ROBOTS" CONTENT="NOINDEX">

In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD tag of the page. More about this meta tag here.

Allow click on twitter bootstrap dropdown toggle link?

For those of you complaining about "the submenus don't drop down", I solved it this way, which looks clean to me:

1) Besides your

<a class="dropdown-toggle disabled" href="http://google.com">
     Dropdown <b class="caret"></b>
</a>

put a new

<a class="dropdown-toggle"><b class="caret"></b></a>

and remove the <b class="caret"></b> tag, so it will look like

<a class="dropdown-toggle disabled" href="http://google.com">
Dropdown</a><a class="dropdown-toggle"><b class="caret"></b></a>

2) Style them with the following css rules:

.caret1 {
    position: absolute !important; top: 0; right: 0;
}

.dropdown-toggle.disabled {
    padding-right: 40px;
}

The style in .caret1 class is for positioning it absolutely inside your li, at the right corner.

The second style is for adding some padding to the right of the dropdown to place the caret, preventing overlapping the text of the menu item.

Now you have a nice responsive menu item which looks nice both in desktop and mobile versions and that is both clickable and dropdownable depending on whether you click on the text or on the caret.

How to subtract X day from a Date object in Java?

Simply use this to get date before 300 days, replace 300 with your days:

Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();

Here,

DateTime is org.joda.time.DateTime;

Date is java.util.Date

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

If you understand the difference between scope and session then it will be very easy to understand these methods.

A very nice blog post by Adam Anderson describes this difference:

Session means the current connection that's executing the command.

Scope means the immediate context of a command. Every stored procedure call executes in its own scope, and nested calls execute in a nested scope within the calling procedure's scope. Likewise, a SQL command executed from an application or SSMS executes in its own scope, and if that command fires any triggers, each trigger executes within its own nested scope.

Thus the differences between the three identity retrieval methods are as follows:

@@identity returns the last identity value generated in this session but any scope.

scope_identity() returns the last identity value generated in this session and this scope.

ident_current() returns the last identity value generated for a particular table in any session and any scope.

What's the difference between Instant and LocalDateTime?

Table of all date-time types in Java, both modern and legacy

tl;dr

Instant and LocalDateTime are two entirely different animals: One represents a moment, the other does not.

  • Instant represents a moment, a specific point in the timeline.
  • LocalDateTime represents a date and a time-of-day. But lacking a time zone or offset-from-UTC, this class cannot represent a moment. It represents potential moments along a range of about 26 to 27 hours, the range of all time zones around the globe. A LocalDateTime value is inherently ambiguous.

Incorrect Presumption

LocalDateTime is rather date/clock representation including time-zones for humans.

Your statement is incorrect: A LocalDateTime has no time zone. Having no time zone is the entire point of that class.

To quote that class’ doc:

This class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

So Local… means “not zoned, no offset”.

Instant

enter image description here

An Instant is a moment on the timeline in UTC, a count of nanoseconds since the epoch of the first moment of 1970 UTC (basically, see class doc for nitty-gritty details). Since most of your business logic, data storage, and data exchange should be in UTC, this is a handy class to be used often.

Instant instant = Instant.now() ;  // Capture the current moment in UTC.

OffsetDateTime

enter image description here

The class OffsetDateTime class represents a moment as a date and time with a context of some number of hours-minutes-seconds ahead of, or behind, UTC. The amount of offset, the number of hours-minutes-seconds, is represented by the ZoneOffset class.

If the number of hours-minutes-seconds is zero, an OffsetDateTime represents a moment in UTC the same as an Instant.

ZoneOffset

enter image description here

The ZoneOffset class represents an offset-from-UTC, a number of hours-minutes-seconds ahead of UTC or behind UTC.

A ZoneOffset is merely a number of hours-minutes-seconds, nothing more. A zone is much more, having a name and a history of changes to offset. So using a zone is always preferable to using a mere offset.

ZoneId

enter image description here

A time zone is represented by the ZoneId class.

A new day dawns earlier in Paris than in Montréal, for example. So we need to move the clock’s hands to better reflect noon (when the Sun is directly overhead) for a given region. The further away eastward/westward from the UTC line in west Europe/Africa the larger the offset.

A time zone is a set of rules for handling adjustments and anomalies as practiced by a local community or region. The most common anomaly is the all-too-popular lunacy known as Daylight Saving Time (DST).

A time zone has the history of past rules, present rules, and rules confirmed for the near future.

These rules change more often than you might expect. Be sure to keep your date-time library's rules, usually a copy of the 'tz' database, up to date. Keeping up-to-date is easier than ever now in Java 8 with Oracle releasing a Timezone Updater Tool.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

Time Zone = Offset + Rules of Adjustments

ZoneId z = ZoneId.of( “Africa/Tunis” ) ; 

ZonedDateTime

enter image description here

Think of ZonedDateTime conceptually as an Instant with an assigned ZoneId.

ZonedDateTime = ( Instant + ZoneId )

To capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone):

ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Pass a `ZoneId` object such as `ZoneId.of( "Europe/Paris" )`. 

Nearly all of your backend, database, business logic, data persistence, data exchange should all be in UTC. But for presentation to users you need to adjust into a time zone expected by the user. This is the purpose of the ZonedDateTime class and the formatter classes used to generate String representations of those date-time values.

ZonedDateTime zdt = instant.atZone( z ) ;
String output = zdt.toString() ;                 // Standard ISO 8601 format.

You can generate text in localized format using DateTimeFormatter.

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ; 
String outputFormatted = zdt.format( f ) ;

mardi 30 avril 2019 à 23 h 22 min 55 s heure de l’Inde

LocalDate, LocalTime, LocalDateTime

Diagram showing only a calendar for a LocalDate.

Diagram showing only a clock for a LocalTime.

Diagram showing a calendar plus clock for a LocalDateTime.

The "local" date time classes, LocalDateTime, LocalDate, LocalTime, are a different kind of critter. The are not tied to any one locality or time zone. They are not tied to the timeline. They have no real meaning until you apply them to a locality to find a point on the timeline.

The word “Local” in these class names may be counter-intuitive to the uninitiated. The word means any locality, or every locality, but not a particular locality.

So for business apps, the "Local" types are not often used as they represent just the general idea of a possible date or time not a specific moment on the timeline. Business apps tend to care about the exact moment an invoice arrived, a product shipped for transport, an employee was hired, or the taxi left the garage. So business app developers use Instant and ZonedDateTime classes most commonly.

So when would we use LocalDateTime? In three situations:

  • We want to apply a certain date and time-of-day across multiple locations.
  • We are booking appointments.
  • We have an intended yet undetermined time zone.

Notice that none of these three cases involve a single certain specific point on the timeline, none of these are a moment.

One time-of-day, multiple moments

Sometimes we want to represent a certain time-of-day on a certain date, but want to apply that into multiple localities across time zones.

For example, "Christmas starts at midnight on the 25th of December 2015" is a LocalDateTime. Midnight strikes at different moments in Paris than in Montréal, and different again in Seattle and in Auckland.

LocalDate ld = LocalDate.of( 2018 , Month.DECEMBER , 25 ) ;
LocalTime lt = LocalTime.MIN ;   // 00:00:00
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;  // Christmas morning anywhere. 

Another example, "Acme Company has a policy that lunchtime starts at 12:30 PM at each of its factories worldwide" is a LocalTime. To have real meaning you need to apply it to the timeline to figure the moment of 12:30 at the Stuttgart factory or 12:30 at the Rabat factory or 12:30 at the Sydney factory.

Booking appointments

Another situation to use LocalDateTime is for booking future events (ex: Dentist appointments). These appointments may be far enough out in the future that you risk politicians redefining the time zone. Politicians often give little forewarning, or even no warning at all. If you mean "3 PM next January 23rd" regardless of how the politicians may play with the clock, then you cannot record a moment – that would see 3 PM turn into 2 PM or 4 PM if that region adopted or dropped Daylight Saving Time, for example.

For appointments, store a LocalDateTime and a ZoneId, kept separately. Later, when generating a schedule, on-the-fly determine a moment by calling LocalDateTime::atZone( ZoneId ) to generate a ZonedDateTime object.

ZonedDateTime zdt = ldt.atZone( z ) ;  // Given a date, a time-of-day, and a time zone, determine a moment, a point on the timeline.

If needed, you can adjust to UTC. Extract an Instant from the ZonedDateTime.

Instant instant = zdt.toInstant() ;  // Adjust from some zone to UTC. Same moment, same point on the timeline, different wall-clock time.

Unknown zone

Some people might use LocalDateTime in a situation where the time zone or offset is unknown.

I consider this case inappropriate and unwise. If a zone or offset is intended but undetermined, you have bad data. That would be like storing a price of a product without knowing the intended currency (dollars, pounds, euros, etc.). Not a good idea.

All date-time types

For completeness, here is a table of all the possible date-time types, both modern and legacy in Java, as well as those defined by the SQL standard. This might help to place the Instant & LocalDateTime classes in a larger context.

Table of all date-time types in Java (both modern & legacy) as well as SQL standard.

Notice the odd choices made by the Java team in designing JDBC 4.2. They chose to support all the java.time times… except for the two most commonly used classes: Instant & ZonedDateTime.

But not to worry. We can easily convert back and forth.

Converting Instant.

// Storing
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;

// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Instant instant = odt.toInstant() ;

Converting ZonedDateTime.

// Storing
OffsetDateTime odt = zdt.toOffsetDateTime() ;
myPreparedStatement.setObject( … , odt ) ;

// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZone( z ) ; 

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

What are the different types of keys in RDBMS?

Sharing my notes which I usually maintain while reading from Internet, I hope it may be helpful to someone

Candidate Key or available keys

Candidate keys are those keys which is candidate for primary key of a table. In simple words we can understand that such type of keys which full fill all the requirements of primary key which is not null and have unique records is a candidate for primary key. So thus type of key is known as candidate key. Every table must have at least one candidate key but at the same time can have several.

Primary Key

Such type of candidate key which is chosen as a primary key for table is known as primary key. Primary keys are used to identify tables. There is only one primary key per table. In SQL Server when we create primary key to any table then a clustered index is automatically created to that column.

Foreign Key

Foreign key are those keys which is used to define relationship between two tables. When we want to implement relationship between two tables then we use concept of foreign key. It is also known as referential integrity. We can create more than one foreign key per table. Foreign key is generally a primary key from one table that appears as a field in another where the first table has a relationship to the second. In other words, if we had a table A with a primary key X that linked to a table B where X was a field in B, then X would be a foreign key in B.

Alternate Key or Secondary

If any table have more than one candidate key, then after choosing primary key from those candidate key, rest of candidate keys are known as an alternate key of that table. Like here we can take a very simple example to understand the concept of alternate key. Suppose we have a table named Employee which has two columns EmpID and EmpMail, both have not null attributes and unique value. So both columns are treated as candidate key. Now we make EmpID as a primary key to that table then EmpMail is known as alternate key.

Composite Key

When we create keys on more than one column then that key is known as composite key. Like here we can take an example to understand this feature. I have a table Student which has two columns Sid and SrefNo and we make primary key on these two column. Then this key is known as composite key.

Natural keys

A natural key is one or more existing data attributes that are unique to the business concept. For the Customer table there was two candidate keys, in this case CustomerNumber and SocialSecurityNumber. Link http://www.agiledata.org/essays/keys.html

Surrogate key

Introduce a new column, called a surrogate key, which is a key that has no business meaning. An example of which is the AddressID column of the Address table in Figure 1. Addresses don't have an "easy" natural key because you would need to use all of the columns of the Address table to form a key for itself (you might be able to get away with just the combination of Street and ZipCode depending on your problem domain), therefore introducing a surrogate key is a much better option in this case. Link http://www.agiledata.org/essays/keys.html

Unique key

A unique key is a superkey--that is, in the relational model of database organization, a set of attributes of a relation variable for which it holds that in all relations assigned to that variable, there are no two distinct tuples (rows) that have the same values for the attributes in this set

Aggregate or Compound keys

When more than one column is combined to form a unique key, their combined value is used to access each row and maintain uniqueness. These keys are referred to as aggregate or compound keys. Values are not combined, they are compared using their data types.

Simple key

Simple key made from only one attribute.

Super key

A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a super key can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent.

Partial Key or Discriminator key

It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator.

Loading DLLs at runtime in C#

Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1 in order to call the method:

class Program
{
    static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var theType = DLL.GetType("DLL.Class1");
        var c = Activator.CreateInstance(theType);
        var method = theType.GetMethod("Output");
        method.Invoke(c, new object[]{@"Hello"});

        Console.ReadLine();
    }
}

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Just check if the request has a status code 200. So for example:

if status != 200:
    print("An error has occured. [Status code", status, "]")
else:
    data = response.json() #Only convert to Json when status is OK.
    if not data["elements"]:
        print("Empty JSON")
    else:
        "You can extract data here"

Razor View Engine : An expression tree may not contain a dynamic operation

Before using (strongly type html helper into view) this line

@Html.TextBoxFor(p => p.Product.Name)

You should include your model into you page for making strongly type view.

@model SampleModel

What is code coverage and how do YOU measure it?

Complementing a few points to many of the previous answers:

Code coverage means, how well your test set is covering your source code. i.e. to what extent is the source code covered by the set of test cases.

As mentioned in above answers, there are various coverage criteria, like paths, conditions, functions, statements, etc. But additional criteria to be covered are

  1. Condition coverage: All boolean expressions to be evaluated for true and false.
  2. Decision coverage: Not just boolean expressions to be evaluated for true and false once, but to cover all subsequent if-elseif-else body.
  3. Loop Coverage: means, has every possible loop been executed one time, more than once and zero time. Also, if we have assumption on max limit, then, if feasible, test maximum limit times and, one more than maximum limit times.
  4. Entry and Exit Coverage: Test for all possible call and its return value.
  5. Parameter Value Coverage (PVC). To check if all possible values for a parameter are tested. For example, a string could be any of these commonly: a) null, b) empty, c) whitespace (space, tabs, new line), d) valid string, e) invalid string, f) single-byte string, g) double-byte string. Failure to test each possible parameter value may leave a bug. Testing only one of these could result in 100% code coverage as each line is covered, but as only one of seven options are tested, means, only 14.2% coverage of parameter value.
  6. Inheritance Coverage: In case of object oriented source, when returning a derived object referred by base class, coverage to evaluate, if sibling object is returned, should be tested.

Note: Static code analysis will find if there are any unreachable code or hanging code, i.e. code not covered by any other function call. And also other static coverage. Even if static code analysis reports that 100% code is covered, it does not give reports about your testing set if all possible code coverage is tested.

jQuery post() with serialize and extra data

You could have the form contain the additional data as hidden fields which you would set right before sending the AJAX request to the corresponding values.

Another possibility consists into using this little gem to serialize your form into a javascript object (instead of string) and add the missing data:

var data = $('#myForm').serializeObject();
// now add some additional stuff
data['wordlist'] = wordlist;
$.post('/page.php', data);

C - freeing structs

First you should know, how much memory is allocated when you define and allocate memory in below case.

   typedef struct person{
       char firstName[100], surName[51]
  } PERSON;
  PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));

1) The sizeof(PERSON) now returns 151 bytes (Doesn't include padding)

2) The memory of 151 bytes is allocated in heap.

3) To free, call free(testPerson).

but If you declare your structure as

  typedef struct person{
      char *firstName, *surName;
  } PERSON;
  PERSON *testPerson = (PERSON*) malloc(sizeof(PERSON));

then

1) The sizeof(PERSON) now returns 8 bytes (Doesn't include padding)

2) Need to allocate memory for firstName and surName by calling malloc() or calloc(). like

        testPerson->firstName = (char *)malloc(100);

3) To free, first free the members in the struct than free the struct. i.e, free(testPerson->firstName); free(testPerson->surName); free(testPerson);

CakePHP 3.0 installation: intl extension missing from system

MAKE this

In XAMPP, intl extension is included but you have to uncomment extension=php_intl.dll in php.ini and restart the server through the XAMPP Control Panel. In WAMP, the intl extension is “activated” by default but not working. To make it work you have to go to php folder (by default) C:\wamp\bin\php\php{version}, copy all the files that looks like icu*.dll and paste them into the apache bin directory C:\wamp\bin\apache\apache{version}\bin. Then restart all services and it should be OK.

if you use XAMPP do this 1. turn off XAMPP 2. Modifed the php.ini is located in c/:xampp/php/php.ini 3. intl extension is included but you have to uncomment extension=php_intl.dll in php.ini and restart the server through the XAMPP Control Panel.

Drop columns whose name contains a specific string from pandas DataFrame

Solution when dropping a list of column names containing regex. I prefer this approach because I'm frequently editing the drop list. Uses a negative filter regex for the drop list.

drop_column_names = ['A','B.+','C.*']
drop_columns_regex = '^(?!(?:'+'|'.join(drop_column_names)+')$)'
print('Dropping columns:',', '.join([c for c in df.columns if re.search(drop_columns_regex,c)]))
df = df.filter(regex=drop_columns_regex,axis=1)

Before and After Suite execution hook in jUnit 4.x

Using annotations, you can do something like this:

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;

class SomethingUnitTest {
    @BeforeClass
    public static void runBeforeClass()
    {

    }

    @AfterClass
    public static void runAfterClass()
    {  

    }

    @Before  
    public void setUp()
    {

    }

    @After
    public void tearDown()
    {

    }

    @Test
    public void testSomethingOrOther()
    {

    }

}

bash: mkvirtualenv: command not found

Use this procedure to create virtual env in ubuntu

Step 1

Install pip

   sudo apt-get install python-pip

step 2

Install virtualenv

   sudo pip install virtualenv

step 3

Create a dir to store your virtualenvs (I use ~/.virtualenvs)

   mkdir ~/.virtualenvs

or use this command to install specific version of python in env

virtualenv -p /usr/bin/python3.6 venv

step 4

   sudo pip install virtualenvwrapper

step 5

   sudo nano ~/.bashrc

step 6

Add this two line code at the end of the bashrc file

  export WORKON_HOME=~/.virtualenvs
  source /usr/local/bin/virtualenvwrapper.sh

step 7

Open new terminal (recommended)

step 8

Create a new virtualenv

  mkvirtualenv myawesomeproject

step 9

To load or switch between virtualenvs, use the workon command:

  workon myawesomeproject

step 10

To exit your new virtualenv, use

 deactivate

and make sure using pip vs pip3

OR follow the steps below to install virtual environment using python3

Install env

python3 -m venv my-project-env

and activate your virtual environment using the following command:

source my-project-env/bin/activate

or if you want particular python version

virtualenv --python=python3.7.5 myenv

Equivalent of explode() to work with strings in MySQL

MYSQL has no explode() like function built in. But you can easily add similar function to your DB and then use it from php queries. That function will look like:

CREATE FUNCTION SPLIT_STRING(str VARCHAR(255), delim VARCHAR(12), pos INT)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos),
       CHAR_LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1),
       delim, '');

Usage:

SELECT SPLIT_STRING('apple, pear, melon', ',', 1)

The example above will return apple. I think that it will be impossible to return array in MySQL so you must specify which occurrence to return explicitly in pos. Let me know if you succeed using it.

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

Set the GET query parameters as managed properties in faces-config.xml so that you don't need to gather them manually:

<managed-bean>
    <managed-bean-name>forward</managed-bean-name>
    <managed-bean-class>com.example.ForwardBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>action</property-name>
        <value>#{param.action}</value>
    </managed-property>
    <managed-property>
        <property-name>actionParam</property-name>
        <value>#{param.actionParam}</value>
    </managed-property>
</managed-bean>

This way the request forward.jsf?action=outcome1&actionParam=123 will let JSF set the action and actionParam parameters as action and actionParam properties of the ForwardBean.

Create a small view forward.xhtml (so small that it fits in default response buffer (often 2KB) so that it can be resetted by the navigationhandler, otherwise you've to increase the response buffer in the servletcontainer's configuration), which invokes a bean method on beforePhase of the f:view:

<!DOCTYPE html>
<html xmlns:f="http://java.sun.com/jsf/core">
    <f:view beforePhase="#{forward.navigate}" />
</html>

The ForwardBean can look like this:

public class ForwardBean {
    private String action;
    private String actionParam;

    public void navigate(PhaseEvent event) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String outcome = action; // Do your thing?
        facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);
    }

    // Add/generate the usual boilerplate.
}

The navigation-rule speaks for itself (note the <redirect /> entries which would do ExternalContext#redirect() instead of ExternalContext#dispatch() under the covers):

<navigation-rule>
    <navigation-case>
        <from-outcome>outcome1</from-outcome>
        <to-view-id>/outcome1.xhtml</to-view-id>
        <redirect />
    </navigation-case>
    <navigation-case>
        <from-outcome>outcome2</from-outcome>
        <to-view-id>/outcome2.xhtml</to-view-id>
        <redirect />
    </navigation-case>
</navigation-rule>

An alternative is to use forward.xhtml as

<!DOCTYPE html>
<html>#{forward}</html>

and update the navigate() method to be invoked on @PostConstruct (which will be invoked after bean's construction and all managed property setting):

@PostConstruct
public void navigate() {
    // ...
}    

It has the same effect, however the view side is not really self-documenting. All it basically does is printing ForwardBean#toString() (and hereby implicitly constructing the bean if not present yet).


Note for the JSF2 users, there is a cleaner way of passing parameters with <f:viewParam> and more robust way of handling the redirect/navigation by <f:event type="preRenderView">. See also among others:

Can promises have multiple arguments to onFulfilled?

You can use E6 destructuring:

Object destructuring:

promise = new Promise(function(onFulfilled, onRejected){
    onFulfilled({arg1: value1, arg2: value2});
})

promise.then(({arg1, arg2}) => {
    // ....
});

Array destructuring:

promise = new Promise(function(onFulfilled, onRejected){
    onFulfilled([value1, value2]);
})

promise.then(([arg1, arg2]) => {
    // ....
});

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

Pentaho Data Integration SQL connection

Missing driver file.

This error is really common for people just getting started with PDI.

Drivers go in \pentaho\design-tools\data-integration\libext\JDBC for PDI. If you are using other tools in the Pentaho suite, you may need to copy drivers to additional locations for those tools. For reference, here are the appropriate folders for some of the other design tools:

  • Aggregation Designer: \pentaho\design-tools\aggregation-designer\drivers
  • Metadata Editor: \pentaho\design-tools\metadata-editor\libext\JDBC
  • Report Designer: \pentaho\design-tools\report-designer\lib\jdbc
  • Schema Workbench: \pentaho\design-tools\schema-workbench\drivers

If this transformation or job will run on another box, such as a test or production server, don't forget to include copying the jar file and restarting PDI or the Data Integration Server in your deployment considerations.

memcpy() vs memmove()

As already pointed out in other answers, memmove is more sophisticated than memcpy such that it accounts for memory overlaps. The result of memmove is defined as if the src was copied into a buffer and then buffer copied into dst. This does NOT mean that the actual implementation uses any buffer, but probably does some pointer arithmetic.

How to update a single library with Composer?

You can basically do following one to install new package as well.

php composer.phar require

then terminal will ask you to enter the name of the package for searching.

$ Search for a package []: //Your package name here

Then terminal will ask the version of the package (If you would like to have the latest version just leave it blank)

$ Enter the version constraint to require (or leave blank to use the latest version) []: //your version number here

Then you just press the return key. Terminal will ask for another package, if you dont want to install another one just press the return key and you will be done.

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

I had the same problem and I chosed to create my own encoder, which will cope by themself with recursion.

I created classes which implements Symfony\Component\Serializer\Normalizer\NormalizerInterface, and a service which holds every NormalizerInterface.

#This is the NormalizerService

class NormalizerService 
{

   //normalizer are stored in private properties
   private $entityOneNormalizer;
   private $entityTwoNormalizer;

   public function getEntityOneNormalizer()
   {
    //Normalizer are created only if needed
    if ($this->entityOneNormalizer == null)
        $this->entityOneNormalizer = new EntityOneNormalizer($this); //every normalizer keep a reference to this service

    return $this->entityOneNormalizer;
   }

   //create a function for each normalizer



  //the serializer service will also serialize the entities 
  //(i found it easier, but you don't really need it)
   public function serialize($objects, $format)
   {
     $serializer = new Serializer(
            array(
                $this->getEntityOneNormalizer(),
                $this->getEntityTwoNormalizer()
            ),
            array($format => $encoder) );

     return $serializer->serialize($response, $format);
}

An example of a Normalizer :

use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class PlaceNormalizer implements NormalizerInterface {

private $normalizerService;

public function __construct($normalizerService)
{
    $this->service = normalizerService;

}

public function normalize($object, $format = null) {
    $entityTwo = $object->getEntityTwo();
    $entityTwoNormalizer = $this->service->getEntityTwoNormalizer();

    return array(
        'param' => object->getParam(),
        //repeat for every parameter
        //!!!! this is where the entityOneNormalizer dealt with recursivity
        'entityTwo' => $entityTwoNormalizer->normalize($entityTwo, $format.'_without_any_entity_one') //the 'format' parameter is adapted for ignoring entity one - this may be done with different ways (a specific method, etc.)
    );
}

}

In a controller :

$normalizerService = $this->get('normalizer.service'); //you will have to configure services.yml
$json = $normalizerService->serialize($myobject, 'json');
return new Response($json);

The complete code is here : https://github.com/progracqteur/WikiPedale/tree/master/src/Progracqteur/WikipedaleBundle/Resources/Normalizer

How can you check for a #hash in a URL using JavaScript?

Put the following:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

If it gets into the selinux arena you've got a much more complicated issue. It's not a good idea to remove the selinux protection but to embrace it and use the tools that were designed to manage it.

If you are serving content out of /var/www/abc, you can verify the selinux permissions with a Z appended to the normal ls -l command. i.e. ls -laZ will give the selinux context.

To add a directory to be served by selinux you can use the semanage command like this. This will change the label on /var/www/abc to httpd_sys_content_t

semanage fcontext -a -t httpd_sys_content_t /var/www/abc

this will update the label for /var/www/abc

restorecon /var/www/abc 

This answer was taken from unixmen and modified to fit this question. I had been searching for this answer for a while and finally found it so felt like I needed to share somewhere. Hope it helps someone.

Java 256-bit AES Password-Based Encryption

What I've done in the past is hash the key via something like SHA256, then extract the bytes from the hash into the key byte[].

After you have your byte[] you can simply do:

SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(clearText.getBytes());

What causes HttpHostConnectException?

A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.

If this is happening intermittently, then the most likely explanations are (IMO):

  • the server you are talking ("proxy.xyz.com" / port 60) to is going up and down, OR
  • there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.

Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.

It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.


1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.

Is it possible to reference one CSS rule within another?

You can't unless you're using some kind of extended CSS such as SASS. However it is very reasonable to apply those two extra classes to .someDiv.

If .someDiv is unique I would also choose to give it an id and referencing it in css using the id.

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

Here is a function that parses without raising errors. It handles obvious cases returns None on failure (handles up to 2000 '-/+' signs by default on CPython!):

#!/usr/bin/env python

def get_int(number):
    splits = number.split('.')
    if len(splits) > 2:
        # too many splits
        return None
    if len(splits) == 2 and splits[1]:
        # handle decimal part recursively :-)
        if get_int(splits[1]) != 0:
            return None

    int_part = splits[0].lstrip("+")
    if int_part.startswith('-'):
        # handle minus sign recursively :-)
        return get_int(int_part[1:]) * -1
    # successful 'and' returns last truth-y value (cast is always valid)
    return int_part.isdigit() and int(int_part)

Some tests:

tests = ["0", "0.0", "0.1", "1", "1.1", "1.0", "-1", "-1.1", "-1.0", "-0", "--0", "---3", '.3', '--3.', "+13", "+-1.00", "--+123", "-0.000"]

for t in tests:
    print "get_int(%s) = %s" % (t, get_int(str(t)))

Results:

get_int(0) = 0
get_int(0.0) = 0
get_int(0.1) = None
get_int(1) = 1
get_int(1.1) = None
get_int(1.0) = 1
get_int(-1) = -1
get_int(-1.1) = None
get_int(-1.0) = -1
get_int(-0) = 0
get_int(--0) = 0
get_int(---3) = -3
get_int(.3) = None
get_int(--3.) = 3
get_int(+13) = 13
get_int(+-1.00) = -1
get_int(--+123) = 123
get_int(-0.000) = 0

For your needs you can use:

def int_predicate(number):
     return get_int(number) is not None

linux script to kill java process

Use jps to list running java processes. The command returns the process id along with the main class. You can use kill command to kill the process with the returned id or use following one liner script.

kill $(jps | grep <MainClass> | awk '{print $1}')

MainClass is a class in your running java program which contains the main method.

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

I have found when I am using a manifest that the listing of jars for the classpath need to have a space after the listing of each jar e.g. "required_lib/sun/pop3.jar required_lib/sun/smtp.jar ". Even if it is the last in the list.

Various ways to remove local Git changes

I think git has one thing that isn't clearly documented. I think it was actually neglected.

git checkout .

Man, you saved my day. I always have things I want to try using the modified code. But the things sometimes end up messing the modified code, add new untracked files etc. So what I want to do is, stage what I want, do the messy stuff, then cleanup quickly and commit if I'm happy.

There's git clean -fd works well for untracked files.

Then git reset simply removes staged, but git checkout is kinda too cumbersome. Specifying file one by one or using directories isn't always ideal. Sometimes the changed files I want to get rid of are within directories I want to keep. I wished for this one command that just removes unstaged changes and here you're. Thanks.

But I think they should just have git checkout without any options, remove all unstaged changes and not touch the the staged. It's kinda modular and intuitive. More like what git reset does. git clean should also do the same.

Why is my CSS style not being applied?

Have you tried forcing the selectors to be in the front of the class?

p span label.fancify {

    font-size: 1.5em;
    font-weight: 800;
    font-family: Consolas, "Segoe UI", Calibri, sans-serif;
    font-style: italic;
}

Usually it will add more weight to your CSS declaration. My mistake ... There should be no space between the selector and the class. The same goes for the ID. If you have for example:

<div id="first">
    <p id="myParagraph">Hello <span class="bolder">World</span></p>
</div>

You would style it like this:

div#first p#myParagraph {
     color : #ff0000;
}

Just to make a complete example using a class:

div#first p#myParagraph span.bolder{
    font-weight:900;
}

For more information about pseudo-selectors and child selectors : http://www.w3.org/TR/CSS2/selector.html

CSS is a whole science :) Beware that some browsers can have incompatibilities and will not show you the proper results. For more information check this site: http://www.caniuse.com/

How to deal with floating point number precision in JavaScript?

0.6 * 3 it's awesome!)) For me this works fine:

function dec( num )
{
    var p = 100;
    return Math.round( num * p ) / p;
}

Very very simple))

try/catch with InputMismatchException creates infinite loop

You need to call next(); when you get the error. Also it is advisable to use hasNextInt()

       catch (Exception e) {
            System.out.println("Error!");
           input.next();// Move to next other wise exception
        }

Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.

    Scanner scanner = new Scanner(System.in);
    int n1 = 0, n2 = 0;
    boolean bError = true;
    while (bError) {
        if (scanner.hasNextInt())
            n1 = scanner.nextInt();
        else {
            scanner.next();
            continue;
        }
        if (scanner.hasNextInt())
            n2 = scanner.nextInt();
        else {
            scanner.next();
            continue;
        }
        bError = false;
    }
    System.out.println(n1);
    System.out.println(n2);

Javadoc of Scanner

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

Detailed 500 error message, ASP + IIS 7.5

Fot people who have tried EVERYTHING and just CANNOT get the error details to show, like me, it's a good idea to check the different levels of configuration. I have a config file on Website level and on Application level (inside the website) check both. Also, as it turned out, I had Detailed Errors disabled on the highest node in IIS (just underneath Start Page, it has the name that is the same as the webservers computername). Check the Error Pages there.

How to reverse a 'rails generate'

Suppose I have created a controller named "sample" like:

rails generate controller sample

If I have to destroy this controller, all I have to do is swap generate with destroy, as in

rails destroy controller sample.

If you want to reverse the generation, all you have to do is swap generate with destroy.

Could not resolve all dependencies for configuration ':classpath'

you should have gradle.properties file defined for the build with proxy settings so that gradle knows how to use http connection

# This file contains the basics for Maven Version control and will be used by the Artifactory Release management
# These settings are for the root project and all sub-projects in this application
releaseVersion=1.0.0-SNAPSHOT
releaseGroup=com.xx.xx.xx
artifactory_user=
artifactory_password=
artifactory_contextUrl=https://artifactory.xxxx.com/artifactory/
systemProp.http.proxyHost=proxy.xxx.com
systemProp.http.proxyPort=8080
systemProp.https.proxyHost=proxy.xxx.com
systemProp.https.proxyPort=8080
systemProp.http.nonProxyHosts=*.xxx.com|localhost|*.int.targoe.com
org.gradle.java.home=C:\\Program Files (x86)\\Java\\jdk1.8.0_121

How to sort an array of ints using a custom comparator?

I tried maximum to use the comparator with primitive type itself. At-last i concluded that there is no way to cheat the comparator.This is my implementation.

public class ArrSortComptr {
    public static void main(String[] args) {

         int[] array = { 3, 2, 1, 5, 8, 6 };
         int[] sortedArr=SortPrimitiveInt(new intComp(),array);
         System.out.println("InPut "+ Arrays.toString(array));
         System.out.println("OutPut "+ Arrays.toString(sortedArr));

    }
 static int[] SortPrimitiveInt(Comparator<Integer> com,int ... arr)
 {
    Integer[] objInt=intToObject(arr);
    Arrays.sort(objInt,com);
    return intObjToPrimitive(objInt);

 }
 static Integer[] intToObject(int ... arr)
 {
    Integer[] a=new Integer[arr.length];
    int cnt=0;
    for(int val:arr)
      a[cnt++]=new Integer(val);
    return a;
 }
 static int[] intObjToPrimitive(Integer ... arr)
 {
     int[] a=new int[arr.length];
     int cnt=0;
     for(Integer val:arr)
         if(val!=null)
             a[cnt++]=val.intValue();
     return a;

 }

}
class intComp implements Comparator<Integer>
{

    @Override //your comparator implementation.
    public int compare(Integer o1, Integer o2) {
        // TODO Auto-generated method stub
        return o1.compareTo(o2);
    }

}

@Roman: I can't say that this is a good example but since you asked this is what came to my mind. Suppose in an array you want to sort number's just based on their absolute value.

Integer d1=Math.abs(o1);
Integer d2=Math.abs(o2);
return d1.compareTo(d2);

Another example can be like you want to sort only numbers greater than 100.It actually depends on the situation.I can't think of any more situations.Maybe Alexandru can give more examples since he say's he want's to use a comparator for int array.

ASP.NET MVC 3 - redirect to another action

return RedirectToAction("ActionName", "ControllerName");

JavaScript private methods

I know it's a bit too late but how about this?

var obj = function(){
    var pr = "private";
    var prt = Object.getPrototypeOf(this);
    if(!prt.hasOwnProperty("showPrivate")){
        prt.showPrivate = function(){
            console.log(pr);
        }
    }    
}

var i = new obj();
i.showPrivate();
console.log(i.hasOwnProperty("pr"));

How can I check if a string contains a character in C#?

You can create your own extention method if you plan to use this a lot.

public static class StringExt
{
    public static bool ContainsInvariant(this string sourceString, string filter)
    {
        return sourceString.ToLowerInvariant().Contains(filter);
    }
}

example usage:

public class test
{
    public bool Foo()
    {
        const string def = "aB";
        return def.ContainsInvariant("s");
    }
}

What's the difference between utf8_general_ci and utf8_unicode_ci?

I wanted to know what is the performance difference between using utf8_general_ci and utf8_unicode_ci, but I did not find any benchmarks listed on the internet, so I decided to create benchmarks myself.

I created a very simple table with 500,000 rows:

CREATE TABLE test(
  ID INT(11) DEFAULT NULL,
  Description VARCHAR(20) DEFAULT NULL
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;

Then I filled it with random data by running this stored procedure:

CREATE PROCEDURE randomizer()
BEGIN
  DECLARE i INT DEFAULT 0;
  DECLARE random CHAR(20) ;
  theloop: loop
    SET random = CONV(FLOOR(RAND() * 99999999999999), 20, 36);
    INSERT INTO test VALUES (i+1, random);
    SET i=i+1;
    IF i = 500000 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END

Then I created the following stored procedures to benchmark simple SELECT, SELECT with LIKE, and sorting (SELECT with ORDER BY):

CREATE PROCEDURE benchmark_simple_select()
BEGIN
  DECLARE i INT DEFAULT 0;
  theloop: loop
    SELECT *
    FROM test
    WHERE Description = 'test' COLLATE utf8_general_ci;
    SET i = i + 1;
    IF i = 30 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END;

CREATE PROCEDURE benchmark_select_like()
BEGIN
  DECLARE i INT DEFAULT 0;
  theloop: loop
    SELECT *
    FROM test
    WHERE Description LIKE '%test' COLLATE utf8_general_ci;
    SET i = i + 1;
    IF i = 30 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END;

CREATE PROCEDURE benchmark_order_by()
BEGIN
  DECLARE i INT DEFAULT 0;
  theloop: loop
    SELECT *
    FROM test
    WHERE ID > FLOOR(1 + RAND() * (400000 - 1))
    ORDER BY Description COLLATE utf8_general_ci LIMIT 1000;
    SET i = i + 1;
    IF i = 10 THEN
      LEAVE theloop;
    END IF;
  END LOOP theloop;
END;

In the stored procedures above utf8_general_ci collation is used, but of course during the tests I used both utf8_general_ci and utf8_unicode_ci.

I called each stored procedure 5 times for each collation (5 times for utf8_general_ci and 5 times for utf8_unicode_ci) and then calculated the average values.

My results are:

benchmark_simple_select()

  • with utf8_general_ci: 9,957 ms
  • with utf8_unicode_ci: 10,271 ms

In this benchmark using utf8_unicode_ci is slower than utf8_general_ci by 3.2%.

benchmark_select_like()

  • with utf8_general_ci: 11,441 ms
  • with utf8_unicode_ci: 12,811 ms

In this benchmark using utf8_unicode_ci is slower than utf8_general_ci by 12%.

benchmark_order_by()

  • with utf8_general_ci: 11,944 ms
  • with utf8_unicode_ci: 12,887 ms

In this benchmark using utf8_unicode_ci is slower than utf8_general_ci by 7.9%.

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

Since no one gave this answer, I would also like to add that, you can just add the jdbc driver file(mysql-connector-java-5.1.27-bin.jar in my case) to the lib folder of your server(Tomcat in my case). Restart the server and it should work.

How to run PowerShell in CMD

Try just:

powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"

Write a file in external storage in Android

Even though above answers are correct, I wanna add a notice to distinguish types of storage:

  • Internal storage: It should say 'private storage' because it belongs to the app and cannot be shared. Where it's saved is based on where the app installed. If the app was installed on an SD card (I mean the external storage card you put more into a cell phone for more space to store images, videos, ...), your file will belong to the app means your file will be in an SD card. And if the app was installed on an Internal card (I mean the onboard storage card coming with your cell phone), your file will be in an Internal card.
  • External storage: It should say 'public storage' because it can be shared. And this mode divides into 2 groups: private external storage and public external storage. Basically, they are nearly the same, you can consult more from this site: https://developer.android.com/training/data-storage/files
  • A real SD card (I mean the external storage card you put more into a cell phone for more space to store images, videos, ...): this was not stated clearly on Android docs, so many people might be confused with how to save files in this card.

Here is the link to source code for cases I mentioned above: https://github.com/mttdat/utils/blob/master/utils/src/main/java/mttdat/utils/FileUtils.java

How to sort a collection by date in MongoDB?

if your date format is like this : 14/02/1989 ----> you may find some problems

you need to use ISOdate like this :

var start_date = new Date(2012, 07, x, x, x); 

-----> the result ------>ISODate("2012-07-14T08:14:00.201Z")

now just use the query like this :

 collection.find( { query : query ,$orderby :{start_date : -1}} ,function (err, cursor) {...}

that's it :)

New line in JavaScript alert box

you have to use double quotes to display special char like \n \t etc... in js alert box for exemple in php script:

$string = 'Hello everybody \n this is an alert box';
echo "<script>alert(\"$string\")</script>";

But a second possible problem arrives when you want to display a string specified in double quoted.

see link text

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters

escape sequences \n is transformed as 0x0A ASCII Escaped character and this character is not displayed in the alert box. The solution consists in to escape this special sequence:

$s = "Hello everybody \\n this is an alert box";
echo "<script>alert(\"$string\")</script>";

if you don't know how the string is enclosed you have to transform special characters to their escape sequences

$patterns = array("/\\\\/", '/\n/', '/\r/', '/\t/', '/\v/', '/\f/');
$replacements = array('\\\\\\', '\n', '\r', '\t', '\v', '\f');
$string = preg_replace($patterns, $replacements, $string);
echo "<script>alert(\"$string\")</script>";

Class name does not name a type in C++

The problem is that you need to include B.h in your A.h file. The problem is that in the definition of A, the compiler still doesn't know what B is. You should include all the definitions of all the types you are using.

Gunicorn worker timeout error

The Microsoft Azure official documentation for running Flask Apps on Azure App Services (Linux App) states the use of timeout as 600

gunicorn --bind=0.0.0.0 --timeout 600 application:app

https://docs.microsoft.com/en-us/azure/app-service/configure-language-python#flask-app

python int( ) function

int() only works for strings that look like integers; it will fail for strings that look like floats. Use float() instead.

How to randomize Excel rows

Here's a macro that allows you to shuffle selected cells in a column:

Option Explicit

Sub ShuffleSelectedCells()
  'Do nothing if selecting only one cell
  If Selection.Cells.Count = 1 Then Exit Sub
  'Save selected cells to array
  Dim CellData() As Variant
  CellData = Selection.Value
  'Shuffle the array
  ShuffleArrayInPlace CellData
  'Output array to spreadsheet
  Selection.Value = CellData
End Sub

Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Dim J As Long, _
    N As Long, _
    Temp As Variant
  'Randomize
  For N = LBound(InArray) To UBound(InArray)
    J = CLng(((UBound(InArray) - N) * Rnd) + N)
    If J <> N Then
      Temp = InArray(N, 1)
      InArray(N, 1) = InArray(J, 1)
      InArray(J, 1) = Temp
    End If
  Next N
End Sub

You can read the comments to see what the macro is doing. Here's how to install the macro:

  1. Open the VBA editor (Alt + F11).
  2. Right-click on "ThisWorkbook" under your currently open spreadsheet (listed in parentheses after "VBAProject") and select Insert / Module.
  3. Paste the code above and save the spreadsheet.

Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).

MySQL: Fastest way to count number of rows

Try this:

SELECT
    table_rows "Rows Count"
FROM
    information_schema.tables
WHERE
    table_name="Table_Name"
AND
    table_schema="Database_Name";

What are the differences between Abstract Factory and Factory design patterns?

Understand the differences in the motivations:

Suppose you’re building a tool where you’ve objects and a concrete implementation of the interrelations of the objects. Since you foresee variations in the objects, you’ve created an indirection by assigning the responsibility of creating variants of the objects to another object (we call it abstract factory). This abstraction finds strong benefit since you foresee future extensions needing variants of those objects.

Another rather intriguing motivation in this line of thoughts is a case where every-or-none of the objects from the whole group will have a corresponding variant. Based on some conditions, either of the variants will be used and in each case all objects must be of same variant. This might be a bit counter intuitive to understand as we often tend think that - as long as the variants of an object follow a common uniform contract (interface in broader sense), the concrete implementation code should never break. The intriguing fact here is that, not always this is true especially when expected behavior cannot be modeled by a programming contract.

A simple (borrowing the idea from GoF) is any GUI applications say a virtual monitor that emulates look-an-feel of MS or Mac or Fedora OS’s. Here, for example, when all widget objects such as window, button, etc. have MS variant except a scroll-bar that is derived from MAC variant, the purpose of the tool fails badly.

These above cases form the fundamental need of Abstract Factory Pattern.

On the other hand, imagine you’re writing a framework so that many people can built various tools (such as the one in above examples) using your framework. By the very idea of a framework, you don’t need to, albeit you could not use concrete objects in your logic. You rather put some high level contracts between various objects and how they interact. While you (as a framework developer) remain at a very abstract level, each builders of the tool is forced to follow your framework-constructs. However, they (the tool builders) have the freedom to decide what object to be built and how all the objects they create will interact. Unlike the previous case (of Abstract Factory Pattern), you (as framework creator) don’t need to work with concrete objects in this case; and rather can stay at the contract level of the objects. Furthermore, unlike the second part of the previous motivations, you or the tool-builders never have the situations of mixing objects from variants. Here, while framework code remains at contract level, every tool-builder is restricted (by the nature of the case itself) to using their own objects. Object creations in this case is delegated to each implementer and framework providers just provide uniform methods for creating and returning objects. Such methods are inevitable for framework developer to proceed with their code and has a special name called Factory method (Factory Method Pattern for the underlying pattern).

Few Notes:

  • If you’re familiar with ‘template method’, then you’d see that factory methods are often invoked from template methods in case of programs pertaining to any form of framework. By contrast, template methods of application-programs are often simple implementation of specific algorithm and void of factory-methods.
  • Furthermore, for the completeness of the thoughts, using the framework (mentioned above), when a tool-builder is building a tool, inside each factory method, instead of creating a concrete object, he/she may further delegate the responsibility to an abstract-factory object, provided the tool-builder foresees variations of the concrete objects for future extensions.

Sample Code:

//Part of framework-code
BoardGame {
    Board createBoard() //factory method. Default implementation can be provided as well
    Piece createPiece() //factory method

    startGame(){        //template method
         Board borad = createBoard()
         Piece piece = createPiece()
         initState(board, piece)
    }
}


//Part of Tool-builder code
Ludo inherits  BoardGame {
     Board createBoard(){ //overriding of factory method
         //Option A: return new LudoBoard() //Lodu knows object creation
         //Option B: return LudoFactory.createBoard() //Lodu asks AbstractFacory
     }
….
}

//Part of Tool-builder code
Chess inherits  BoardGame {
    Board createBoard(){ //overriding of factory method
        //return a Chess board
    }
    ….
}

Undefined reference to pthread_create in Linux

You need to use the option -lpthread with gcc.