Programs & Examples On #Quantlib

SQL Server procedure declare a list

That is not possible with a normal query since the in clause needs separate values and not a single value containing a comma separated list. One solution would be a dynamic query

declare @myList varchar(100)
set @myList = '(1,2,5,7,10)'
exec('select * from DBTable where id IN ' + @myList)

Brew install docker does not include docker engine?

To install Docker for Mac with homebrew:

brew cask install docker

To install the command line completion:

brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

I found a solution in the guide here:

http://www.samontab.com/web/2014/06/installing-opencv-2-4-9-in-ubuntu-14-04-lts/

I resorted to compiling and installing from source. The process was very smooth, had I known, I would have started with that instead of trying to find a more simple way to install. Hopefully this information is helpful to someone.

How can I export data to an Excel file

 private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp ;
        Excel.Workbook xlWorkBook ;
        Excel.Worksheet xlWorkSheet ;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);

        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

        xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

        MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");
    }

    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }

The above code is taken directly off csharp.net please take a look on the site.

Pandas percentage of total with groupby

The most elegant way to find percentages across columns or index is to use pd.crosstab.

Sample Data

df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': list(range(1, 7)) * 2,
               'sales': [np.random.randint(100000, 999999) for _ in range(12)]})

The output dataframe is like this

print(df)

        state   office_id   sales
    0   CA  1   764505
    1   WA  2   313980
    2   CO  3   558645
    3   AZ  4   883433
    4   CA  5   301244
    5   WA  6   752009
    6   CO  1   457208
    7   AZ  2   259657
    8   CA  3   584471
    9   WA  4   122358
    10  CO  5   721845
    11  AZ  6   136928

Just specify the index, columns and the values to aggregate. The normalize keyword will calculate % across index or columns depending upon the context.

result = pd.crosstab(index=df['state'], 
                     columns=df['office_id'], 
                     values=df['sales'], 
                     aggfunc='sum', 
                     normalize='index').applymap('{:.2f}%'.format)




print(result)
office_id   1   2   3   4   5   6
state                       
AZ  0.00%   0.20%   0.00%   0.69%   0.00%   0.11%
CA  0.46%   0.00%   0.35%   0.00%   0.18%   0.00%
CO  0.26%   0.00%   0.32%   0.00%   0.42%   0.00%
WA  0.00%   0.26%   0.00%   0.10%   0.00%   0.63%

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

How do JavaScript closures work?

A function in JavaScript is not just a reference to a set of instructions (as in C language), but it also includes a hidden data structure which is composed of references to all nonlocal variables it uses (captured variables). Such two-piece functions are called closures. Every function in JavaScript can be considered a closure.

Closures are functions with a state. It is somewhat similar to "this" in the sense that "this" also provides state for a function but function and "this" are separate objects ("this" is just a fancy parameter, and the only way to bind it permanently to a function is to create a closure). While "this" and function always live separately, a function cannot be separated from its closure and the language provides no means to access captured variables.

Because all these external variables referenced by a lexically nested function are actually local variables in the chain of its lexically enclosing functions (global variables can be assumed to be local variables of some root function), and every single execution of a function creates new instances of its local variables, it follows that every execution of a function returning (or otherwise transferring it out, such as registering it as a callback) a nested function creates a new closure (with its own potentially unique set of referenced nonlocal variables which represent its execution context).

Also, it must be understood that local variables in JavaScript are created not on the stack frame, but on the heap and destroyed only when no one is referencing them. When a function returns, references to its local variables are decremented, but they can still be non-null if during the current execution they became part of a closure and are still referenced by its lexically nested functions (which can happen only if the references to these nested functions were returned or otherwise transferred to some external code).

An example:

function foo (initValue) {
   //This variable is not destroyed when the foo function exits.
   //It is 'captured' by the two nested functions returned below.
   var value = initValue;

   //Note that the two returned functions are created right now.
   //If the foo function is called again, it will return
   //new functions referencing a different 'value' variable.
   return {
       getValue: function () { return value; },
       setValue: function (newValue) { value = newValue; }
   }
}

function bar () {
    //foo sets its local variable 'value' to 5 and returns an object with
    //two functions still referencing that local variable
    var obj = foo(5);

    //Extracting functions just to show that no 'this' is involved here
    var getValue = obj.getValue;
    var setValue = obj.setValue;

    alert(getValue()); //Displays 5
    setValue(10);
    alert(getValue()); //Displays 10

    //At this point getValue and setValue functions are destroyed
    //(in reality they are destroyed at the next iteration of the garbage collector).
    //The local variable 'value' in the foo is no longer referenced by
    //anything and is destroyed too.
}

bar();

Is there a vr (vertical rule) in html?

No there is not. And I will tell you a little story on why it is not. But first, quick solutions:

a) Use CSS class for basic elements span/div, e.g.: <span class="vr"></span>:

.vr{ 
   display: inline-block; 
   vertical-align: middle; 
   /* note that height must be precise, 100% does not work in some major browsers */
   height: 100px; 
   width: 1px; 
   background-color: #000;
}

Demonstration of use => https://jsfiddle.net/fe3tasa0/

b) Make a use of a one-side-only border and possibly CSS :first-child selector if you want to apply a general dividers among sibling/neigbour elements.

The story about <vr> FITTING in the original paradigm,
but still not being there:

Many answers here suggest, that vertical divider does not fit the original HTML paradigm/approach ... that is completely wrong. Also the answers contradict themselves a lot.

Those same people are probably calling their clear CSS class "clearfix" - there is nothing to fix about floating, you are just clearing it ... There was even an element in HTML3: <clear>. Sadly, this and clearance of floating is one of the few common misconceptions.

Anyway. "Back then" in the "original HTML ages", there was no thought about something like inline-block, there were just blocks, inlines and tables.

The last one is actually the reason why <vr> does not exist.
Back then it was assumed that:
If you want to verticaly divide something and/or make more blocks from left to right =>
=> you are making/want to make columns =>
=> that implies you are creating a table =>
=> tables have natural borders between their cells =>
no reason to make a <vr>

This approach is actually still valid, but as time showed, the syntax made for tables is not suitable for every case as well as it's default styles.


Another, probably later, assumption was that if you are not creating table, you are probably floating block elements. That meaning they are sticking together, and again, you can set a border, and those days probably even use the :first-child selector I suggested above...

How to set background image of a view?

You can set multiple background image in every view using custom method as below.

make plist for every theam with background image name and other color

#import <Foundation/Foundation.h>
@interface ThemeManager : NSObject
@property (nonatomic,strong) NSDictionary*styles;
+ (ThemeManager *)sharedManager;
-(void)selectTheme;
 @end

             #import "ThemeManager.h"

            @implementation ThemeManager
            @synthesize styles;
            + (ThemeManager *)sharedManager
            {
                static ThemeManager *sharedManager = nil;
                if (sharedManager == nil)
                {
                    sharedManager = [[ThemeManager alloc] init];
                }
                [sharedManager selectTheme];
                return sharedManager;
            }
            - (id)init
            {
                if ((self = [super init]))
                {

                }
                return self;
            }
            -(void)selectTheme{
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *themeName = [defaults objectForKey:@"AppTheme"] ?: @"DefaultTheam";

                NSString *path = [[NSBundle mainBundle] pathForResource:themeName ofType:@"plist"];
                self.styles = [NSDictionary dictionaryWithContentsOfFile:path];
            }
            @end

Can use this via

 NSDictionary *styles = [ThemeManager sharedManager].styles;
 NSString *imageName = [styles objectForKey:@"backgroundImage"];
[imgViewBackGround setImage:[UIImage imageNamed:imageName]];

How to retrieve Jenkins build parameters using the Groovy API?

To get the parameterized build params from the current build from your GroovyScript (using Pipeline), all you need to do is: Say you had a variable called VARNAME.

def myVariable = env.VARNAME

Cannot open include file with Visual Studio

Go to your Project properties (Project -> Properties -> Configuration Properties -> C/C++ -> General) and in the field Additional Include Directories add the path to your .h file.

And be sure that your Configuration and Platform are the active ones. Example: Configuration: Active(Debug) Platform: Active(Win32).

Copy files without overwrite

It won't let me comment directly on the incorrect messages - but let me just warn everyone, that the definition of the /XN and /XO options are REVERSED compared to what has been posted in previous messages.

The Exclude Older/Newer files option is consistent with the information displayed in RoboCopy's logging: RoboCopy will iterate through the SOURCE and then report whether each file in the SOURCE is "OLDER" or "NEWER" than the file in the destination.

Consequently, /XO will exclude OLDER SOURCE files (which is intuitive), not "older than the source" as had been claimed here.

If you want to copy only new or changed source files, but avoid replacing more recent destination files, then /XO is the correct option to use.

How to uncheck checkbox using jQuery Uniform library

$('#check1').prop('checked', true).uniform(); 
$('#check1').prop('checked', false).uniform(); 

This worked for me.

MySQL - Replace Character in Columns

Just running the SELECT statement will have no effect on the data. You have to use an UPDATE statement with the REPLACE to make the change occur:

UPDATE photos
   SET caption = REPLACE(caption,'"','\'')

Here is a working sample: http://sqlize.com/7FjtEyeLAh

Update a dataframe in pandas while iterating row by row

A method you can use is itertuples(), it iterates over DataFrame rows as namedtuples, with index value as first element of the tuple. And it is much much faster compared with iterrows(). For itertuples(), each row contains its Index in the DataFrame, and you can use loc to set the value.

for row in df.itertuples():
    if <something>:
        df.at[row.Index, 'ifor'] = x
    else:
        df.at[row.Index, 'ifor'] = x

    df.loc[row.Index, 'ifor'] = x

Under most cases, itertuples() is faster than iat or at.

Thanks @SantiStSupery, using .at is much faster than loc.

How do I disable directory browsing?

To complete @GauravKachhadiya's answer :

IndexIgnore *.jpg

means "hide only .jpg extension files from indexing.

IndexIgnore directive uses wildcard expression to match against directories and files.

  • a star character , it matches any charactes in a string ,eg : foo or foo.extension, in the following example, we are going to turn off the directory listing, no files or dirs will appear in the index :

    IndexIgnore *

Or if you want to hide spacific files , in the directory listing, then we can use

IndexIgnore *.php

*.php => matches a string that starts with any char and ends with .php

The example above hides all files that end with .php

Get class name using jQuery

If we have a code:

<div id="myDiv" class="myClass myClass2"></div> 

to take class name by using jQuery we could define and use a simple plugin method:

$.fn.class = function(){
  return Array.prototype.slice.call( $(this)[0].classList );
}

or

 $.fn.class = function(){
   return $(this).prop('class');
 } 

The use of the method will be:

$('#myDiv').class();

We have to notice that it will return a list of classes unlike of native method element.className which returns only first class of the attached classes. Because often the element has more than one class attached to it, I recommend you not to use this native method but element.classlist or the method described above.

The first variant of it will return a list of classes as an array, the second as a string - class names separated by spaces:

// [myClass, myClass2]
// "myClass myClass2"

Another important notice is that both methods as well as jQuery method

$('div').prop('class');

return only class list of the first element caught by the jQuery object if we use a more common selector which points many other elements. In such a case we have to mark the element, we want to get his classes, by using some index, e.g.

$('div:eq(2)').prop('class');

It depends also what you need to do with these classes. If you want just to check for a class into the class list of the element with this id you should just use method "hasClass":

if($('#myDiv').hasClass('myClass')){
   // do something
}

as mentioned in the comments above. But if you could need to take all classes as a selector, then use this code:

$.fn.classes = function(){
   var o = $(this);
   return o.prop('class')? [''].concat( o.prop('class').split(' ') ).join('.') : '';
 } 

 var mySelector = $('#myDiv').classes();

The result will be:

// .myClass.myClass2

and you could get it to create dynamically a specific rewriting css rule for example.

Regards

Resizing SVG in html?

I have an SVG file in HTML [....] IS there any way to specify that you want an SVG image displayed smaller or larger than it actually is stored in the file system?

SVG graphics, like other creative works, are protected under copyright law in most countries. Depending on jurisdiction, license of the work or whether or not you are the copyright holder you may not be able to modify the SVG without violating copyright law, believe it or not.

But laws are tricky topics and sometimes you just want to get shit done. Therefore you may adjust the scale of the graphic without modifying the work itself using the img tag with width attribute within your HTML.

Using an external HTTP request to specify the size:

<img width="96" src="/path/to/image.svg">

Specifying size in markup using a Data URI:

<img width="96" src="data:image/svg+xml,...">

SVGs can be Optimized for Data URIs to create SVG Favicon images suitable for any size:

<link rel="icon" sizes="any" href="data:image/svg+xml,%3Csvg%20viewBox='0%200%2046%2045'%20xmlns='http://www.w3.org/2000/svg'%3E%3Ctitle%3EAfter%20Dark%3C/title%3E%3Cpath%20d='M.708%2045L23%20.416%2045.292%2045H.708zM35%2038L23%2019%2011%2038h24z'%20fill='%23000'/%3E%3C/svg%3E">

Remove all newlines from inside a string

As mentioned by @john, the most robust answer is:

string = "a\nb\rv"
new_string = " ".join(string.splitlines())

NotificationCenter issue on Swift 3

I think it has changed again.

For posting this works in Xcode 8.2.

NotificationCenter.default.post(Notification(name:.UIApplicationWillResignActive)

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)

The differences between initialize, define, declare a variable

"So does it mean definition equals declaration plus initialization."

Not necessarily, your declaration might be without any variable being initialized like:

 void helloWorld(); //declaration or Prototype.

 void helloWorld()
 {
    std::cout << "Hello World\n";
 } 

Proper Linq where clauses

The first one will be implemented:

Collection.Where(x => x.Age == 10)
          .Where(x => x.Name == "Fido") // applied to the result of the previous
          .Where(x => x.Fat == true)    // applied to the result of the previous

As opposed to the much simpler (and far fasterpresumably faster):

// all in one fell swoop
Collection.Where(x => x.Age == 10 && x.Name == "Fido" && x.Fat == true)

