Programs & Examples On #Diacritics

A Diacritic is a mark near or through an orthographic or phonetic character or combination of characters indicating a phonetic value different from that given the unmarked or otherwise marked element - http://www.merriam-webster.com/dictionary/diacritic

Microsoft Excel mangles Diacritics in .csv files?

With Ruby 1.8.7 I encode every field to UTF-16 and discard BOM (maybe).

The following code is extracted from active_scaffold_export:

<%                                                                                                                                                                                                                                                                                                                           
      require 'fastercsv'                                                                                                                                                                                                                                                                                                        
      fcsv_options = {                                                                                                                                                                                                                                                                                                           
        :row_sep => "\n",                                                                                                                                                                                                                                                                                                        
        :col_sep => params[:delimiter],                                                                                                                                                                                                                                                                                          
        :force_quotes => @export_config.force_quotes,                                                                                                                                                                                                                                                                            
        :headers => @export_columns.collect { |column| format_export_column_header_name(column) }                                                                                                                                                                                                                                
      }                                                                                                                                                                                                                                                                                                                          

      data = FasterCSV.generate(fcsv_options) do |csv|                                                                                                                                                                                                                                                                           
        csv << fcsv_options[:headers] unless params[:skip_header] == 'true'                                                                                                                                                                                                                                                      
        @records.each do |record|                                                                                                                                                                                                                                                                                                
          csv << @export_columns.collect { |column|                                                                                                                                                                                                                                                                              
            # Convert to UTF-16 discarding the BOM, required for Excel (> 2003 ?)                                                                                                                                                                                                                                     
            Iconv.conv('UTF-16', 'UTF-8', get_export_column_value(record, column))[2..-1]                                                                                                                                                                                                                                        
          }                                                                                                                                                                                                                                                                                                                      
        end                                                                                                                                                                                                                                                                                                                      
      end                                                                                                                                                                                                                                                                                                                        
    -%><%= data -%>

The important line is:

Iconv.conv('UTF-16', 'UTF-8', get_export_column_value(record, column))[2..-1]

Converting Symbols, Accent Letters to English Alphabet

The original request has been answered already.

However, I am posting the below answer for those who might be looking for generic transliteration code to transliterate any charset to Latin/English in Java.

Naive meaning of tranliteration: Translated string in it's final form/target charset sounds like the string in it's original form. If we want to transliterate any charset to Latin(English alphabets), then ICU4(ICU4J library in java ) will do the job.

Here is the code snippet in java:

    import com.ibm.icu.text.Transliterator; //ICU4J library import

    public static String TRANSLITERATE_ID = "NFD; Any-Latin; NFC";
    public static String NORMALIZE_ID = "NFD; [:Nonspacing Mark:] Remove; NFC";

    /**
    * Returns the transliterated string to convert any charset to latin.
    */
    public static String transliterate(String input) {
        Transliterator transliterator = Transliterator.getInstance(TRANSLITERATE_ID + "; " + NORMALIZE_ID);
        String result = transliterator.transliterate(input);
        return result;
    }

How do I remove diacritics (accents) from a string in .NET?

I often use an extenstion method based on another version I found here (see Replacing characters in C# (ascii)) A quick explanation:

  • Normalizing to form D splits charactes like è to an e and a nonspacing `
  • From this, the nospacing characters are removed
  • The result is normalized back to form C (I'm not sure if this is neccesary)

Code:

using System.Linq;
using System.Text;
using System.Globalization;

// namespace here
public static class Utility
{
    public static string RemoveDiacritics(this string str)
    {
        if (null == str) return null;
        var chars =
            from c in str.Normalize(NormalizationForm.FormD).ToCharArray()
            let uc = CharUnicodeInfo.GetUnicodeCategory(c)
            where uc != UnicodeCategory.NonSpacingMark
            select c;

        var cleanStr = new string(chars.ToArray()).Normalize(NormalizationForm.FormC);

        return cleanStr;
    }

    // or, alternatively
    public static string RemoveDiacritics2(this string str)
    {
        if (null == str) return null;
        var chars = str
            .Normalize(NormalizationForm.FormD)
            .ToCharArray()
            .Where(c=> CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
            .ToArray();

        return new string(chars).Normalize(NormalizationForm.FormC);
    }
}

Is there a way to get rid of accents and convert a whole string to regular letters?

I suggest Junidecode . It will handle not only 'L' and 'Ø', but it also works well for transcribing from other alphabets, such as Chinese, into Latin alphabet.

Remove accents/diacritics in a string in JavaScript

I used string.js's latinise() method, which lets you do it like this:

var output = S(input).latinise().toString();

What is the best way to remove accents (normalize) in a Python unicode string?

How about this:

import unicodedata
def strip_accents(s):
   return ''.join(c for c in unicodedata.normalize('NFD', s)
                  if unicodedata.category(c) != 'Mn')

This works on greek letters, too:

>>> strip_accents(u"A \u00c0 \u0394 \u038E")
u'A A \u0394 \u03a5'
>>> 

The character category "Mn" stands for Nonspacing_Mark, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit).

And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration".

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

For me the issue was caused by com.google.android.exoplayer conflicting with com.facebook.android:audience-network-sdk.

I fixed the problem by excluding the exoplayer library from the audience-network-sdk :

compile ('com.facebook.android:audience-network-sdk:4.24.0') {
    exclude group: 'com.google.android.exoplayer'
}

How to draw circle in html page?

If you're using sass to write your CSS you can do:

@mixin draw_circle($radius){
  width: $radius*2;
  height: $radius*2;
  -webkit-border-radius: $radius;
  -moz-border-radius: $radius;
  border-radius: $radius;
}

.my-circle {
  @include draw_circle(25px);
  background-color: red;
}

Which outputs:

.my-circle {
  width: 50px;
  height: 50px;
  -webkit-border-radius: 25px;
  -moz-border-radius: 25px;
  border-radius: 25px;
  background-color: red;
}

Try it here: https://www.sassmeister.com/

INSERT with SELECT

Yes, absolutely, but check your syntax.

INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM   courses
WHERE  cid = 2

You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.

Carousel with Thumbnails in Bootstrap 3.0

  1. Use the carousel's indicators to display thumbnails.
  2. Position the thumbnails outside of the main carousel with CSS.
  3. Set the maximum height of the indicators to not be larger than the thumbnails.
  4. Whenever the carousel has slid, update the position of the indicators, positioning the active indicator in the middle of the indicators.

I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.

Also, my templating engine is smarty, but I'm sure you get the idea.

The meat...

Updating the indicators:

<ol class="carousel-indicators">
    {assign var='walker' value=0}
    {foreach from=$item["imagearray"] key="key" item="value"}
        <li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
            <img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
        </li>

        {assign var='walker' value=1 + $walker}
    {/foreach}
</ol>

Changing the CSS related to the indicators:

.carousel-indicators {
    bottom:-50px;
    height: 36px;
    overflow-x: hidden;
    white-space: nowrap;
}

.carousel-indicators li {
    text-indent: 0;
    width: 34px !important;
    height: 34px !important;
    border-radius: 0;
}

.carousel-indicators li img {
    width: 32px;
    height: 32px;
    opacity: 0.5;
}

.carousel-indicators li:hover img, .carousel-indicators li.active img {
    opacity: 1;
}

.carousel-indicators .active {
    border-color: #337ab7;
}

When the carousel has slid, update the list of thumbnails:

$('#myCarousel').on('slid.bs.carousel', function() {
    var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width(); 
    var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
    var toScroll = newIndicatorPosition + indicatorPosition;
    var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
    if (adjustedScroll < 0)
        adjustedScroll = 0;

    if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
        adjustedScroll = widthEstimate - $(".carousel-indicators").width();

    $('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);

    indicatorPosition = adjustedScroll;
});

And, when your page loads, set the initial scroll position of the thumbnails:

var indicatorPosition = 0;

How to get Selected Text from select2 when using <input>

The correct way to do this as of v4 is:

$('.select2-chosen').select2('data')[0].text

It is undocumented so could break in the future without warning.

You will probably want to check if there is a selection first however:

var s = $('.select2-chosen');

if(s.select2('data') && !!s.select2('data')[0]){
    //do work
}

Why do we need C Unions?

A simple and very usefull example, is....

Imagine:

you have a uint32_t array[2] and want to access the 3rd and 4th Byte of the Byte chain. you could do *((uint16_t*) &array[1]). But this sadly breaks the strict aliasing rules!

But known compilers allow you to do the following :

union un
{
    uint16_t array16[4];
    uint32_t array32[2];
}

technically this is still a violation of the rules. but all known standards support this usage.

Convert an image to grayscale

The code below is the simplest solution:

Bitmap bt = new Bitmap("imageFilePath");

for (int y = 0; y < bt.Height; y++)
{
    for (int x = 0; x < bt.Width; x++)
    {
        Color c = bt.GetPixel(x, y);

        int r = c.R;
        int g = c.G;
        int b = c.B;
        int avg = (r + g + b) / 3;
        bt.SetPixel(x, y, Color.FromArgb(avg,avg,avg));
    }   
}

bt.Save("d:\\out.bmp");

How to run batch file from network share without "UNC path are not supported" message?

Instead of launching the batch directly from explorer - create a shortcut to the batch and set the starting directory in the properties of the shortcut to a local path like %TEMP% or something.

To delete the symbolic link, use the rmdir command.

Calculating distance between two geographic locations

    private static Double _MilesToKilometers = 1.609344;
    private static Double _MilesToNautical = 0.8684;


    /// <summary>
    /// Calculates the distance between two points of latitude and longitude.
    /// Great Link - http://www.movable-type.co.uk/scripts/latlong.html
    /// </summary>
    /// <param name="coordinate1">First coordinate.</param>
    /// <param name="coordinate2">Second coordinate.</param>
    /// <param name="unitsOfLength">Sets the return value unit of length.</param>
    public static Double Distance(Coordinate coordinate1, Coordinate coordinate2, UnitsOfLength unitsOfLength)
    {

        double theta = coordinate1.getLongitude() - coordinate2.getLongitude();
        double distance = Math.sin(ToRadian(coordinate1.getLatitude())) * Math.sin(ToRadian(coordinate2.getLatitude())) +
                       Math.cos(ToRadian(coordinate1.getLatitude())) * Math.cos(ToRadian(coordinate2.getLatitude())) *
                       Math.cos(ToRadian(theta));

        distance = Math.acos(distance);
        distance = ToDegree(distance);
        distance = distance * 60 * 1.1515;

        if (unitsOfLength == UnitsOfLength.Kilometer)
            distance = distance * _MilesToKilometers;
        else if (unitsOfLength == UnitsOfLength.NauticalMiles)
            distance = distance * _MilesToNautical;

        return (distance);

    }

Start an external application from a Google Chrome Extension?

There's an extension for Chrome (SimpleGet) that has a plugin for Windows and Linux that can execute an app with command line parameters.....
http://pinel.cc/
http://code.google.com/p/simple-get/
http://www.chromeextensions.org/other/simple-get/

getting the error: expected identifier or ‘(’ before ‘{’ token

{
int main(void);

should be

int main(void)
{

Then I let you fix the next compilation errors of your program...

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

How to add custom method to Spring Data JPA

I liked Danila's solution and started using it but nobody else on the team liked having to create 4 classes for each repository. Danila's solution is the only one here that let's you use the Spring Data methods in the Impl class. However, I found a way to do it with just a single class:

public interface UserRepository extends MongoAccess, PagingAndSortingRepository<User> {

    List<User> getByUsername(String username);


    default List<User> getByUsernameCustom(String username) {
        // Can call Spring Data methods!
        findAll();

        // Can write your own!
        MongoOperations operations = getMongoOperations();
        return operations.find(new Query(Criteria.where("username").is(username)), User.class);
    }
}

You just need some way of getting access to your db bean (in this example, MongoOperations). MongoAccess provides that access to all of your repositories by retrieving the bean directly:

public interface MongoAccess {
    default MongoOperations getMongoOperations() {
        return BeanAccessor.getSingleton(MongoOperations.class);
    }
}

Where BeanAccessor is:

@Component
public class BeanAccessor implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static <T> T getSingleton(Class<T> clazz){
        return applicationContext.getBean(clazz);
    }

    public static <T> T getSingleton(String beanName, Class<T> clazz){
        return applicationContext.getBean(beanName, clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanAccessor.applicationContext = applicationContext;
    }

}

Unfortunately, you can't @Autowire in an interface. You could autowire the bean into a MongoAccessImpl and provide a method in the interface to access it, but Spring Data blows up. I don't think it expects to see an Impl associated even indirectly with PagingAndSortingRepository.

Trigger event on body load complete js/jquery

You may also use the defer attribute in the script tag. As long as you do not specify async which would of course not be useful for your aim.

Example:

<script src="//other-domain.com/script.js" defer></script>
<script src="myscript.js" defer></script>

As described here:

In the above example, the browser will download both scripts in parallel and execute them just before DOMContentLoaded fires, maintaining their order.

[...] deferred scripts should run after the document had parsed, in the order they were added [...]

Related Stackoverflow discussions: How exactly does <script defer=“defer”> work?

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

Strangely Java9 is not compatible with android-sdk

$ avdmanager
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
    at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
    at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
    at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
    at com.android.sdklib.tool.AvdManagerCli.run(AvdManagerCli.java:213)
    at com.android.sdklib.tool.AvdManagerCli.main(AvdManagerCli.java:200)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    ... 5 more

Combined all commands into one for easy reference:

$ sudo rm -fr /Library/Java/JavaVirtualMachines/jdk-9*.jdk/
$ sudo rm -fr /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
$ sudo rm -fr /Library/PreferencePanes/JavaControlPanel.prefPane

$ /usr/libexec/java_home -V
Unable to find any JVMs matching version "(null)".
Matching Java Virtual Machines (0):
Default Java Virtual Machines (0):
No Java runtime present, try --request to install

$ brew tap caskroom/versions
$ brew cask install java8
$ touch ~/.android/repositories.cfg
$ brew cask install android-sdk
$ echo 'export ANDROID_SDK_ROOT="/usr/local/share/android-sdk"' >> ~/.bash_profile
$ java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
$ avdmanager

Usage:
      avdmanager [global options] [action] [action options]
      Global options:
  -s --silent     : Silent mode, shows errors only.
  -v --verbose    : Verbose mode, shows errors, warnings and all messages.
     --clear-cache: Clear the SDK Manager repository manifest cache.
  -h --help       : Help on a specific command.

Valid actions are composed of a verb and an optional direct object:
-   list              : Lists existing targets or virtual devices.
-   list avd          : Lists existing Android Virtual Devices.
-   list target       : Lists existing targets.
-   list device       : Lists existing devices.
- create avd          : Creates a new Android Virtual Device.
-   move avd          : Moves or renames an Android Virtual Device.
- delete avd          : Deletes an Android Virtual Device.

How to search a list of tuples in Python

tl;dr

A generator expression is probably the most performant and simple solution to your problem:

l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

result = next((i for i, v in enumerate(l) if v[0] == 53), None)
# 2

Explanation

There are several answers that provide a simple solution to this question with list comprehensions. While these answers are perfectly correct, they are not optimal. Depending on your use case, there may be significant benefits to making a few simple modifications.

The main problem I see with using a list comprehension for this use case is that the entire list will be processed, although you only want to find 1 element.

Python provides a simple construct which is ideal here. It is called the generator expression. Here is an example:

# Our input list, same as before
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

# Call next on our generator expression.
next((i for i, v in enumerate(l) if v[0] == 53), None)

We can expect this method to perform basically the same as list comprehensions in our trivial example, but what if we're working with a larger data set? That's where the advantage of using the generator method comes into play. Rather than constructing a new list, we'll use your existing list as our iterable, and use next() to get the first item from our generator.

Lets look at how these methods perform differently on some larger data sets. These are large lists, made of 10000000 + 1 elements, with our target at the beginning (best) or end (worst). We can verify that both of these lists will perform equally using the following list comprehension:

List comprehensions

"Worst case"

worst_case = ([(False, 'F')] * 10000000) + [(True, 'T')]
print [i for i, v in enumerate(worst_case) if v[0] is True]

# [10000000]
#          2 function calls in 3.885 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    3.885    3.885    3.885    3.885 so_lc.py:1(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

"Best case"

best_case = [(True, 'T')] + ([(False, 'F')] * 10000000)
print [i for i, v in enumerate(best_case) if v[0] is True]

# [0]
#          2 function calls in 3.864 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    3.864    3.864    3.864    3.864 so_lc.py:1(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Generator expressions

Here's my hypothesis for generators: we'll see that generators will significantly perform better in the best case, but similarly in the worst case. This performance gain is mostly due to the fact that the generator is evaluated lazily, meaning it will only compute what is required to yield a value.

Worst case

# 10000000
#          5 function calls in 1.733 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         2    1.455    0.727    1.455    0.727 so_lc.py:10(<genexpr>)
#         1    0.278    0.278    1.733    1.733 so_lc.py:9(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
#         1    0.000    0.000    1.455    1.455 {next}

Best case

best_case  = [(True, 'T')] + ([(False, 'F')] * 10000000)
print next((i for i, v in enumerate(best_case) if v[0] == True), None)

# 0
#          5 function calls in 0.316 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    0.316    0.316    0.316    0.316 so_lc.py:6(<module>)
#         2    0.000    0.000    0.000    0.000 so_lc.py:7(<genexpr>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
#         1    0.000    0.000    0.000    0.000 {next}

WHAT?! The best case blows away the list comprehensions, but I wasn't expecting the our worst case to outperform the list comprehensions to such an extent. How is that? Frankly, I could only speculate without further research.

Take all of this with a grain of salt, I have not run any robust profiling here, just some very basic testing. This should be sufficient to appreciate that a generator expression is more performant for this type of list searching.

Note that this is all basic, built-in python. We don't need to import anything or use any libraries.

I first saw this technique for searching in the Udacity cs212 course with Peter Norvig.

Shell Script: Execute a python program from within a shell script

This works best for me: Add this at the top of the script:

#!c:/Python27/python.exe

(C:\Python27\python.exe is the path to the python.exe on my machine) Then run the script via:

chmod +x script-name.py && script-name.py

'setInterval' vs 'setTimeout'

setInterval repeats the call, setTimeout only runs it once.

matplotlib colorbar for scatter

If you're looking to scatter by two variables and color by the third, Altair can be a great choice.

Creating the dataset

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])

Altair plot

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)

Plot

enter image description here

How do I get the first element from an IEnumerable<T> in .net?

Well, you didn't specify which version of .Net you're using.

Assuming you have 3.5, another way is the ElementAt method:

var e = enumerable.ElementAt(0);

Disable validation of HTML5 form elements

Instead of trying to do an end run around the browser's validation, you could put the http:// in as placeholder text. This is from the very page you linked:

Placeholder Text

The first improvement HTML5 brings to web forms is the ability to set placeholder text in an input field. Placeholder text is displayed inside the input field as long as the field is empty and not focused. As soon as you click on (or tab to) the input field, the placeholder text disappears.

You’ve probably seen placeholder text before. For example, Mozilla Firefox 3.5 now includes placeholder text in the location bar that reads “Search Bookmarks and History”:

enter image description here

When you click on (or tab to) the location bar, the placeholder text disappears:

enter image description here

Ironically, Firefox 3.5 does not support adding placeholder text to your own web forms. C’est la vie.

Placeholder Support

IE  FIREFOX SAFARI  CHROME  OPERA   IPHONE  ANDROID
·   3.7+    4.0+    4.0+    ·       ·       ·

Here’s how you can include placeholder text in your own web forms:

<form>
  <input name="q" placeholder="Search Bookmarks and History">
  <input type="submit" value="Search">
</form>

Browsers that don’t support the placeholder attribute will simply ignore it. No harm, no foul. See whether your browser supports placeholder text.

It wouldn't be exactly the same since it wouldn't provide that "starting point" for the user, but it's halfway there at least.

SQL Server stored procedure parameters

SQL Server doesn't allow you to pass parameters to a procedure that you haven't defined. I think the closest you can get to this sort of design is to use optional parameters like so:

CREATE PROCEDURE GetTaskEvents
    @TaskName varchar(50),
    @ID int = NULL
AS
BEGIN
-- SP Logic
END;

You would need to include every possible parameter that you might use in the definition. Then you'd be free to call the procedure either way:

EXEC GetTaskEvents @TaskName = 'TESTTASK', @ID = 2;
EXEC GetTaskEvents @TaskName = 'TESTTASK'; -- @ID gets NULL here

Symfony2 : How to get form validation errors after binding the request to the form

SYMFONY 3.1

I simply implemented a static method to handle the display of errors

static function serializeFormErrors(Form\Form $form)
{
    $errors = array();
    /**
     * @var  $key
     * @var Form\Form $child
     */
    foreach ($form->all() as $key => $child) {
        if (!$child->isValid()) {
            foreach ($child->getErrors() as $error) {
                $errors[$key] = $error->getMessage();
            }
        }
    }

    return $errors;
}

Hoping to help

How to pass a list from Python, by Jinja2 to JavaScript

To add up on the selected answer, I have been testing a new option that is working too using jinja2 and flask:

@app.route('/')
def my_view():
    data = [1, 2, 3, 4, 5]
    return render_template('index.html', data=data)

The template:

<script>
    console.log( {{ data | tojson }} )
</script>

the output of the rendered template:

<script>
    console.log( [1, 2, 3, 4] )
</script>

The safe could be added but as well like {{ data | tojson | safe }} to avoid html escape but it is working without too.

Filtering Pandas DataFrames on dates

Previous answer is not correct in my experience, you can't pass it a simple string, needs to be a datetime object. So:

import datetime 
df.loc[datetime.date(year=2014,month=1,day=1):datetime.date(year=2014,month=2,day=1)]

How can I tell jaxb / Maven to generate multiple schema packages?

You can use also JAXB bindings to specify different package for each schema, e.g.

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0" schemaLocation="book.xsd">

    <jaxb:globalBindings>
        <xjc:serializable uid="1" />
    </jaxb:globalBindings>

    <jaxb:schemaBindings>
        <jaxb:package name="com.stackoverflow.book" />
    </jaxb:schemaBindings>

</jaxb:bindings>

Then just use the new maven-jaxb2-plugin 0.8.0 <schemas> and <bindings> elements in the pom.xml. Or specify the top most directory in <schemaDirectory> and <bindingDirectory> and by <include> your schemas and bindings:

<schemaDirectory>src/main/resources/xsd</schemaDirectory>
<schemaIncludes>
    <include>book/*.xsd</include>
    <include>person/*.xsd</include>
</schemaIncludes>
<bindingDirectory>src/main/resources</bindingDirectory>
<bindingIncludes>
    <include>book/*.xjb</include>
    <include>person/*.xjb</include>
</bindingIncludes>

I think this is more convenient solution, because when you add a new XSD you do not need to change Maven pom.xml, just add a new XJB binding file to the same directory.

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

What you can do is set your default database using the sp_defaultdb system stored procedure. Log in as you have done and then click the New Query button. After that simply run the sp_defaultdb command as follows:

Exec sp_defaultdb @loginame='login', @defdb='master' 

Should we @Override an interface's method implementation?

Overriding your own methods inherited from your own classes will typically not break on refactorings using an ide. But if you override a method inherited from a library it is recommended to use it. If you dont, you will often get no error on a later library change, but a well hidden bug.

Where does SVN client store user authentication data?

Read SVNBook | Client Credentials.

With modern SVN you can just run svn auth to display the list of cached credentials. Don't forget to make sure that you run up-to-date SVN client version because svn auth was introduced in version 1.9. The last line will specify the path to credential store which by default is %APPDATA%\Subversion\auth on Windows and ~/.subversion/auth/ on Unix-like systems.

PS C:\Users\MyUser> svn auth
------------------------------------------------------------------------
Credential kind: svn.simple
Authentication realm: <https://svn.example.local:443> VisualSVN Server
Password cache: wincrypt
Password: [not shown]
Username: user

Credentials cache in 'C:\Users\MyUser\AppData\Roaming\Subversion' contains 5 credentials

When should a class be Comparable and/or Comparator?

The text below comes from Comparator vs Comparable

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

Giving height to table and row in Bootstrap

http://jsfiddle.net/isherwood/gfgux

html, body {
    height: 100%;
}
#table-row, #table-col, #table-wrapper {
    height: 80%;
}

<div id="content" class="container">
    <div id="table-row" class="row">
        <div id="table-col" class="col-md-7 col-xs-10 pull-left">
            <p>Hello</p>
            <div id="table-wrapper" class="table-responsive">
                <table class="table table-bordered ">

Java - Get a list of all Classes loaded in the JVM

It's not a programmatic solution but you can run

java -verbose:class ....

and the JVM will dump out what it's loading, and from where.

[Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar]
[Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.Comparable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.CharSequence from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.String from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]

See here for more details.

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Using the Script console at https://my-jenkins/script

import hudson.model.Job
import org.jenkinsci.plugins.workflow.job.WorkflowRun

Collection<Job> jobs = Jenkins.instance.getItem('My-Folder').getAllJobs()
for (int i = 0; i < jobs.size(); i++) {
  def job = jobs[i]
  for (int j = 0; j < job.builds.size(); j++) {
    WorkflowRun build = job.builds[j]
    if (build.isBuilding()) {
      println("Stopping $job ${build.number}")
      build.setResult(Result.FAILURE)
    }
  }
}

How to access parent Iframe from JavaScript

Old question, but I just had this same issue and found a way to get the iframe. It's simply a matter of iterating through the parent window's frames[] array and testing each frame's contentWindow against the window in which your code is running. Example:

var arrFrames = parent.document.getElementsByTagName("IFRAME");
for (var i = 0; i < arrFrames.length; i++) {
  if (arrFrames[i].contentWindow === window) alert("yay!");
}

Or, using jQuery:

parent.$("iframe").each(function(iel, el) {
  if(el.contentWindow === window) alert("got it");
});

This method saves assigning an ID to each iframe, which is good in your case as they are dynamically created. I couldn't find a more direct way, since you can't get the iframe element using window.parent - it goes straight to the parent window element (skipping the iframe). So looping through them seems the only way, unless you want to use IDs.

How to print exact sql query in zend framework ?

Check out the Zend_Db_Profiler. This allows you to log any SQL statement as it is prepared and executed. It works for UPDATE statements as well as SELECT queries.

In Python try until no error

Maybe decorator based? You can pass as decorator arguments list of exceptions on which we want to retry and/or number of tries.

def retry(exceptions=None, tries=None):
    if exceptions:
        exceptions = tuple(exceptions)
    def wrapper(fun):
        def retry_calls(*args, **kwargs):
            if tries:
                for _ in xrange(tries):
                    try:
                        fun(*args, **kwargs)
                    except exceptions:
                        pass
                    else:
                        break
            else:
                while True:
                    try:
                        fun(*args, **kwargs)
                    except exceptions:
                        pass
                    else:
                        break
        return retry_calls
    return wrapper


from random import randint

@retry([NameError, ValueError])
def foo():
    if randint(0, 1):
        raise NameError('FAIL!')
    print 'Success'

@retry([ValueError], 2)
def bar():
    if randint(0, 1):
        raise ValueError('FAIL!')
    print 'Success'

@retry([ValueError], 2)
def baz():
    while True:
        raise ValueError('FAIL!')

foo()
bar()
baz()

of course the 'try' part should be moved to another funcion becouse we using it in both loops but it's just example;)

Inline CSS styles in React: how to implement a:hover?

This can be a nice hack for having inline style inside a react component (and also using :hover CSS function):

...

<style>
  {`.galleryThumbnail.selected:hover{outline:2px solid #00c6af}`}
</style>

...

linux shell script: split string, put them in an array then loop through them

sentence="one;two;three"
a="${sentence};"
while [ -n "${a}" ]
do
    echo ${a%%;*}
    a=${a#*;}
done

AWS : The config profile (MyName) could not be found

For me it was because I had my .aws/config file looking like this:

[profile myname]
aws_access_key_id = ....
aws_secret_access_key = ....
region=us-west-1

I think the reason is I based it off my .aws/credentials file, which requires having [profile myname] for Zappa and maybe some other aws/elastic beanstalk tools.

When I changed config to this it worked great:

[myname]
aws_access_key_id = ....
aws_secret_access_key = ....
region=us-west-1

Convert NSDate to String in iOS Swift

You can use this extension:

extension Date {

    func toString(withFormat format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        let myString = formatter.string(from: self)
        let yourDate = formatter.date(from: myString)
        formatter.dateFormat = format

        return formatter.string(from: yourDate!)
    }
}

And use it in your view controller like this (replace <"yyyy"> with your format):

yourString = yourDate.toString(withFormat: "yyyy")

How can I generate a list of consecutive numbers?

Using Python's built in range function:

Python 2

input = 8
output = range(input + 1)

print output
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Python 3

input = 8
output = list(range(input + 1))

print(output)
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Autoplay an audio with HTML5 embed tag while the player is invisible

If you are using React, make sure autoplay is set to,

autoPlay

React wants it to be camelcase!

Why does the C preprocessor interpret the word "linux" as the constant "1"?

From info gcc (emphasis mine):

-ansi

In C mode, this is equivalent to -std=c90. In C++ mode, it is equivalent to -std=c++98. This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or of standard C++ (when compiling C++ code), such as the asm and typeof keywords, and predefined macros such as 'unix' and 'vax' that identify the type of system you are using. It also enables the undesirable and rarely used ISO trigraph feature. For the C compiler, it disables recognition of C++ style // comments as well as the inline keyword.

(It uses vax in the example instead of linux because when it was written maybe it was more popular ;-).

The basic idea is that GCC only tries to fully comply with the ISO standards when it is invoked with the -ansi option.

Can jQuery read/write cookies to a browser?

You'll need the cookie plugin, which provides several additional signatures to the cookie function.

$.cookie('cookie_name', 'cookie_value') stores a transient cookie (only exists within this session's scope, while $.cookie('cookie_name', 'cookie_value', 'cookie_expiration") creates a cookie that will last across sessions - see http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/ for more information on the JQuery cookie plugin.

If you want to set cookies that are used for the entire site, you'll need to use JavaScript like this:

document.cookie = "name=value; expires=date; domain=domain; path=path; secure"

DropDownList's SelectedIndexChanged event not firing

Also make sure the page is valid. You can check this in the browsers developer tools (F12)

In the Console tab select the correct Target/Frame and check for the [Page_IsValid] property

If the page is not valid the form will not submit and therefore not fire the event.

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

Adding import 'core-js/es7/array'; to my polyfill.ts fixed the issue for me.

AngularJS: factory $http.get JSON file

++ This worked for me. It's vanilla javascirpt and good for use cases such as de-cluttering when testing with ngMocks library:

<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!--  Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>

This is your javascript file that contains the JSON data

// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
     "Title": "Star Wars",
     "Year": "1983",
     "Rated": "N/A",
     "Released": "01 May 1983",
     "Runtime": "N/A",
     "Genre": "Action, Adventure, Sci-Fi",
     "Director": "N/A",
     "Writer": "N/A",
     "Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
     "Plot": "N/A",
     "Language": "English",
     "Country": "USA",
     "Awards": "N/A",
     "Poster": "N/A",
     "Metascore": "N/A",
     "imdbRating": "7.9",
     "imdbVotes": "342",
     "imdbID": "tt0251413",
     "Type": "game",
     "Response": "True"
};

Finally, work with the JSON data anywhere in your code

// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;

Note:- This is great for testing and even karma.conf.js accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development environment.

// extract from karma.conf.js
files: [
     'json-data/JSONSearchResultHardcodedData.js',
     'json-data/JSONFindByIdResults.js'
     ...
]

Hope this helps.

++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733

UPDATE

An easier way that worked for me is just include a function at the bottom of the code returning whatever JSON.

// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
      return {
         "Title": "Bri Squared",
         "Year": "2011",
         "Rated": "N/A",
         "Released": "N/A",
         "Runtime": "N/A",
         "Genre": "Comedy",
         "Director": "Joy Gohring",
         "Writer": "Briana Lane",
         "Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
         "Plot": "N/A",
         "Language": "English",
         "Country": "USA",
         "Awards": "N/A",
         "Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
         "Metascore": "N/A",
         "imdbRating": "8.2",
         "imdbVotes": "5",
         "imdbID": "tt1937109",
         "Type": "movie",
         "Response": "True"
   }
}

PermGen elimination in JDK 8

The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace.The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error. The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace. Read More>>

How to use jQuery to select a dropdown option?

I would do it this way

 $("#idElement").val('optionValue').trigger('change');

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

  1. replace all single quotes with double quotes
  2. replace 'u"' from your strings to '"' ... so basically convert internal unicodes to strings before loading the string into json
>> strs = "{u'key':u'val'}"
>> strs = strs.replace("'",'"')
>> json.loads(strs.replace('u"','"'))

What exceptions should be thrown for invalid or unexpected parameters in .NET?

argument exception.

  • System.ArgumentException
  • System.ArgumentNullException
  • System.ArgumentOutOfRangeException

No 'Access-Control-Allow-Origin' header in Angular 2 app

I got the same error and here how I solved it, by adding the following to your spring controller:

@CrossOrigin(origins = {"http://localhost:3000"})

Generate random 5 characters string

If it's fine that you'll get only letters A-F, then here's my solution:

str_pad(dechex(mt_rand(0, 0xFFFFF)), 5, '0', STR_PAD_LEFT);

I believe that using hash functions is an overkill for such a simple task as generating a sequence of random hexadecimal digits. dechex + mt_rand will do the same job, but without unnecessary cryptographic work. str_pad guarantees 5-character length of the output string (if the random number is less than 0x10000).

Duplicate probability depends on mt_rand's reliability. Mersenne Twister is known for high-quality randomness, so it should fit the task well.

How to call a button click event from another method

You can simply call it:

SubGraphButton_Click(sender, args);

Now, if your SubGraphButton_Click does something with the args, you might be in trouble, but usually you don't do anything with them.

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

How do I match any character across multiple lines in a regular expression?

generally . doesn't match newlines, so try ((.|\n)*)<foobar>

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

I encountered a similar problem using windows command line for R script, Rscript.exe, which is very sensitive to spaces in the path. The solution was to create a virtual path to the binary folder using the windows subst command.

The following fails: "C:\Program Files\R\R-3.4.0\bin\Rscript.exe"

Doing following succeeds:

subst Z: "C:\Program Files\R\R-3.4.0"
Z:\bin\Rscript.exe

The reason the above-proposed solutions didn't work, evidently, has to do with the Rscript.exe executable's own internal path resolution from its working directory (which has a space in it) rather the windows command line being confused with the space. So using ~ or " to resolve the issue at the command line is moot. The executable must be called within a path lacking spaces.

How get value from URL

There are two ways to get variable from URL in PHP:

When your URL is: http://www.example.com/index.php?id=7 you can get this id via $_GET['id'] or $_REQUEST['id'] command and store in $id variable.

Lest's take a look:

// url is www.example.com?id=7

//get id from url via $_GET['id'] command:
$id = $_GET['id']

same will be:

//get id from url via $_REQUEST['id'] command:
$id = $_REQUEST['id']

the difference is that variables can be passed to file via URL or via POST method.

if variable is passed through url, then you can get it with $_GET['variable_name'] or $_REQUEST['variable_name'] but if variable is posted, then you need to you $_POST['variable_name'] or $_REQUEST['variable_name']

So as you see $_REQUEST['variable_name'] can be used in both ways.

P.S: Also remember - never do like this: $results = mysql_query("SELECT * FROM next WHERE id=$id"); it may cause MySQL Injection and your database can be hacked.

Try to use:

$results = mysql_query("SELECT * FROM next WHERE id='".mysql_real_escape_string($id)."'");

How can I show/hide component with JSF?

Generally, you need to get a handle to the control via its clientId. This example uses a JSF2 Facelets view with a request-scope binding to get a handle to the other control:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
  <h:head><title>Show/Hide</title></h:head>
  <h:body>
    <h:form>
      <h:button value="toggle"
               onclick="toggle('#{requestScope.foo.clientId}'); return false;" />
      <h:inputText binding="#{requestScope.foo}" id="x" style="display: block" />
    </h:form>
    <script type="text/javascript">
      function toggle(id) {
        var element = document.getElementById(id);
        if(element.style.display == 'block') {
          element.style.display = 'none';
        } else {
          element.style.display = 'block'
        }
      }
    </script>
  </h:body>
</html>

Exactly how you do this will depend on the version of JSF you're working on. See this blog post for older JSF versions: JSF: working with component identifiers.

.ssh directory not being created

As a slight improvement over the other answers, you can do the mkdir and chmod as a single operation using mkdir's -m switch.

$ mkdir -m 700 ${HOME}/.ssh

Usage

From a Linux system

$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx - umask
...
...

Change width of select tag in Twitter Bootstrap

In bootstrap 3, it is recommended that you size inputs by wrapping them in col-**-# div tags. It seems that most things have 100% width, especially .form-control elements.

https://getbootstrap.com/docs/3.3/css/#forms-control-sizes

How do I import the javax.servlet API in my Eclipse project?

You should above all never manually copy/download/move/include the individual servletcontainer-specific libraries like servlet-api.jar

@BalusC,

I would prefer to use the exact classes that my application is going to use rather than one provided by Eclipse (when I am feeling like a paranoid developer).

Another solution would be to use Eclipse "Configure Build Path" > Libraries > Add External Jars, and add servlet api of whatever Container one chooses to use.

And follow @kaustav datta's solution when using ant to build - have a property like tomcat.home or weblogic.home. However it introduces another constraint that the developer must install Weblogic on his/her local machine if weblogic is being used ! Any other cleaner solution?

How to retrieve the first word of the output of a command in bash?

no need to use external commands. Bash itself can do the job. Assuming "word1 word2" you got from somewhere and stored in a variable, eg

$ string="word1 word2"
$ set -- $string
$ echo $1
word1
$ echo $2
word2

now you can assign $1, or $2 etc to another variable if you like.

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

In case you need the [] syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:

[routerLink]="['edit', business._id]"

As for an "about page" with no parameters like yours,

[routerLink]="/about"

or

[routerLink]=['about']

will do the trick.

How to call a function after a div is ready?

To do something after certain div load from function .load(). I think this exactly what you need:

  $('#divIDer').load(document.URL +  ' #divIDer',function() {

       // call here what you want .....


       //example
       $('#mydata').show();
  });

jquery to change style attribute of a div class

Try with

$('.handle').css({'left': '300px'});

Instead of

$('.handle').css({'style':'left: 300px'})

Make the size of a heatmap bigger with seaborn

add plt.figure(figsize=(16,5)) before the sns.heatmap and play around with the figsize numbers till you get the desired size

...

plt.figure(figsize = (16,5))

ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

If using WORD for mac enable 'use maths autocorrect rules outside maths regions' Type \therefore

Effect of NOLOCK hint in SELECT statements

NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.

NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.

Here is information about all of the isolation levels at your disposal, as well as table hints.

SET TRANSACTION ISOLATION LEVEL

Table Hint (Transact-SQL)

ssh : Permission denied (publickey,gssapi-with-mic)

As everybody else has already said you need to edit /etc/ssh/sshd_config and change PasswordAuthentication no to PasswordAuthentication yes

I ran into this problem setting up a Vagrant box - so therefore it makes sense to script this and do it automatically in a shell provisioner:

sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config;

sudo systemctl restart sshd;

How do I check if an array includes a value in JavaScript?

Use lodash's some function.

It's concise, accurate and has great cross platform support.

The accepted answer does not even meet the requirements.

Requirements: Recommend most concise and efficient way to find out if a JavaScript array contains an object.

Accepted Answer:

$.inArray({'b': 2}, [{'a': 1}, {'b': 2}])
> -1

My recommendation:

_.some([{'a': 1}, {'b': 2}], {'b': 2})
> true

Notes:

$.inArray works fine for determining whether a scalar value exists in an array of scalars...

$.inArray(2, [1,2])
> 1

... but the question clearly asks for an efficient way to determine if an object is contained in an array.

In order to handle both scalars and objects, you could do this:

(_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) > -1)

Tomcat is not running even though JAVA_HOME path is correct

I set the

variable name : JAVA_HOME value : C:\Program Files\Java\jdk1.6.0_32

I set these properties in system/environment variables without semicolon, tomcat is running on my system.

It really works.

laravel Eloquent ORM delete() method

I think you can change your query and try it like :

$res=User::where('id',$id)->delete();

PHP array() to javascript array()

 <script> var disabledDaysRange = $disabledDaysRange ???? Please Help;
 $(function() {
     function disableRangeOfDays(d) {

in the above assign array to javascript variable "disableDaysRange"

$disallowDates = "";
echo "[";
foreach($disabledDaysRange as $disableDates){
 $disallowDates .= "'".$disableDates."',";
}

echo substr(disallowDates,0,(strlen(disallowDates)-1)); // this will escape the last comma from $disallowDates
echo "];";

so your javascript var diableDateRange shoudl be 

var diableDateRange = ["2013-01-01","2013-01-02","2013-01-03"];

HttpRequest maximum allowable size in tomcat?

Just to add to the answers, App Server Apache Geronimo 3.0 uses Tomcat 7 as the web server, and in that environment the file server.xml is located at <%GERONIMO_HOME%>/var/catalina/server.xml.

The configuration does take effect even when the Geronimo Console at Application Server->WebServer->TomcatWebConnector->maxPostSize still displays 2097152 (the default value)

How to round a number to significant figures in Python

Using python 2.6+ new-style formatting (as %-style is deprecated):

>>> "{0}".format(float("{0:.1g}".format(1216)))
'1000.0'
>>> "{0}".format(float("{0:.1g}".format(0.00356)))
'0.004'

In python 2.7+ you can omit the leading 0s.

Bash integer comparison

This script works!

#/bin/bash
if [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then
    echo this script requires a 1 or 0 as first parameter.
else
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
fi

But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:

#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
else
    echo this script requires a 1 or 0 as first parameter.
fi

The output is the same1:

$ ./tmp.sh 
this script requires a 1 or 0 as first parameter.

$ ./tmp.sh 0
first parameter is 0

$ ./tmp.sh 1
first parameter is 1

$ ./tmp.sh 2
this script requires a 1 or 0 as first parameter.

[1] the second fails if the first argument is a string

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

Returning boolean if set is empty

Not as clean as bool(c) but it was an excuse to use ternary.

def myfunc(a,b):
    return True if a.intersection(b) else False

Also using a bit of the same logic there is no need to assign to c unless you are using it for something else.

def myfunc(a,b):
    return bool(a.intersection(b))

Finally, I would assume you want a True / False value because you are going to perform some sort of boolean test with it. I would recommend skipping the overhead of a function call and definition by simply testing where you need it.

Instead of:

if (myfunc(a,b)):
    # Do something

Maybe this:

if a.intersection(b):
    # Do something

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.

Can't get Gulp to run: cannot find module 'gulp-util'

Linux Ubuntu 18:04 user here. I tried all the solutions on this board to date. Even though I read above in the accepted answer that "From later versions, there is no need to manually install gulp-util.", it was the thing that worked for me. (...maybe bc I'm on Ubuntu? I don't know. )

To recap, I kept getting the "cannot find module 'gulp-util'" error when just checking to see if gulp was installed by running:

gulp --version

...again, the 'gulp-util' error kept appearing...

So, I followed the npm install [package name] advice listed above, but ended up getting several other packages that needed to be installed as well. And one had a issue of already existing, and i wasn't sure how to replace it. ...I will put all the packages/install commands that I had to use here, just as reference in case someone else experiences this problem:

sudo npm install -g gulp-util

(then I got an error for 'pretty-hrtime' so I added that, and then the others as Error: Cannot find module ___ kept popping up after each gulp --version check. ...so I just kept installing each one.)

sudo npm install -g pretty-hrtime
sudo npm install -g chalk
sudo npm install -g semver --force

(without --force, on my system I got an error: "EEXIST: file already exists, symlink". --force is not recommended, but idk any other way. )

sudo npm install -g archy
sudo npm install -g liftoff
sudo npm install -g tildify
sudo npm install -g interpret
sudo npm install -g v8flags
sudo npm install -g minimist

And now gulp --version is finally showing: CLI version 3.9.1 Local version 3.9.1

JavaScript/jQuery to download file via POST with JSON data

letronje's solution only works for very simple pages. document.body.innerHTML += takes the HTML text of the body, appends the iframe HTML, and sets the innerHTML of the page to that string. This will wipe out any event bindings your page has, amongst other things. Create an element and use appendChild instead.

$.post('/create_binary_file.php', postData, function(retData) {
  var iframe = document.createElement("iframe");
  iframe.setAttribute("src", retData.url);
  iframe.setAttribute("style", "display: none");
  document.body.appendChild(iframe);
}); 

Or using jQuery

$.post('/create_binary_file.php', postData, function(retData) {
  $("body").append("<iframe src='" + retData.url+ "' style='display: none;' ></iframe>");
}); 

What this actually does: perform a post to /create_binary_file.php with the data in the variable postData; if that post completes successfully, add a new iframe to the body of the page. The assumption is that the response from /create_binary_file.php will include a value 'url', which is the URL that the generated PDF/XLS/etc file can be downloaded from. Adding an iframe to the page that references that URL will result in the browser promoting the user to download the file, assuming that the web server has the appropriate mime type configuration.

Regex for not empty and not whitespace

I ended up using something similar to the accepted answer, with minor modifications

(^$)|(\s+$)

Explanation by the Expresso

Select from 2 alternatives (^$)
    [1] A numbered captured group ^$
        Beginning of line ^
        End of line $
    [2] A numbered captured group (\s+$)
        Whitespace, one or more repetitions \s+
        End of line $

Passing an array of data as an input parameter to an Oracle procedure

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

Count cells that contain any text

Sample file

enter image description here

Note:

  • Tried to find the formula for counting non-blank cells (="" is a blank cell) without a need to use data twice. The solution for : =ARRAYFORMULA(SUM(IFERROR(IF(data="",0,1),1))). For ={SUM(IFERROR(IF(data="",0,1),1))} should work (press Ctrl+Shift+Enter in the formula).

How to test valid UUID/GUID?

Beside Gambol's answer that will do the job in nearly all cases, all answers given so far missed that the grouped formatting (8-4-4-4-12) is not mandatory to encode GUIDs in text. It's used extremely often but obviously also a plain chain of 32 hexadecimal digits can be valid.[1] regexenh:

/^[0-9a-f]{8}-?[0-9a-f]{4}-?[1-5][0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$/i

[1] The question is about checking variables, so we should include the user-unfriendly form as well.

How to run ssh-add on windows?

The Git GUI for Windows has a window-based application that allows you to paste in locations for ssh keys and repo url etc:

https://gitforwindows.org/

convert iso date to milliseconds in javascript

var date = new Date(date_string); var milliseconds = date.getTime();

This worked for me!

Removing all script tags from html with JS Regular Expression

Try this:

var text = text.replace(/<script[^>]*>(?:(?!<\/script>)[^])*<\/script>/g, "")

How to evaluate a boolean variable in an if block in bash?

Note that the if $myVar; then ... ;fi construct has a security problem you might want to avoid with

case $myvar in
  (true)    echo "is true";;
  (false)   echo "is false";;
  (rm -rf*) echo "I just dodged a bullet";;
esac

You might also want to rethink why if [ "$myvar" = "true" ] appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case solution is also handled without forks.

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

MongoDB has a simple web based administrative port at 28017 by default.

There is no HTTP access at the default port of 27017 (which is what the error message is trying to suggest). The default port is used for native driver access, not HTTP traffic.

To access MongoDB, you'll need to use a driver like the MongoDB native driver for NodeJS. You won't "POST" to MongoDB directly (but you might create a RESTful API using express which uses the native drivers). Instead, you'll use a wrapper library that makes accessing MongoDB convenient. You might also consider using Mongoose (which uses the native driver) which adds an ORM-like model for MongoDB in NodeJS.

If you can't get to the web interface, it may be disabled. Normally, I wouldn't expect that you'd need it for doing development unless you're checking logs and such.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

Curly braces. Passing keyword arguments into dict(), though it works beautifully in a lot of scenarios, can only initialize a map if the keys are valid Python identifiers.

This works:

a = {'import': 'trade', 1: 7.8}
a = dict({'import': 'trade', 1: 7.8})

This won't work:

a = dict(import='trade', 1=7.8)

It will result in the following error:

    a = dict(import='trade', 1=7.8)
             ^
SyntaxError: invalid syntax

angular2 submit form by pressing enter without submit button

Hopefully this can help somebody: for some reason I couldn't track because of lack of time, if you have a form like:

<form (ngSubmit)="doSubmit($event)">
  <button (click)="clearForm()">Clear</button>
  <button type="submit">Submit</button>
</form>

when you hit the Enter button, the clearForm function is called, even though the expected behaviour was to call the doSubmit function. Changing the Clear button to a <a> tag solved the issue for me. I would still like to know if that's expected or not. Seems confusing to me

How to calculate the SVG Path for an arc (of a circle)

@opsb's answers is neat, but the center point is not accurate, moreover, as @Jithin noted, if the angle is 360, then nothing is drawn at all.

@Jithin fixed the 360 issue, but if you selected less than 360 degree, then you'll get a line closing the arc loop, which is not required.

I fixed that, and added some animation in the code below:

_x000D_
_x000D_
function myArc(cx, cy, radius, max){       _x000D_
       var circle = document.getElementById("arc");_x000D_
        var e = circle.getAttribute("d");_x000D_
        var d = " M "+ (cx + radius) + " " + cy;_x000D_
        var angle=0;_x000D_
        window.timer = window.setInterval(_x000D_
        function() {_x000D_
            var radians= angle * (Math.PI / 180);  // convert degree to radians_x000D_
            var x = cx + Math.cos(radians) * radius;  _x000D_
            var y = cy + Math.sin(radians) * radius;_x000D_
           _x000D_
            d += " L "+x + " " + y;_x000D_
            circle.setAttribute("d", d)_x000D_
            if(angle==max)window.clearInterval(window.timer);_x000D_
            angle++;_x000D_
        }_x000D_
      ,5)_x000D_
 }     _x000D_
_x000D_
  myArc(110, 110, 100, 360);_x000D_
    
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" style="width:220; height:220;"> _x000D_
    <path d="" id="arc" fill="none" stroke="red" stroke-width="2" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

How to hide a TemplateField column in a GridView

Am I missing something ?

If you can't set visibility on TemplateField then set it on its content

<asp:TemplateField>
  <ItemTemplate>
    <asp:LinkButton Visible='<%# MyBoolProperty %>' ID="foo" runat="server" ... />
  </ItemTemplate>
</asp:TemplateField> 

or if your content is complex then enclose it into a div and set visibility on the div

<asp:TemplateField>
  <ItemTemplate>
    <div runat="server" visible='<%# MyBoolProperty  %>' >
      <asp:LinkButton ID="attachmentButton" runat="server" ... />
    </div>
  </ItemTemplate>
</asp:TemplateField> 

How can I transition height: 0; to height: auto; using CSS?

There was little mention of the Element.prototype.scrollHeight property which can be useful here and still may be used with a pure CSS transition, although scripting support would obviously be required. The property always contains the "full" height of an element, regardless of whether and how its content overflows as a result of collapsed height (e.g. height: 0).

As such, for a height: 0 (effectively fully collapsed) element, its "normal" or "full" height is still readily available through its scrollHeight value (invariably a pixel length).

For such an element, assuming it already has the transition set up like e.g. (using ul as per original question):

ul {
    height: 0;
    transition: height 1s; /* An example transition. */
}

We can trigger desired animated "expansion" of height, using CSS only, with something like the following (here assuming ul variable refers to the list):

ul.style.height = ul.scrollHeight + "px";

That's it. If you need to collapse the list, either of the two following statements will do:

ul.style.height = "0";
ul.style.removeProperty("height");

My particular use case revolved around animating lists of unknown and often considerable lengths, so I was not comfortable settling on an arbitrary "large enough" height or max-height specification and risking cut-off content or content that you suddenly need to scroll (if overflow: auto, for example). Additionally, the easing and timing is broken with max-height-based solutions, because the used height may reach its maximum value a lot sooner than it would take for max-height to reach 9999px. And as screen resolutions grow, pixel lengths like 9999px leave a bad taste in my mouth. This particular solution solves the problem in an elegant manner, in my opinion.

Finally, here is hoping that future revisions of CSS address authors' need to do these kind of things even more elegantly -- revisit the notion of "computed" vs "used" and "resolved" values, and consider whether transitions should apply to computed values, including transitions with width and height (which currently get a bit of a special treatment).

python-dev installation error: ImportError: No module named apt_pkg

Solve it by this:

/usr/lib/python3/dist-packages# cp apt_pkg.cpython-34m-i386-linux-gnu.so apt_pkg.so

Or:

/usr/lib/python3/dist-packages# cp apt_pkg.cpython-35m-x86_64-linux-gnu.so apt_pkg.so

Basically, if you get a No such file or directory just ls to try to get the right name.

Find out whether radio button is checked with JQuery?

//Check through class

if($("input:radio[class='className']").is(":checked")) {
     //write your code         
}

//Check through name

if($("input:radio[name='Name']").is(":checked")) {
         //write your code         
}

//Check through data

if($("input:radio[data-name='value']").is(":checked")) {
         //write your code         
}

XML Schema (XSD) validation tool?

For Windows there is the free XML Notepad 2007. You can select XSD's for it to validate against

UPDATE: better yet, use Notepad++ with the XML Tools plugin

Java stack overflow error - how to increase the stack size in Eclipse?

You need to have a launch configuration inside Eclipse in order to adjust the JVM parameters.

After running your program with either F11 or Ctrl-F11, open the launch configurations in Run -> Run Configurations... and open your program under "Java Applications". Select the Arguments pane, where you will find "VM arguments".

This is where -Xss1024k goes.

If you want the launch configuration to be a file in your workspace (so you can right click and run it), select the Common pane, and check the Save as -> Shared File checkbox and browse to the location you want the launch file. I usually have them in a separate folder, as we check them into CVS.

Changing background color of selected item in recyclerview

In your adapter class make Integer variable as index and assign it to "0" (if you want to select 1st item by default, if not assign "-1").Then on your onBindViewHolder method,

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
    holder.texttitle.setText(listTitle.get(position));
    holder.itemView.setTag(listTitle.get(position));
    holder.texttitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            index = position;
            notifyDataSetChanged();
        }
    });
    if (index == position)
        holder.texttitle.setTextColor(mContext.getResources().getColor(R.color.selectedColor));
    else
        holder.texttitle.setTextColor(mContext.getResources().getColor(R.color.unSelectedColor));
}

Thats it and you are good to go.in If condition true section place your selected color or what ever you need, and else section place unselected color or what ever.

What does 'wb' mean in this code, using Python?

That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).

Check out the documentation for more: clicky

How to detect input type=file "change" for the same file?

Here's the React-y way solution i've found that worked for me:

onClick={event => event.target.value = null}

MongoDB via Mongoose JS - What is findByID?

As opposed to find() which can return 1 or more documents, findById() can only return 0 or 1 document. Document(s) can be thought of as record(s).

Pandas read_csv from url

UPDATE: From pandas 0.19.2 you can now just pass read_csv() the url directly, although that will fail if it requires authentication.


For older pandas versions, or if you need authentication, or for any other HTTP-fault-tolerant reason:

Use pandas.read_csv with a file-like object as the first argument.

  • If you want to read the csv from a string, you can use io.StringIO.

  • For the URL https://github.com/cs109/2014_data/blob/master/countries.csv, you get html response, not raw csv; you should use the url given by the Raw link in the github page for getting raw csv response , which is https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv

Example:

import pandas as pd
import io
import requests
url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
s=requests.get(url).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))