Relational Database Design Patterns?

After many years of database development I can say there are some no goes and some question that you should answer before you begin:

questions:

  • Do you want use in the future another DBMS? If yes then does not use to special SQL stuff of the current DBMS. Remove logic in your application.

Does not use:

  • white spaces in table names and column names
  • Non Ascii characters in table and column names
  • binding to a specific lower case or upper case. And never use 2 tables or columns that differ only with lower case and upper case.
  • does not use SQL keywords for tables or columns names like "FROM", "BETWEEN", "DELETE", etc

recomendations:

  • Use NVARCHAR or equivalents for unicode support then you have no problems with codepages.
  • Give every column a unique name. This make it easer on join to select the column. It is very difficult if every table has a column "ID" or "Name" or "Description". Use XyzID and AbcID.
  • Use a resource bundle or equals for complex SQL expressions. It make it easer to switch to another DBMS.
  • Does not cast hard on any data type. Another DBMS can not have this data type. FOr example Oracle daes not have a SMALLINT only a number.

I hope this is a good starting point.

Cross field validation with Hibernate Validator (JSR 303)

Why not try Oval: http://oval.sourceforge.net/

I looks like it supports OGNL so maybe you could do it by a more natural

@Assert(expr = "_value ==_this.pass").

Any easy way to use icons from resources?

After adding the ICO file to your apps resources, you can use references it using My.Resources.YourIconNameWithoutExtension

For example if I had a file called Logo-square.ico added to my apps resources, I can set it to an icon with:

NotifyIcon1.Icon = My.Resources.Logo_square

When should an IllegalArgumentException be thrown?

The API doc for IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

From looking at how it is used in the JDK libraries, I would say:

  • It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.

  • It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).

I would use IllegalArgumentException to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.

How to Lazy Load div background images

Lazy loading images using above mentioned plugins uses conventional way of attaching listener to scroll events or by making use of setInterval and is highly non-performant as each call to getBoundingClientRect() forces the browser to re-layout the entire page and will introduce considerable jank to your website.

Use Lozad.js (just 569 bytes with no dependencies), which uses InteractionObserver to lazy load images performantly.

Sorting A ListView By Column

My solution is a class to sort listView items when you click on column header.

You can specify the type of each column.

listView.ListViewItemSorter = new ListViewColumnSorter();
listView.ListViewItemSorter.ColumnsTypeComparer.Add(0, DateTime);
listView.ListViewItemSorter.ColumnsTypeComparer.Add(1, int);

That's it !

The C# class :

using System.Collections;
using System.Collections.Generic;
using EDV;

namespace System.Windows.Forms
{
    /// <summary>
    /// Cette classe est une implémentation de l'interface 'IComparer' pour le tri des items de ListView. Adapté de http://support.microsoft.com/kb/319401.
    /// </summary>
    /// <remarks>Intégré par EDVariables.</remarks>
    public class ListViewColumnSorter : IComparer
    {
        /// <summary>
        /// Spécifie la colonne à trier
        /// </summary>
        private int ColumnToSort;
        /// <summary>
        /// Spécifie l'ordre de tri (en d'autres termes 'Croissant').
        /// </summary>
        private SortOrder OrderOfSort;
        /// <summary>
        /// Objet de comparaison ne respectant pas les majuscules et minuscules
        /// </summary>
        private CaseInsensitiveComparer ObjectCompare;

        /// <summary>
        /// Constructeur de classe.  Initialise la colonne sur '0' et aucun tri
        /// </summary>
        public ListViewColumnSorter()
            : this(0, SortOrder.None) { }

        /// <summary>
        /// Constructeur de classe.  Initializes various elements
        /// <param name="columnToSort">Spécifie la colonne à trier</param>
        /// <param name="orderOfSort">Spécifie l'ordre de tri</param>
        /// </summary>
        public ListViewColumnSorter(int columnToSort, SortOrder orderOfSort)
        {
            // Initialise la colonne
            ColumnToSort = columnToSort;

            // Initialise l'ordre de tri
            OrderOfSort = orderOfSort;

            // Initialise l'objet CaseInsensitiveComparer
            ObjectCompare = new CaseInsensitiveComparer();

            // Dictionnaire de comparateurs
            ColumnsComparer = new Dictionary<int, IComparer>();
            ColumnsTypeComparer = new Dictionary<int, Type>();

        }

        /// <summary>
        /// Cette méthode est héritée de l'interface IComparer.  Il compare les deux objets passés en effectuant une comparaison 
        ///qui ne tient pas compte des majuscules et des minuscules.
        /// <br/>Si le comparateur n'existe pas dans ColumnsComparer, CaseInsensitiveComparer est utilisé.
        /// </summary>
        /// <param name="x">Premier objet à comparer</param>
        /// <param name="x">Deuxième objet à comparer</param>
        /// <returns>Le résultat de la comparaison. "0" si équivalent, négatif si 'x' est inférieur à 'y' 
        ///et positif si 'x' est supérieur à 'y'</returns>
        public int Compare(object x, object y)
        {
            int compareResult;
            ListViewItem listviewX, listviewY;

            // Envoit les objets à comparer aux objets ListViewItem
            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;

            if (listviewX.SubItems.Count < ColumnToSort + 1 || listviewY.SubItems.Count < ColumnToSort + 1)
                return 0;

            IComparer objectComparer = null;
            Type comparableType = null;
            if (ColumnsComparer == null || !ColumnsComparer.TryGetValue(ColumnToSort, out objectComparer))
                if (ColumnsTypeComparer == null || !ColumnsTypeComparer.TryGetValue(ColumnToSort, out comparableType))
                    objectComparer = ObjectCompare;

            // Compare les deux éléments
            if (comparableType != null) {
                //Conversion du type
                object valueX = listviewX.SubItems[ColumnToSort].Text;
                object valueY = listviewY.SubItems[ColumnToSort].Text;
                if (!edvTools.TryParse(ref valueX, comparableType) || !edvTools.TryParse(ref valueY, comparableType))
                    return 0;
                compareResult = (valueX as IComparable).CompareTo(valueY);
            }
            else
                compareResult = objectComparer.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);

            // Calcule la valeur correcte d'après la comparaison d'objets
            if (OrderOfSort == SortOrder.Ascending) {
                // Le tri croissant est sélectionné, renvoie des résultats normaux de comparaison
                return compareResult;
            }
            else if (OrderOfSort == SortOrder.Descending) {
                // Le tri décroissant est sélectionné, renvoie des résultats négatifs de comparaison
                return (-compareResult);
            }
            else {
                // Renvoie '0' pour indiquer qu'ils sont égaux
                return 0;
            }
        }

        /// <summary>
        /// Obtient ou définit le numéro de la colonne à laquelle appliquer l'opération de tri (par défaut sur '0').
        /// </summary>
        public int SortColumn
        {
            set
            {
                ColumnToSort = value;
            }
            get
            {
                return ColumnToSort;
            }
        }

        /// <summary>
        /// Obtient ou définit l'ordre de tri à appliquer (par exemple, 'croissant' ou 'décroissant').
        /// </summary>
        public SortOrder Order
        {
            set
            {
                OrderOfSort = value;
            }
            get
            {
                return OrderOfSort;
            }
        }

        /// <summary>
        /// Dictionnaire de comparateurs par colonne.
        /// <br/>Pendant le tri, si le comparateur n'existe pas dans ColumnsComparer, CaseInsensitiveComparer est utilisé.
        /// </summary>
        public Dictionary<int, IComparer> ColumnsComparer { get; set; }

        /// <summary>
        /// Dictionnaire de comparateurs par colonne.
        /// <br/>Pendant le tri, si le comparateur n'existe pas dans ColumnsTypeComparer, CaseInsensitiveComparer est utilisé.
        /// </summary>
        public Dictionary<int, Type> ColumnsTypeComparer { get; set; }
    }
}

Initializing a ListView :

    <var>Visual.WIN.ctrlListView.OnShown</var>  : 
    eventSender.Columns.Clear();
    eventSender.SmallImageList = edvWinForm.ImageList16;
    eventSender.ListViewItemSorter = new ListViewColumnSorter();
    var col = eventSender.Columns.Add("Répertoire");
    col.Width = 160;
    col.ImageKey = "Domain";
    col = eventSender.Columns.Add("Fichier");
    col.Width = 180;
    col.ImageKey = "File";
    col = eventSender.Columns.Add("Date");
    col.Width = 120;
    col.ImageKey = "DateTime";
    eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, DateTime);
    col = eventSender.Columns.Add("Position");
    col.TextAlign = HorizontalAlignment.Right;
    col.Width = 80;
    col.ImageKey = "Num";
    eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, Int32);

Fill a ListView :

<var>Visual.WIN.cmdSearch.OnClick</var>  : 
//non récursif et sans fonction
    ..ctrlListView:Items.Clear();
    ..ctrlListView:Sorting = SortOrder.None;
    var group = ..ctrlListView:Groups.Add(DateTime.Now.ToString()
                , Path.Combine(..cboDir:Text, ..ctrlPattern1:Text) + " contenant " + ..ctrlSearch1:Text);
    var perf =  Environment.TickCount;

    var files = new DirectoryInfo(..cboDir:Text).GetFiles(..ctrlPattern1:Text)
    var search = ..ctrlSearch1:Text;
    var ignoreCase = ..Search.IgnoreCase;
    //var result = new StringBuilder();
    var dirLength : int = ..cboDir:Text.Length;
    var position : int;
    var added : int = 0;
    for(var i : int = 0; i &lt; files.Length; i++){
        var file = files[i];
        if(search == ""
        || (position = File.ReadAllText(file.FullName).IndexOf(String(search)
                            , StringComparison(ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture))) &gt; =0) {

        //  result.AppendLine(file.FullName.Substring(dirLength) + "\tPos : " + pkvFile.Value);
            var item = ..ctrlListView:Items.Add(file.FullName.Substring(dirLength));
            item.SubItems.Add(file.Name);
            item.SubItems.Add(File.GetLastWriteTime(file.FullName).ToString());
            item.SubItems.Add(position.ToString("# ### ##0"));
            item.Group = group;
            ++added;
        }
    }
    group.Header += " : " + added + "/" + files.Length + " fichier(s)"
                + "  en " + (Environment.TickCount - perf).ToString("# ##0 msec");

On ListView column click :

<var>Visual.WIN.ctrlListView.OnColumnClick</var>  : 
// Déterminer si la colonne sélectionnée est déjà la colonne triée.
var sorter = eventSender.ListViewItemSorter;
if ( eventArgs.Column == sorter .SortColumn )
{
    // Inverser le sens de tri en cours pour cette colonne.
    if (sorter.Order == SortOrder.Ascending)
    {
        sorter.Order = SortOrder.Descending;
    }
    else
    {
        sorter.Order = SortOrder.Ascending;
    }
}
else
{
    // Définir le numéro de colonne à trier ; par défaut sur croissant.
    sorter.SortColumn = eventArgs.Column;
    sorter.Order = SortOrder.Ascending;
}

// Procéder au tri avec les nouvelles options.
eventSender.Sort();

Function edvTools.TryParse used above

class edvTools {
    /// <summary>
    /// Tente la conversion d'une valeur suivant un type EDVType
    /// </summary>
    /// <param name="pValue">Référence de la valeur à convertir</param>
    /// <param name="pType">Type EDV en sortie</param>
    /// <returns></returns>
    public static bool TryParse(ref object pValue, System.Type pType)
    {
        int lIParsed;
        double lDParsed;
        string lsValue;
        if (pValue == null) return false;
        if (pType.Equals(typeof(bool))) {
            bool lBParsed;
            if (pValue is bool) return true;
            if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = lDParsed != 0D;
                return true;
            }
            if (bool.TryParse(pValue.ToString(), out lBParsed)) {
                pValue = lBParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Double))) {
            if (pValue is Double) return true;
            if (double.TryParse(pValue.ToString(), out lDParsed)
                || double.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lDParsed)) {
                pValue = lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(int))) {
            if (pValue is int) return true;
            if (Int32.TryParse(pValue.ToString(), out lIParsed)) {
                pValue = lIParsed;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (int)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Byte))) {
            if (pValue is byte) return true;
            byte lByte;
            if (Byte.TryParse(pValue.ToString(), out lByte)) {
                pValue = lByte;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (byte)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(long))) {
            long lLParsed;
            if (pValue is long) return true;
            if (long.TryParse(pValue.ToString(), out lLParsed)) {
                pValue = lLParsed;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (long)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Single))) {
            if (pValue is float) return true;
            Single lSParsed;
            if (Single.TryParse(pValue.ToString(), out lSParsed)
                || Single.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lSParsed)) {
                pValue = lSParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(DateTime))) {
            if (pValue is DateTime) return true;
            DateTime lDTParsed;
            if (DateTime.TryParse(pValue.ToString(), out lDTParsed)) {
                pValue = lDTParsed;
                return true;
            }
            else if (pValue.ToString().Contains("UTC")) //Date venant de JScript
            {
                if (_MonthsUTC == null) InitMonthsUTC();
                string[] lDateParts = pValue.ToString().Split(' ');
                lDTParsed = new DateTime(int.Parse(lDateParts[5]), _MonthsUTC[lDateParts[1]], int.Parse(lDateParts[2]));
                lDateParts = lDateParts[3].ToString().Split(':');
                pValue = lDTParsed.AddSeconds(int.Parse(lDateParts[0]) * 3600 + int.Parse(lDateParts[1]) * 60 + int.Parse(lDateParts[2]));
                return true;
            }
            else
                return false;

        }
        if (pType.Equals(typeof(Array))) {
            if (pValue is System.Collections.ICollection || pValue is System.Collections.ArrayList)
                return true;
            return pValue is System.Data.DataTable
                || pValue is string && (pValue as string).StartsWith("<");
        }
        if (pType.Equals(typeof(DataTable))) {
            return pValue is System.Data.DataTable
                || pValue is string && (pValue as string).StartsWith("<");

        }
        if (pType.Equals(typeof(System.Drawing.Bitmap))) {
            return pValue is System.Drawing.Image || pValue is byte[];

        }
        if (pType.Equals(typeof(System.Drawing.Image))) {
            return pValue is System.Drawing.Image || pValue is byte[];

        }
        if (pType.Equals(typeof(System.Drawing.Color))) {
            if (pValue is System.Drawing.Color) return true;
            if (pValue is System.Drawing.KnownColor) {
                pValue = System.Drawing.Color.FromKnownColor((System.Drawing.KnownColor)pValue);
                return true;
            }

            int lARGB;
            if (!int.TryParse(lsValue = pValue.ToString(), out lARGB)) {
                if (lsValue.StartsWith("Color [A=", StringComparison.InvariantCulture)) {
                    foreach (string lsARGB in lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length).Split(','))
                        switch (lsARGB.TrimStart().Substring(0, 1)) {
                            case "A":
                                lARGB = int.Parse(lsARGB.Substring(2)) * 0x1000000;
                                break;
                            case "R":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x10000;
                                break;
                            case "G":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x100;
                                break;
                            case "B":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2));
                                break;
                            default:
                                break;
                        }
                    pValue = System.Drawing.Color.FromArgb(lARGB);
                    return true;
                }
                if (lsValue.StartsWith("Color [", StringComparison.InvariantCulture)) {
                    pValue = System.Drawing.Color.FromName(lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length));
                    return true;
                }
                return false;
            }
            pValue = System.Drawing.Color.FromArgb(lARGB);
            return true;
        }
        if (pType.IsEnum) {
            try {
                if (pValue == null) return false;
                if (pValue is int || pValue is byte || pValue is ulong || pValue is long || pValue is double)
                    pValue = Enum.ToObject(pType, pValue);
                else
                    pValue = Enum.Parse(pType, pValue.ToString());
            }
            catch {
                return false;
            }
        }
        return true;
    }
}