Notes:

in Python 2.x, the string-buffer object was StringIO.StringIO

How to change the default encoding to UTF-8 for Apache?

Add this to your .htaccess:

IndexOptions +Charset=UTF-8

Or, if you have administrator rights, you could set it globally by editing httpd.conf and adding:

AddDefaultCharset UTF-8

(You can use AddDefaultCharset in .htaccess too, but it won’t affect Apache-generated directory listings that way.)

Start ssh-agent on login

Old question, but I did come across a similar situation. Don't think the above answer fully achieves what is needed. The missing piece is keychain; install it if it isn't already.

sudo apt-get install keychain

Then add the following line to your ~/.bashrc

eval $(keychain --eval id_rsa)

This will start the ssh-agent if it isn't running, connect to it if it is, load the ssh-agent environment variables into your shell, and load your ssh key.

Change id_rsa to whichever private key in ~/.ssh you want to load.

Some useful options for keychain:

  • -q Quiet mode
  • --noask Don't ask for the password upon start, but on demand when ssh key is actually used.

Reference

https://unix.stackexchange.com/questions/90853/how-can-i-run-ssh-add-automatically-without-password-prompt

Using msbuild to execute a File System Publish Profile

Still had trouble after trying all of the answers above (I use Visual Studio 2013). Nothing was copied to the publish folder.

The catch was that if I run MSBuild with an individual project instead of a solution, I have to put an additional parameter that specifies Visual Studio version:

/p:VisualStudioVersion=12.0

12.0 is for VS2013, replace with the version you use. Once I added this parameter, it just worked.

The complete command line looks like this:

MSBuild C:\PathToMyProject\MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=MyPublishProfile /p:VisualStudioVersion=12.0

I've found it here:

http://www.asp.net/mvc/overview/deployment/visual-studio-web-deployment/command-line-deployment

They state:

If you specify an individual project instead of a solution, you have to add a parameter that specifies the Visual Studio version.

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

Not Knowing all of your requirements. For example, are you trying to uniquely identify a computer from all of the computers in the world, or are you just trying to uniquely identify a computer from a set of users of your application. Also, can you create files on the system?

If you are able to create a file. You could create a file and use the creation time of the file as your unique id. If you create it in user space then it would uniquely identify a user of your application on a particular machine. If you created it somewhere global then it could uniquely identify the machine.

Again, as most things, How fast is fast enough.. or in this case, how unique is unique enough.

$http get parameters does not work

The 2nd parameter in the get call is a config object. You want something like this:

$http
    .get('accept.php', {
        params: {
            source: link,
            category_id: category
        }
     })
     .success(function (data,status) {
          $scope.info_show = data
     });