git stash blunder: git stash pop and ended up with merge conflicts

Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.

See commit ed178ef by Jeff King (peff), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster -- in commit 05c3967, 19 May 2015)

Note: This has been reverted. See below.

stash: require a clean index to apply/pop

Problem

If you have staged contents in your index and run "stash apply/pop", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.

In other words:

"git stash pop/apply" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.

Solution

We can make this safer by refusing to apply when there are staged changes.

That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:

Cannot apply stash: Your index contains uncommitted changes.

Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before git stash apply/pop) with a git reset --hard.


See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfb539b, 24 Jun 2015)

That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.

Unfortunately, this hurts some common workflows around "git stash -k", like:

git add -p       ;# (1) stage set of proposed changes
git stash -k     ;# (2) get rid of everything else
make test        ;# (3) make sure proposal is reasonable
git stash apply  ;# (4) restore original working tree

If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).

Binding a generic list to a repeater - ASP.NET

You may want to create a subRepeater.

<asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
  <ItemTemplate>
    <span><%# Eval("Name") %></span>
  </ItemTemplate>
</asp:Repeater>

You can also cast your fields

<%# ((ArrayFields)Container.DataItem).Fields[0].Name %>

Finally you could do a little CSV Function and write out your fields with a function

<%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>

public string GetAsCsv(IEnumerable<Fields> fields)
{
  var builder = new StringBuilder();
  foreach(var f in fields)
  {
    builder.Append(f);
    builder.Append(",");
  }
  builder.Remove(builder.Length - 1);
  return builder.ToString();
}

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

I increase max memory to start node-chrome with -Xmx3g, and it's work for me

PHP server on local machine?

AppServ is a small program in Windows to run:

  • Apache
  • PHP
  • MySQL
  • phpMyAdmin

It will also give you a startup and stop button for Apache. Which I find very useful.

JFrame Exit on close Java

this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

this worked for me in case of Class Extends Frame

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

Javascript - removing undefined fields from an object

var obj = { a: 1, b: undefined, c: 3 }

To remove undefined props in an object we use like this

JSON.parse(JSON.stringify(obj));

Output: {a: 1, c: 3}

Changing project port number in Visual Studio 2013

There are two project types in VS for ASP.NET projects:

Web Application Projects (which notably have a .csproj or .vbproj file to store these settings) have a Properties node under the project. On the Web tab, you can configure the Project URL (assuming IIS Express or IIS) to use whatever port you want, and just click the Create Virtual Directory button. These settings are saved to the project file:

<ProjectExtensions>
  <VisualStudio>
    <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
      <WebProjectProperties>
       <DevelopmentServerPort>10531</DevelopmentServerPort>
       ...
     </WebProjectProperties>
    </FlavorProperties>
  </VisualStudio>
</ProjectExtensions>

Web Site Projects are different. They don't have a .*proj file to store settings in; instead, the settings are set in the solution file. In VS2013, the settings look something like this:

Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "WebSite1(1)", "http://localhost:10528", "{401397AC-86F6-4661-A71B-67B4F8A3A92F}"
    ProjectSection(WebsiteProperties) = preProject
        UseIISExpress = "true"
        TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.5"
        ...
        SlnRelativePath = "..\..\WebSites\WebSite1\"
        DefaultWebSiteLanguage = "Visual Basic"
    EndProjectSection
EndProject

Because the project is identified by the URL (including port), there isn't a way in the VS UI to change this. You should be able to modify the solution file though, and it should work.

Detecting when user scrolls to bottom of div with jQuery

In simple DOM usage you can check the condition

element.scrollTop + element.clientHeight == element.scrollHeight

if true then you have reached the end.

How to get thread id of a pthread in linux c program?

As noted in other answers, pthreads does not define a platform-independent way to retrieve an integral thread ID.

On Linux systems, you can get thread ID thus:

#include <sys/types.h>
pid_t tid = gettid();

On many BSD-based platforms, this answer https://stackoverflow.com/a/21206357/316487 gives a non-portable way.

However, if the reason you think you need a thread ID is to know whether you're running on the same or different thread to another thread you control, you might find some utility in this approach

static pthread_t threadA;

// On thread A...
threadA = pthread_self();

// On thread B...
pthread_t threadB = pthread_self();
if (pthread_equal(threadA, threadB)) printf("Thread B is same as thread A.\n");
else printf("Thread B is NOT same as thread A.\n");

If you just need to know if you're on the main thread, there are additional ways, documented in answers to this question how can I tell if pthread_self is the main (first) thread in the process?.

Adding Google Translate to a web site

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'th,zh-CN,zh-TW', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Export to CSV using jQuery and html

What if you have your data in CSV format and convert it to HTML for display on the web page? You may use the http://code.google.com/p/js-tables/ plugin. Check this example http://code.google.com/p/js-tables/wiki/Table As you are already using jQuery library I have assumed you are able to add other javascript toolkit libraries.

If the data is in CSV format, you should be able to use the generic 'application/octetstream' mime type. All the 3 mime types you have tried are dependent on the software installed on the clients computer.

Printf width specifier to maintain precision of floating-point value

I run a small experiment to verify that printing with DBL_DECIMAL_DIG does indeed exactly preserve the number's binary representation. It turned out that for the compilers and C libraries I tried, DBL_DECIMAL_DIG is indeed the number of digits required, and printing with even one digit less creates a significant problem.

#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

union {
    short s[4];
    double d;
} u;

void
test(int digits)
{
    int i, j;
    char buff[40];
    double d2;
    int n, num_equal, bin_equal;

    srand(17);
    n = num_equal = bin_equal = 0;
    for (i = 0; i < 1000000; i++) {
        for (j = 0; j < 4; j++)
            u.s[j] = (rand() << 8) ^ rand();
        if (isnan(u.d))
            continue;
        n++;
        sprintf(buff, "%.*g", digits, u.d);
        sscanf(buff, "%lg", &d2);
        if (u.d == d2)
            num_equal++;
        if (memcmp(&u.d, &d2, sizeof(double)) == 0)
            bin_equal++;
    }
    printf("Tested %d values with %d digits: %d found numericaly equal, %d found binary equal\n", n, digits, num_equal, bin_equal);
}

int
main()
{
    test(DBL_DECIMAL_DIG);
    test(DBL_DECIMAL_DIG - 1);
    return 0;
}

I run this with Microsoft's C compiler 19.00.24215.1 and gcc version 7.4.0 20170516 (Debian 6.3.0-18+deb9u1). Using one less decimal digit halves the number of numbers that compare exactly equal. (I also verified that rand() as used indeed produces about one million different numbers.) Here are the detailed results.

Microsoft C

Tested 999507 values with 17 digits: 999507 found numericaly equal, 999507 found binary equal
Tested 999507 values with 16 digits: 545389 found numericaly equal, 545389 found binary equal

GCC

Tested 999485 values with 17 digits: 999485 found numericaly equal, 999485 found binary equal
Tested 999485 values with 16 digits: 545402 found numericaly equal, 545402 found binary equal

What is the best way to tell if a character is a letter or number in Java without using regexes?

Character.isDigit(string.charAt(index)) (JavaDoc) will return true if it's a digit
Character.isLetter(string.charAt(index)) (JavaDoc) will return true if it's a letter

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

I do in that way:

UIDevice.current.model

It shows the name of the device.

To check if is iPad or iPhone:

if ( UIDevice.current.model.range(of: "iPad") != nil){
    print("I AM IPAD")
} else {
    print("I AM IPHONE")
}

How can I create a Java method that accepts a variable number of arguments?

This is known as varargs see the link here for more details

In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:

Object[] arguments = {
    new Integer(7),
    new Date(),
    "a disturbance in the Force"
};
    String result = MessageFormat.format(
        "At {1,time} on {1,date}, there was {2} on planet "
         + "{0,number,integer}.", arguments);

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:

public static String format(String pattern,
                            Object... arguments);

ViewPager PagerAdapter not updating the View

After hours of frustration while trying all the above solutions to overcome this problem and also trying many solutions on other similar questions like this, this and this which all FAILED with me to solve this problem and to make the ViewPager to destroy the old Fragment and fill the pager with the new Fragments. I have solved the problem as following:

1) Make the ViewPager class to extends FragmentPagerAdapter as following:

 public class myPagerAdapter extends FragmentPagerAdapter {

2) Create an Item for the ViewPager that store the title and the fragment as following:

public class PagerItem {
private String mTitle;
private Fragment mFragment;


public PagerItem(String mTitle, Fragment mFragment) {
    this.mTitle = mTitle;
    this.mFragment = mFragment;
}
public String getTitle() {
    return mTitle;
}
public Fragment getFragment() {
    return mFragment;
}
public void setTitle(String mTitle) {
    this.mTitle = mTitle;
}

public void setFragment(Fragment mFragment) {
    this.mFragment = mFragment;
}

}

3) Make the constructor of the ViewPager take my FragmentManager instance to store it in my class as following:

private FragmentManager mFragmentManager;
private ArrayList<PagerItem> mPagerItems;

public MyPagerAdapter(FragmentManager fragmentManager, ArrayList<PagerItem> pagerItems) {
    super(fragmentManager);
    mFragmentManager = fragmentManager;
    mPagerItems = pagerItems;
}

4) Create a method to re-set the adapter data with the new data by deleting all the previous fragment from the fragmentManager itself directly to make the adapter to set the new fragment from the new list again as following:

public void setPagerItems(ArrayList<PagerItem> pagerItems) {
    if (mPagerItems != null)
        for (int i = 0; i < mPagerItems.size(); i++) {
            mFragmentManager.beginTransaction().remove(mPagerItems.get(i).getFragment()).commit();
        }
    mPagerItems = pagerItems;
}

5) From the container Activity or Fragment do not re-initialize the adapter with the new data. Set the new data through the method setPagerItems with the new data as following:

ArrayList<PagerItem> pagerItems = new ArrayList<PagerItem>();
pagerItems.add(new PagerItem("Fragment1", new MyFragment1()));
pagerItems.add(new PagerItem("Fragment2", new MyFragment2()));

mPagerAdapter.setPagerItems(pagerItems);
mPagerAdapter.notifyDataSetChanged();

I hope it helps.

Do conditional INSERT with SQL?

It is possible with EXISTS condition. WHERE EXISTS tests for the existence of any records in a subquery. EXISTS returns true if the subquery returns one or more records. Here is an example

UPDATE  TABLE_NAME 
SET val1=arg1 , val2=arg2
WHERE NOT EXISTS
    (SELECT FROM TABLE_NAME WHERE val1=arg1 AND val2=arg2)

How to run vi on docker container?

If you need to change a file just once. You should prefer making the change locally and build a new docker image with this file.

Say in a docker image, you need to change a file named myFile.xml under /path/to/docker/image/. So, you need to do.

  1. Copy myFile.xml in your local filesystem and make necessary changes.
  2. Create a file named 'Dockerfile' with the following content-
FROM docker-repo:tag
ADD myFile.xml /path/to/docker/image/

Then build your own docker image with docker build -t docker-repo:v-x.x.x .

Then use your newly build docker image.

Summernote image upload

Summernote converts your uploaded images to a base64 encoded string by default, you can process this string or as other fellows mentioned you can upload images using onImageUpload callback. You can take a look at this gist which I modified a bit to adapt laravel csrf token here. But that did not work for me and I had no time to find out why! Instead, I solved it via a server-side solution based on this blog post. It gets the output of the summernote and then it will upload the images and updates the final markdown HTML.

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

Route::get('/your-route-to-editor', function () {
    return view('your-view');
});

Route::post('/your-route-to-processor', function (Request $request) {

       $this->validate($request, [
           'editordata' => 'required',
       ]);

       $data = $request->input('editordata');

       //loading the html data from the summernote editor and select the img tags from it
       $dom = new \DomDocument();
       $dom->loadHtml($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);    
       $images = $dom->getElementsByTagName('img');
       
       foreach($images as $k => $img){
           //for now src attribute contains image encrypted data in a nonsence string
           $data = $img->getAttribute('src');
           //getting the original file name that is in data-filename attribute of img
           $file_name = $img->getAttribute('data-filename');
           //extracting the original file name and extension
           $arr = explode('.', $file_name);
           $upload_base_directory = 'public/';

           $original_file_name='time()'.$k;
           $original_file_extension='png';

           if (sizeof($arr) ==  2) {
                $original_file_name = $arr[0];
                $original_file_extension = $arr[1];
           }
           else
           {
                //the file name contains extra . in itself
                $original_file_name = implode("_",array_slice($arr,0,sizeof($arr)-1));
                $original_file_extension = $arr[sizeof($arr)-1];
           }

           list($type, $data) = explode(';', $data);
           list(, $data)      = explode(',', $data);

           $data = base64_decode($data);

           $path = $upload_base_directory.$original_file_name.'.'.$original_file_extension;

           //uploading the image to an actual file on the server and get the url to it to update the src attribute of images
           Storage::put($path, $data);

           $img->removeAttribute('src');       
           //you can remove the data-filename attribute here too if you want.
           $img->setAttribute('src', Storage::url($path));
           // data base stuff here :
           //saving the attachments path in an array
       }

       //updating the summernote WYSIWYG markdown output.
       $data = $dom->saveHTML();

       // data base stuff here :
       // save the post along with it attachments array
       return view('your-preview-page')->with(['data'=>$data]);

});

How can I parse a JSON file with PHP?

<?php
$json = '{
    "response": {
        "data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
        "status": 0,
        "totalRows": 83,
        "startRow": 0,
        "endRow": 82
    }
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status']; 
echo $json['response']['totalRows']; 
echo $json['response']['startRow']; 
echo $json['response']['endRow']; 

?>

How can I find an element by CSS class with XPath?

I'm just providing this as an answer, as Tomalak provided as a comment to meder's answer a long time ago

//div[contains(concat(' ', @class, ' '), ' Test ')]

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Variables not showing while debugging in Eclipse

For me the solution of the problem was to configure xdebug properly. I added in the php.ini this lines of code :

zend_extension = "C:\xampp\php\ext\php_xdebug.dll"

xdebug.remote_enable = 1

xdebug.show_local_vars = 1

The important part I was missing : xdebug.remote_enable = 1

How do I remove a single file from the staging area (undo git add)?

For newer versions of Git there is git restore --staged <file>.

When I do a git status with Git version 2.26.2.windows.1 it is also recommended for unstaging:

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)

(This post shows, that in earlier versions git reset HEAD was recommended at this point)

I can highly recommend this post explaining the differences between git revert, git restore and git reset and also additional parameters for git restore.

SQL Query to search schema of all tables

For me I only have read access to run querys so I need to use this function often here is what I use:

SELECT  *
FROM    INFORMATION_SCHEMA.TABLES
where   TABLES.TABLE_NAME like '%your table name here%'

You can replace .TABLES with .COLUMNS then it would look like this:

 SELECT *
 FROM   INFORMATION_SCHEMA.COLUMNS
 WHERE  columns.COLUMN_NAME like '%your column name here%'

An error occurred while signing: SignTool.exe not found

Windows 10 users can find signtool.exe in C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64 folder (10.0.18362.0 in my case, or other version).


But first, make sure you've installed Windows 10 SDK

Then, check Windows SDK Signing Tools for Desktop Apps is installed by going to Control Panel > Programs > Programs and Features, choose Windows Software Development Kit - Windows 10.0.18362.1 (in my case, you version may be different), right-click, choose Change, choose options Change then click Next.

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Don't reload application when orientation changes

There are generally three ways to do this:

  1. As some of the answers suggested, you could distinguish the cases of your activity being created for the first time and being restored from savedInstanceState. This is done by overriding onSaveInstanceState and checking the parameter of onCreate.

  2. You could lock the activity in one orientation by adding android:screenOrientation="portrait" (or "landscape") to <activity> in your manifest.

  3. You could tell the system that you meant to handle screen changes for yourself by specifying android:configChanges="orientation|screenSize" in the <activity> tag. This way the activity will not be recreated, but will receive a callback instead (which you can ignore as it's not useful for you).

Personally I'd go with (3). Of course if locking the app to one of the orientations is fine with you, you can also go with (2).

Finding duplicate values in a SQL table

try this:

declare @YourTable table (id int, name varchar(10), email varchar(50))

INSERT @YourTable VALUES (1,'John','John-email')
INSERT @YourTable VALUES (2,'John','John-email')
INSERT @YourTable VALUES (3,'fred','John-email')
INSERT @YourTable VALUES (4,'fred','fred-email')
INSERT @YourTable VALUES (5,'sam','sam-email')
INSERT @YourTable VALUES (6,'sam','sam-email')

SELECT
    name,email, COUNT(*) AS CountOf
    FROM @YourTable
    GROUP BY name,email
    HAVING COUNT(*)>1

OUTPUT:

name       email       CountOf
---------- ----------- -----------
John       John-email  2
sam        sam-email   2

(2 row(s) affected)

if you want the IDs of the dups use this:

SELECT
    y.id,y.name,y.email
    FROM @YourTable y
        INNER JOIN (SELECT
                        name,email, COUNT(*) AS CountOf
                        FROM @YourTable
                        GROUP BY name,email
                        HAVING COUNT(*)>1
                    ) dt ON y.name=dt.name AND y.email=dt.email

OUTPUT:

id          name       email
----------- ---------- ------------
1           John       John-email
2           John       John-email
5           sam        sam-email
6           sam        sam-email

(4 row(s) affected)

to delete the duplicates try:

DELETE d
    FROM @YourTable d
        INNER JOIN (SELECT
                        y.id,y.name,y.email,ROW_NUMBER() OVER(PARTITION BY y.name,y.email ORDER BY y.name,y.email,y.id) AS RowRank
                        FROM @YourTable y
                            INNER JOIN (SELECT
                                            name,email, COUNT(*) AS CountOf
                                            FROM @YourTable
                                            GROUP BY name,email
                                            HAVING COUNT(*)>1
                                        ) dt ON y.name=dt.name AND y.email=dt.email
                   ) dt2 ON d.id=dt2.id
        WHERE dt2.RowRank!=1
SELECT * FROM @YourTable

OUTPUT:

id          name       email
----------- ---------- --------------
1           John       John-email
3           fred       John-email
4           fred       fred-email
5           sam        sam-email

(4 row(s) affected)

Is it possible to get only the first character of a String?

Answering for C++ 14,

Yes, you can get the first character of a string simply by the following code snippet.

string s = "Happynewyear";
cout << s[0];

if you want to store the first character in a separate string,

string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;

ImportError: No module named MySQLdb

I got this issue when I was working on SQLAlchemy. The default dialect used by SQLAlchemy for MySQL is mysql+mysqldb.

engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')

I got the "No module named MySQLdb" error when the above command was executed. To fix it I installed the mysql-python module and the issue was fixed.

sudo pip install mysql-python

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

Difference between h:button and h:commandButton

This is taken from the book - The Complete Reference by Ed Burns & Chris Schalk

h:commandButton vs h:button

What’s the difference between h:commandButton|h:commandLink and h:button|h:link ?

The latter two components were introduced in 2.0 to enable bookmarkable JSF pages, when used in concert with the View Parameters feature.

There are 3 main differences between h:button|h:link and h:commandButton|h:commandLink.

First, h:button|h:link causes the browser to issue an HTTP GET request, while h:commandButton|h:commandLink does a form POST. This means that any components in the page that have values entered by the user, such as text fields, checkboxes, etc., will not automatically be submitted to the server when using h:button|h:link. To cause values to be submitted with h:button|h:link, extra action has to be taken, using the “View Parameters” feature.

The second main difference between the two kinds of components is that h:button|h:link has an outcome attribute to describe where to go next while h:commandButton|h:commandLink uses an action attribute for this purpose. This is because the former does not result in an ActionEvent in the event system, while the latter does.

Finally, and most important to the complete understanding of this feature, the h:button|h:link components cause the navigation system to be asked to derive the outcome during the rendering of the page, and the answer to this question is encoded in the markup of the page. In contrast, the h:commandButton|h:commandLink components cause the navigation system to be asked to derive the outcome on the POSTBACK from the page. This is a difference in timing. Rendering always happens before POSTBACK.

Getting the HTTP Referrer in ASP.NET

You could use the UrlReferrer property of the current request:

Request.UrlReferrer

This will read the Referer HTTP header from the request which may or may not be supplied by the client (user agent).

Error on line 2 at column 1: Extra content at the end of the document

On each loop of the result set, you're appending a new root element to the document, creating an XML document like this:

<?xml version="1.0"?>
<mycatch>...</mycatch>
<mycatch>...</mycatch>
...

An XML document can only have one root element, which is why the error is stating there is "extra content". Create a single root element and add all the mycatch elements to that:

$root = $dom->createElement("root");
$dom->appendChild($root);
// ...
while ($row = @mysql_fetch_assoc($result)){
  $node = $dom->createElement("mycatch");
  $root->appendChild($node);

How do you add a Dictionary of items into another Dictionary

You can iterate over the Key Value combinations ob the value you want to merge and add them via the updateValue(forKey:) method:

dictionaryTwo.forEach {
    dictionaryOne.updateValue($1, forKey: $0)
}

Now all values of dictionaryTwo got added to dictionaryOne.

Instagram: Share photo from webpage

As of November 17, 2015. This rule has officially changed. Instagram has deprecated the rule against using their API to upload images.

Good luck.

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

To even do better boolean mapping to Y/N, add to your hibernate configuration:

<!-- when using type="yes_no" for booleans, the line below allow booleans in HQL expressions: -->
<property name="hibernate.query.substitutions">true 'Y', false 'N'</property>

Now you can use booleans in HQL, for example:

"FROM " + SomeDomainClass.class.getName() + " somedomainclass " +
"WHERE somedomainclass.someboolean = false"

Try-catch speeding up my code?

One of the Roslyn engineers who specializes in understanding optimization of stack usage took a look at this and reports to me that there seems to be a problem in the interaction between the way the C# compiler generates local variable stores and the way the JIT compiler does register scheduling in the corresponding x86 code. The result is suboptimal code generation on the loads and stores of the locals.

For some reason unclear to all of us, the problematic code generation path is avoided when the JITter knows that the block is in a try-protected region.

This is pretty weird. We'll follow up with the JITter team and see whether we can get a bug entered so that they can fix this.

Also, we are working on improvements for Roslyn to the C# and VB compilers' algorithms for determining when locals can be made "ephemeral" -- that is, just pushed and popped on the stack, rather than allocated a specific location on the stack for the duration of the activation. We believe that the JITter will be able to do a better job of register allocation and whatnot if we give it better hints about when locals can be made "dead" earlier.

Thanks for bringing this to our attention, and apologies for the odd behaviour.

Execute CMD command from code

if you want to start application with cmd use this code:

string YourApplicationPath = "C:\\Program Files\\App\\MyApp.exe"   
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.FileName = "cmd.exe";
processInfo.WorkingDirectory = Path.GetDirectoryName(YourApplicationPath);
processInfo.Arguments = "/c START " + Path.GetFileName(YourApplicationPath);
Process.Start(processInfo);

How to use Google fonts in React.js?

It could be the self-closing tag of link at the end, try:

<link href="https://fonts.googleapis.com/css?family=Bungee+Inline" rel="stylesheet"/> 

and in your main.css file try:

body,div {
  font-family: 'Bungee Inline', cursive;
}

AndroidStudio: Failed to sync Install build tools

There may be some file access permission/restriction problems. First check to access the below directory manually, check whether your TARGET_VERSION exists, Then check the android sdk manager.

  • sdk/build-tools/{TARGET_VERSION}

How do I check if an HTML element is empty using jQuery?

document.getElementById("id").innerHTML == "" || null

or

$("element").html() == "" || null

How to get file name from file path in android

FilenameUtils to the rescue:

String filename = FilenameUtils.getName("/storage/sdcard0/DCIM/Camera/1414240995236.jpg");

Is it possible to include one CSS file in another?

I stumbled upon this and I just wanted to say PLEASE DON'T USE @IMPORT IN CSS!!!! The import statement is sent to the client and the client does another request. If you want to divide your CSS between various files use Less. In Less the import statement happens on the server and the output is cached and does not create a performance penalty by forcing the client to make another connection. Sass is also an option another not one I have explored. Frankly, if you are not using Less or Sass then you should start. http://willseitz-code.blogspot.com/2013/01/using-less-to-manage-css-files.html

What is the purpose of meshgrid in Python / NumPy?

meshgrid helps in creating a rectangular grid from two 1-D arrays of all pairs of points from the two arrays.

x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])

Now, if you have defined a function f(x,y) and you wanna apply this function to all the possible combination of points from the arrays 'x' and 'y', then you can do this:

f(*np.meshgrid(x, y))

Say, if your function just produces the product of two elements, then this is how a cartesian product can be achieved, efficiently for large arrays.

Referred from here

What's the best practice for primary keys in tables?

Just an extra comment on something that is often overlooked. Sometimes not using a surrogate key has benefits in the child tables. Let's say we have a design that allows you to run multiple companies within the one database (maybe it's a hosted solution, or whatever).

Let's say we have these tables and columns:

Company:
  CompanyId   (primary key)

CostCenter:
  CompanyId   (primary key, foreign key to Company)
  CostCentre  (primary key)

CostElement
  CompanyId   (primary key, foreign key to Company)
  CostElement (primary key)

Invoice:
  InvoiceId    (primary key)
  CompanyId    (primary key, in foreign key to CostCentre, in foreign key to CostElement)
  CostCentre   (in foreign key to CostCentre)
  CostElement  (in foreign key to CostElement)

In case that last bit doesn't make sense, Invoice.CompanyId is part of two foreign keys, one to the CostCentre table and one to the CostElement table. The primary key is (InvoiceId, CompanyId).

In this model, it's not possible to screw-up and reference a CostElement from one company and a CostCentre from another company. If a surrogate key was used on the CostElement and CostCentre tables, it would be.

The fewer chances to screw up, the better.

Padding characters in printf

Bash + seq to allow parameter expansion