See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail

Base64 length calculation?

I believe that this one is an exact answer if n%3 not zero, no ?

    (n + 3-n%3)
4 * ---------
       3

Mathematica version :

SizeB64[n_] := If[Mod[n, 3] == 0, 4 n/3, 4 (n + 3 - Mod[n, 3])/3]

Have fun

GI

Which Protocols are used for PING?

ICMP means Internet Control Message Protocol and is always coupled with the IP protocol (There's 2 ICMP variants one for IPv4 and one for IPv6.)

echo request and echo response are the two operation codes of ICMP used to implement ping.

Besides the original ping program, ping might simply mean the action of checking if a remote node is responding, this might be done on several layers in a protocol stack - e.g. ARP ping for testing hosts on a local network. The term ping might be used on higher protocol layers and APIs as well, e.g. the act of checking if a database is up, done at the database layer protocol.

ICMP sits on top of IP. What you have below depends on the network you're on, and are not in themselves relevant to the operation of ping.

Shell - How to find directory of some command?

In the TENEX C Shell, tcsh, one can list a command's location(s), or if it is a built-in command, using the where command e.g.:

tcsh% where python
/usr/local/bin/python
/usr/bin/python

tcsh% where cd
cd is a shell built-in
/usr/bin/cd

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

Yes, there is a better way: You can use the $parse service in your directive to evaluate an expression in the context of the parent scope while binding certain identifiers in the expression to values visible only inside your directive:

$parse(attributes.callback)(scope.$parent, { arg2: yourSecondArgument });

Add this line to the link function of the directive where you can access the directive's attributes.

Your callback attribute may then be set like callback = "callback(item.id, arg2)" because arg2 is bound to yourSecondArgument by the $parse service inside the directive. Directives like ng-click let you access the click event via the $event identifier inside the expression passed to the directive by using exactly this mechanism.

Note that you do not have to make callback a member of your isolated scope with this solution.

How to connect to remote Redis server?

There are two ways to connect remote redis server using redis-cli:

1. Using host & port individually as options in command

redis-cli -h host -p port

If your instance is password protected

redis-cli -h host -p port -a password

e.g. if my-web.cache.amazonaws.com is the host url and 6379 is the port

Then this will be the command:

redis-cli -h my-web.cache.amazonaws.com -p 6379

if 92.101.91.8 is the host IP address and 6379 is the port:

redis-cli -h 92.101.91.8 -p 6379

command if the instance is protected with password pass123:

redis-cli -h my-web.cache.amazonaws.com -p 6379 -a pass123

2. Using single uri option in command

redis-cli -u redis://password@host:port

command in a single uri form with username & password

redis-cli -u redis://username:password@host:port

e.g. for the same above host - port configuration command would be

redis-cli -u redis://[email protected]:6379

command if username is also provided user123

redis-cli -u redis://user123:[email protected]:6379

This detailed answer was for those who wants to check all options. For more information check documentation: Redis command line usage

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

How do I verify that an Android apk is signed with a release certificate?

The easiest of all:

keytool -list -printcert -jarfile file.apk

This uses the Java built-in keytool app and does not require extraction or any build-tools installation.

Array of structs example

Given an instance of the struct, you set the values.

    student thisStudent;
    Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
    thisStudent.s_id = int.Parse(Console.ReadLine());
    thisStudent.s_name = Console.ReadLine();
    thisStudent.c_name = Console.ReadLine();
    thisStudent.s_dob = Console.ReadLine();

Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.

Constructor in an Interface?

A problem that you get when you allow constructors in interfaces comes from the possibility to implement several interfaces at the same time. When a class implements several interfaces that define different constructors, the class would have to implement several constructors, each one satisfying only one interface, but not the others. It will be impossible to construct an object that calls each of these constructors.

Or in code:

interface Named { Named(String name); }
interface HasList { HasList(List list); }

class A implements Named, HasList {

  /** implements Named constructor.
   * This constructor should not be used from outside, 
   * because List parameter is missing
   */
  public A(String name)  { 
    ...
  }

  /** implements HasList constructor.
   * This constructor should not be used from outside, 
   * because String parameter is missing
   */
  public A(List list) {
    ...
  }

  /** This is the constructor that we would actually 
   * need to satisfy both interfaces at the same time
   */ 
  public A(String name, List list) {
    this(name);
    // the next line is illegal; you can only call one other super constructor
    this(list); 
  }
}

OpenMP set_num_threads() is not working

According to the GCC manual for omp_get_num_threads:

In a sequential section of the program omp_get_num_threads returns 1

So this:

cout<<"sum="<<sum<<endl;
cout<<"threads="<<omp_get_num_threads()<<endl;

Should be changed to something like:

#pragma omp parallel
{
    cout<<"sum="<<sum<<endl;
    cout<<"threads="<<omp_get_num_threads()<<endl;
}

The code I use follows Hristo's advice of disabling dynamic teams, too.

Using request.setAttribute in a JSP page

Correct me if wrong...I think request does persist between consecutive pages..

Think you traverse from page 1--> page 2-->page 3.

You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".

I mean something like this in page 2 fails:

Where as the same thing has worked in case of page 1 like:

So I think I would need to proceed with either of the two options suggested by Phill.

Check if a record exists in the database

I had a requirement to register user. In that case I need to check whether that username is already present in the database or not. I have tried the below in C# windows form application(EntityFramework) and it worked.

 var result = incomeExpenseManagementDB.Users.FirstOrDefault(x => x.userName == registerUserView.uNameText);
  if (result == null) {
      register.registerUser(registerUserView.fnameText, registerUserView.lnameText, registerUserView.eMailText, registerUserView.mobileText, registerUserView.bDateText, registerUserView.uNameText, registerUserView.pWordText);
  } else {
      MessageBox.Show("User Alreay Exist. Try with Different Username");
  }

When should I use a table variable vs temporary table in sql server?

Variable table is available only to the current session, for example, if you need to EXEC another stored procedure within the current one you will have to pass the table as Table Valued Parameter and of course this will affect the performance, with temporary tables you can do this with only passing the temporary table name

To test a Temporary table:

  • Open management studio query editor
  • Create a temporary table
  • Open another query editor window
  • Select from this table "Available"

To test a Variable table:

  • Open management studio query editor
  • Create a Variable table
  • Open another query editor window
  • Select from this table "Not Available"

something else I have experienced is: If your schema doesn't have GRANT privilege to create tables then use variable tables.

Redirect to specified URL on PHP script completion?

<?
ob_start(); // ensures anything dumped out will be caught

// do stuff here
$url = 'http://example.com/thankyou.php'; // this can be set based on whatever

// clear out the output buffer
while (ob_get_status()) 
{
    ob_end_clean();
}

// no redirect
header( "Location: $url" );
?>

Java System.out.print formatting

Are you sure that you want "055" as opposed to "55"? Some programs interpret a leading zero as meaning octal, so that it would read 055 as (decimal) 45 instead of (decimal) 55.

That should just mean dropping the '0' (zero-fill) flag.

e.g., change System.out.printf("%03d ", x); to the simpler System.out.printf("%3d ", x);

How to print spaces in Python?

simply assign a variable to () or " ", then when needed type

print(x, x, x, Hello World, x)

or something like that.

Hope this is a little less complicated:)

how to rename an index in a cluster?

If you can't REINDEX a workaround is to use aliases. From the official documentation:

APIs in elasticsearch accept an index name when working against a specific index, and several indices when applicable. The index aliases API allow to alias an index with a name, with all APIs automatically converting the alias name to the actual index name. An alias can also be mapped to more than one index, and when specifying it, the alias will automatically expand to the aliases indices. An alias can also be associated with a filter that will automatically be applied when searching, and routing values. An alias cannot have the same name as an index.

Be aware that this solution does not work if you're using More Like This feature. https://github.com/elastic/elasticsearch/issues/16560

What is getattr() exactly and how do I use it?

It is also clarifying from https://www.programiz.com/python-programming/methods/built-in/getattr

class Person:
    age = 23
    name = "Adam"

person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)

The age is: 23

The age is: 23

class Person:
    age = 23
    name = "Adam"

person = Person()

# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))

# when no default value is provided
print('The sex is:', getattr(person, 'sex'))

The sex is: Male

AttributeError: 'Person' object has no attribute 'sex'

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JavaFX open new window

If you just want a button to open up a new window, then something like this works:

btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent event) {
        Parent root;
        try {
            root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
            Stage stage = new Stage();
            stage.setTitle("My New Stage Title");
            stage.setScene(new Scene(root, 450, 450));
            stage.show();
            // Hide this current window (if this is what you want)
            ((Node)(event.getSource())).getScene().getWindow().hide();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Half circle with CSS (border, outline only)

Below is a minimal code to achieve the effect.

This also works responsively since the border-radius is in percentage.

_x000D_
_x000D_
.semi-circle{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
border-radius: 50% 50% 0 0 / 100% 100% 0 0;_x000D_
border: 10px solid #000;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div class="semi-circle"></div>
_x000D_
_x000D_
_x000D_

jQuery: Change button text on click

This should work for you:

    $('.SeeMore2').click(function(){
        var $this = $(this);
        $this.toggleClass('SeeMore2');
        if($this.hasClass('SeeMore2')){
            $this.text('See More');         
        } else {
            $this.text('See Less');
        }
});

Formatting Phone Numbers in PHP

$data = '+11234567890';

if(  preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data,  $matches ) )
{
    $result = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
    return $result;
}

PHP is not recognized as an internal or external command in command prompt

Extra info:

If you are using PhpStorm as IDE, after updating the path variable you need to restart PhpStorm so that it takes effect.

Restarting terminal window was not enough for me. (PhpStorm 2020.3.2)

Filtering Table rows using Jquery

I chose @nrodic's answer (thanks, by the way), but it has several drawbacks:

1) If you have rows containing "cat", "dog", "mouse", "cat dog", "cat dog mouse" (each on separate row), then when you search explicitly for "cat dog mouse", you'll be displayed "cat", "dog", "mouse", "cat dog", "cat dog mouse" rows.

2) .toLowerCase() was not implemented, that is, when you enter lower case string, rows with matching upper case text will not be showed.

So I came up with a fork of @nrodic's code, where

var data = this.value; //plain text, not an array

and

jo.filter(function (i, v) {
    var $t = $(this);
    var stringsFromRowNodes = $t.children("td:nth-child(n)")
    .text().toLowerCase();
    var searchText = data.toLowerCase();
    if (stringsFromRowNodes.contains(searchText)) {
        return true;
        }
    return false;
})
//show the rows that match.
.show();

Here goes the full code: http://jsfiddle.net/jumasheff/081qyf3s/

Getting the class of the element that fired an event using JQuery

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $("a").click(function(event) {_x000D_
    var myClass = $(this).attr("class");_x000D_
    var myId = $(this).attr('id');_x000D_
    alert(myClass + " " + myId);_x000D_
  });_x000D_
})
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <a href="#" id="kana1" class="konbo">click me 1</a>_x000D_
  <a href="#" id="kana2" class="kinta">click me 2</a>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

This works for me. There is no event.target.class function in jQuery.

What's the best way to add a full screen background image in React Native

Oh God Finally I find a great way for React-Native V 0.52-RC and native-base:

Your Content Tag Should be something like this: //==============================================================

<Content contentContainerStyle={styles.container}>
    <ImageBackground
        source={require('./../assets/img/back.jpg')}
        style={styles.backgroundImage}>
        <Text>
            Some text here ...
        </Text>
    </ImageBackground>
</Content>

And Your essential style is : //==============================================================

container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
},
backgroundImage:{
    flex : 1,
    width : '100%'
}

It works fine friends ... have fun

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

This code worked for me

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserDetail>()
            .HasRequired(d => d.User)
            .WithOptional(u => u.UserDetail)
            .WillCascadeOnDelete(true);
    }

The migration code was:

public override void Up()
    {
        AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
    }

And it worked fine. When I first used

modelBuilder.Entity<User>()
    .HasOptional(a => a.UserDetail)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);

The migration code was:

AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true); 

but it does not match any of the two overloads available (in EntityFramework 6)

Parse JSON response using jQuery

The data returned by the JSON is in json format : which is simply an arrays of values. Thats why you are seeing [object Object],[object Object],[object Object].

You have to iterate through that values to get actuall value. Like the following

jQuery provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (linktext, link) {
        console.log(linktext);
        console.log(link);
    });
});

Now just create an Hyperlink using that info.

Single Line Nested For Loops

The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.

Look at this longer list comprehension from the tutorial (the if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)):

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.

On to your questions:

What type must object be in order to use this for loop structure?

An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.

What is the order in which i and j are assigned to elements in object?

They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)

Can it be simulated by a different for loop structure?

Yes, already shown above.

Can this for loop be nested with a similar or different structure for loop? And how would it look?

Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:

[[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]

jQuery rotate/transform

It's because you have a recursive function inside of rotate. It's calling itself again:

// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);

Take that out and it won't keep on running recursively.

I would also suggest just using this function instead:

function rotate($el, degrees) {
    $el.css({
  '-webkit-transform' : 'rotate('+degrees+'deg)',
     '-moz-transform' : 'rotate('+degrees+'deg)',  
      '-ms-transform' : 'rotate('+degrees+'deg)',  
       '-o-transform' : 'rotate('+degrees+'deg)',  
          'transform' : 'rotate('+degrees+'deg)',  
               'zoom' : 1

    });
}

It's much cleaner and will work for the most amount of browsers.

EF Code First "Invalid column name 'Discriminator'" but no inheritance

Turns out that Entity Framework will assume that any class that inherits from a POCO class that is mapped to a table on the database requires a Discriminator column, even if the derived class will not be saved to the DB.

The solution is quite simple and you just need to add [NotMapped] as an attribute of the derived class.

Example:

class Person
{
    public string Name { get; set; }
}

[NotMapped]
class PersonViewModel : Person
{
    public bool UpdateProfile { get; set; }
}

Now, even if you map the Person class to the Person table on the database, a "Discriminator" column will not be created because the derived class has [NotMapped].

As an additional tip, you can use [NotMapped] to properties you don't want to map to a field on the DB.

$(window).scrollTop() vs. $(document).scrollTop()

They are both going to have the same effect.

However, as pointed out in the comments: $(window).scrollTop() is supported by more web browsers than $('html').scrollTop().

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

It's been a while since the OP, but here's my solution for this using Bootstrap 3. In my use case, I was only targeting rows, but the same could be applied to the container, etc.

Just change .row to whatever you want.

jQuery(document).ready(function ($) {

    var alterClass = function () {

        var ww = document.body.clientWidth;

        if (ww < 768) {

            $('.row').addClass('is-xs').removeClass('is-sm').removeClass('is-lg').removeClass('is-md');

        } else if (ww >= 768 && ww < 992) {

            $('.row').addClass('is-sm').removeClass('is-xs').removeClass('is-lg').removeClass('is-md');

        } else if (ww >= 992 && ww < 1200) {

            $('.row').addClass('is-md').removeClass('is-xs').removeClass('is-lg').removeClass('is-sm');

        } else if (ww >= 1200) {

            $('.row').addClass('is-lg').removeClass('is-md').removeClass('is-sm').removeClass('is-xs');

        };
    };

    // Make Changes when the window is resized
    $(window).resize(function () {
        alterClass();
    });

    // Fire when the page first loads
    alterClass();
});

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

I would like to extend Mohamed Elrashid answer, in case you require to pass a variable from the child widget to the parent widget

On child widget:

class ChildWidget extends StatefulWidget {
  final Function() notifyParent;
  ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}

On parent widget

void refresh(dynamic childValue) {
  setState(() {
    _parentVariable = childValue;
  });
}

On parent widget: pass the function above to the child widget

new ChildWidget( notifyParent: refresh ); 

On child widget: call the parent function with any variable from the the child widget

widget.notifyParent(childVariable);

Get only the Date part of DateTime in mssql

This may also help:

SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM (or PM)
                                        -- Oct  2 2008 11:01AM
SELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy - 10/02/2008                  
SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd – 2008.10.02           
SELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) -- dd mon yyyy
SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy
SELECT convert(varchar, getdate(), 108) --  hh:mm:ss
SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)
                                        -- Oct  2 2008 11:02:44:013AM   
SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) -- yyyymmdd
SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm
                                        --  02 Oct 2008 11:02:07:577     
SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) --  yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
                                        --  2008-10-02T10:52:47.513
-- SQL create different date styles with t-sql string functions
SELECT replace(convert(varchar, getdate(), 111), '/', ' ') -- yyyy mm dd
SELECT convert(varchar(7), getdate(), 126)                 -- yyyy-mm
SELECT right(convert(varchar, getdate(), 106), 8)          -- mon yyyy

The Source

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

To change to x86:

  1. Create a setup project for your solution.
  2. After you create it, Go to Solution Explorer, right click the setup project.
    • Press Configuration Manager.
    • Click on: "Active Solution Platform" combobox and select New (If there is no x86 displayed)
    • Select from first combo x86 then press OK.
    • rebuild Setup project, then rebuild All the project.

CSS float right not working correctly