Similar to @Dennis Williamson answer, but if seq is available, the length of the pad string need not be hardcoded. The following code allows for passing a variable to the script as a positional parameter:

COLUMNS="${COLUMNS:=80}"
padlength="${1:-$COLUMNS}"
pad=$(printf '\x2D%.0s' $(seq "$padlength") )

string2='bbbbbbb'
for string1 in a aa aaaa aaaaaaaa
do
     printf '%s' "$string1"
     printf '%*.*s' 0 $(("$padlength" - "${#string1}" - "${#string2}" )) "$pad"
     printf '%s\n' "$string2"
     string2=${string2:1}
done

The ASCII code "2D" is used instead of the character "-" to avoid the shell interpreting it as a command flag. Another option is "3D" to use "=".

In absence of any padlength passed as an argument, the code above defaults to the 80 character standard terminal width.

To take advantage of the the bash shell variable COLUMNS (i.e., the width of the current terminal), the environment variable would need to be available to the script. One way is to source all the environment variables by executing the script preceded by . ("dot" command), like this:

. /path/to/script

or (better) explicitly pass the COLUMNS variable when executing, like this:

/path/to/script $COLUMNS

Reference jars inside a jar

You will need a custom class loader for this, have a look at One Jar.

One-JAR lets you package a Java application together with its dependency Jars into a single executable Jar file.

It has an ant task which can simplify the building of it as well.

REFERENCE (from background)

Most developers reasonably assume that putting a dependency Jar file into their own Jar file, and adding a Class-Path attribute to the META-INF/MANIFEST will do the trick:


jarname.jar
| /META-INF
| |  MANIFEST.MF
| |    Main-Class: com.mydomain.mypackage.Main
| |    Class-Path: commons-logging.jar
| /com/mydomain/mypackage
| |  Main.class
| commons-logging.jar

Unfortunately this is does not work. The Java Launcher$AppClassLoader does not know how to load classes from a Jar inside a Jar with this kind of Class-Path. Trying to use jar:file:jarname.jar!/commons-logging.jar also leads down a dead-end. This approach will only work if you install (i.e. scatter) the supporting Jar files into the directory where the jarname.jar file is installed.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

try grant privileges again.

GRANT ALL PRIVILEGES ON the_database.* TO 'the_user'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;

Which maven dependencies to include for spring 3.0?

Use a BOM to solve version issues.

you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.

To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency.

https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/html/overview.html#overview-maven-bom

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-framework-bom</artifactId>
  <version>3.2.12.RELEASE</version>
  <type>pom</type>
</dependency>

How to Round to the nearest whole number in C#

You can use Math.Round as others have suggested (recommended), or you could add 0.5 and cast to an int (which will drop the decimal part).

double value = 1.1;
int roundedValue = (int)(value + 0.5); // equals 1

double value2 = 1.5;
int roundedValue2 = (int)(value2 + 0.5); // equals 2

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

While I was able to solve this problem in one computer following the other users solutions, the command netsh didn't solve the issue in one of my machines and even though the current user had administrator rights I was still getting the "HTTP could not register URL.... Your process does not have access rights to this namespace". So I'm sharing my solution in case you still don't get it to work with the other solutions too.

After also trying to give write permissions to the user in the physical directory of my website and getting no success, I finally decided trying to change IIS settings.

As the images below show, I configured the Physical Path Credentials of my website to connect as an specifc user, which was an admin account with DOMAIN\username and password, and this was enough to make the error disapear.

enter image description here

enter image description here

enter image description here

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

Explanation of the UML arrows

Here is simplified tutorial:

Practical UML

For more I recommend to get some literature.

php random x digit number

function random_number($size = 5)
{
    $random_number='';
    $count=0;
    while ($count < $size ) 
        {
            $random_digit = mt_rand(0, 9);
            $random_number .= $random_digit;
            $count++;
        }
    return $random_number;  
}

Share data between AngularJS controllers

Just do it simple (tested with v1.3.15):

<article ng-controller="ctrl1 as c1">
    <label>Change name here:</label>
    <input ng-model="c1.sData.name" />
    <h1>Control 1: {{c1.sData.name}}, {{c1.sData.age}}</h1>
</article>
<article ng-controller="ctrl2 as c2">
    <label>Change age here:</label>
    <input ng-model="c2.sData.age" />
    <h1>Control 2: {{c2.sData.name}}, {{c2.sData.age}}</h1>
</article>

<script>
    var app = angular.module("MyApp", []);

    var dummy = {name: "Joe", age: 25};

    app.controller("ctrl1", function () {
        this.sData = dummy;
    });

    app.controller("ctrl2", function () {
        this.sData = dummy;
    });
</script>

Android image caching

Late answer, but I figured I should add a link to my site because I have written a tutorial how to make an image cache for android: http://squarewolf.nl/2010/11/android-image-cache/ Update: the page has been taken offline as the source was outdated. I join @elenasys in her advice to use Ignition.

So to all the people who stumble upon this question and haven't found a solution: hope you enjoy! =D

How do you create a custom AuthorizeAttribute in ASP.NET Core?

You can create your own AuthorizationHandler that will find custom attributes on your Controllers and Actions, and pass them to the HandleRequirementAsync method.

public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
    {
        var attributes = new List<TAttribute>();

        var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
        if (action != null)
        {
            attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
            attributes.AddRange(GetAttributes(action.MethodInfo));
        }

        return HandleRequirementAsync(context, requirement, attributes);
    }

    protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);

    private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo)
    {
        return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
    }
}

Then you can use it for any custom attributes you need on your controllers or actions. For example to add permission requirements. Just create your custom attribute.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class PermissionAttribute : AuthorizeAttribute
{
    public string Name { get; }

    public PermissionAttribute(string name) : base("Permission")
    {
        Name = name;
    }
}

Then create a Requirement to add to your Policy

public class PermissionAuthorizationRequirement : IAuthorizationRequirement
{
    //Add any custom requirement properties if you have them
}

Then create the AuthorizationHandler for your custom attribute, inheriting the AttributeAuthorizationHandler that we created earlier. It will be passed an IEnumerable for all your custom attributes in the HandleRequirementsAsync method, accumulated from your Controller and Action.

public class PermissionAuthorizationHandler : AttributeAuthorizationHandler<PermissionAuthorizationRequirement, PermissionAttribute>
{
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement, IEnumerable<PermissionAttribute> attributes)
    {
        foreach (var permissionAttribute in attributes)
        {
            if (!await AuthorizeAsync(context.User, permissionAttribute.Name))
            {
                return;
            }
        }

        context.Succeed(requirement);
    }

    private Task<bool> AuthorizeAsync(ClaimsPrincipal user, string permission)
    {
        //Implement your custom user permission logic here
    }
}

And finally, in your Startup.cs ConfigureServices method, add your custom AuthorizationHandler to the services, and add your Policy.

        services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();

        services.AddAuthorization(options =>
        {
            options.AddPolicy("Permission", policyBuilder =>
            {
                policyBuilder.Requirements.Add(new PermissionAuthorizationRequirement());
            });
        });

Now you can simply decorate your Controllers and Actions with your custom attribute.

[Permission("AccessCustomers")]
public class CustomersController
{
    [Permission("AddCustomer")]
    IActionResult AddCustomer([FromBody] Customer customer)
    {
        //Add customer
    }
}

How to display my application's errors in JSF?

You also have to include the FormID in your call to addMessage().

 FacesContext.getCurrentInstance().addMessage("myform:newPassword1", new FacesMessage("Error: Your password is NOT strong enough."));

This should do the trick.

Regards.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

You need to change the Solution Platform from "Any CPU" to "x86" or "x64" based on the bitness of office installation.

The steps are given below:

  1. Right click on the Solution File in Solution Explorer: enter image description here

    1. Click on the Configuration Manager.
    2. Click on the Active Platform Drop down, if x86 is already there then select that, else click on New. enter image description here

    3. Select x86 or x64 from the new platform dropdown: enter image description here

Compile and run your application.

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

You should restart your Xampp or whatever server you're runnung, make sure sq

JAVA_HOME should point to a JDK not a JRE

do it thru cmd -

echo %JAVA_HOME% set set JAVA_HOME=C:\Program Files\Java\jdk1.8.0 echo %JAVA_HOME%

How to retrieve the dimensions of a view?

Simple Response: This worked for me with no Problem. It seems the key is to ensure that the View has focus before you getHeight etc. Do this by using the hasFocus() method, then using getHeight() method in that order. Just 3 lines of code required.

ImageButton myImageButton1 =(ImageButton)findViewById(R.id.imageButton1); myImageButton1.hasFocus();

int myButtonHeight = myImageButton1.getHeight();

Log.d("Button Height: ", ""+myButtonHeight );//Not required

Hope it helps.

Simple prime number generator in Python

If you wanted to find all the primes in a range you could do this:

def is_prime(num):
"""Returns True if the number is prime
else False."""
if num == 0 or num == 1:
    return False
for x in range(2, num):
    if num % x == 0:
        return False
else:
    return True
num = 0
itr = 0
tot = ''
while itr <= 100:
    itr = itr + 1
    num = num + 1
    if is_prime(num) == True:
        print(num)
        tot = tot + ' ' + str(num)
print(tot)

Just add while its <= and your number for the range.
OUTPUT:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101

what's the easiest way to put space between 2 side-by-side buttons in asp.net

If you are using bootstrap, add ml-3 to your second button:

 <div class="row justify-content-center mt-5">
        <button class="btn btn-secondary" type="button">Button1</button>
        <button class="btn btn-secondary ml-3" type="button">Button2</button>
 </div>

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

I'll throw this in just in case someone is running into this issue while working in a parallel loop:

Parallel.ForEach(query, deet =>
{
    MyContext ctx = new MyContext();
    //do some stuff with this to identify something
    if(something)
    {
         //Do stuff
         ctx.MyObjects.Add(myObject);
         ctx.SaveChanges() //this is where my error was being thrown
    }
    else
    {
        //same stuff, just an update rather than add
    }
}

I changed it to the following:

Parallel.ForEach(query, deet =>
{
    MyContext ctxCheck = new MyContext();
    //do some stuff with this to identify something
    if(something)
    {
         MyContext ctxAdd = new MyContext();
         //Do stuff
         ctxAdd .MyObjects.Add(myObject);
         ctxAdd .SaveChanges() //this is where my error was being thrown
    }
    else
    {
        MyContext ctxUpdate = new MyContext();
        //same stuff, just an update rather than add
        ctxUpdate.SaveChanges();
    }
}

Not sure if this is 'Best Practice', but it fixed my issue by having each parallel operation use its own context.

Interesting 'takes exactly 1 argument (2 given)' Python error

Yes, when you invoke e.extractAll(foo), Python munges that into extractAll(e, foo).

From http://docs.python.org/tutorial/classes.html

the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.

Emphasis added.

jquery datatables default sort

Here is the actual code that does it...

$(document).ready(function()
{
  var oTable = $('#myTable').dataTable();

  // Sort immediately with column 2 (at position 1 in the array (base 0). More could be sorted with additional array elements
  oTable.fnSort( [ [1,'asc'] ] );

  // And to sort another column descending (at position 2 in the array (base 0).
  oTable.fnSort( [ [2,'desc'] ] );
} );

To not have the column highlighted, modify the CSS like so:

table.dataTable tr.odd td.sorting_1 { background-color: transparent; }
table.dataTable tr.even td.sorting_1 { background-color: transparent; }

Calling Non-Static Method In Static Method In Java

You need an instance of the class containing the non static method.

Is like when you try to invoke the non-static method startsWith of class String without an instance:

 String.startsWith("Hello");

What you need is to have an instance and then invoke the non-static method:

 String greeting = new String("Hello World");
 greeting.startsWith("Hello"); // returns true 

So you need to create and instance to invoke it.

Fill Combobox from database

Out side the loop, set following.

cmbTripName.ValueMember = "FleetID"
cmbTripName.DisplayMember = "FleetName"

Where can I download mysql jdbc jar from?

Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.

Download zip file and extract it, with in that you will find mysql-connector-XXX.jar file

If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java

Select the version you want to use and add the dependency in your pom.xml file

How to send and receive JSON data from a restful webservice using Jersey API

The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.0</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>   


    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.25</version>
    </dependency>

Why do I get a SyntaxError for a Unicode escape in my file path?

Use this

os.chdir('C:/Users\expoperialed\Desktop\Python')

How can I extract the folder path from file path in Python?

WITH PATHLIB MODULE (UPDATED ANSWER)

One should consider using pathlib for new development. It is in the stdlib for Python3.4, but available on PyPI for earlier versions. This library provides a more object-orented method to manipulate paths <opinion> and is much easier read and program with </opinion>.

>>> import pathlib
>>> existGDBPath = pathlib.Path(r'T:\Data\DBDesign\DBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:\Data\DBDesign')

WITH OS MODULE

Use the os.path module:

>>> import os
>>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr 
'T:\Data\DBDesign'

You can go ahead and assume that if you need to do some sort of filename manipulation it's already been implemented in os.path. If not, you'll still probably need to use this module as the building block.

HtmlSpecialChars equivalent in Javascript?

Worth a read: http://bigdingus.com/2007/12/29/html-escaping-in-javascript/

escapeHTML: (function() {
 var MAP = {
   '&': '&amp;',
   '<': '&lt;',
   '>': '&gt;',
   '"': '&#34;',
   "'": '&#39;'
 };
  var repl = function(c) { return MAP[c]; };
  return function(s) {
    return s.replace(/[&<>'"]/g, repl);
  };
})()

Note: Only run this once. And don't run it on already encoded strings e.g. &amp; becomes &amp;amp;

Microsoft.Office.Core Reference Missing

After installing the Office PIA (primary interop assemblies), add a reference to your project -> its on the .NET tab - component name "Office"

How to destroy JWT Tokens on logout?

You cannot manually expire a token after it has been created. Thus, you cannot log out with JWT on the server-side as you do with sessions.

JWT is stateless, meaning that you should store everything you need in the payload and skip performing a DB query on every request. But if you plan to have a strict log out functionality, that cannot wait for the token auto-expiration, even though you have cleaned the token from the client-side, then you might need to neglect the stateless logic and do some queries. so what's a solution?

  • Set a reasonable expiration time on tokens

  • Delete the stored token from client-side upon log out

  • Query provided token against The Blacklist on every authorized request

Blacklist

“Blacklist” of all the tokens that are valid no more and have not expired yet. You can use a DB that has a TTL option on documents which would be set to the amount of time left until the token is expired.

Redis

Redis is a good option for blacklist, which will allow fast in-memory access to the list. Then, in the middleware of some kind that runs on every authorized request, you should check if the provided token is in The Blacklist. If it is you should throw an unauthorized error. And if it is not, let it go and the JWT verification will handle it and identify if it is expired or still active.

For more information, see How to log out when using JWT. by Arpy Vanyan

bash shell nested for loop

One one line (semi-colons necessary):

for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done

Formatted for legibility (no semi-colons needed):

for i in 0 1 2 3 4 5 6 7 8 9
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do 
        echo "$i$j"
    done
done

There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do (saving two lines here).

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

Using Get-childitem to get a list of files modified in the last 3 days

Try this:

(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
  $_.LastWriteTime -gt (Get-Date).AddDays(-3) 
}).Count

How to put an image in div with CSS?

This answer by Jaap :

<div class="image"></div>?

and in CSS :

div.image {
   content:url(http://placehold.it/350x150);
}?

you can try it on this link : http://jsfiddle.net/XAh2d/

this is a link about css content http://css-tricks.com/css-content/

This has been tested on Chrome, firefox and Safari. (I'm on a mac, so if someone has the result on IE, tell me to add it)

Best way to retrieve variable values from a text file?

Suppose that you have a file Called "test.txt" with:

a=1.251
b=2.65415
c=3.54
d=549.5645
e=4684.65489

And you want to find a variable (a,b,c,d or e):

ffile=open('test.txt','r').read()

variable=raw_input('Wich is the variable you are looking for?\n')

ini=ffile.find(variable)+(len(variable)+1)
rest=ffile[ini:]
search_enter=rest.find('\n')
number=float(rest[:search_enter])

print "value:",number

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

I stumbled upon another solution, which is quite nice.

Basically, only do step 2 from the blog posted mentioned, and define a custom ObjectMapper as a Spring @Component. (Things started working when I just removed all the AnnotationMethodHandlerAdapter stuff from step 3.)

@Component
@Primary
public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        setSerializationInclusion(JsonInclude.Include.NON_NULL); 
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
    }
}

Works as long as the component is in a package scanned by Spring. (Using @Primary is not mandatory in my case, but why not make things explicit.)

For me there are two benefits compared to the other approach:

  • This is simpler; I can just extend a class from Jackson and don't need to know about highly Spring-specific stuff like Jackson2ObjectMapperBuilder.
  • I want to use the same Jackson configs for deserialising JSON in another part of my app, and this way it's very simple: new CustomObjectMapper() instead of new ObjectMapper().

Passing parameters to click() & bind() event in jquery?

An alternative for the bind() method.

Use the click() method, do something like this:

commentbtn.click({id: 10, name: "João"}, onClickCommentBtn);

function onClickCommentBtn(event)
{
  alert("Id=" + event.data.id + ", Name = " + event.data.name);
}

Or, if you prefer:

commentbtn.click({id: 10, name: "João"},  function (event) {
  alert("Id=" + event.data.id + ", Nome = " + event.data.name);
});

It will show an alert box with the following infos:

Id = 10, Name = João

Tooltip with HTML content without JavaScript

Another similar way to do it by css:

_x000D_
_x000D_
#img {  }_x000D_
#img:hover {visibility:hidden}_x000D_
#thistext {font-size:22px;color:white }_x000D_
#thistext:hover {color:black;}_x000D_
#hoverme {width:50px;height:50px;}_x000D_
_x000D_
#hoverme:hover { _x000D_
background-color:green;_x000D_
position:absolute ;_x000D_
left:300px;_x000D_
top:100px;_x000D_
width:40%;_x000D_
height:20%;_x000D_
}
_x000D_
<p id="hoverme"><img id="img" src="http://a.deviantart.net/avatars/l/o/lol-cat.jpg"></img><span id="thistext">LOCATZ!!!!</span></p>
_x000D_
_x000D_
_x000D_

Try it: http://jsfiddle.net/FdBu7/

And here is some links about transitions and new ways to do it: http://www.w3schools.com/css3/css3_transitions.asp http://dev.opera.com/articles/view/css3-show-and-hide/

Mocking a class: Mock() or patch()?

Key points which explain difference and provide guidance upon working with unittest.mock

  1. Use Mock if you want to replace some interface elements(passing args) of the object under test
  2. Use patch if you want to replace internal call to some objects and imported modules of the object under test
  3. Always provide spec from the object you are mocking
    • With patch you can always provide autospec
    • With Mock you can provide spec
    • Instead of Mock, you can use create_autospec, which intended to create Mock objects with specification.

In the question above the right answer would be to use Mock, or to be more precise create_autospec (because it will add spec to the mock methods of the class you are mocking), the defined spec on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some

from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch


class MyClass:
    
    @staticmethod
    def method(foo, bar):
        print(foo)


def something(some_class: MyClass):
    arg = 1
    # Would fail becuase of wrong parameters passed to methd.
    return some_class.method(arg)


def second(some_class: MyClass):
    arg = 1
    return some_class.unexisted_method(arg)


class TestSomethingTestCase(TestCase):
    def test_something_with_autospec(self):
        mock = create_autospec(MyClass)
        mock.method.return_value = True
        # Fails because of signature misuse.
        result = something(mock)
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
    
    def test_something(self):
        mock = Mock()  # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
        mock.method.return_value = True
        
        result = something(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
        
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)


class TestSecondTestCase(TestCase):
    def test_second_with_autospec(self):
        mock = Mock(spec=MyClass)
        # Fails because of signature misuse.
        result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second(self):
        mock = Mock()
        mock.unexisted_method.return_value = True
        
        result = second(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)

The test cases with defined spec used fail because methods called from something and second functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock will display.

As a side note there is one more option: use patch.object to mock just the class method which is called with.

The good use cases for patch would be the case when the class is used as inner part of function:

def something():
    arg = 1
    return MyClass.method(arg)

Then you will want to use patch as a decorator to mock the MyClass.

How to fix UITableView separator on iOS 7?

This is default by iOS7 design. try to do the below:

[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

You can set the 'Separator Inset' from the storyboard:

enter image description here

enter image description here

A warning - comparison between signed and unsigned integer expressions

It is usually a good idea to declare variables as unsigned or size_t if they will be compared to sizes, to avoid this issue. Whenever possible, use the exact type you will be comparing against (for example, use std::string::size_type when comparing with a std::string's length).

Compilers give warnings about comparing signed and unsigned types because the ranges of signed and unsigned ints are different, and when they are compared to one another, the results can be surprising. If you have to make such a comparison, you should explicitly convert one of the values to a type compatible with the other, perhaps after checking to ensure that the conversion is valid. For example:

unsigned u = GetSomeUnsignedValue();
int i = GetSomeSignedValue();

if (i >= 0)
{
    // i is nonnegative, so it is safe to cast to unsigned value
    if ((unsigned)i >= u)
        iIsGreaterThanOrEqualToU();
    else
        iIsLessThanU();
}
else
{
    iIsNegative();
}

Getting the name of a variable as a string

Even if variable values don't point back to the name, you have access to the list of every assigned variable and its value, so I'm astounded that only one person suggested looping through there to look for your var name.

Someone mentioned on that answer that you might have to walk the stack and check everyone's locals and globals to find foo, but if foo is assigned in the scope where you're calling this retrieve_name function, you can use inspect's current frame to get you all of those local variables.

My explanation might be a little bit too wordy (maybe I should've used a "foo" less words), but here's how it would look in code (Note that if there is more than one variable assigned to the same value, you will get both of those variable names):

import inspect

x,y,z = 1,2,3

def retrieve_name(var):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return [var_name for var_name, var_val in callers_local_vars if var_val is var]

print retrieve_name(y)

If you're calling this function from another function, something like:

def foo(bar):
    return retrieve_name(bar)

foo(baz)

And you want the baz instead of bar, you'll just need to go back a scope further. This can be done by adding an extra .f_back in the caller_local_vars initialization.

See an example here: ideone

Delete all lines beginning with a # from a file

You can use the following for an awk solution -

awk '/^#/ {sub(/#.*/,"");getline;}1' inputfile

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

What's the difference between "&nbsp;" and " "?

You can see a working example here:

http://codepen.io/anon/pen/GJzBxo

and

http://codepen.io/anon/pen/LVqBQo

Same div, same text, different "spaces"

<div style="width: 500px; background: red"> [loooong text with spaces]</div>

vs

<div style="width: 500px; background: red"> [loooong text with &nbsp;]</div>

Nodejs send file in response

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

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

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

Here are the commands to retrieve key value:

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

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

  • type <key>

SQL Server table creation date query

For SQL Server 2005 upwards:

SELECT [name] AS [TableName], [create_date] AS [CreatedDate] FROM sys.tables

For SQL Server 2000 upwards:

SELECT so.[name] AS [TableName], so.[crdate] AS [CreatedDate]
FROM INFORMATION_SCHEMA.TABLES AS it, sysobjects AS so 
WHERE it.[TABLE_NAME] = so.[name]

Where does PostgreSQL store the database?

Open pgAdmin and go to Properties for specific database. Find OID and then open directory

<POSTGRESQL_DIRECTORY>/data/base/<OID>

There should be your DB files.

Is it possible to write data to file using only JavaScript?

Try

_x000D_
_x000D_
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();
_x000D_
_x000D_
_x000D_

If you want to download binary data look here

Update

2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here

Deep copy in ES6 using the spread syntax

I often use this:

function deepCopy(obj) {
    if(typeof obj !== 'object' || obj === null) {
        return obj;
    }

    if(obj instanceof Date) {
        return new Date(obj.getTime());
    }

    if(obj instanceof Array) {
        return obj.reduce((arr, item, i) => {
            arr[i] = deepCopy(item);
            return arr;
        }, []);
    }

    if(obj instanceof Object) {
        return Object.keys(obj).reduce((newObj, key) => {
            newObj[key] = deepCopy(obj[key]);
            return newObj;
        }, {})
    }
}

What is PostgreSQL equivalent of SYSDATE from Oracle?

NOW() is the replacement of Oracle Sysdate in Postgres.

Try "Select now()", it will give you the system timestamp.

Using multiprocessing.Process with a maximum number of simultaneous processes

It might be most sensible to use multiprocessing.Pool which produces a pool of worker processes based on the max number of cores available on your system, and then basically feeds tasks in as the cores become available.

The example from the standard docs (http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers) shows that you can also manually set the number of cores:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)              # start 4 worker processes
    result = pool.apply_async(f, [10])    # evaluate "f(10)" asynchronously
    print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
    print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"

And it's also handy to know that there is the multiprocessing.cpu_count() method to count the number of cores on a given system, if needed in your code.

Edit: Here's some draft code that seems to work for your specific case:

import multiprocessing

def f(name):
    print 'hello', name

if __name__ == '__main__':
    pool = multiprocessing.Pool() #use all available cores, otherwise specify the number you want as an argument
    for i in xrange(0, 512):
        pool.apply_async(f, args=(i,))
    pool.close()
    pool.join()

What do we mean by Byte array?

From wikipedia:

In computer science, an array data structure or simply array is a data structure consisting of a collection of elements (values or variables), each identified by one or more integer indices, stored so that the address of each element can be computed from its index tuple by a simple mathematical formula.

So when you say byte array, you're referring to an array of some defined length (e.g. number of elements) that contains a collection of byte (8 bits) sized elements.

In C# a byte array could look like:

byte[] bytes = { 3, 10, 8, 25 };

The sample above defines an array of 4 elements, where each element can be up to a Byte in length.

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

Find files with size in Unix

Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.

Example

find . -size +10000k -printf "%h/%f,%s\n"

Output

./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116

Best practices for adding .gitignore file for Python projects?

Here are some other files that may be left behind by setuptools:

MANIFEST
*.egg-info

How to print a list with integers without the brackets, commas and no quotes?

Using .format from Python 2.6 and higher:

>>> print '{}{}{}{}'.format(*[7,7,7,7])
7777
>>> data = [7, 7, 7, 7] * 3
>>> print ('{}'*len(data)).format(*data)
777777777777777777777777

For Python 3:

>>> print(('{}'*len(data)).format(*data))
777777777777777777777777

How to get the number of columns from a JDBC ResultSet?

After establising the connection and executing the query try this:

 ResultSet resultSet;
 int columnCount = resultSet.getMetaData().getColumnCount();
 System.out.println("column count : "+columnCount);

How can I check out a GitHub pull request with git?

The problem with some of options above, is that if someone pushes more commits to the PR after opening the PR, they won't give you the most updated version. For me what worked best is - go to the PR, and press 'Commits', scroll to the bottom to see the most recent commit hash enter image description here and then simply use git checkout, i.e.

git checkout <commit number>

in the above example

git checkout 0ba1a50

How to perform case-insensitive sorting in JavaScript?

It is time to revisit this old question.

You should not use solutions relying on toLowerCase. They are inefficient and simply don't work in some languages (Turkish for instance). Prefer this:

['Foo', 'bar'].sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}))

Check the documentation for browser compatibility and all there is to know about the sensitivity option.

java.util.NoSuchElementException: No line found

with Scanner you need to check if there is a next line with hasNextLine()

so the loop becomes

while(sc.hasNextLine()){
    str=sc.nextLine();
    //...
}

it's readers that return null on EOF

ofcourse in this piece of code this is dependent on whether the input is properly formatted

How to return a part of an array in Ruby?

You can use slice() for this:

>> foo = [1,2,3,4,5,6]
=> [1, 2, 3, 4, 5, 6]
>> bar = [10,20,30,40,50,60]
=> [10, 20, 30, 40, 50, 60]
>> half = foo.length / 2
=> 3
>> foobar = foo.slice(0, half) + bar.slice(half, foo.length)
=> [1, 2, 3, 40, 50, 60]

By the way, to the best of my knowledge, Python "lists" are just efficiently implemented dynamically growing arrays. Insertion at the beginning is in O(n), insertion at the end is amortized O(1), random access is O(1).

Display unescaped HTML in Vue.js

You can use the directive v-html to show it. like this:

<td v-html="desc"></td>

Change project name on Android Studio

Just change the application id in build.gradle

applicationId "yourpackageName"

For changing application label, in manifest

<application 
android:label="@string/app_name" 
... />

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

As of Oct 2019, SQL Server Management Studio, they did not upgraded the SSMS to add create ER Diagram feature.

I would suggest try using DBWeaver from here :

https://dbeaver.io/download/

I am using Mac and Windows both and I was able to download the community edition and logged into my SQL server database and was able to create the ER diagram using the DB Weaver.

ER Diagram using the Community Version Db Viewer

Can't change table design in SQL Server 2008

The answer is on the MSDN site:

The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.

The following actions might require a table to be re-created:

  • Adding a new column to the middle of the table
  • Dropping a column
  • Changing column nullability
  • Changing the order of the columns
  • Changing the data type of a column

EDIT 1:

Additional useful informations from here:

To change the Prevent saving changes that require the table re-creation option, follow these steps:

  1. Open SQL Server Management Studio (SSMS).
  2. On the Tools menu, click Options.
  3. In the navigation pane of the Options window, click Designers.
  4. Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.

Risk of turning off the "Prevent saving changes that require table re-creation" option

Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.

Settings, screen shot

How to force deletion of a python object?

In general, to make sure something happens no matter what, you use

from exceptions import NameError

try:
    f = open(x)
except ErrorType as e:
    pass # handle the error
finally:
    try:
        f.close()
    except NameError: pass

finally blocks will be run whether or not there is an error in the try block, and whether or not there is an error in any error handling that takes place in except blocks. If you don't handle an exception that is raised, it will still be raised after the finally block is excecuted.

The general way to make sure a file is closed is to use a "context manager".

http://docs.python.org/reference/datamodel.html#context-managers

with open(x) as f:
    # do stuff

This will automatically close f.

For your question #2, bar gets closed on immediately when it's reference count reaches zero, so on del foo if there are no other references.

Objects are NOT created by __init__, they're created by __new__.

http://docs.python.org/reference/datamodel.html#object.new

When you do foo = Foo() two things are actually happening, first a new object is being created, __new__, then it is being initialized, __init__. So there is no way you could possibly call del foo before both those steps have taken place. However, if there is an error in __init__, __del__ will still be called because the object was actually already created in __new__.

Edit: Corrected when deletion happens if a reference count decreases to zero.

Run command on the Ansible host

ansible your_server_name -i custom_inventory_file_name -m -a "uptime"

The default module is command module, hence command keyword is not required.

If you need to issue any command with elevated privileges use -b at the end of the same command.

ansible your_server_name -i custom_inventory_file_name -m -a "uptime" -b

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

Rails Model find where not equal

Rails 4

GroupUser.where.not(user_id: me)

How to delete a folder with files using Java

you can try as follows

  File dir = new File("path");
   if (dir.isDirectory())
   {
         dir.delete();
   }

If there are sub folders inside your folder you may need to recursively delete them.

Linux: where are environment variables stored?

Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

fastest MD5 Implementation in JavaScript

As of 2020 the fastest MD5 implementation is probably written in WASM (Web Assembly).

hash-wasm is a library that implements MD5 hash in WASM.

You can find the benchmarks here.

You can either install it with npm:

npm i hash-wasm

or just add a script tag

<script src="https://cdn.jsdelivr.net/npm/hash-wasm"></script>

then use the hashwasm global variable.

Example:

async function run() {
  console.log('MD5:', await hashwasm.md5('The quick brown fox jumps over the lazy dog'));
}

run();

outputs

MD5: 9e107d9d372bb6826bd81d3542a419d6

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

I had the same problem, and here's how it was fixed:

  1. My .jsp was calling attributes that I had not yet defined in the servlet.
  2. I had two column names that I was passing into an object through ResultSet (getString("columnName")) that didn't match the column names in my database.

I'm not exactly sure which one fixed the problem, but it worked. Also, be sure that you create a new Statement and ResultSet for each table query.

What's the correct way to communicate between controllers in AngularJS?

Since defineProperty has browser compatibility issue, I think we can think about using a service.

angular.module('myservice', [], function($provide) {
    $provide.factory('msgBus', ['$rootScope', function($rootScope) {
        var msgBus = {};
        msgBus.emitMsg = function(msg) {
        $rootScope.$emit(msg);
        };
        msgBus.onMsg = function(msg, scope, func) {
            var unbind = $rootScope.$on(msg, func);
            scope.$on('$destroy', unbind);
        };
        return msgBus;
    }]);
});

and use it in controller like this:

  • controller 1

    function($scope, msgBus) {
        $scope.sendmsg = function() {
            msgBus.emitMsg('somemsg')
        }
    }
    
  • controller 2

    function($scope, msgBus) {
        msgBus.onMsg('somemsg', $scope, function() {
            // your logic
        });
    }
    

Counting no of rows returned by a select query

The syntax error is just due to a missing alias for the subquery:

select COUNT(*) from
(
select m.Company_id
from Monitor as m
    inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
    group by m.Company_id
    having COUNT(m.Monitor_id)>=5)  mySubQuery  /* Alias */

Get table column names in MySQL?

You can use DESCRIBE:

DESCRIBE my_table;

Or in newer versions you can use INFORMATION_SCHEMA:

SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

Or you can use SHOW COLUMNS:

SHOW COLUMNS FROM my_table;

Or to get column names with comma in a line:

SELECT group_concat(COLUMN_NAME)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

Is a Python dictionary an example of a hash table?

To expand upon nosklo's explanation:

a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']

How can I preview a merge in git?

If you already fetched the changes, my favourite is:

git log ...@{u}

That needs git 1.7.x I believe though. The @{u} notation is a "shorthand" for the upstream branch so it's a little more versatile than git log ...origin/master.

Note: If you use zsh and the extended glog thing on, you likely have to do something like:

git log ...@\{u\}

How do I redirect to the previous action in ASP.NET MVC?

For ASP.NET Core You can use asp-route-* attribute:

<form asp-action="Login" asp-route-previous="@Model.ReturnUrl">

Other in details example: Imagine that you have a Vehicle Controller with actions

Index

Details

Edit

and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit and if you clicked edit from details you must return to details after edit.

//In your viewmodel add the ReturnUrl Property
public class VehicleViewModel
{
     ..............
     ..............
     public string ReturnUrl {get;set;}
}



Details.cshtml
<a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>

Index.cshtml
<a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>

Edit.cshtml
<form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
        <div class="box-footer">
            <a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
            <button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
        </div>
    </form>

In your controller:

// GET: Vehicle/Edit/5
    public ActionResult Edit(int id,string previous)
    {
            var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
            var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
    //or by this code if you are not use automapper
    var viewModel = new VehicleViewModel();

    if (!string.IsNullOrWhiteSpace(previous)
                viewModel.ReturnUrl = previous;
            else
                viewModel.ReturnUrl = "Index";
            return View(viewModel);
        }



[HttpPost]
    public IActionResult Edit(VehicleViewModel model, string previous)
    {
            if (!string.IsNullOrWhiteSpace(previous))
                model.ReturnUrl = previous;
            else
                model.ReturnUrl = "Index";
            ............. 
            .............
            return RedirectToAction(model.ReturnUrl);
    }

RuntimeError: module compiled against API version a but this version of numpy is 9

This works for me:

My pip is not work after upgrade, so the first thing I need to do is to fix it with

sudo gedit /usr/bin/pip

Change the line

from pip import main

to

from pip._internal import main

Then,

 sudo pip install -U numpy

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

How to remove blank lines from a Unix file

Use grep to match any line that has nothing between the start anchor (^) and the end anchor ($):

grep -v '^$' infile.txt > outfile.txt

If you want to remove lines with only whitespace, you can still use grep. I am using Perl regular expressions in this example, but here are other ways:

grep -P -v '^\s*$' infile.txt > outfile.txt

or, without Perl regular expressions:

grep -v '^[[:space:]]*$' infile.txt > outfile.txt

Rebuild all indexes in a Database

DECLARE @Database NVARCHAR(255)   
DECLARE @Table NVARCHAR(255)  
DECLARE @cmd NVARCHAR(1000)  

DECLARE DatabaseCursor CURSOR READ_ONLY FOR  
SELECT name FROM master.sys.databases   
WHERE name NOT IN ('master','msdb','tempdb','model','distribution')  -- databases to exclude
--WHERE name IN ('DB1', 'DB2') -- use this to select specific databases and comment out line above
AND state = 0 -- database is online
AND is_in_standby = 0 -- database is not read only for log shipping
ORDER BY 1  

OPEN DatabaseCursor  

FETCH NEXT FROM DatabaseCursor INTO @Database  
WHILE @@FETCH_STATUS = 0  
BEGIN  

   SET @cmd = 'DECLARE TableCursor CURSOR READ_ONLY FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +  
   table_name + '']'' as tableName FROM [' + @Database + '].INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE'''   

   -- create table cursor  
   EXEC (@cmd)  
   OPEN TableCursor   

   FETCH NEXT FROM TableCursor INTO @Table   
   WHILE @@FETCH_STATUS = 0   
   BEGIN
      BEGIN TRY   
         SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD' 
         --PRINT @cmd -- uncomment if you want to see commands
         EXEC (@cmd) 
      END TRY
      BEGIN CATCH
         PRINT '---'
         PRINT @cmd
         PRINT ERROR_MESSAGE() 
         PRINT '---'
      END CATCH

      FETCH NEXT FROM TableCursor INTO @Table   
   END   

   CLOSE TableCursor   
   DEALLOCATE TableCursor  

   FETCH NEXT FROM DatabaseCursor INTO @Database  
END  
CLOSE DatabaseCursor   
DEALLOCATE DatabaseCursor

jQuery: how to get which button was clicked upon form submission?

Here is my solution:

   $('#form').submit(function(e){   
        console.log($('#'+e.originalEvent.submitter.id));
        e.preventDefault();
    });

How do I add space between two variables after a print in Python

A simple way would be:

print str(count) + '  ' + str(conv)

If you need more spaces, simply add them to the string:

print str(count) + '    ' + str(conv)

A fancier way, using the new syntax for string formatting:

print '{0}  {1}'.format(count, conv)

Or using the old syntax, limiting the number of decimals to two:

print '%d  %.2f' % (count, conv)

YouTube embedded video: set different thumbnail

It's possible using jQuery it depends on your site load time you can adjust your timeout. It can be your custom image or you can use youtube image maxres1.jpg, maxres2.jpg or maxres3.jpg

var newImage = 'http://i.ytimg.com/vi/[Video_ID]/maxres1.jpg';
window.setTimeout(function() {
jQuery('div > div.video-container-thumb > div > a > img').attr('src',newImage );
}, 300);

Eclipse - Unable to install breakpoint due to missing line number attributes

Check/do the following:

1) Under "Window --> Preferences --> Java --> Compiler --> Classfile Generation", all options have to be to True:

(1) Add variable attributes...
(2) Add line number attributes...
(3) Add source file name...
(4) Preserve unused (never read) local variables

2) In .settings folder of your project, look for a file called org.eclipse.jdt.core.prefs. Verify or set org.eclipse.jdt.core.compiler.debug.lineNumber=generate

3) If error window still appears, click the checkbox to not display the error message.

4) Clean and build the project. Start debugging.

Normally the error window is not displayed any more and the debugging informations is displayed correctly.

How to handle the modal closing event in Twitter Bootstrap?

Bootstrap Modal Events:

  1. hide.bs.modal => Occurs when the modal is about to be hidden.
  2. hidden.bs.modal => Occurs when the modal is fully hidden (after CSS transitions have completed).
<script type="text/javascript">
    $("#salesitems_modal").on('hide.bs.modal', function () {
        //actions you want to perform after modal is closed.
    });
</script>

I hope this will Help.

How to call a shell script from python code?

There are some ways using os.popen() (deprecated) or the whole subprocess module, but this approach

import os
os.system(command)

is one of the easiest.

Best implementation for Key Value Pair Data Structure?

There is a KeyValuePair built-in type. As a matter of fact, this is what the IDictionary is giving you access to when you iterate in it.

Also, this structure is hardly a tree, finding a more representative name might be a good exercise.

Processing $http response in service

tosh shimayama have a solution but you can simplify a lot if you use the fact that $http returns promises and that promises can return a value:

app.factory('myService', function($http, $q) {
  myService.async = function() {
    return $http.get('test.json')
    .then(function (response) {
      var data = reponse.data;
      console.log(data);
      return data;
    });
  };

  return myService;
});

app.controller('MainCtrl', function( myService,$scope) {
  $scope.asyncData = myService.async();
  $scope.$watch('asyncData', function(asyncData) {
    if(angular.isDefined(asyncData)) {
      // Do something with the returned data, angular handle promises fine, you don't have to reassign the value to the scope if you just want to use it with angular directives
    }
  });

});

A little demonstration in coffeescript: http://plunker.no.de/edit/ksnErx?live=preview

Your plunker updated with my method: http://plnkr.co/edit/mwSZGK?p=preview

What is Parse/parsing?

Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number.

String tenString = "10"

//This won't work since you can't add an integer and a string
Integer result = 20 + tenString;

//This will set result to 30
Integer result = 20 + Integer.parseInt(tenString);

Simple Java Client/Server Program

this is client code

first run the server program then on another cmd run client program

import java.io.*;
import java.net.*;

public class frmclient 
{
 public static void main(String args[])throws Exception
 {

   try
        {
          DataInputStream d=new DataInputStream(System.in);
          System.out.print("\n1.fact\n2.Sum of digit\nEnter ur choice:");

           int ch=Integer.parseInt(d.readLine());
           System.out.print("\nEnter number:");
           int num=Integer.parseInt(d.readLine());

           Socket s=new Socket("localhost",1024);

           PrintStream ps=new PrintStream(s.getOutputStream());
           ps.println(ch+"");
           ps.println(num+"");

          DataInputStream dis=new DataInputStream(s.getInputStream());
           String response=dis.readLine();
                 System.out.print("Answer:"+response);


                s.close();
        }
        catch(Exception ex)
        {

        }
 }


}

this is sever side code

import java.io.*;
import java.net.*;
public class frmserver {

  public static void main(String args[])throws Exception
  {

try
    {

    ServerSocket ss=new ServerSocket(1024);
       System.out.print("\nWaiting for client.....");
       Socket s=ss.accept();
       System.out.print("\nConnected");

       DataInputStream d=new DataInputStream(s.getInputStream());

        int ch=Integer.parseInt(d.readLine());
       int num=Integer.parseInt(d.readLine());
         int result=0;

        PrintStream ps=new PrintStream(s.getOutputStream());
        switch(ch)
        {
          case 1:result=fact(num);
                 ps.println(result);
                  break;
          case 2:result=sum(num);
                 ps.println(result);
                  break;
        }

          ss.close();
          s.close();
    }
catch(Exception ex)
{

}
  }

  public static int fact(int n)
  {
  int ans=1;
    for(int i=n;i>0;i--)
    {
      ans=ans*i;
    }
    return ans;
  }
  public static int sum(int n)
  {
   String str=n+"";
   int ans=0;
    for(int i=0;i<str.length();i++)
    {
      int tmp=Integer.parseInt(str.charAt(i)+"");
      ans=ans+tmp;
    }
    return ans;
  }
}

How to match a substring in a string, ignoring case

Try:

if haystackstr.lower().find(needlestr.lower()) != -1:
  # True

how to install multiple versions of IE on the same system?

I would use VMs. Create an XP (or whatever) VM using VMware Workstation or similar product, and snapshot it. That is your oldest version. Then perform the upgrades one at a time, and snapshot each time. Then you can switch to any snapshot you need later, or clone independent VMs based on all the snapshots so you can run them all at once. You probably want to test on different operating systems as well as different versions, so VMs generalize that solution as well rather than some one-off solution of hacking multiple IEs to coexist on a single instance of Windows.

How to set the maxAllowedContentLength to 500MB while running on IIS7?

According to MSDN maxAllowedContentLength has type uint, its maximum value is 4,294,967,295 bytes = 3,99 gb

So it should work fine.

See also Request Limits article. Does IIS return one of these errors when the appropriate section is not configured at all?

See also: Maximum request length exceeded

In-place edits with sed on OS X

You can use:

sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path>

Example:

sed -i -e 's/Hello/Bye/' file.txt

This works flawless in Mac.

How to delete a character from a string using Python

Strings are immutable. But you can convert them to a list, which is mutable, and then convert the list back to a string after you've changed it.

s = "this is a string"

l = list(s)  # convert to list

l[1] = ""    # "delete" letter h (the item actually still exists but is empty)
l[1:2] = []  # really delete letter h (the item is actually removed from the list)
del(l[1])    # another way to delete it

p = l.index("a")  # find position of the letter "a"
del(l[p])         # delete it

s = "".join(l)  # convert back to string

You can also create a new string, as others have shown, by taking everything except the character you want from the existing string.

How to open remote files in sublime text 3

On server

Install rsub:

wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate
chmod a+x /usr/local/bin/rsub

On local

  1. Install rsub Sublime3 package:

On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub and install it

  1. Open command line and connect to remote server:

ssh -R 52698:localhost:52698 server_user@server_address

  1. after connect to server run this command on server:

rsub path_to_file/file.txt

  1. File opening auto in Sublime 3

As of today (2018/09/05) you should use : https://github.com/randy3k/RemoteSubl because you can find it in packagecontrol.io while "rsub" is not present.

Android: No Activity found to handle Intent error? How it will resolve

Generally to avoid this kind of exceptions, you will need to surround your code by try and catch like this

try{

// your intent here

} catch (ActivityNotFoundException e) {
// show message to user 
}

Convert list of ASCII codes to string (byte array) in Python

For Python 2.6 and later if you are dealing with bytes then a bytearray is the most obvious choice:

>>> str(bytearray([17, 24, 121, 1, 12, 222, 34, 76]))
'\x11\x18y\x01\x0c\xde"L'

To me this is even more direct than Alex Martelli's answer - still no string manipulation or len call but now you don't even need to import anything!

RegEx to exclude a specific string constant

This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:

$var !~ /^foo$/
    or die "too much foo";

If not, you have to do something evil:

$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
    or die "too much foo";

That one basically says "if it starts with non-f, the rest can be anything; if it starts with f, non-o, the rest can be anything; otherwise, if it starts fo, the next character had better not be another o".

Updating a local repository with changes from a GitHub repository

This question is very general and there are a couple of assumptions I'll make to simplify it a bit. We'll assume that you want to update your master branch.

If you haven't made any changes locally, you can use git pull to bring down any new commits and add them to your master.

git pull origin master

If you have made changes, and you want to avoid adding a new merge commit, use git pull --rebase.

git pull --rebase origin master

git pull --rebase will work even if you haven't made changes and is probably your best call.

Initialize array of strings

There is no right way, but you can initialize an array of literals:

char **values = (char *[]){"a", "b", "c"};

or you can allocate each and initialize it:

char **values = malloc(sizeof(char*) * s);
for(...)
{
    values[i] = malloc(sizeof(char) * l);
    //or
    values[i] = "hello";
}

Create a sample login page using servlet and JSP?

You're comparing the message with the empty string using ==.

First, your comparison is wrong because the message will be null (and not the empty string).

Second, it's wrong because Objects must be compared with equals() and not with ==.

Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:

<c:id test="${!empty message}">
    <c:out value="${message}"/>
</c:if>

How to use SqlClient in ASP.NET Core?

I think you may have missed this part in the tutorial:

Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:

System.Data.Common and System.Data.SqlClient.

Currently this creates dependency in project.json –> aspnetcore50 section to these two libraries.

"aspnetcore50": {
       "dependencies": {
           "System.Runtime": "4.0.20-beta-22523",
           "System.Data.Common": "4.0.0.0-beta-22605",
           "System.Data.SqlClient": "4.0.0.0-beta-22605"
       }
}

Try getting System.Data.Common and System.Data.SqlClient via Nuget and see if this adds the above dependencies for you, but in a nutshell you are missing System.Runtime.

Edit: As per Mozarts answer, if you are using .NET Core 3+, reference Microsoft.Data.SqlClient instead.

How to initialize weights in PyTorch?

Cuz I haven't had the enough reputation so far, I can't add a comment under

the answer posted by prosti in Jun 26 '19 at 13:16.

    def reset_parameters(self):
        init.kaiming_uniform_(self.weight, a=math.sqrt(3))
        if self.bias is not None:
            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in)
            init.uniform_(self.bias, -bound, bound)

But I wanna point out that actually we know some assumptions in the paper of Kaiming He, Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification, are not appropriate, though it looks like the deliberately designed initialization method makes a hit in practice.

E.g., within the subsection of Backward Propagation Case, they assume that $w_l$ and $\delta y_l$ are independent of each other. But as we all known, take the score map $\delta y^L_i$ as an instance, it often is $y_i-softmax(y^L_i)=y_i-softmax(w^L_ix^L_i)$ if we use a typical cross entropy loss function objective.

So I think the true underlying reason why He's Initialization works well remains to unravel. Cuz everyone has witnessed its power on boosting deep learning training.

Variable might not have been initialized error

Since no other answer has cited the Java language standard, I have decided to write an answer of my own:

In Java, local variables are not, by default, initialized with a certain value (unlike, for example, the field of classes). From the language specification one (§4.12.5) can read the following:

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

Therefore, since the variables a and b are not initialized :

 for (int l= 0; l<x.length; l++) 
    {
        if (x[l] == 0) 
        a++ ;
        else if (x[l] == 1) 
        b++ ;
    }

the operations a++; and b++; could not produce any meaningful results, anyway. So it is logical for the compiler to notify you about it:

Rand.java:72: variable a might not have been initialized
                a++ ;
                ^
Rand.java:74: variable b might not have been initialized
                b++ ;
                ^

However, one needs to understand that the fact that a++; and b++; could not produce any meaningful results has nothing to do with the reason why the compiler displays an error. But rather because it is explicitly set on the Java language specification that

A local variable (§14.4, §14.14) must be explicitly given a value (...)

To showcase the aforementioned point, let us change a bit your code to:

public static Rand searchCount (int[] x) 
{
    if(x == null || x.length  == 0)
      return null;
    int a ; 
    int b ; 

    ...   

    for (int l= 0; l<x.length; l++) 
    {
        if(l == 0)
           a = l;
        if(l == 1)
           b = l;
    }

    ...   
}

So even though the code above can be formally proven to be valid (i.e., the variables a and b will be always assigned with the value 0 and 1, respectively) it is not the compiler job to try to analyze your application's logic, and neither does the rules of local variable initialization rely on that. The compiler checks if the variables a and b are initialized according to the local variable initialization rules, and reacts accordingly (e.g., displaying a compilation error).

How to change DatePicker dialog color for Android 5.0

Just to mention, you can also use the default a theme like android.R.style.Theme_DeviceDefault_Light_Dialog instead.

new DatePickerDialog(MainActivity.this, android.R.style.Theme_DeviceDefault_Light_Dialog, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    //DO SOMETHING
    }
}, 2015, 02, 26).show();

Access 2010 VBA query a table and iterate through results

Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:

EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!

Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Set colReturn = New Collection

Dim SQL As String
SQL = _
    "SELECT tblState.State, tblState.StateName " & _
    "FROM tblState"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
    Do Until .EOF
        colReturn.Add Nz(!State, "")
        .MoveNext
    Loop
    End If
    .Close
End With
cn.Close

Set rs = Nothing
Set cn = Nothing

Set StatesCollection = colReturn

End Function

AngularJS - Find Element with attribute

You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)

If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.

So, for this HTML:

<div ng-controller='MyCtrl'>
    <div>
        <div name='foo' class='myElementClass'>this one</div>
    </div>
</div>

This AngularJS code should work:

angular.module('MyClient').controller('MyCtrl', [
    '$scope',
    '$element',
    '$log',
    function ($scope, $element, $log) {

        // Find the element by its class attribute, within your controller's scope
        var myElements = $element.find('.myElementClass');

        // myElements is now an array of jQuery DOM elements

        if (myElements.length == 0) {
            // Not found. Are you sure you've included the full jQuery?
        } else {
            // There should only be one, and it will be element 0
            $log.debug(myElements[0].name); // "foo"
        }

    }
]);

Boolean operators ( &&, -a, ||, -o ) in Bash

-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ]

The shell is evaluating the and condition. In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ]

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]]

Which is more similar to modern programming languages and thus is more readable.

How to deal with bad_alloc in C++?

You can catch it like any other exception:

try {
  foo();
}
catch (const std::bad_alloc&) {
  return -1;
}

Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.



In general you cannot, and should not try, to respond to this error. bad_alloc indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.

Worse, modern operating systems often over-allocate: on such systems, malloc and new can return a valid pointer even if there is not enough free memory left – std::bad_alloc will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).

The only thing you could do when catching std::bad_alloc is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).

In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:

  1. The application must ensure that it runs on a system that does not overcommit memory, i.e. it signals failure upon allocation rather than later.
  2. The application must be able to free memory immediately, without any further accidental allocations in the meantime.

It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1

OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:

lru_cache<widget> widget_cache;

double perform_operation(int widget_id) {
    std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
    if (not maybe_widget) {
        maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
    }
    return maybe_widget->frobnicate();
}

…

for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
    try {
        return perform_operation(widget_id);
    } catch (std::bad_alloc const&) {
        if (widget_cache.empty()) throw; // memory error elsewhere.
        widget_cache.remove_oldest();
    }
}

// Handle too many failed attempts here.

But even here, using std::set_new_handler instead of handling std::bad_alloc provides the same benefit and would be much simpler.


1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.


What is the C++ Standard specified behavior of new in c++?

The usual notion is that if new operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc.
However, something more happens even before a bad_alloc exception is thrown:

C++03 Section 3.7.4.1.3: says

An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.

Consider the following code sample:

#include <iostream>
#include <cstdlib>

// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
    std::cerr << "Unable to satisfy request for memory\n";

    std::abort();
}

int main()
{
    //set the new_handler
    std::set_new_handler(outOfMemHandler);

    //Request huge memory size, that will cause ::operator new to fail
    int *pBigDataArray = new int[100000000L];

    return 0;
}

In the above example, operator new (most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler() will be called, and the program will abort after issuing an error message.

As seen here the default behavior of new operator when unable to fulfill a memory request, is to call the new-handler function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort(), outOfMemHandler() would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.

What is the new_handler and set_new_handler?

new_handler is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler is a function that takes and returns a new_handler.

Something like:

typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();

set_new_handler's parameter is a pointer to the function operator new should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.

How to handle out of memory conditions in C++?

Given the behavior of newa well designed user program should handle out of memory conditions by providing a proper new_handlerwhich does one of the following:

Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.

Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler). The next time operator new calls the new-handler function, it will get the one most recently installed.

(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)

Uninstall the new-handler: This is done by passing a null pointer to set_new_handler. With no new-handler installed, operator new will throw an exception ((convertible to) std::bad_alloc) when memory allocation is unsuccessful.

Throw an exception convertible to std::bad_alloc. Such exceptions are not be caught by operator new, but will propagate to the site originating the request for memory.

Not return: By calling abort or exit.

Purge or recreate a Ruby on Rails database

I use:

  • rails db:drop to delete the databases.
  • rails db:create to create the databases based on config/database.yml

The previous commands may be replaced with rails db:reset.

Don't forget to run rails db:migrate to run the migrations.