Verry Easy, change order of element:

Origin

<div style="">

    My Text

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

</div>

Change to:

<div style=""> 

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

   My Text

</div>

Force to open "Save As..." popup open at text link click for PDF in HTML

I found a very simple solution for Firefox (only works with a relative rather than a direct href): add type="application/octet-stream":

<a href="./file.pdf" id='example' type="application/octet-stream">Example</a>

How can I call PHP functions by JavaScript?

This work perfectly for me:

To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.

I found a way:

This for JavaScript:

function callPHP(expression, objs, afterHandler) {
        expression = expression.trim();
        var si = expression.indexOf("(");
        if (si == -1)
            expression += "()";
        else if (Object.keys(objs).length > 0) {
            var sfrom = expression.substring(si + 1);
            var se = sfrom.indexOf(")");
            var result = sfrom.substring(0, se).trim();
            if (result.length > 0) {
                var params = result.split(",");
                var theend = expression.substring(expression.length - sfrom.length + se);
                expression = expression.substring(0, si + 1);
                for (var i = 0; i < params.length; i++) {
                    var param = params[i].trim();
                    if (param in objs) {
                        var value = objs[param];
                        if (typeof value == "string")
                            value = "'" + value + "'";
                        if (typeof value != "undefined")
                            expression += value + ",";
                    }
                }
                expression = expression.substring(0, expression.length - 1) + theend;
            }
        }
        var doc = document.location;
        var phpFile = "URL of your PHP file";
        var php =
            "$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
            "$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
            "set_include_path($folder);include $fileName;" + expression + ";";
        var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
        $.ajax({
            type: 'GET',
            url: url,
            complete: function(resp){
                var response = resp.responseText;
                afterHandler(response);
            }
        });
    }


This for a PHP file which isn't your PHP file, but another, which path is written in url variable of JS function callPHP , and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:

<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
    eval(trim($line, " ") . ";");
?>


So, your PHP code remain equals except return values, which will be echoed:

<?php
function add($a,$b){
  $c=$a+$b;
  echo $c;
}
function mult($a,$b){
  $c=$a*$b;
  echo $c;
}

function divide($a,$b){
  $c=$a/$b;
  echo $c;
}
?>


I suggest you to remember that jQuery is required:
Download it from Google CDN:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

or from Microsoft CDN: "I prefer Google! :)"

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>

Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster!

The choice is to you!


Now you finished! I just tell you how to use callPHP function. This is the JavaScript to call PHP:

//Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
            'num1' : 1,
            'num2' : 2
        },
            function(output) {
                alert(output); //This to display the output of the PHP file.
        });

How do I sort a dictionary by value?

You could use:

sorted(d.items(), key=lambda x: x[1])

This will sort the dictionary by the values of each entry within the dictionary from smallest to largest.

To sort it in descending order just add reverse=True:

sorted(d.items(), key=lambda x: x[1], reverse=True)

Input:

d = {'one':1,'three':3,'five':5,'two':2,'four':4}
a = sorted(d.items(), key=lambda x: x[1])    
print(a)

Output:

[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]

Iterating Over Dictionary Key Values Corresponding to List in Python

Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__ you can do simplify things a bit.

Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.

from __future__ import division

def Pythag(league):
    def win_percentages():
        for team, (runs_scored, runs_allowed) in league.iteritems():
            win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
            yield win_percentage

    for win_percentage in win_percentages():
        print win_percentage

Get and Set a Single Cookie with Node.js HTTP Server

You can use the "cookies" npm module, which has a comprehensive set of features.

Documentation and examples at:
https://github.com/jed/cookies

How to dynamically load a Python class

If you happen to already have an instance of your desired class, you can use the 'type' function to extract its class type and use this to construct a new instance:

class Something(object):
    def __init__(self, name):
        self.name = name
    def display(self):
        print(self.name)

one = Something("one")
one.display()
cls = type(one)
two = cls("two")
two.display()

How to calculate time elapsed in bash script?

Here is a solution using only the date commands capabilities using "ago", and not using a second variable to store the finish time:

#!/bin/bash

# save the current time
start_time=$( date +%s.%N )

# tested program
sleep 1

# the current time after the program has finished
# minus the time when we started, in seconds.nanoseconds
elapsed_time=$( date +%s.%N --date="$start_time seconds ago" )

echo elapsed_time: $elapsed_time

this gives:

$ ./time_elapsed.sh 
elapsed_time: 1.002257120

Invoking Java main method with parameters from Eclipse

Another idea:

Place all your parameters in a properties file (one parameter = one property in this file), then in your main method, load this file (using Properties.load(*fileInputStream*)). So if you want to modify one argument, you will just need to edit your args.properties file, and launch your application without more steps to do...

Of course, this is only for development purposes, but can be really helpfull if you have to change your arguments often...

Kill a postgresql session/connection

MacOS, if postgresql was installed with brew:

brew services restart postgresql

Source: Kill a postgresql session/connection

Is there a CSS parent selector?

In CSS, we can cascade to the properties down the hierarchy but not in the oppostite direction. To modify the parent style on child event, probably use jQuery.

$el.closest('.parent').css('prop','value');

Is there a way to check for both `null` and `undefined`?

if(data){}

it's mean !data

  • null
  • undefined
  • false
  • ....

How to implement a read only property

With the introduction of C# 6 (in VS 2015), you can now have get-only automatic properties, in which the implicit backing field is readonly (i.e. values can be assigned in the constructor but not elsewhere):

public string Name { get; }

public Customer(string name)  // Constructor
{
    Name = name;
}

private void SomeFunction()
{
    Name = "Something Else";  // Compile-time error
}

And you can now also initialise properties (with or without a setter) inline:

public string Name { get; } = "Boris";

Referring back to the question, this gives you the advantages of option 2 (public member is a property, not a field) with the brevity of option 1.

Unfortunately, it doesn't provide a guarantee of immutability at the level of the public interface (as in @CodesInChaos's point about self-documentation), because to a consumer of the class, having no setter is indistinguishable from having a private setter.

Is bool a native C type?

stdbool.h was introduced in c99

How do I convert a long to a string in C++?

Well if you are fan of copy-paste, here it is:

#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
    std::stringstream ss;
    ss << t;
    return ss.str();
}

How to programmatically round corners and set random background colors

Here's an example using an extension. This assumes the view has the same width and height.

Need to use a layout change listener to get the view size. Then you can just call this on a view like this myView.setRoundedBackground(Color.WHITE)

fun View.setRoundedBackground(@ColorInt color: Int) {
    addOnLayoutChangeListener(object: View.OnLayoutChangeListener {
        override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {

            val shape = GradientDrawable()
            shape.cornerRadius = measuredHeight / 2f
            shape.setColor(color)

            background = shape

            removeOnLayoutChangeListener(this)
        }
    })
}

Div side by side without float

You can try with margin for right div

margin: -200px 0 0 350px;

SDK Location not found Android Studio + Gradle

To fix this problem, I had to define the ANDROID_HOME environment variable in the Windows OS.

To do this, I went to the System control panel.
I selected "Advanced system settings" in the left column.
On the "Advanced" tab, I selected "Environment Variables" at the bottom.

Here, I did not have an ANDROID_HOME variable defined. For this case, I selected "New..." and:
1) for "Variable name" I typed ANDROID_HOME,
2) for "Variable value", I typed the path to my SDK folder, e.g. "C:\...\AppData\Local\Android\sdk".

I then closed Android Studio and reopened, and everything worked.

Thanks to Dibish (https://stackoverflow.com/users/2244411/dibish) for one of his posts that gave me this idea.

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Replace input type=file by an image

I have had lots of issues with hidden and not visible inputs over the past decade sometimes things are way simpler than we think.

I have had a little wish with IE 5,6,7,8 and 9 for not supporting the opacity and thus the file input would cover the upload image however the following css code has resolved the issue.

-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);  

The following snipped is tested on chrome, IE 5,6,7,8,9,10 the only issue in IE 5 is that it does not support auto margin.

Run the snippet simply copy and paste the CSS and HTML modify the size as you like.

_x000D_
_x000D_
.file-upload{_x000D_
 height:100px;_x000D_
 width:100px;_x000D_
 margin:40px auto;_x000D_
 border:1px solid #f0c0d0;_x000D_
 border-radius:100px;_x000D_
 overflow:hidden;_x000D_
 position:relative;_x000D_
}_x000D_
.file-upload input{_x000D_
 position:absolute;_x000D_
 height:400px;_x000D_
 width:400px;_x000D_
 left:-200px;_x000D_
 top:-200px;_x000D_
 background:transparent;_x000D_
 opacity:0;_x000D_
 -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
 filter: alpha(opacity=0);  _x000D_
}_x000D_
.file-upload img{_x000D_
 height:70px;_x000D_
 width:70px;_x000D_
 margin:15px;_x000D_
}
_x000D_
<div class="file-upload">_x000D_
<!--place upload image/icon first !-->_x000D_
<img src="https://i.stack.imgur.com/dy62M.png" />_x000D_
<!--place input file last !-->_x000D_
<input type="file" name="somename" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

I don't understand -Wl,-rpath -Wl,

You could also write

-Wl,-rpath=.

To get rid of that pesky space. It's arguably more readable than adding extra commas (it's exactly what gets passed to ld).

Loading cross-domain endpoint with AJAX

If the external site doesn't support JSONP or CORS, your only option is to use a proxy.

Build a script on your server that requests that content, then use jQuery ajax to hit the script on your server.

What's the difference between ASCII and Unicode?

Beyond how UTF is a superset of ASCII, another good difference to know between ASCII and UTF is in terms of disk file encoding and data representation and storage in random memory. Programs know that given data should be understood as an ASCII or UTF string either by detecting special byte order mark codes at the start of the data, or by assuming from programmer intent that the data is text and then checking it for patterns that indicate it is in one text encoding or another.

Using the conventional prefix notation of 0x for hexadecimal data, basic good reference is that ASCII text starts with byte values 0x00 to 0x7F representing one of the possible ASCII character values. UTF text is normally indicated by starting with the bytes 0xEF 0xBB 0xBF for UTF8. For UTF16, start bytes 0xFE 0xFF, or 0xFF 0xFE are used, with the endian-ness order of the text bytes indicated by the order of the start bytes. The simple presence of byte values that are not in the ASCII range of possible byte values also indicates that data is probably UTF.

There are other byte order marks that use different codes to indicate data should be interpreted as text encoded in a certain encoding standard.

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

I got the error...

Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

...when I was trying to make contact from a Git Bash prompt to Bitbucket after my laptop died from a bad Windows 10 update and was returned to factory settings. I had restored all my ssh files from a backup.

The cause of the error turned out to be a mismatch in my Windows account name after the computer rebuild. I learned that the public key file id_rsa.pub ends with an easily readable string comprising my Windows account name followed by an @ sign and then the computer name.

When I originally set up my computer, I created my Windows account name including my middle initial but when my computer was reset to factory settings, our new DevOps guy created my account name without my middle initial.

To resolve the issue, I simply edited my public key file id_rsa.pub and removed the middle initial in my name at the end. I had stuck with the same computer name so that was okay. I copied the file contents to the Windows clipboard. I then signed into Bitbucket, went to Bitbucket Settings under my avatar, and added a new public key where I pasted in the new contents.

Back at the Git Bash prompt, I confirmed that it now worked by entering the command...

ssh -T [email protected]

...and I got back a message that I was signed in.

Including a .js file within a .js file

There is no straight forward way of doing this.

What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).

Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript

My favorite is(not applicable always):

<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");

Google's closure also provides similar functionality.

Remove IE10's "clear field" X button on certain inputs?

I found it's better to set the width and height to 0px. Otherwise, IE10 ignores the padding defined on the field -- padding-right -- which was intended to keep the text from typing over the 'X' icon that I overlayed on the input field. I'm guessing that IE10 is internally applying the padding-right of the input to the ::--ms-clear pseudo element, and hiding the pseudo element does not restore the padding-right value to the input.

This worked better for me:

.someinput::-ms-clear {
  width : 0;
  height: 0;
}

Creating a new column based on if-elif-else condition

For this particular relationship, you could use np.sign:

>>> df["C"] = np.sign(df.A - df.B)
>>> df
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

How to convert the time from AM/PM to 24 hour format in PHP?

We can use Carbon

 $time = '09:15 PM';
 $s=Carbon::parse($time);
 echo $military_time =$s->format('G:i');

http://carbon.nesbot.com/docs/

Checking password match while typing

if we use bootstrap our text will be green or red depending on the result

HTML

<div class="col-12 col-md-6 col-lg-4 mb-3">
            <label class="form-group d-block mb-0">
        <span class="text-secondary d-block font-weight-semibold mb-1">New Password</span>
<input type="password" id="txtNewPassword" class="form-control">     
        </label>
        </div>
        <div class="col-12 col-md-6 col-lg-4 mb-3">
            <label class="form-group d-block mb-0">
        <span class="text-secondary d-block font-weight-semibold mb-1">Confirm Password
        </span>
        <input class="form-control" type="password" id="txtConfirmPassword" onkeyup="checkPasswordMatch();">   
            </label>
        </div>
        <div class="registrationFormAlert" id="divCheckPasswordMatch"></div>

CSS

.text-success {
    color: #28a745;
}
.text-danger {
    color: #dc3545;
}

JS

function checkPasswordMatch() {
        var password = $("#txtNewPassword").val();
        var confirmPassword = $("#txtConfirmPassword").val();

        if (password != confirmPassword)
            $("#divCheckPasswordMatch").html("Passwords do not match!").addClass('text-danger').removeClass('text-success');

        else
            $("#divCheckPasswordMatch").html("Passwords match.").addClass('text-success').removeClass('text-danger');
    }

Angular.js directive dynamic templateURL

I have an example about this.

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  </head>

  <body>
    <div class="container-fluid body-content" ng-controller="formView">
        <div class="row">
            <div class="col-md-12">
                <h4>Register Form</h4>
                <form class="form-horizontal" ng-submit="" name="f" novalidate>
                    <div ng-repeat="item in elements" class="form-group">
                        <label>{{item.Label}}</label>
                        <element type="{{item.Type}}" model="item"></element>
                    </div>
                    <input ng-show="f.$valid" type="submit" id="submit" value="Submit" class="" />
                </form>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
    <script src="app.js"></script>
  </body>

</html>

angular.module('app', [])
    .controller('formView', function ($scope) {
        $scope.elements = [{
            "Id":1,
            "Type":"textbox",
            "FormId":24,
            "Label":"Name",
            "PlaceHolder":"Place Holder Text",
            "Max":20,
            "Required":false,
            "Options":null,
            "SelectedOption":null
          },
          {
            "Id":2,
            "Type":"textarea",
            "FormId":24,
            "Label":"AD2",
            "PlaceHolder":"Place Holder Text",
            "Max":20,
            "Required":true,
            "Options":null,
            "SelectedOption":null
        }];
    })
    .directive('element', function () {
        return {
            restrict: 'E',
            link: function (scope, element, attrs) {
                scope.contentUrl = attrs.type + '.html';
                attrs.$observe("ver", function (v) {
                    scope.contentUrl = v + '.html';
                });
            },
            template: '<div ng-include="contentUrl"></div>'
        }
    })

Certificate has either expired or has been revoked

A new problem with Xcode 8, what worked for me was to turn off the new "automatically manage signing" checkbox on the General tab for the target, then turn it back on.

This initiates an on-boarding wizard that sets things up correctly for Xcode 8.

Scale the contents of a div by a percentage?

You can simply use the zoom property:

#myContainer{
    zoom: 0.5;
    -moz-transform: scale(0.5);
}

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

How to select some rows with specific rownames from a dataframe?

df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <-  letters[1:10]
df[c('a','b'),]

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Upgrade pip as follows:

curl https://bootstrap.pypa.io/get-pip.py | python

Note: You may need to use sudo python above if not in a virtual environment.

What's happening:

Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.

(Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue)

This thread explains it (thanks to this Twitter post):

Mac users who use pip and PyPI:

If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:

curl https://bootstrap.pypa.io/get-pip.py | python

and we recommend you do that by April 8th.

Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/

Also, the Python status page:

Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC

Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC

Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:

pip install --upgrade setuptools

Appending to an object

You can do this with Object.assign(). Sometimes you need an array, but when working with functions that expect a single JSON object -- such as an OData call -- I've found this method simpler than creating an array only to unpack it.

var alerts = { 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
}

alerts = Object.assign({3: {app:'helloagain_again',message:'yet another message'}}, alerts)

//Result:
console.log(alerts)
{ 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
    3: {app: "helloagain_again",message: "yet another message"}
} 

EDIT: To address the comment regarding getting the next key, you can get an array of the keys with the Object.keys() function -- see Vadi's answer for an example of incrementing the key. Similarly, you can get all the values with Object.values() and key-values pairs with Object.entries().

var alerts = { 
    1: {app:'helloworld',message:'message'},
    2: {app:'helloagain',message:'another message'}
}
console.log(Object.keys(alerts))
// Output
Array [ "1", "2" ]

Reading InputStream as UTF-8

String file = "";

try {

    InputStream is = new FileInputStream(filename);
    String UTF8 = "utf8";
    int BUFFER_SIZE = 8192;

    BufferedReader br = new BufferedReader(new InputStreamReader(is,
            UTF8), BUFFER_SIZE);
    String str;
    while ((str = br.readLine()) != null) {
        file += str;
    }
} catch (Exception e) {

}

Try this,.. :-)

How to use HttpWebRequest (.NET) asynchronously?

.NET has changed since many of these answers were posted, and I'd like to provide a more up-to-date answer. Use an async method to start a Task that will run on a background thread:

private async Task<String> MakeRequestAsync(String url)
{    
    String responseText = await Task.Run(() =>
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            WebResponse response = request.GetResponse();            
            Stream responseStream = response.GetResponseStream();
            return new StreamReader(responseStream).ReadToEnd();            
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
        return null;
    });

    return responseText;
}

To use the async method:

String response = await MakeRequestAsync("http://example.com/");

Update:

This solution does not work for UWP apps which use WebRequest.GetResponseAsync() instead of WebRequest.GetResponse(), and it does not call the Dispose() methods where appropriate. @dragansr has a good alternative solution that addresses these issues.

lexers vs parsers

Yes, they are very different in theory, and in implementation.

Lexers are used to recognize "words" that make up language elements, because the structure of such words is generally simple. Regular expressions are extremely good at handling this simpler structure, and there are very high-performance regular-expression matching engines used to implement lexers.

Parsers are used to recognize "structure" of a language phrases. Such structure is generally far beyond what "regular expressions" can recognize, so one needs "context sensitive" parsers to extract such structure. Context-sensitive parsers are hard to build, so the engineering compromise is to use "context-free" grammars and add hacks to the parsers ("symbol tables", etc.) to handle the context-sensitive part.

Neither lexing nor parsing technology is likely to go away soon.

They may be unified by deciding to use "parsing" technology to recognize "words", as is currently explored by so-called scannerless GLR parsers. That has a runtime cost, as you are applying more general machinery to what is often a problem that doesn't need it, and usually you pay for that in overhead. Where you have lots of free cycles, that overhead may not matter. If you process a lot of text, then the overhead does matter and classical regular expression parsers will continue to be used.

Detecting Back Button/Hash Change in URL

Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

The first line of every source file of your project must be the following:

#include <stdafx.h>

Visit here to understand Precompiled Headers

Passing string to a function in C - with or without pointers?

An array is a pointer. It points to the start of a sequence of "objects".

If we do this: ìnt arr[10];, then arr is a pointer to a memory location, from which ten integers follow. They are uninitialised, but the memory is allocated. It is exactly the same as doing int *arr = new int[10];.

Forward declaring an enum in C++

I'd do it this way:

[in the public header]

typedef unsigned long E;

void Foo(E e);

[in the internal header]

enum Econtent { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X,
  FORCE_32BIT = 0xFFFFFFFF };

By adding FORCE_32BIT we ensure that Econtent compiles to a long, so it's interchangeable with E.

How to determine the version of the C++ standard used by the compiler?

From the Bjarne Stroustrup C++0x FAQ:

__cplusplus

In C++11 the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.

Although this isn't as helpful as one would like. gcc (apparently for nearly 10 years) had this value set to 1, ruling out one major compiler, until it was fixed when gcc 4.7.0 came out.

These are the C++ standards and what value you should be able to expect in __cplusplus:

  • C++ pre-C++98: __cplusplus is 1.
  • C++98: __cplusplus is 199711L.
  • C++98 + TR1: This reads as C++98 and there is no way to check that I know of.
  • C++11: __cplusplus is 201103L.
  • C++14: __cplusplus is 201402L.
  • C++17: __cplusplus is 201703L.

If the compiler might be an older gcc, we need to resort to compiler specific hackery (look at a version macro, compare it to a table with implemented features) or use Boost.Config (which provides relevant macros). The advantage of this is that we actually can pick specific features of the new standard, and write a workaround if the feature is missing. This is often preferred over a wholesale solution, as some compilers will claim to implement C++11, but only offer a subset of the features.

The Stdcxx Wiki hosts a comprehensive matrix for compiler support of C++0x features (archive.org link) (if you dare to check for the features yourself).

Unfortunately, more finely-grained checking for features (e.g. individual library functions like std::copy_if) can only be done in the build system of your application (run code with the feature, check if it compiled and produced correct results - autoconf is the tool of choice if taking this route).

Responsive design with media query : screen size?

Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience

When you design your responsive website you should consider the size of the screen and not the device type. The media queries helps you do that.

If you want to style your site per device, you can use the user agent value, but this is not recommended since you'll have to work hard to maintain your code for new devices, new browsers, browsers versions etc while when using the screen size, all of this does not matter.

You can see some standard resolutions in this link.

BUT, in my opinion, you should first design your website layout, and only then adjust it with media queries to fit possible screen sizes.

Why? As I said before, the screen resolutions variety is big and if you'll design a mobile version that is targeted to 320px your site won't be optimized to 350px screens or 400px screens.

TIPS

  1. When designing a responsive page, open it in your desktop browser and change the width of the browser to see how the width of the screen affects your layout and style.
  2. Use percentage instead of pixels, it will make your work easier.

Example

I have a table with 5 columns. The data looks good when the screen size is bigger than 600px so I add a breakpoint at 600px and hides 1 less important column when the screen size is smaller. Devices with big screens such as desktops and tablets will display all the data, while mobile phones with small screens will display part of the data.


State of mind

Not directly related to the question but important aspect in responsive design. Responsive design also relate to the fact that the user have a different state of mind when using a mobile phone or a desktop. For example, when you open your bank's site in the evening and check your stocks you want as much data on the screen. When you open the same page in the your lunch break your probably want to see few important details and not all the graphs of last year.

How can I truncate a string to the first 20 words in PHP?

what about

chunk_split($str,20);

Entry in the PHP Manual

Using "If cell contains" in VBA excel

This will loop through all cells in a given range that you define ("RANGE TO SEARCH") and add dashes at the cell below using the Offset() method. As a best practice in VBA, you should never use the Select method.

Sub AddDashes()

Dim SrchRng As Range, cel As Range

Set SrchRng = Range("RANGE TO SEARCH")

For Each cel In SrchRng
    If InStr(1, cel.Value, "TOTAL") > 0 Then
        cel.Offset(1, 0).Value = "-"
    End If
Next cel

End Sub

What is the default boolean value in C#?

http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx

Remember that using uninitialized variables in C# is not allowed.

With

bool foo = new bool();

foo will have the default value.

Boolean default is false

How do you properly use namespaces in C++?

Another difference between java and C++, is that in C++, the namespace hierarchy does not need to mach the filesystem layout. So I tend to put an entire reusable library in a single namespace, and subsystems within the library in subdirectories:

#include "lib/module1.h"
#include "lib/module2.h"

lib::class1 *v = new lib::class1();

I would only put the subsystems in nested namespaces if there was a possibility of a name conflict.

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

android: how to change layout on button click?

  Button btnDownload = (Button) findViewById(R.id.DownloadView);
  Button btnApp = (Button) findViewById(R.id.AppView);

  btnDownload.setOnClickListener(handler);
  btnApp.setOnClickListener(handler);

  View.OnClickListener handler = new View.OnClickListener(){

  public void onClick(View v) {

    if(v==btnDownload){ 
            // doStuff
            Intent intentMain = new Intent(CurrentActivity.this , 
                                           SecondActivity.class);
            CurrentActivity.this.startActivity(intentMain);
            Log.i("Content "," Main layout ");
    }

    if(v==btnApp){ 
            // doStuff
            Intent intentApp = new Intent(CurrentActivity.this, 
                                          ThirdActivity.class);

            CurrentActivity.this.startActivity(intentApp);

            Log.i("Content "," App layout ");

    }
   }
  };

Note : and then you should declare all your activities in the manifest .xml file like this :

<activity android:name=".SecondActivity" ></activity>
<activity android:name=".ThirdActivity" ></activity>

EDIT : update this part of Code :) :

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);// Add THIS LINE

    setContentView(R.layout.app);

    TextView tv = (TextView) this.findViewById(R.id.thetext);
    tv.setText("App View yo!?\n");
}

NB : check this (Broken link) Tutorial About How To Switch Between Activities.

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID