Programs & Examples On #Itemssource

Error: the entity type requires a primary key

The entity type 'DisplayFormatAttribute' requires a primary key to be defined.

In my case I figured out the problem was that I used properties like this:

public string LastName { get; set; }  //OK
public string Address { get; set; }   //OK 
public string State { get; set; }     //OK
public int? Zip { get; set; }         //OK
public EmailAddressAttribute Email { get; set; } // NOT OK
public PhoneAttribute PhoneNumber { get; set; }  // NOT OK

Not sure if there is a better way to solve it but I changed the Email and PhoneNumber attribute to a string. Problem solved.

Get current index from foreach loop

Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)

list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});

foreach(var row in list)
{
    bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
    row.Index ...
}

Call asynchronous method in constructor?

You can also do just like this:

Task.Run(() => this.FunctionAsync()).Wait();

Note: Be careful about thread blocking!

How to bind DataTable to Datagrid

You could use DataGrid in WPF

SqlDataAdapter da = new SqlDataAdapter("Select * from Table",con);
DataTable dt = new DataTable("Call Reciept");
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.ItemsSource = dt.DefaultView;

Binding ComboBox SelectedItem using MVVM

You seem to be unnecessarily setting properties on your ComboBox. You can remove the DisplayMemberPath and SelectedValuePath properties which have different uses. It might be an idea for you to take a look at the Difference between SelectedItem, SelectedValue and SelectedValuePath post here for an explanation of these properties. Try this:

<ComboBox Name="cbxSalesPeriods"
    ItemsSource="{Binding SalesPeriods}"
    SelectedItem="{Binding SelectedSalesPeriod}"
    IsSynchronizedWithCurrentItem="True"/>

Furthermore, it is pointless using your displayPeriod property, as the WPF Framework would call the ToString method automatically for objects that it needs to display that don't have a DataTemplate set up for them explicitly.


UPDATE >>>

As I can't see all of your code, I cannot tell you what you are doing wrong. Instead, all I can do is to provide you with a complete working example of how to achieve what you want. I've removed the pointless displayPeriod property and also your SalesPeriodVO property from your class as I know nothing about it... maybe that is the cause of your problem??. Try this:

public class SalesPeriodV
{
    private int month, year;

    public int Year
    {
        get { return year; }
        set
        {
            if (year != value)
            {
                year = value;
                NotifyPropertyChanged("Year");
            }
        }
    }

    public int Month
    {
        get { return month; }
        set
        {
            if (month != value)
            {
                month = value;
                NotifyPropertyChanged("Month");
            }
        }
    }

    public override string ToString()
    {
        return String.Format("{0:D2}.{1}", Month, Year);
    }

    public virtual event PropertyChangedEventHandler PropertyChanged;
    protected virtual void NotifyPropertyChanged(params string[] propertyNames)
    {
        if (PropertyChanged != null)
        {
            foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
        }
    }
}

Then I added two properties into the view model:

private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
    get { return salesPeriods; }
    set { salesPeriods = value; NotifyPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
    get { return selectedItem; }
    set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}

Then initialised the collection with your values:

SalesPeriods.Add(new SalesPeriodV() { Month = 3, Year = 2013 } );
SalesPeriods.Add(new SalesPeriodV() { Month = 4, Year = 2013 } );

And then data bound only these two properties to a ComboBox:

<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />

That's it... that's all you need for a perfectly working example. You should see that the display of the items comes from the ToString method without your displayPeriod property. Hopefully, you can work out your mistakes from this code example.

How to set DataGrid's row Background, based on a property value using data bindings

The same can be done without DataTrigger too:

 <DataGrid.RowStyle>
     <Style TargetType="DataGridRow">
         <Setter Property="Background" >
             <Setter.Value>
                 <Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
                     <Binding.ConverterParameter>
                         <x:Array Type="SolidColorBrush">
                             <SolidColorBrush Color="{StaticResource RedColor}"/>
                             <SolidColorBrush Color="{StaticResource TransparentColor}"/>
                         </x:Array>
                     </Binding.ConverterParameter>
                 </Binding>
             </Setter.Value>
         </Setter>
     </Style>
 </DataGrid.RowStyle>

Where BooleanToBrushConverter is the following class:

public class BooleanToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return Brushes.Transparent;

        Brush[] brushes = parameter as Brush[];
        if (brushes == null)
            return Brushes.Transparent;

        bool isTrue;
        bool.TryParse(value.ToString(), out isTrue);

        if (isTrue)
        {
            var brush =  (SolidColorBrush)brushes[0];
            return brush ?? Brushes.Transparent;
        }
        else
        {
            var brush = (SolidColorBrush)brushes[1];
            return brush ?? Brushes.Transparent;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Wpf DataGrid Add new row

Try this MSDN blog

Also, try the following example:

Xaml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

WPF ListView - detect when selected item is clicked

You can handle click on list view item like this:

<ListView.ItemTemplate>
  <DataTemplate>
     <Button BorderBrush="Transparent" Background="Transparent" Focusable="False">
        <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <i:InvokeCommandAction Command="{Binding DataContext.MyCommand, ElementName=ListViewName}" CommandParameter="{Binding}"/>
                </i:EventTrigger>
        </i:Interaction.Triggers>
      <Button.Template>
      <ControlTemplate>
         <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
    ...

The calling thread cannot access this object because a different thread owns it

The problem is that you are calling GetGridData from a background thread. This method accesses several WPF controls which are bound to the main thread. Any attempt to access them from a background thread will lead to this error.

In order to get back to the correct thread you should use SynchronizationContext.Current.Post. However in this particular case it seems like the majority of the work you are doing is UI based. Hence you would be creating a background thread just to go immediately back to the UI thread and do some work. You need to refactor your code a bit so that it can do the expensive work on the background thread and then post the new data to the UI thread afterwards

Notify ObservableCollection when Item changes

A simple solution is to use BindingList<T> instead of ObservableCollection<T> . Indeed the BindingList relay item change notifications. So with a binding list, if the item implements the interface INotifyPropertyChanged then you can simply get notifications using the ListChanged event.

See also this SO answer.

Date formatting in WPF datagrid

Very late to the party here but in case anyone else stumbles across this page...

You can do it by setting the AutoGeneratingColumn handler in XAML:

<DataGrid AutoGeneratingColumn="OnAutoGeneratingColumn"  ..etc.. />

And then in code behind do something like this:

private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyType == typeof(System.DateTime))
        (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";
}

How to bind an enum to a combobox control in WPF?

All the above posts have missed a simple trick. It is possible from the binding of SelectedValue to find out how to populate the ItemsSource AUTOMAGICALLY so that your XAML markup is just.

<Controls:EnumComboBox SelectedValue="{Binding Fool}"/>

For example in my ViewModel I have

public enum FoolEnum
    {
        AAA, BBB, CCC, DDD

    };


    FoolEnum _Fool;
    public FoolEnum Fool
    {
        get { return _Fool; }
        set { ValidateRaiseAndSetIfChanged(ref _Fool, value); }
    }

ValidateRaiseAndSetIfChanged is my INPC hook. Yours may differ.

The implementation of EnumComboBox is as follows but first I'll need a little helper to get my enumeration strings and values

    public static List<Tuple<object, string, int>> EnumToList(Type t)
    {
        return Enum
            .GetValues(t)
            .Cast<object>()
            .Select(x=>Tuple.Create(x, x.ToString(), (int)x))
            .ToList();
    }

and the main class ( Note I'm using ReactiveUI for hooking property changes via WhenAny )

using ReactiveUI;
using ReactiveUI.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Documents;

namespace My.Controls
{
    public class EnumComboBox : System.Windows.Controls.ComboBox
    {
        static EnumComboBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(EnumComboBox), new FrameworkPropertyMetadata(typeof(EnumComboBox)));
        }

        protected override void OnInitialized( EventArgs e )
        {
            base.OnInitialized(e);

            this.WhenAnyValue(p => p.SelectedValue)
                .Where(p => p != null)
                .Select(o => o.GetType())
                .Where(t => t.IsEnum)
                .DistinctUntilChanged()
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(FillItems);
        }

        private void FillItems(Type enumType)
        {
            List<KeyValuePair<object, string>> values = new List<KeyValuePair<object,string>>();

            foreach (var idx in EnumUtils.EnumToList(enumType))
            {
                values.Add(new KeyValuePair<object, string>(idx.Item1, idx.Item2));
            }

            this.ItemsSource = values.Select(o=>o.Key.ToString()).ToList();

            UpdateLayout();
            this.ItemsSource = values;
            this.DisplayMemberPath = "Value";
            this.SelectedValuePath = "Key";

        }
    }
}

You also need to set the style correctly in Generic.XAML or your box won't render anything and you will pull your hair out.

<Style TargetType="{x:Type local:EnumComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
</Style>

and that is that. This could obviously be extended to support i18n but would make the post longer.

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

Your ComboBox is trying to bind to bind to GridItem[x].CompanyItems, which doesn't exist.

Your RelativeBinding is close, however it needs to bind to DataContext.CompanyItems because Window.CompanyItems does not exist

Change background color for selected ListBox item

Or you can apply HighlightBrushKey directly to the ListBox. Setter Property="Background" Value="Transparent" did NOT work. But I did have to set the Foreground to Black.

<ListBox  ... >
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True" >
                    <Setter Property="FontWeight" Value="Bold" />
                    <Setter Property="Background" Value="Transparent" />
                    <Setter Property="Foreground" Value="Black" />
                </Trigger>
            </Style.Triggers>
            <Style.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
            </Style.Resources>
        </Style>                
    </ListBox.ItemContainerStyle>
</ListBox>

WPF binding to Listbox selectedItem

First off, you need to implement INotifyPropertyChanged interface in your view model and raise the PropertyChanged event in the setter of the Rule property. Otherwise no control that binds to the SelectedRule property will "know" when it has been changed.

Then, your XAML

<TextBlock Text="{Binding Path=SelectedRule.Name}" />

is perfectly valid if this TextBlock is outside the ListBox's ItemTemplate and has the same DataContext as the ListBox.

How to get a List<string> collection of values from app.config in WPF?

In App.config:

<add key="YOURKEY" value="a,b,c"/>

In C#:

string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);

WPF Databinding: How do I access the "parent" data context?

You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

C# generic list <T> how to get the type of T?

Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

More generally, to support any IList<T>, you need to check the interfaces:

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}

Data binding to SelectedItem in a WPF Treeview

I realise this has already had an answer accepted, but I put this together to solve the problem. It uses a similar idea to Delta's solution, but without the need to subclass the TreeView:

public class BindableSelectedItemBehavior : Behavior<TreeView>
{
    #region SelectedItem Property

    public object SelectedItem
    {
        get { return (object)GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register("SelectedItem", typeof(object), typeof(BindableSelectedItemBehavior), new UIPropertyMetadata(null, OnSelectedItemChanged));

    private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var item = e.NewValue as TreeViewItem;
        if (item != null)
        {
            item.SetValue(TreeViewItem.IsSelectedProperty, true);
        }
    }

    #endregion

    protected override void OnAttached()
    {
        base.OnAttached();

        this.AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        if (this.AssociatedObject != null)
        {
            this.AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
        }
    }

    private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        this.SelectedItem = e.NewValue;
    }
}

You can then use this in your XAML as:

<TreeView>
    <e:Interaction.Behaviors>
        <behaviours:BindableSelectedItemBehavior SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
    </e:Interaction.Behaviors>
</TreeView>

Hopefully it will help someone!

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.

"Items collection must be empty before using ItemsSource."

In my case, it was not using a DataTemplate for the ItemsControl.

Old:

<ItemsControl Width="243" ItemsSource="{Binding List, Mode=TwoWay}">
    <StackPanel Orientation="Horizontal">
        <TextBox Width="25" Margin="0,0,5,0" Text="{Binding Path=Property1}"/>
        <Label Content="{Binding Path=Property2}"/>
    </StackPanel>
</ItemsControl>

New:

<ItemsControl Width="243" ItemsSource="{Binding List, Mode=TwoWay}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBox Width="25" Margin="0,0,5,0" Text="{Binding Path=Property1}"/>
                <Label Content="{Binding Path=Property2}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

how can I enable scrollbars on the WPF Datagrid?

If any of the parent containers RowDefinition Height set to "Auto" also stoppers for scrollbars

Alternatively you may set Height "*"

Which happened in my case.

WPF MVVM ComboBox SelectedItem or SelectedValue not working

When leaving the current page, the CollectionView associated with the ItemsSource property of the ComboBox is purged. And because the ComboBox IsSyncronizedWithCurrent property is true by default, the SelectedItem and SelectedValue properties are reset.
This seems to be an internal data type issue in the binding. As others suggested above, if you use SelectedValue instead by binding to an int property on the viewmodel, it will work. A shortcut for you would be to override the Equals operator on MyObject so that when comparing two MyObjects, the actual Id properties are compared.

Another hint: If you do restructure your viewmodels and use SelectedValue, use it only when SelectedValuePath=Id where Id is int. If using a string key, bind to the Text property of the ComboBox instead of SelectedValue.

Binding a WPF ComboBox to a custom list

You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.

Have you set the DataContext to your ConnectionViewModel object?

I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.

Here is my XAML content:

<Window x:Class="WpfApplication6.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
<Grid>
    <StackPanel>
        <Button Click="Button_Click">asdf</Button>
        <ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
                  DisplayMemberPath="Name"
                  SelectedValuePath="Name"
                  SelectedValue="{Binding Path=PhonebookEntry}" />
    </StackPanel>
</Grid>
</Window>

And here is my code-behind:

namespace WpfApplication6
{

    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            ConnectionViewModel vm = new ConnectionViewModel();
            DataContext = vm;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ((ConnectionViewModel)DataContext).PhonebookEntry = "test";
        }
    }

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

        public PhoneBookEntry(string name)
        {
            Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }

    public class ConnectionViewModel : INotifyPropertyChanged
    {
        public ConnectionViewModel()
        {
            IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
            list.Add(new PhoneBookEntry("test"));
            list.Add(new PhoneBookEntry("test2"));
            _phonebookEntries = new CollectionView(list);
        }

        private readonly CollectionView _phonebookEntries;
        private string _phonebookEntry;

        public CollectionView PhonebookEntries
        {
            get { return _phonebookEntries; }
        }

        public string PhonebookEntry
        {
            get { return _phonebookEntry; }
            set
            {
                if (_phonebookEntry == value) return;
                _phonebookEntry = value;
                OnPropertyChanged("PhonebookEntry");
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.

Maybe there is an issue with the CollectionView? I noticed a warning in the output console:

System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.

Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.

How to autosize and right-align GridViewColumn data in WPF?

I had trouble with the accepted answer (because I missed the HorizontalAlignment=Stretch portion and have adjusted the original answer).

This is another technique. It uses a Grid with a SharedSizeGroup.

Note: the Grid.IsSharedScope=true on the ListView.

<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
    <ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}" Grid.IsSharedSizeScope="True">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID" Width="40">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                             <Grid>
                                  <Grid.ColumnDefinitions>
                                       <ColumnDefinition Width="Auto" SharedSizeGroup="IdColumn"/>
                                  </Grid.ColumnDefinitions>
                                  <TextBlock HorizontalAlignment="Right" Text={Binding Path=Id}"/>
                             </Grid>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>
</Window>

How can I get a vertical scrollbar in my ListBox?

Scroll Bar is added to the List box automatically unless its visibility is set to Hidden. Whenever the size of List Items exceeds the one, which can be shown inside a list box vertical or horizontal list box can be seen during the run time.

Databinding an enum property to a ComboBox in WPF

Based on the accepted but now deleted answer provided by ageektrapped I created a slimmed down version without some of the more advanced features. All the code is included here to allow you to copy-paste it and not get blocked by link-rot.

I use the System.ComponentModel.DescriptionAttribute which really is intended for design time descriptions. If you dislike using this attribute you may create your own but I think using this attribute really gets the job done. If you don't use the attribute the name will default to the name of the enum value in code.

public enum ExampleEnum {

  [Description("Foo Bar")]
  FooBar,

  [Description("Bar Foo")]
  BarFoo

}

Here is the class used as the items source:

public class EnumItemsSource : Collection<String>, IValueConverter {

  Type type;

  IDictionary<Object, Object> valueToNameMap;

  IDictionary<Object, Object> nameToValueMap;

  public Type Type {
    get { return this.type; }
    set {
      if (!value.IsEnum)
        throw new ArgumentException("Type is not an enum.", "value");
      this.type = value;
      Initialize();
    }
  }

  public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {
    return this.valueToNameMap[value];
  }

  public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {
    return this.nameToValueMap[value];
  }

  void Initialize() {
    this.valueToNameMap = this.type
      .GetFields(BindingFlags.Static | BindingFlags.Public)
      .ToDictionary(fi => fi.GetValue(null), GetDescription);
    this.nameToValueMap = this.valueToNameMap
      .ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
    Clear();
    foreach (String name in this.nameToValueMap.Keys)
      Add(name);
  }

  static Object GetDescription(FieldInfo fieldInfo) {
    var descriptionAttribute =
      (DescriptionAttribute) Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));
    return descriptionAttribute != null ? descriptionAttribute.Description : fieldInfo.Name;
  }

}

You can use it in XAML like this:

<Windows.Resources>
  <local:EnumItemsSource
    x:Key="ExampleEnumItemsSource"
    Type="{x:Type local:ExampleEnum}"/>
</Windows.Resources>
<ComboBox
  ItemsSource="{StaticResource ExampleEnumItemsSource}"
  SelectedValue="{Binding ExampleProperty, Converter={StaticResource ExampleEnumItemsSource}}"/> 

How to Set Active Tab in jQuery Ui

I know this is an old question. But I think the way to change the selected tab have changed slight

The way to change the active tab now is by giving active the index of the tab. Note the index starts at 0 not 1. To make the second tab active you will use the the index 1.

//this will select your first tab
$( "#tabs" ).tabs({ active: 0 });

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.

http://jsfiddle.net/P2QhE/

Javascript code embedded aswell:

$(document).ready(function () {
    var map;
    var elevator;
    var myOptions = {
        zoom: 1,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: 'terrain'
    };
    map = new google.maps.Map($('#map_canvas')[0], myOptions);

    var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];

    for (var x = 0; x < addresses.length; x++) {
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
            var p = data.results[0].geometry.location
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            new google.maps.Marker({
                position: latlng,
                map: map
            });

        });
    }

}); 

How to redirect to another page in node.js

In another way you can use window.location.href="your URL"

e.g.:

res.send('<script>window.location.href="your URL";</script>');

or:

return res.redirect("your url");

jQuery.active function

For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:

jQuery.ajaxPrefilter(function( options ) {
    options.global = true;
});

Keep in mind that you'll need a timeout on your JSONP request to catch failures.

How to get a Char from an ASCII Character Code in c#

It is important to notice that in C# the char type is stored as Unicode UTF-16.

From ASCII equivalent integer to char

char c = (char)88;

or

char c = Convert.ToChar(88)

From char to ASCII equivalent integer

int asciiCode = (int)'A';

The literal must be ASCII equivalent. For example:

string str = "X?????????";
Console.WriteLine((int)str[0]);
Console.WriteLine((int)str[1]);

will print

X
3626

Extended ASCII ranges from 0 to 255.

From default UTF-16 literal to char

Using the Symbol

char c = 'X';

Using the Unicode code

char c = '\u0058';

Using the Hexadecimal

char c = '\x0058';

Print Html template in Angular 2 (ng-print in Angular 2)

The best option I found to solve this without getting into trouble with my styles was using a separate route for my printed output and load this route into an iframe.

My surrounding component is shown as a tab page.

@Component({
  template: '<iframe id="printpage" name="printpage" *ngIf="printSrc" [src]="printSrc"></iframe>',
  styleUrls: [ 'previewTab.scss' ]
})
export class PreviewTabPage {
  printSrc: SafeUrl;

  constructor(
    private navParams: NavParams,
    private sanitizer: DomSanitizer,
  ) {
    // item to print is passed as url parameter
    const itemId = navParams.get('itemId');

    // set print page source for iframe in template
    this.printSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.getAbsoluteUrl(itemId));
  }

  getAbsoluteUrl(itemId: string): string {
    // some code to generate an absolute url for your item
    return itemUrl;
  }
}

The iframe just loads the print route that renders a print component in the app. In this page the print might be triggered after the view is fully initialized. Another way could be a print button on the parent component that triggers the print on the iframe by window.frames["printpage"].print();.

@Component({
  templateUrl: './print.html',
  styleUrls: [ 'print.scss' ]
})
export class PrintPage implements AfterViewInit {

  constructor() {}

  ngAfterViewInit() {
    // wait some time, so all images or other async data are loaded / rendered.
    // print could be triggered after button press in the parent component as well.
    setTimeout(() => {
      // print current iframe
      window.print();
    }, 2000);
  }

}

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

If your PHP version is 5, try installing cURL by typing the following command in the terminal:

sudo apt-get install php5-curl

How to make a website secured with https

For business data, if the data is private I would use a secured connection, otherwise a forms authentication is sufficient.

If you do decide to use a secured connection, please note that I do not have experience with securing websites, I am just recanting off what I encountered during my own personal experience. If I am wrong in anyway, please feel free to correct me.

What should I do to prepare my website for https. (Do I need to alter the code / Config)

In order to enable SSL (Secure Sockets Layer) for your website, you would need to set-up a certificate, code or config is not altered.

I have enabled SSL for an internal web-server, by using OpenSSL and ActivePerl from this online tutorial. If this is used for a larger audience (my audience was less than 10 people) and is in the public domain, I suggest seeking professional alternatives.

Is SSL and https one and the same...

Not exactly, but they go hand in hand! SSL ensures that data is encrypted and decrypted back and forth while you are viewing the website, https is the URI that is need to access the secure website. You will notice when you try to access http://secure.mydomain.com it displays an error message.

Do I need to apply with someone to get some license or something.

You would not need to obtain a license, but rather a certificate. You can look into companies that offer professional services with securing websites, such as VeriSign as an example.

Do I need to make all my pages secured or only the login page...

Once your certificate is enabled for mydomain.com every page that falls under *.mydomain.com will be secured.

Testing for empty or nil-value string

The second clause does not need a !variable.nil? check—if evaluation reaches that point, variable.nil is guaranteed to be false (because of short-circuiting).

This should be sufficient:

variable = id if variable.nil? || variable.empty?

If you're working with Ruby on Rails, Object.blank? solves this exact problem:

An object is blank if it’s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are all blank.

Node.js: Difference between req.query[] and req.params

I want to mention one important note regarding req.query , because currently I am working on pagination functionality based on req.query and I have one interesting example to demonstrate to you...

Example:

// Fetching patients from the database
exports.getPatients = (req, res, next) => {

const pageSize = +req.query.pageSize;
const currentPage = +req.query.currentPage;

const patientQuery = Patient.find();
let fetchedPatients;

// If pageSize and currentPage are not undefined (if they are both set and contain valid values)
if(pageSize && currentPage) {
    /**
     * Construct two different queries 
     * - Fetch all patients 
     * - Adjusted one to only fetch a selected slice of patients for a given page
     */
    patientQuery
        /**
         * This means I will not retrieve all patients I find, but I will skip the first "n" patients
         * For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
         * 
         * Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
         * so I want to skip (7 * (2 - 1)) => 7 items
         */
        .skip(pageSize * (currentPage - 1))

        /**
         * Narrow dont the amound documents I retreive for the current page
         * Limits the amount of returned documents
         * 
         * For example: If I got 7 items per page, then I want to limit the query to only
         * return 7 items. 
         */
        .limit(pageSize);
}
patientQuery.then(documents => {
    res.status(200).json({
        message: 'Patients fetched successfully',
        patients: documents
    });
  });
};

You will noticed + sign in front of req.query.pageSize and req.query.currentPage

Why? If you delete + in this case, you will get an error, and that error will be thrown because we will use invalid type (with error message 'limit' field must be numeric).

Important: By default if you extracting something from these query parameters, it will always be a string, because it's coming the URL and it's treated as a text.

If we need to work with numbers, and convert query statements from text to number, we can simply add a plus sign in front of statement.

Multiple GitHub Accounts & SSH Config

A possibly simpler alternative to editing the ssh config file (as suggested in all other answers), is to configure an individual repository to use a different (e.g. non-default) ssh key.

Inside the repository for which you want to use a different key, run:

git config core.sshCommand 'ssh -i ~/.ssh/id_rsa_anotheraccount'

If your key is passhprase-protected and you don't want to type your password every time, you have to add it to the ssh-agent. Here's how to do it for ubuntu and here for macOS.

It should also be possible to scale this approach to multiple repositories using global git config and conditional includes (see example).

Get current index from foreach loop

You can't, because IEnumerable doesn't have an index at all... if you are sure your enumerable has less than int.MaxValue elements (or long.MaxValue if you use a long index), you can:

  1. Don't use foreach, and use a for loop, converting your IEnumerable to a generic enumerable first:

    var genericList = list.Cast<object>();
    for(int i = 0; i < genericList.Count(); ++i)
    {
       var row = genericList.ElementAt(i);
       /* .... */
    }
    
  2. Have an external index:

    int i = 0;
    foreach(var row in list)
    {
       /* .... */
       ++i;
    }
    
  3. Get the index via Linq:

    foreach(var rowObject in list.Cast<object>().Select((r, i) => new {Row=r, Index=i}))
    {
      var row = rowObject.Row;
      var i = rowObject.Index;
      /* .... */    
    }
    

In your case, since your IEnumerable is not a generic one, I'd rather use the foreach with external index (second method)... otherwise, you may want to make the Cast<object> outside your loop to convert it to an IEnumerable<object>.

Your datatype is not clear from the question, but I'm assuming object since it's an items source (it could be DataGridRow)... you may want to check if it's directly convertible to a generic IEnumerable<object> without having to call Cast<object>(), but I'll make no such assumptions.


All this said:

The concept of an "index" is foreign to an IEnumerable. An IEnumerable can be potentially infinite. In your example, you are using the ItemsSource of a DataGrid, so more likely your IEnumerable is just a list of objects (or DataRows), with a finite (and hopefully less than int.MaxValue) number of members, but IEnumerable can represent anything that can be enumerated (and an enumeration can potentially never end).

Take this example:

public static IEnumerable InfiniteEnumerable()
{
  var rnd = new Random();
  while(true)
  {
    yield return rnd.Next();
  }
}

So if you do:

foreach(var row in InfiniteEnumerable())
{
  /* ... */
}

Your foreach will be infinite: if you used an int (or long) index, you'll eventually overflow it (and unless you use an unchecked context, it'll throw an exception if you keep adding to it: even if you used unchecked, the index would be meaningless also... at some point -when it overflows- the index will be the same for two different values).

So, while the examples given work for a typical usage, I'd rather not use an index at all if you can avoid it.

Generate a random point within a circle (uniformly)

You can also use your intuition.

The area of a circle is pi*r^2

For r=1

This give us an area of pi. Let us assume that we have some kind of function fthat would uniformly distrubute N=10 points inside a circle. The ratio here is 10 / pi

Now we double the area and the number of points

For r=2 and N=20

This gives an area of 4pi and the ratio is now 20/4pi or 10/2pi. The ratio will get smaller and smaller the bigger the radius is, because its growth is quadratic and the N scales linearly.

To fix this we can just say

x = r^2
sqrt(x) = r

If you would generate a vector in polar coordinates like this

length = random_0_1();
angle = random_0_2pi();

More points would land around the center.

length = sqrt(random_0_1());
angle = random_0_2pi();

length is not uniformly distributed anymore, but the vector will now be uniformly distributed.

Is there a kind of Firebug or JavaScript console debug for Android?

If you don't mind forwarding through a 3rd party server, JSConsole is a rather useful remote debugger for JavaScript.

How to do a Jquery Callback after form submit?

I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.

<form id="form">
...
<button type="submit"></button>
</form>

<script>
$(document).ready(function() {
  $("#form_selector").submit(function() {

    $.ajax({
     type: "POST",
      url: "form_handler.php",
      data: $(this).serialize(),
      success: function() {
        // callback code here
       }
    })

  })
})
</script>

How to set variable from a SQL query?

To ASSIGN variables using a SQL select the best practice is as shown below

->DECLARE co_id INT ;
->DECLARE sname VARCHAR(10) ;

->SELECT course_id INTO co_id FROM course_details ;
->SELECT student_name INTO sname FROM course_details;

IF you have to assign more than one variable in a single line you can use this same SELECT INTO

->DECLARE val1 int;
->DECLARE val2 int;

->SELECT student__id,student_name INTO val1,val2 FROM student_details;

--HAPPY CODING-- 

Subscripts in plots in R

As other users have pointed out, we use expression(). I'd like to answer the original question which involves a comma in the subscript:

How can I write v 1,2 with 1,2 as subscripts?

plot(1:10, 11:20 , main=expression(v["1,2"]))

Also, I'd like to add the reference for those looking to find the full expression syntax in R plotting: For more information see the ?plotmath help page. Running demo(plotmath) will showcase many expressions and relevant syntax.

Remember to use * to join different types of text within an expression.

Here is some of the sample output from demo(plotmath):

enter image description here

Scroll to bottom of div with Vue.js

For those that haven't found a working solution above, I believe I have a working one. My specific use case was that I wanted to scroll to the bottom of a specific div - in my case a chatbox - whenever a new message was added to the array.

const container = this.$el.querySelector('#messagesCardContent');
        this.$nextTick(() => {
          // DOM updated
          container.scrollTop = container.scrollHeight;
        });

I have to use nextTick as we need to wait for the dom to update from the data change before doing the scroll!

I just put the above code in a watcher for the messages array, like so:

messages: {
      handler() {
        // this scrolls the messages to the bottom on loading data
        const container = this.$el.querySelector('#messagesCard');
        this.$nextTick(() => {
          // DOM updated
          container.scrollTop = container.scrollHeight;
        });
      },
      deep: true,
    }, 

SVN icon overlays not showing properly

In my case all icons suddenly disappeared .

Solution :

  1. Go To Task Manager and kill Explorer
  2. In Task Manager File (New Task (Run) ) => explorer

and all appeared again...

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

For me, I mistakenly added a parameter to the test method which caused initialization error.

Concept of void pointer in C programming

You should be aware that in C, unlike Java or C#, there is absolutely no possibility to successfully "guess" the type of object a void* pointer points at. Something similar to getClass() simply doesn't exist, since this information is nowhere to be found. For that reason, the kind of "generic" you are looking for always comes with explicit metainformation, like the int b in your example or the format string in the printf family of functions.

Get an object attribute

You can do the following:

class User(object):
    fullName = "John Doe"

    def __init__(self, name):
        self.SName = name

    def print_names(self):
        print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)

user = User('Test Name')

user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'

E.g any object attributes could be retrieved using istance.

How can I scale the content of an iframe?

If you want the iframe and its contents to scale when the window resizes, you can set the following to the window's resize event as well as the iframes onload event.

function()
{
    var _wrapWidth=$('#wrap').width();
    var _frameWidth=$($('#frame')[0].contentDocument).width();

    if(!this.contentLoaded)
      this.initialWidth=_frameWidth;
    this.contentLoaded=true;
    var frame=$('#frame')[0];

    var percent=_wrapWidth/this.initialWidth;

    frame.style.width=100.0/percent+"%";
    frame.style.height=100.0/percent+"%";

    frame.style.zoom=percent;
    frame.style.webkitTransform='scale('+percent+')';
    frame.style.webkitTransformOrigin='top left';
    frame.style.MozTransform='scale('+percent+')';
    frame.style.MozTransformOrigin='top left';
    frame.style.oTransform='scale('+percent+')';
    frame.style.oTransformOrigin='top left';
  };

This will make the iframe and its content scale to 100% width of the wrap div (or whatever percent you want). As an added bonus, you don't have to set the css of the frame to hard coded values since they'll all be set dynamically, you'll just need to worry about how you want the wrap div to display.

I've tested this and it works on chrome, IE11, and firefox.

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

First of all its not the Notepad++ problem for sure. Its your "String Matching problem"

The common string throughout all IE version is MSIE Check out the various userAgent strings at http://www.useragentstring.com/pages/Internet%20Explorer/

if(navigator.userAgent.indexOf("MSIE") != -1){
   alert('I am Internet Explorer!!');
}

Show Console in Windows Application?

Check this source code out. All commented code – used to create a console in a Windows app. Uncommented – to hide the console in a console app. From here. (Previously here.) Project reg2run.

// Copyright (C) 2005-2015 Alexander Batishchev (abatishchev at gmail.com)

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace Reg2Run
{
    static class ManualConsole
    {
        #region DllImport
        /*
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool AllocConsole();
        */

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        /*
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        private static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)]string fileName, [MarshalAs(UnmanagedType.I4)]int desiredAccess, [MarshalAs(UnmanagedType.I4)]int shareMode, IntPtr securityAttributes, [MarshalAs(UnmanagedType.I4)]int creationDisposition, [MarshalAs(UnmanagedType.I4)]int flagsAndAttributes, IntPtr templateFile);
        */

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool FreeConsole();

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        private static extern IntPtr GetStdHandle([MarshalAs(UnmanagedType.I4)]int nStdHandle);

        /*
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetStdHandle(int nStdHandle, IntPtr handle);
        */
        #endregion

        #region Methods
        /*
        public static void Create()
        {
            var ptr = GetStdHandle(-11);
            if (!AllocConsole())
            {
                throw new Win32Exception("AllocConsole");
            }
            ptr = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
            if (!SetStdHandle(-11, ptr))
            {
                throw new Win32Exception("SetStdHandle");
            }
            var newOut = new StreamWriter(Console.OpenStandardOutput());
            newOut.AutoFlush = true;
            Console.SetOut(newOut);
            Console.SetError(newOut);
        }
        */

        public static void Hide()
        {
            var ptr = GetStdHandle(-11);
            if (!CloseHandle(ptr))
            {
                throw new Win32Exception();
            }
            ptr = IntPtr.Zero;
            if (!FreeConsole())
            {
                throw new Win32Exception();
            }
        }
        #endregion
    }
}

Get selected value of a dropdown's item using jQuery

this will do the trick

$('#dropDownId').val();

ASP.NET DateTime Picker

@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control", @type = "date" } })

this works well

Fastest way(s) to move the cursor on a terminal command line?

I made a script to make the command line cursor move on mouse click :

  1. Enable xterm mouse tracking reporting
  2. Set readline bindings to consume the escape sequence generated by clicks

It can be found on github

More info on another post

Will work if echo -e "\e[?1000;1006;1015h" # Enable tracking print escape sequences on terminal when clicking with mouse

curl posting with header application/x-www-form-urlencoded

<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://xxxxxxxx.xxx/xx/xx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "dispnumber=567567567&extension=6");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));


// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($server_output == "OK") { ... } else { ... }

?>

How can I create a copy of an Oracle table without copying the data?

I used the method that you accepted a lot, but as someone pointed out it doesn't duplicate constraints (except for NOT NULL, I think).

A more advanced method if you want to duplicate the full structure is:

SET LONG 5000
SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME' ) FROM DUAL;

This will give you the full create statement text which you can modify as you wish for creating the new table. You would have to change the names of the table and all constraints of course.

(You could also do this in older versions using EXP/IMP, but it's much easier now.)

Edited to add If the table you are after is in a different schema:

SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME', 'OTHER_SCHEMA_NAME' ) FROM DUAL;

Using sed, how do you print the first 'N' characters of a line?

don't have to use grep either

an example:

sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file

How do I search within an array of hashes by hash values in ruby?

(Adding to previous answers (hope that helps someone):)

Age is simpler but in case of string and with ignoring case:

  • Just to verify the presence:

@fathers.any? { |father| father[:name].casecmp("john") == 0 } should work for any case in start or anywhere in the string i.e. for "John", "john" or "JoHn" and so on.

  • To find first instance/index:

@fathers.find { |father| father[:name].casecmp("john") == 0 }

  • To select all such indices:

@fathers.select { |father| father[:name].casecmp("john") == 0 }

Border length smaller than div width?

div{
    font-size: 25px;
    line-height: 27px;
    display:inline-block;
    width:200px;
    text-align:center;
}

div::after {
    background: #f1991b none repeat scroll 0 0;
    content: "";
    display: block;
    height: 3px;
    margin-top: 15px;
    width: 100px;
    margin:auto;
}

Convert .class to .java

This is for Mac users:

first of all you have to clarify where the class file is... so for example, in 'Terminal' (A Mac Application) you would type:

cd

then wherever you file is e.g:

cd /Users/CollarBlast/Desktop/JavaFiles/

then you would hit enter. After that you would do the command. e.g:

cd /Users/CollarBlast/Desktop/JavaFiles/ (then i would press enter...)

Then i would type the command:

javap -c JavaTestClassFile.class (then i would press enter again...)

and hopefully it should work!

Floating Div Over An Image

Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:

_x000D_
_x000D_
    .container {_x000D_
       border: 1px solid #DDDDDD;_x000D_
       width: 200px;_x000D_
       height: 200px;_x000D_
       position: relative;_x000D_
    }_x000D_
    .tag {_x000D_
       float: left;_x000D_
       position: absolute;_x000D_
       left: 0px;_x000D_
       top: 0px;_x000D_
       z-index: 1000;_x000D_
       background-color: #92AD40;_x000D_
       padding: 5px;_x000D_
       color: #FFFFFF;_x000D_
       font-weight: bold;_x000D_
    }
_x000D_
<div class="container">_x000D_
       <div class="tag">Featured</div>_x000D_
       <img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
_x000D_
_x000D_

The key is the container has to be positioned relative and the tag positioned absolute.

SQL: How To Select Earliest Row

SELECT company
   , workflow
   , MIN(date)
FROM workflowTable
GROUP BY company
       , workflow

How to install numpy on windows using pip install?

As of March 2016, pip install numpy works on Windows without a Fortran compiler. See here.

pip install scipy still tries to use a compiler.

July 2018: mojoken reports pip install scipy working on Windows without a Fortran compiler.

C - function inside struct

It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;

        pno (*AddClient)(client_t *);    
};

pno client_t_AddClient(client_t *self) { /* code */ }

int main()
{

    client_t client;
    client.AddClient = client_t_AddClient; // probably really done in some init fn

    //code ..

    client.AddClient(&client);

}

It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.

how to refresh my datagridview after I add new data

In the code of the button that saves the changes to the database eg the update button, add the following lines of code:

MyDataGridView.DataSource = MyTableBindingSource

MyDataGridView.Update()

MyDataGridView.RefreshEdit()

fatal: Not a valid object name: 'master'

First off, when you create a "bare repository", you're not going to be doing any work with it (it doesn't contain a working copy, so the git branch command is not useful).

Now, the reason you wouldn't have a master branch even after doing a git init is that there are no commits: when you create your first commit, you will then have a master branch.

Transfer data between databases with PostgreSQL

Just like leonbloy suggested, using two schemas in a database is the way to go. Suppose a source schema (old DB) and a target schema (new DB), you can try something like this (you should consider column names, types, etc.):

INSERT INTO target.Awards SELECT * FROM source.Nominations;

Can someone explain mappedBy in JPA and Hibernate?

You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).

Should I use JSLint or JSHint JavaScript validation?

[EDIT]
This answer has been edited. I'm leaving the original answer below for context (otherwise the comments wouldn't make sense).

When this question was originally asked, JSLint was the main linting tool for JavaScript. JSHint was a new fork of JSLint, but had not yet diverged much from the original.

Since then, JSLint has remained pretty much static, while JSHint has changed a great deal - it has thrown away many of JSLint's more antagonistic rules, has added a whole load of new rules, and has generally become more flexible. Also, another tool ESLint is now available, which is even more flexible and has more rule options.

In my original answer, I said that you should not force yourself to stick to JSLint's rules; as long as you understood why it was throwing a warning, you could make a judgement for yourself about whether to change the code to resolve the warning or not.

With the ultra-strict ruleset of JSLint from 2011, this was reasonable advice -- I've seen very few JavaScript codesets that could pass a JSLint test. However with the more pragmatic rules available in today's JSHint and ESLint tools, it is a much more realistic proposition to try to get your code passing through them with zero warnings.

There may still occasionally be cases where a linter will complain about something that you've done intentionally -- for example, you know that you should always use === but just this one time you have a good reason to use ==. But even then, with ESLint you have the option to specify eslint-disable around the line in question so you can still have a passing lint test with zero warnings, with the rest of your code obeying the rule. (just don't do that kind of thing too often!)


[ORIGINAL ANSWER FOLLOWS]

By all means use JSLint. But don't get hung up on the results and on fixing everything that it warns about. It will help you improve your code, and it will help you find potential bugs, but not everything that JSLint complains about turns out to be a real problem, so don't feel like you have to complete the process with zero warnings.

Pretty much any Javascript code with any significant length or complexity will produce warnings in JSLint, no matter how well written it is. If you don't believe me, try running some popular libraries like JQuery through it.

Some JSLint warnings are more valuable than others: learn which ones to watch out for, and which ones are less important. Every warning should be considered, but don't feel obliged to fix your code to clear any given warning; it's perfectly okay to look at the code and decide you're happy with it; there are times when things that JSlint doesn't like are actually the right thing to do.

Select a Dictionary<T1, T2> with LINQ

The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.

class SomeObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

SomeObject[] objects = new SomeObject[]
{
    new SomeObject { ID = 1, Name = "Hello" },
    new SomeObject { ID = 2, Name = "World" }
};

Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);

Then objectDictionary[1] Would contain the value "Hello"

Convert php array to Javascript

I use a fake php array

<?php 
       // instead to create your array like this
       $php_array = ["The","quick","brown","fox","jumps","over","the","lazy","dog"];

       // do it like this (a simple variable but with separator)
       $php_fake_array = "The,quick,brown,fox,jumps,over,the,lazy,dog";
?>

<script type="text/javascript">

        // use the same separator for the JS split() function
        js_array = '<?php echo $php_fake_array; ?>'.split(',');

</script>

if ever your array is unknown (already made)

<?php 
        $php_array = file('my_file.txt');
        $php_fake_array = "";

        // transform your array with concatenate like this
        foreach ($php_array as $cell){

            // since this array is unknown, use clever separator
            $php_fake_array .= $cell.",,,,,"; 
        }
?>

<script type="text/javascript">

        // use the same separator for the JS split() function
        js_array = '<?php echo $php_fake_array; ?>'.split(',,,,,');

</script>

What is difference between Errors and Exceptions?

In general error is which nobody can control or guess when it occurs.Exception can be guessed and can be handled. In Java Exception and Error are sub class of Throwable.It is differentiated based on the program control.Error such as OutOfMemory Error which no programmer can guess and can handle it.It depends on dynamically based on architectire,OS and server configuration.Where as Exception programmer can handle it and can avoid application's misbehavior.For example if your code is looking for a file which is not available then IOException is thrown.Such instances programmer can guess and can handle it.

Convert double to BigDecimal and set BigDecimal Precision

You want to try String.format("%f", d), which will print your double in decimal notation. Don't use BigDecimal at all.

Regarding the precision issue: You are first storing 47.48 in the double c, then making a new BigDecimal from that double. The loss of precision is in assigning to c. You could do

BigDecimal b = new BigDecimal("47.48")

to avoid losing any precision.

How to select the last column of dataframe

Somewhat similar to your original attempt, but more Pythonic, is to use Python's standard negative-indexing convention to count backwards from the end:

df[df.columns[-1]]

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

@Dinh Nhat, your setter method looks wrong because you put a primitive type there again and it should be:

public void setClient_os_id(Integer clientOsId) {
client_os_id = clientOsId;
}

Dependency injection with Jersey 2.0

For me it works without the AbstractBinder if I include the following dependencies in my web application (running on Tomcat 8.5, Jersey 2.27):

<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>${jersey-version}</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.ext.cdi</groupId>
    <artifactId>jersey-cdi1x</artifactId>
    <version>${jersey-version}</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>${jersey-version}</version>
</dependency>

It works with CDI 1.2 / CDI 2.0 for me (using Weld 2 / 3 respectively).

Youtube API Limitations

Version 3 of the YouTube Data API has concrete quota numbers listed in the Google API Console where you register for your API Key. You can use 10,000 units per day. Projects that had enabled the YouTube Data API before April 20, 2016, have a default quota of 50M/day.

You can read about what a unit is here: https://developers.google.com/youtube/v3/getting-started#quota

  • A simple read operation that only retrieves the ID of each returned resource has a cost of approximately 1 unit.
  • A write operation has a cost of approximately 50 units.
  • A video upload has a cost of approximately 1600 units.

If you hit the limits, Google will stop returning results until your quota is reset. You can apply for more than 1M requests per day, but you will have to pay for those extra requests.

Also, you can read about why Google has deferred support to StackOverflow on their YouTube blog here: https://youtube-eng.googleblog.com/2012/09/the-youtube-api-on-stack-overflow_14.html

There are a number of active members on the YouTube Developer Relations team here including Jeff Posnick, Jarek Wilkiewicz, and Ibrahim Ulukaya who all have knowledge of Youtube internals...

UPDATE: Increased the quota numbers to reflect current limits on December 10, 2013.

UPDATE: Decreased the quota numbers from 50M to 1M per day to reflect current limits on May 13, 2016.

UPDATE: Decreased the quota numbers from 1M to 10K per day as of January 11, 2019.

Comparing double values in C#

It's a standard problem due to how the computer stores floating point values. Search here for "floating point problem" and you'll find tons of information.

In short – a float/double can't store 0.1 precisely. It will always be a little off.

You can try using the decimal type which stores numbers in decimal notation. Thus 0.1 will be representable precisely.


You wanted to know the reason:

Float/double are stored as binary fractions, not decimal fractions. To illustrate:

12.34 in decimal notation (what we use) means

1 * 101 + 2 * 100 + 3 * 10-1 + 4 * 10-2

The computer stores floating point numbers in the same way, except it uses base 2: 10.01 means

1 * 21 + 0 * 20 + 0 * 2-1 + 1 * 2-2

Now, you probably know that there are some numbers that cannot be represented fully with our decimal notation. For example, 1/3 in decimal notation is 0.3333333…. The same thing happens in binary notation, except that the numbers that cannot be represented precisely are different. Among them is the number 1/10. In binary notation that is 0.000110011001100….

Since the binary notation cannot store it precisely, it is stored in a rounded-off way. Hence your problem.

jquery: how to get the value of id attribute?

You can also try this way

<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>

jquery

$('.select_continent').click(function () {
alert($(this).data('value'));
});

Good luck !!!!

Node.js - use of module.exports as a constructor

This question doesn't really have anything to do with how require() works. Basically, whatever you set module.exports to in your module will be returned from the require() call for it.

This would be equivalent to:

var square = function(width) {
  return {
    area: function() {
      return width * width;
    }
  };
}

There is no need for the new keyword when calling square. You aren't returning the function instance itself from square, you are returning a new object at the end. Therefore, you can simply call this function directly.

For more intricate arguments around new, check this out: Is JavaScript's "new" keyword considered harmful?

How to get 'System.Web.Http, Version=5.2.3.0?

In Package Manager Console

Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

asp.net Button OnClick event not firing

Even i had two forms one for desktop view and other for mobile view , Removed one formed worked for me . I dint knew asp.page should have only one form.

Create stacked barplot where each stack is scaled to sum to 100%

Chris Beeley is rigth, you only need the proportions by column. Using your data is:

 your_matrix<-( 
               rbind(
                       c(23,234,324), 
                       c(34,534,12), 
                       c(56,324,124), 
                       c(34,234,124),
                       c(123,534,654)
                    )
                )

 barplot(prop.table(your_matrix, 2) )

Gives:

enter image description here

413 Request Entity Too Large - File Upload Issue

Use:

php -i

command or add:

phpinfo();

to get the location of configuration file.

Update these variables according to your need and server

max_input_time = 24000
max_execution_time = 24000
upload_max_filesize = 12000M
post_max_size = 24000M
memory_limit = 12000M

On Linux you will need to restart nginx / apache and phpfpm service so the new ini settings are loaded. On xampp, ammps you can restart these from control panel that comes with such applications.

How can I initialize an array without knowing it size?

Here is the code for you`r class . but this also contains lot of refactoring. Please add a for each rather than for. cheers :)

 static int isLeft(ArrayList<String> left, ArrayList<String> right)

    {
        int f = 0;
        for (int i = 0; i < left.size(); i++) {
            for (int j = 0; j < right.size(); j++)

            {
                if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
                    System.out.println("Grammar is left recursive");
                    f = 1;
                }

            }
        }
        return f;

    }

    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<String> left = new ArrayList<String>();
        ArrayList<String> right = new ArrayList<String>();


        Scanner sc = new Scanner(System.in);
        System.out.println("enter no of prod");
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            System.out.println("enter left prod");
            String leftText = sc.next();
            left.add(leftText);
            System.out.println("enter right prod");
            String rightText = sc.next();
            right.add(rightText);
        }

        System.out.println("the productions are");
        for (int i = 0; i < n; i++) {
            System.out.println(left.get(i) + "->" + right.get(i));
        }
        int flag;
        flag = isLeft(left, right);
        if (flag == 1) {
            System.out.println("Removing left recursion");
        } else {
            System.out.println("No left recursion");
        }

    }

Is it possible to disable scrolling on a ViewPager

I created a Kotlin version based on converting this answer from Java: https://stackoverflow.com/a/13437997/8023278

There is no built in way to disable swiping between pages of a ViewPager, what's required is an extension of ViewPager that overrides onTouchEvent and onInterceptTouchEvent to prevent the swiping action. To make it more generalised we can add a method setSwipePagingEnabled to enable/disable swiping between pages.

class SwipeLockableViewPager(context: Context, attrs: AttributeSet): ViewPager(context, attrs) {
    private var swipeEnabled = false

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return when (swipeEnabled) {
            true -> super.onTouchEvent(event)
            false -> false
        }
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        return when (swipeEnabled) {
            true -> super.onInterceptTouchEvent(event)
            false -> false
        }
    }

    fun setSwipePagingEnabled(swipeEnabled: Boolean) {
        this.swipeEnabled = swipeEnabled
    }
}

Then in our layout xml we use our new SwipeLockableViewPager instead of the standard ViewPager

<mypackage.SwipeLockableViewPager 
        android:id="@+id/myViewPager" 
        android:layout_height="match_parent" 
        android:layout_width="match_parent" />

Now in our activity/fragment we can call myViewPager.setSwipePagingEnabled(false) and users won't be able to swipe between pages


UPDATE

As of 2020 we now have ViewPager2. If you migrate to ViewPager2 there is a built in method to disable swiping: myViewPager2.isUserInputEnabled = false

document.all vs. document.getElementById

document.querySelectorAll (and its document.querySelector() variant that returns the first found element) is much, much more powerful. You can easily:

  • get an entire collection with document.querySelectorAll("*"), effectively emulating non-standard document.all property;
  • use document.querySelector("#your-id"), effectively emulating document.getElementById() function;
  • use document.querySelectorAll(".your-class"), effectively emulating document.getElementsByClassName() function;
  • use document.querySelectorAll("form") instead of document.forms, and document.querySelectorAll("a") instead of document.links;
  • and perform any much more complex DOM querying (using any available CSS selector) that just cannot be covered with other document builtins.

Unified querying API is the way to go. Even if document.all would be in the standard, it's just inconvenient.

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table

How to set a default value with Html.TextBoxFor?

you can try this

<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>

How to lazy load images in ListView in Android

I use droidQuery. There are two mechanisms for loading an image from a URL. The first (shorthand) is simply:

$.with(myView).image(url);

This can be added into an ArrayAdapter's getView(...) method very easily.


The longhand method will give a lot more control, and has options not even discussed here (such as cacheing and callbacks), but a basic implementation that specifies the output size as 200px x 200px can be found here:

$.ajax(new AjaxOptions().url(url)
    .type("GET")
    .dataType("image")
    .imageWidth(200).imageHeight(200)
    .success(new Function() {
        @Override
        public void invoke($ droidQuery, Object... params) {
            myImageView.setImageBitmap((Bitmap) params[0]);
        }
    })
    .error(new Function() {
        @Override
        public void invoke($ droidQuery, Object... params) {
            AjaxError e = (AjaxError) params[0];
            Log.e("$", "Error " + e.status + ": " + e.error);
        }
    })
);

How to set the height and the width of a textfield in Java?

     f.setLayout(null);

add the above lines ( f is a JFrame or a Container where you have added the JTestField )

But try to learn 'LayoutManager' in java ; refer to other answers for the links of the tutorials .Or try This http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

Change working directory in my current shell context when running Node script

There is no built-in method for Node to change the CWD of the underlying shell running the Node process.

You can change the current working directory of the Node process through the command process.chdir().

var process = require('process');
process.chdir('../');

When the Node process exists, you will find yourself back in the CWD you started the process in.

How to get time difference in minutes in PHP

This will help....

function get_time($date,$nosuffix=''){
    $datetime = new DateTime($date);
    $interval = date_create('now')->diff( $datetime );
    if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
    else $suffix='';
    //return $interval->y;
    if($interval->y >=1)        {$count = date(VDATE, strtotime($date)); $text = '';}
    elseif($interval->m >=1)    {$count = date('M d', strtotime($date)); $text = '';}
    elseif($interval->d >=1)    {$count = $interval->d; $text = 'day';} 
    elseif($interval->h >=1)    {$count = $interval->h; $text = 'hour';}
    elseif($interval->i >=1)    {$count = $interval->i; $text = 'minute';}
    elseif($interval->s ==0)    {$count = 'Just Now'; $text = '';}
    else                        {$count = $interval->s; $text = 'second';}
    if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
    return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;     
}

How can I get sin, cos, and tan to use degrees instead of radians?

You can use a function like this to do the conversion:

function toDegrees (angle) {
  return angle * (180 / Math.PI);
}

Note that functions like sin, cos, and so on do not return angles, they take angles as input. It seems to me that it would be more useful to you to have a function that converts a degree input to radians, like this:

function toRadians (angle) {
  return angle * (Math.PI / 180);
}

which you could use to do something like tan(toRadians(45)).

Angular Directive refresh on parameter change

What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:

angular.module('myApp').directive('conversation', function() {
  return {
    restrict: 'E',
    replace: true,
    compile: function(tElement, attr) {
      attr.$observe('typeId', function(data) {
            console.log("Updated data ", data);
      }, true);

    }
  };
});

Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.

If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:

<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>

And in the directive:

angular.module('myApp').directive('conversation', function() {
  return {
    scope: {
      typeId: '=',
    },
    link: function(scope, elm, attr) {

      scope.$watch('typeId', function(newValue, oldValue) {
          if (newValue !== oldValue) {
            // You actions here
            console.log("I got the new value! ", newValue);
          }
      }, true);

    }
  };
});

disable viewport zooming iOS 10+ safari?

I tried the previous answer about pinch-to-zoom

document.documentElement.addEventListener('touchstart', function (event) {
    if (event.touches.length > 1) {
        event.preventDefault();
    }
}, false);

however sometime the screen still zoom when the event.touches.length > 1 I found out the best way is using touchmove event, to avoid any finger moving on the screen. The code will be something like this:

document.documentElement.addEventListener('touchmove', function (event) {
    event.preventDefault();      
}, false);

Hope it will help.

Create session factory in Hibernate 4

The following expresses the experience I had with hibernate 4.0.0.Final.

The javadoc (distributed under LGPL license) of org.hibernate.cfg.Configuration class states that:

NOTE : This will be replaced by use of ServiceRegistryBuilder and org.hibernate.metamodel.MetadataSources instead after the 4.0 release at which point this class will become deprecated and scheduled for removal in 5.0. See HHH-6183, HHH-2578 and HHH-6586 for details

After looking at issue 2578, i used something like this:

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().configure().buildServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addResource("some_mapping.hbm.xml")
SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory();

For it to start reading configuration, i had to modify my hibernate 3.2.6 configuration and mapping files to use xmlns="http://www.hibernate.org/xsd/hibernate-configuration" and xmlns="http://www.hibernate.org/xsd/hibernate-mapping" and also remove the dtd specifications.

I couldn't find a way for it to inspect mappings defined in hibernate.cfg.xml and hibernate. prefix for hibernate-related properties in hibernate.cfg.xml is no longer optional.

This might work for some.

I, for one, ran into some error because mapping files contained <cache usage="read-write" /> and ended up using deprecated Configuration way:

Configuration configuration = new Configuration().configure();
SessionFactoryImpl sessionFactory = (SessionFactoryImpl) configuration.buildSessionFactory();
EventListenerRegistry listenerRegistry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
SolrIndexEventListener indexListener = new SolrIndexEventListener(); // a SaveOrUpdateEventListener i wanted to attach
listenerRegistry.appendListeners(EventType.SAVE_UPDATE, indexListener);

I had to programatically append event listeners because Configuration no longer looks for them in hibernate.cfg.xml

How can I split a delimited string into an array in PHP?

Use explode() or preg_split() function to split the string in php with given delimiter

// Use preg_split() function 
$string = "123,456,78,000";  
$str_arr = preg_split ("/\,/", $string);  
print_r($str_arr); 
  
// use of explode 
$string = "123,46,78,000"; 
$str_arr = explode (",", $string);  
print_r($str_arr); 

What does `ValueError: cannot reindex from a duplicate axis` mean?

This can also be a cause for this[:) I solved my problem like this]

It may happen even if you are trying to insert a dataframe type column inside dataframe

you can try this

df['my_new']=pd.Series(my_new.values)

How to check if a registry value exists using C#?

  RegistryKey rkSubKey = Registry.CurrentUser.OpenSubKey(" Your Registry Key Location", false);
        if (rkSubKey == null)
        {
           // It doesn't exist
        }
        else
        {
           // It exists and do something if you want to
         }

Getting fb.me URL

You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com

Can I load a UIImage from a URL?

get DLImageLoader and try folowing code

   [DLImageLoader loadImageFromURL:imageURL
                          completed:^(NSError *error, NSData *imgData) {
                              imageView.image = [UIImage imageWithData:imgData];
                              [imageView setContentMode:UIViewContentModeCenter];

                          }];

Another typical real-world example of using DLImageLoader, which may help someone...

PFObject *aFacebookUser = [self.fbFriends objectAtIndex:thisRow];
NSString *facebookImageURL = [NSString stringWithFormat:
    @"http://graph.facebook.com/%@/picture?type=large",
    [aFacebookUser objectForKey:@"id"] ];

__weak UIImageView *loadMe = self.userSmallAvatarImage;
// ~~note~~ you my, but usually DO NOT, want a weak ref
[DLImageLoader loadImageFromURL:facebookImageURL
   completed:^(NSError *error, NSData *imgData)
    {
    if ( loadMe == nil ) return;

    if (error == nil)
        {
        UIImage *image = [UIImage imageWithData:imgData];
        image = [image ourImageScaler];
        loadMe.image = image;
        }
    else
        {
        // an error when loading the image from the net
        }
    }];

As I mention above another great library to consider these days is Haneke (unfortunately it's not as lightweight).

Background image jumps when address bar hides iOS/Android/Mobile Chrome

this is my solution to resolve this issue, i have added comments directly on code. I've tested this solution and works fine. Hope we will be useful for everyone has the same problem.

//remove height property from file css because we will set it to first run of page
//insert this snippet in a script after declarations of your scripts in your index

var setHeight = function() {    
  var h = $(window).height();   
  $('#bg1, #bg2').css('height', h);
};

setHeight(); // at first run of webpage we set css height with a fixed value

if(typeof window.orientation !== 'undefined') { // this is more smart to detect mobile devices because desktop doesn't support this property
  var query = window.matchMedia("(orientation:landscape)"); //this is is important to verify if we put 
  var changeHeight = function(query) {                      //mobile device in landscape mode
    if (query.matches) {                                    // if yes we set again height to occupy 100%
      setHeight(); // landscape mode
    } else {                                                //if we go back to portrait we set again
      setHeight(); // portrait mode
    }
  }
  query.addListener(changeHeight);                          //add a listner too this event
} 
else { //desktop mode                                       //this last part is only for non mobile
  $( window ).resize(function() {                           // so in this case we use resize to have
    setHeight();                                            // responsivity resisizing browser window
  }); 
};

return, return None, and no return at all?

In terms of functionality these are all the same, the difference between them is in code readability and style (which is important to consider)

Converting a value to 2 decimal places within jQuery

You need to use the .toFixed() method

It takes as a parameter the number of digits to show after the decimal point.

$(document).ready(function() {
  $('.add').click(function() {
     var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
     $('#total').text( value.toFixed(2) );
  });
})

How to display a confirmation dialog when clicking an <a> link?

USING PHP, HTML AND JAVASCRIPT for prompting

Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.

<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>

the reason i used php code in the middle is because i cant use it from the beginning..

the code below doesnt work for me:-

echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";

and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.

100% Min Height CSS layout

I am using the following one: CSS Layout - 100 % height

Min-height

The #container element of this page has a min-height of 100%. That way, if the content requires more height than the viewport provides, the height of #content forces #container to become longer as well. Possible columns in #content can then be visualised with a background image on #container; divs are not table cells, and you don't need (or want) the physical elements to create such a visual effect. If you're not yet convinced; think wobbly lines and gradients instead of straight lines and simple color schemes.

Relative positioning

Because #container has a relative position, #footer will always remain at its bottom; since the min-height mentioned above does not prevent #container from scaling, this will work even if (or rather especially when) #content forces #container to become longer.

Padding-bottom

Since it is no longer in the normal flow, padding-bottom of #content now provides the space for the absolute #footer. This padding is included in the scrolled height by default, so that the footer will never overlap the above content.

Scale the text size a bit or resize your browser window to test this layout.

html,body {
    margin:0;
    padding:0;
    height:100%; /* needed for container min-height */
    background:gray;

    font-family:arial,sans-serif;
    font-size:small;
    color:#666;
}

h1 { 
    font:1.5em georgia,serif; 
    margin:0.5em 0;
}

h2 {
    font:1.25em georgia,serif; 
    margin:0 0 0.5em;
}
    h1, h2, a {
        color:orange;
    }

p { 
    line-height:1.5; 
    margin:0 0 1em;
}

div#container {
    position:relative; /* needed for footer positioning*/
    margin:0 auto; /* center, not in IE5 */
    width:750px;
    background:#f0f0f0;

    height:auto !important; /* real browsers */
    height:100%; /* IE6: treaded as min-height*/

    min-height:100%; /* real browsers */
}

div#header {
    padding:1em;
    background:#ddd url("../csslayout.gif") 98% 10px no-repeat;
    border-bottom:6px double gray;
}
    div#header p {
        font-style:italic;
        font-size:1.1em;
        margin:0;
    }

div#content {
    padding:1em 1em 5em; /* bottom padding for footer */
}
    div#content p {
        text-align:justify;
        padding:0 1em;
    }

div#footer {
    position:absolute;
    width:100%;
    bottom:0; /* stick to bottom */
    background:#ddd;
    border-top:6px double gray;
}
div#footer p {
    padding:1em;
    margin:0;
}

Works fine for me.

Automatically size JPanel inside JFrame

You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);

This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.

Swift addsubview and remove it

I've a view inside my custom CollectionViewCell, and embedding a graph on that view. In order to refresh it, I've to check if there is already a graph placed on that view, remove it and then apply new. Here's the solution

cell.cellView.addSubview(graph)
graph.tag = 10

now, in code block where you want to remove it (in your case gestureRecognizerFunction)

if let removable = cell.cellView.viewWithTag(10){
   removable.removeFromSuperview()
}

to embed it again

cell.cellView.addSubview(graph)
graph.tag = 10

CSS full screen div with text in the middle

The standard approach is to give the centered element fixed dimensions, and place it absolutely:

<div class='fullscreenDiv'>
    <div class="center">Hello World</div>
</div>?

.center {
    position: absolute;
    width: 100px;
    height: 50px;
    top: 50%;
    left: 50%;
    margin-left: -50px; /* margin is -0.5 * dimension */
    margin-top: -25px; 
}?

Mongoose limit/offset and count query

After having to tackle this issue myself, I would like to build upon user854301's answer.

Mongoose ^4.13.8 I was able to use a function called toConstructor() which allowed me to avoid building the query multiple times when filters are applied. I know this function is available in older versions too but you'll have to check the Mongoose docs to confirm this.

The following uses Bluebird promises:

let schema = Query.find({ name: 'bloggs', age: { $gt: 30 } });

// save the query as a 'template'
let query = schema.toConstructor();

return Promise.join(
    schema.count().exec(),
    query().limit(limit).skip(skip).exec(),

    function (total, data) {
        return { data: data, total: total }
    }
);

Now the count query will return the total records it matched and the data returned will be a subset of the total records.

Please note the () around query() which constructs the query.

How can I compare a date and a datetime in Python?

Here is another take, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:

datetime.datetime(d.year, d.month, d.day)

Suggestion:

from datetime import datetime

def ensure_datetime(d):
    """
    Takes a date or a datetime as input, outputs a datetime
    """
    if isinstance(d, datetime):
        return d
    return datetime.datetime(d.year, d.month, d.day)

def datetime_cmp(d1, d2):
    """
    Compares two timestamps.  Tolerates dates.
    """
    return cmp(ensure_datetime(d1), ensure_datetime(d2))

How to change password using TortoiseSVN?

Password changes are handled by the subversion server administrator. As a user there is no password change option.

Check with your server admin.

If you are the admin, find your SVN Server installation. If you don't know where it is, it could be listed in Start->Programs, running under services in Start->Control Panel->Services or it could be listed under C:\Program Files.

The SVN Server should have an application to run to add/change/delete authentication and users.

How can I create Min stl priority_queue?

In C++11 you could also create an alias for convenience:

template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;

And use it like this:

min_heap<int> my_heap;

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

DevTools failed to load SourceMap: Could not load content for chrome-extension

That's because Chrome added support for source maps.

Go to the developer tools (F12 in the browser), then select the three dots in the upper right corner, and go to Settings.

Then, look for Sources, and disable the options: "Enable javascript source maps" "Enable CSS source maps"

If you do that, that would get rid of the warnings. It has nothing to do with your code. Check the developer tools in other pages and you will see the same warning.

How do I remove/delete a virtualenv?

The following command works for me.

rm -rf /path/to/virtualenv

No resource found - Theme.AppCompat.Light.DarkActionBar

If you are using Android Studio then just add the dependency

dependencies {
     implementation 'com.android.support:appcompat-v7:25.0.1'
}

to app/build.gradle. And that will work

Prevent typing non-numeric in input type number

This solution seems to be working well for me. It builds on @pavok's solution by preserving ctrl key commands.

document.querySelector("input").addEventListener("keypress", function (e) {
  if (
    e.key.length === 1 && e.key !== '.' && isNaN(e.key) && !e.ctrlKey || 
    e.key === '.' && e.target.value.toString().indexOf('.') > -1
  ) {
    e.preventDefault();
  }
});

Specified cast is not valid?

From your comment:

this line DateTime Date = reader.GetDateTime(0); was throwing the exception

The first column is not a valid DateTime. Most likely, you have multiple columns in your table, and you're retrieving them all by running this query:

SELECT * from INFO

Replace it with a query that retrieves only the two columns you're interested in:

SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO

Then try reading the values again:

var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1);  // equivalent to time(7) from your database

Or:

var Date = Convert.ToDateTime(reader["YOUR_DATE_COLUMN"]);
var Time = (TimeSpan)reader["YOUR_TIME_COLUMN"];

jQuery if div contains this text, replace that part of the text

Very simple just use this code, it will preserve the HTML, while removing unwrapped text only:

jQuery(function($){

    // Replace 'td' with your html tag
    $("td").html(function() { 

    // Replace 'ok' with string you want to change, you can delete 'hello everyone' to remove the text
          return $(this).html().replace("ok", "hello everyone");  

    });
});

Here is full example: https://blog.hfarazm.com/remove-unwrapped-text-jquery/

Setting and getting localStorage with jQuery

You said you are attempting to get the text from a div and store it on local storage.

Please Note: Text and Html are different. In the question you mentioned text. html() will return Html content like <a>example</a>. if you want to get Text content then you have to use text() instead of html() then the result will be example instead of <a>example<a>. Anyway, I am using your terminology let it be Text.

Step 1: get the text from div.

what you did is not get the text from div but set the text to a div.

$('#test').html("Test"); 

is actually setting text to div and the output will be a jQuery object. That is why it sets it as [object Object].

To get the text you have to write like this
$('#test').html();

This will return a string not an object so the result will be Test in your case.

Step 2: set it to local storage.

Your approach is correct and you can write it as

localStorage.key=value

But the preferred approach is

localStorage.setItem(key,value); to set

localStorage.getItem(key); to get.

key and value must be strings.

so in your context code will become

$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);

But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like a=10; b=a; a=b;

If you are facing any other problems please update your question accordingly.

How to check Spark Version

Addition to @Binary Nerd

If you are using Spark, use the following to get the Spark version:

spark-submit --version

or

Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster

Appending to an object

As an alternative, in ES6, spread syntax might be used. ${Object.keys(alerts).length + 1} returns next id for alert.

_x000D_
_x000D_
let alerts = { _x000D_
    1: {app:'helloworld',message:'message'},_x000D_
    2: {app:'helloagain',message:'another message'}_x000D_
};_x000D_
_x000D_
alerts = {_x000D_
  ...alerts, _x000D_
  [`${Object.keys(alerts).length + 1}`]: _x000D_
  { _x000D_
    app: `helloagain${Object.keys(alerts).length + 1}`,message: 'next message' _x000D_
  } _x000D_
};_x000D_
_x000D_
console.log(alerts);
_x000D_
_x000D_
_x000D_

Java - How to create new Entry (key, value)

Why Map.Entry? I guess something like a key-value pair is fit for the case.

Use java.util.AbstractMap.SimpleImmutableEntry or java.util.AbstractMap.SimpleEntry

ImportError: No module named win32com.client

pip install pywin32 didn't work for me but pypiwin32 did.

How can I conditionally import an ES6 module?

obscuring it in an eval worked for me, hiding it from the static analyzer ...

if (typeof __CLI__ !== 'undefined') {
  eval("require('fs');")
}

What is the best way to extract the first word from a string in Java?

I know this question has been answered already, but I have another solution (For those still searching for answers) which can fit on one line: It uses the split functionality but only gives you the 1st entity.

String test = "123_456";
String value = test.split("_")[0];
System.out.println(value);

The output will show:

123

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Find number of decimal places in decimal value regardless of culture

So far, nearly all of the listed solutions are allocating GC Memory, which is very much the C# way to do things but far from ideal in performance critical environments. (The ones that do not allocate use loops and also don't take trailing zeros into consideration.)

So to avoid GC Allocs, you can just access the scale bits in an unsafe context. That might sound fragile but as per Microsoft's reference source, the struct layout of decimal is Sequential and even has a comment in there, not to change the order of the fields:

    // NOTE: Do not change the order in which these fields are declared. The
    // native methods in this class rely on this particular order.
    private int flags;
    private int hi;
    private int lo;
    private int mid;

As you can see, the first int here is the flags field. From the documentation and as mentioned in other comments here, we know that only the bits from 16-24 encode the scale and that we need to avoid the 31st bit which encodes the sign. Since int is the size of 4 bytes, we can safely do this:

internal static class DecimalExtensions
{
  public static byte GetScale(this decimal value)
  {
    unsafe
    {
      byte* v = (byte*)&value;
      return v[2];
    }
  }
}

This should be the most performant solution since there is no GC alloc of the bytes array or ToString conversions. I've tested it against .Net 4.x and .Net 3.5 in Unity 2019.1. If there are any versions where this does fail, please let me know.

Edit:

Thanks to @Zastai for reminding me about the possibility to use an explicit struct layout to practically achieve the same pointer logic outside of unsafe code:

[StructLayout(LayoutKind.Explicit)]
public struct DecimalHelper
{
    const byte k_SignBit = 1 << 7;

    [FieldOffset(0)]
    public decimal Value;

    [FieldOffset(0)]
    public readonly uint Flags;
    [FieldOffset(0)]
    public readonly ushort Reserved;
    [FieldOffset(2)]
    byte m_Scale;
    public byte Scale
    {
        get
        {
            return m_Scale;
        }
        set
        {
            if(value > 28)
                throw new System.ArgumentOutOfRangeException("value", "Scale can't be bigger than 28!")
            m_Scale = value;
        }
    }
    [FieldOffset(3)]
    byte m_SignByte;
    public int Sign
    {
        get
        {
            return m_SignByte > 0 ? -1 : 1;
        }
    }
    public bool Positive
    {
        get
        {
            return (m_SignByte & k_SignBit) > 0 ;
        }
        set
        {
            m_SignByte = value ? (byte)0 : k_SignBit;
        }
    }
    [FieldOffset(4)]
    public uint Hi;
    [FieldOffset(8)]
    public uint Lo;
    [FieldOffset(12)]
    public uint Mid;

    public DecimalHelper(decimal value) : this()
    {
        Value = value;
    }

    public static implicit operator DecimalHelper(decimal value)
    {
        return new DecimalHelper(value);
    }

    public static implicit operator decimal(DecimalHelper value)
    {
        return value.Value;
    }
}

To solve the original problem, you could strip away all fields besides Value and Scale but maybe it could be useful for someone to have them all.

Common CSS Media Queries Break Points

Keep your code clean and stylesheets logically separated per screen 'media' type config...


1) Using himansu's answer from above as a reference: Common CSS Media Queries Break Points
AND
2) https://www.w3schools.com/css/css3_mediaqueries.asp

your answer would be:

<link rel="stylesheet" media="@media only screen and (min-width : 320px) and (max-width : 480px)" href="mobilePortrait.css">

<link rel="stylesheet" media="@media only screen and (min-width : 481px) and (max-width : 595px)" href="mobileLandscape.css">

How to convert a timezone aware string to datetime in Python without dateutil?

As of Python 3.7, datetime.datetime.fromisoformat() can handle your format:

>>> import datetime
>>> datetime.datetime.fromisoformat('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

In older Python versions you can't, not without a whole lot of painstaking manual timezone defining.

Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you.

As a side-effect, this means that timezone parsing also needs to be an external library. If dateutil is too heavy-weight for you, use iso8601 instead, it'll parse your specific format just fine:

>>> import iso8601
>>> iso8601.parse_date('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=<FixedOffset '-04:00'>)

iso8601 is a whopping 4KB small. Compare that tot python-dateutil's 148KB.

As of Python 3.2 Python can handle simple offset-based timezones, and %z will parse -hhmm and +hhmm timezone offsets in a timestamp. That means that for a ISO 8601 timestamp you'd have to remove the : in the timezone:

>>> from datetime import datetime
>>> iso_ts = '2012-11-01T04:16:13-04:00'
>>> datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))

The lack of proper ISO 8601 parsing is being tracked in Python issue 15873.

One-line list comprehension: if-else variants

Just another solution, hope some one may like it :

Using: [False, True][Expression]

>>> map(lambda x: [x*100, x][x % 2 != 0], range(1,10))
[1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>

How to install package from github repo in Yarn

I use this short format for github repositories:

yarn add github_user/repository_name#commit_hash

Stored procedure return into DataSet in C# .Net

You can declare SqlConnection and SqlCommand instances at global level so that you can use it through out the class. Connection string is in Web.Config.

SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();

Now you can use the below method to pass values to Stored Procedure and get the DataSet.

public DataSet GetDataSet(string paramValue)
{
    sqlcomm.Connection = sqlConn;
    using (sqlConn)
    {
        try
        {
            using (SqlDataAdapter da = new SqlDataAdapter())
            {  
                // This will be your input parameter and its value
                sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);

                // You can retrieve values of `output` variables
                var returnParam = new SqlParameter
                {
                    ParameterName = "@Error",
                    Direction = ParameterDirection.Output,
                    Size = 1000
                };
                sqlcomm.Parameters.Add(returnParam);
                // Name of stored procedure
                sqlcomm.CommandText = "StoredProcedureName";
                da.SelectCommand = sqlcomm;
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                DataSet ds = new DataSet();
                da.Fill(ds);                            
            }
        }
        catch (SQLException ex)
        {
            Console.WriteLine("SQL Error: " + ex.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
    return new DataSet();
}

The following is the sample of connection string in config file

<connectionStrings>
    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
         providerName="System.Data.SqlClient" />
</connectionStrings>

AngularJS resource promise

/*link*/
$q.when(scope.regions).then(function(result) {
    console.log(result);
});
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
    return response;
});

MySQL: What's the difference between float and double?

Perhaps this example could explain.

CREATE TABLE `test`(`fla` FLOAT,`flb` FLOAT,`dba` DOUBLE(10,2),`dbb` DOUBLE(10,2)); 

We have a table like this:

+-------+-------------+
| Field | Type        |
+-------+-------------+
| fla   | float       |
| flb   | float       |
| dba   | double(10,2)|
| dbb   | double(10,2)|
+-------+-------------+

For first difference, we try to insert a record with '1.2' to each field:

INSERT INTO `test` values (1.2,1.2,1.2,1.2);

The table showing like this:

SELECT * FROM `test`;

+------+------+------+------+
| fla  | flb  | dba  | dbb  |
+------+------+------+------+
|  1.2 |  1.2 | 1.20 | 1.20 |
+------+------+------+------+

See the difference?

We try to next example:

SELECT fla+flb, dba+dbb FROM `test`;

Hola! We can find the difference like this:

+--------------------+---------+
| fla+flb            | dba+dbb |
+--------------------+---------+
| 2.4000000953674316 |    2.40 |
+--------------------+---------+

Get paragraph text inside an element

HTML:

<ul>
  <li onclick="myfunction(this)">
    <span></span>
    <p>This Text</p>
  </li>
</ul>?

JavaScript:

function myfunction(foo) {
    var elem = foo.getElementsByTagName('p');
    var TextInsideLi = elem[0].innerHTML;
}?

Adding a directory to PATH in Ubuntu

you can set it in .bashrc

PATH=$PATH:/opt/ActiveTcl-8.5/bin;export PATH;

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

I was having the same error, but had a proper connection string. My problem was that the driver was not being used, therefore was optimized out of the compiled war.

Be sure to import the driver:

import com.microsoft.sqlserver.jdbc.SQLServerDriver;

And then to force it to be included in the final war, you can do something like this:

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

That line is in the original question. This will also work:

SQLServerDriver driver = new SQLServerDriver();

The difference in months between dates in MySQL

PERIOD_DIFF calculates months between two dates.

For example, to calculate the difference between now() and a time column in your_table:

select period_diff(date_format(now(), '%Y%m'), date_format(time, '%Y%m')) as months from your_table;

Change application's starting activity

Just go to your AndroidManifest.xml file and add like below

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

then save and run your android project.

How to set a tkinter window to a constant size

There are 2 solutions for your problem:

  1. Either you set a fixed size of the Tkinter window; mw.geometry('500x500')

OR

  1. Make the Frame adjust to the size of the window automatically;back.place(x = 0, y = 0, relwidth = 1, relheight = 1)

*The second option should be used in place of back.pack()

How to load an ImageView by URL in Android?

Hi I have the most easiest code try this

    public class ImageFromUrlExample extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);  
            ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
            Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
            imgView.setImageDrawable(drawable);

    }

    private Drawable LoadImageFromWebOperations(String url)
    {
          try{
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
      }catch (Exception e) {
        System.out.println("Exc="+e);
        return null;
      }
    }
   }

main.xml

  <LinearLayout 
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
   <ImageView 
       android:id="@+id/ImageView01"
       android:layout_height="wrap_content" 
       android:layout_width="wrap_content"/>

try this

How can I set response header on express.js assets

_x000D_
_x000D_
service.use(function(req, res, next) {_x000D_
    res.header("Access-Control-Allow-Origin", "*");_x000D_
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");_x000D_
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");_x000D_
    next();_x000D_
  });
_x000D_
_x000D_
_x000D_

CSS strikethrough different color from text?

If you do not care about internet explorer\edge, then simplest way to achieve different color for strike-through would be to use CSS property: text-decoration-color in conjunction with text-decoration:line-through;

.yourClass {
    text-decoration: line-through !important;
    text-decoration-color: red !important;
}

-- Does not work with Edge\Internet Explorer

C# static class why use?

Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.

As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.

The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.

Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.

One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,

public class Foo
{
    public static Foo New(string fooString)
    {
        ProxyGenerator generator = new ProxyGenerator();

        return (Foo)generator.CreateClassProxy
             (typeof(Foo), new object[] { fooString }, new Interceptor()); 
    }

This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.

Maven is not working in Java 8 when Javadoc tags are incomplete

The best solution would be to fix the javadoc errors. If for some reason that is not possible (ie: auto generated source code) then you can disable this check.

DocLint is a new feature in Java 8, which is summarized as:

Provide a means to detect errors in Javadoc comments early in the development cycle and in a way that is easily linked back to the source code.

This is enabled by default, and will run a whole lot of checks before generating Javadocs. You need to turn this off for Java 8 as specified in this thread. You'll have to add this to your maven configuration:

<profiles>
  <profile>
    <id>java8-doclint-disabled</id>
    <activation>
      <jdk>[1.8,)</jdk>
    </activation>
    <properties>
      <javadoc.opts>-Xdoclint:none</javadoc.opts>
    </properties>
  </profile>
</profiles>
<build>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9</version>
        <executions>
            <execution>
                <id>attach-javadocs</id>
                <goals>
                    <goal>jar</goal>
                </goals>
                <configuration>
                    <additionalparam>${javadoc.opts}</additionalparam>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <reportPlugins>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-javadoc-plugin</artifactId>
              <configuration>
                <additionalparam>${javadoc.opts}</additionalparam>
              </configuration>
            </plugin>
          </reportPlugins>
        </configuration>
      </plugin>
   </plugins>
</build>

For maven-javadoc-plugin 3.0.0+: Replace

<additionalparam>-Xdoclint:none</additionalparam>

with

<doclint>none</doclint>

Programmatically Check an Item in Checkboxlist where text is equal to what I want

I tried adding dynamically created ListItem and assigning the selected value.

foreach(var item in yourListFromDB)
{
 ListItem listItem = new ListItem();
 listItem.Text = item.name;
 listItem.Value = Convert.ToString(item.value);
 listItem.Selected=item.isSelected;                 
  checkedListBox1.Items.Add(listItem);
}
checkedListBox1.DataBind();

avoid using binding the DataSource as it will not bind the checked/unchecked from DB.

How to automatically generate getters and setters in Android Studio

Use Ctrl+Enter on Mac to get list of options to generate setter, getter, constructor etc

enter image description here

How to provide animation when calling another activity in Android?

Jelly Bean adds support for this with the ActivityOptions.makeCustomAnimation() method. Of course, since it's only on Jelly Bean, it's pretty much worthless for practical purposes.

Python division

Personally I preferred to insert a 1. * at the very beginning. So the expression become something like this:

1. * (20-10) / (100-10)

As I always do a division for some formula like:

accuracy = 1. * (len(y_val) - sum(y_val)) / len(y_val)

so it is impossible to simply add a .0 like 20.0. And in my case, wrapping with a float() may lose a little bit readability.

How to update TypeScript to latest version with npm?

Just use the command # npm update -g typescript
For update all global installed module, Use this command# npm update -g

How do I assign a null value to a variable in PowerShell?

If the goal simply is to list all computer objects with an empty description attribute try this

import-module activedirectory  
$domain = "domain.example.com" 
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }

Exit codes in Python

There is an errno module that defines standard exit codes:

For example, Permission denied is error code 13:

import errno, sys

if can_access_resource():
    do_something()
else:
    sys.exit(errno.EACCES)

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

Sample output:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

Get the cell value of a GridView row

I suggest you use a HiddenField inside template field use FindControl to find this field.

ie:

ASPX

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HiddenField ID="hfFname" runat="server" Value='<%# Eval("FileName") %>' />
                    </ItemTemplate>
                </asp:TemplateField>

Code behind

protected void gvAttachments_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView gv1 = (GridView)sender;
        GridViewRow gvr1 = (GridViewRow)gv1.Rows[e.RowIndex];

        //get hidden field value and not directly from the GridviewRow, as that will be null or empty!
        HiddenField hf1 = (HiddenField)gvr1.FindControl("hfFname");
        if (hf1 != null)
        {
           ..
        }
    }

How to track untracked content?

To point out what I had to dig out of Chris Johansen's chat with OP (linked from a reply to an answer):

git add vendor/plugins/open_flash_chart_2 # will add gitlink, content will stay untracked

git add vendor/plugins/open_flash_chart_2/ # NOTICE THE SLASH!!!!

The second form will add it without gitlink, and the contents are trackable. The .git dir is conveniently & automatically ignored. Thank you Chris!

Add animated Gif image in Iphone UIImageView

Here is an interesting library: https://github.com/Flipboard/FLAnimatedImage

I tested the demo example and it's working great. It's a child of UIImageView. So I think you can use it in your Storyboard directly as well.

Cheers

How to read a file line-by-line into a list?

with open(filename) as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content] 

Trying to get property of non-object - Laravel 5

I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo. Here it is:

First, as suggested by Jimmy Zoto, my code in blade from

$article->poster->name 

to

$article->poster['name']

Next is to add a second parameter in my belongsTo, from

return $this->belongsTo('App\User');

to

return $this->belongsTo('App\User', 'user_id');

in which user_id is my foreign key in the news table.

How do I read the first line of a file using cat?

cat alone may not be possible, but if you don't want to use head this works:

 cat <file> | awk 'NR == 1'

Bootstrap 4 img-circle class not working

It's now called rounded-circle as explained here in the BS4 docs

<img src="img/gallery2.JPG" class="rounded-circle">

Demo

What does "Use of unassigned local variable" mean?

The compiler isn't smart enough to know that at least one of your if blocks will be executed. Therefore, it doesn't see that variables like annualRate will be assigned no matter what. Here's how you can make the compiler understand:

if (creditPlan == "0")
{
    // ...
}
else if (creditPlan == "1")
{
    // ...
}
else if (creditPlan == "2")
{
    // ...
}
else
{
    // ...
}

The compiler knows that with an if/else block, one of the blocks is guaranteed to be executed, and therefore if you're assigning the variable in all of the blocks, it won't give the compiler error.

By the way, you can also use a switch statement instead of ifs to maybe make your code cleaner.

Getting request payload from POST request in Java servlet

You only need

request.getParameterMap()

for getting the POST and GET - Parameters.

The Method returns a Map<String,String[]>.

You can read the parameters in the Map by

Map<String, String[]> map = request.getParameterMap();
//Reading the Map
//Works for GET && POST Method
for(String paramName:map.keySet()) {
    String[] paramValues = map.get(paramName);

    //Get Values of Param Name
    for(String valueOfParam:paramValues) {
        //Output the Values
        System.out.println("Value of Param with Name "+paramName+": "+valueOfParam);
    }
}

How to compare the contents of two string objects in PowerShell

You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title

-match is for regex matching ( the second argument is a regex )

How to use export with Python on Linux

You actually want to do

import os
os.environ["MY_DATA"] = "my_export"

<div> cannot appear as a descendant of <p>

This is a constraint of browsers. You should use div or article or something like that in the render method of App because that way you can put whatever you like inside it. Paragraph tags are limited to only containing a limited set of tags (mostly tags for formatting text. You cannot have a div inside a paragraph

<p><div></div></p>

is not valid HTML. Per the tag omission rules listed in the spec, the <p> tag is automatically closed by the <div> tag, which leaves the </p> tag without a matching <p>. The browser is well within its rights to attempt to correct it by adding an open <p> tag after the <div>:

<p></p><div></div><p></p>

You can't put a <div> inside a <p> and get consistent results from various browsers. Provide the browsers with valid HTML and they will behave better.

You can put <div> inside a <div> though so if you replace your <p> with <div class="p"> and style it appropriately, you can get what you want.

Read from database and fill DataTable

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function

Linux command for extracting war file?

Using unzip

unzip -c whatever.war META-INF/MANIFEST.MF  

It will print the output in terminal.

And for extracting all the files,

 unzip whatever.war

Using jar

jar xvf test.war

Note! The jar command will extract war contents to current directory. Not to a subdirectory (like Tomcat does).

Is there a way to add/remove several classes in one single instruction with classList?

The new spread operator makes it even easier to apply multiple CSS classes as array:

const list = ['first', 'second', 'third'];
element.classList.add(...list);

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

Remove all pods and install again.

Steps:

  1. comment all pods and run pod install
  2. uncomment all pods and run pod install

How do I declare a global variable in VBA?

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

In short, consider this "module":

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

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

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

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

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

Two other quick things:

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

bash export command

if u cant use " export " cmd
then Just use:

setenv path /dir

like this

setenv ORACLE_HOME /data/u01/apps/oracle/11.2.0.3.0

How to decrypt hash stored by bcrypt

# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password 
encrypted and test with the current Password not encrypted to verify 
if it's the same User. 

For example :

public function updateUser(Request $req)
      {
         $entityManager = $this->getDoctrine()->getManager();
         $repository = $entityManager->getRepository(User::class);
         $user = $repository->find($req->get(id)); /// get User from your DB

         if($user == null){
            throw  $this->createNotFoundException('User don't exist!!', $user);
         }
         $password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
         $passwordToUpdate = $req->get('password'); // not encrypted yet from request.

         $passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);

          ////////////VERIFY IF IT'S THE SAME PASSWORD
         $isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );

         if($isPass === false){ // failure
            throw  $this->createNotFoundException('Your password it's not verify', null);
         }

        return $isPass; //// true!! it's the same password !!!

      }

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

Mapping a JDBC ResultSet to an object

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import com.google.gson.Gson;

public class ObjectMapper {

//generic method to convert JDBC resultSet into respective DTo class
@SuppressWarnings("unchecked")
public static Object mapValue(List<Map<String, Object>> rows,Class<?> className) throws Exception
{

        List<Object> response=new ArrayList<>(); 
        Gson gson=new Gson();

        for(Map<String, Object> row:rows){
        org.json.simple.JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(row);
        String json=jsonObject.toJSONString();
        Object actualObject=gson.fromJson(json, className);
        response.add(actualObject);
        }
        return response;

    }

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

        List<Map<String, Object>> rows=new ArrayList<Map<String, Object>>(); 

        //Hardcoded data for testing
        Map<String, Object> row1=new HashMap<String, Object>();
        row1.put("name", "Raja");
        row1.put("age", 22);
        row1.put("location", "India");


        Map<String, Object> row2=new HashMap<String, Object>();
        row2.put("name", "Rani");
        row2.put("age", 20);
        row2.put("location", "India");

        rows.add(row1);
        rows.add(row2);


        @SuppressWarnings("unchecked")
        List<Dto> res=(List<Dto>) mapValue(rows, Dto.class);


    }

    }

    public class Dto {

    private String name;
    private Integer age;
    private String location;

    //getters and setters

    }

Try the above code .This can be used as a generic method to map JDBC result to respective DTO class.

Count number of rows within each group

There are plenty of wonderful answers here already, but I wanted to throw in 1 more option for those wanting to add a new column to the original dataset that contains the number of times that row is repeated.

df1$counts <- sapply(X = paste(df1$Year, df1$Month), 
                     FUN = function(x) { sum(paste(df1$Year, df1$Month) == x) })

The same could be accomplished by combining any of the above answers with the merge() function.

Jenkins: Can comments be added to a Jenkinsfile?

The official Jenkins documentation only mentions single line commands like the following:

// Declarative //

and (see)

pipeline {
    /* insert Declarative Pipeline here */
}

The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:

/* a standalone multiline comment
   spanning two lines */
println "hello" /* a multiline comment starting
                   at the end of a statement */
println 1 /* one */ + 2 /* two */

or

/**
 * such a nice comment
 */

Script for rebuilding and reindexing the fragmented index?

I have found the following script is very good at maintaining indexes, you can have this scheduled to run nightly or whatever other timeframe you wish.

http://sqlfool.com/2011/06/index-defrag-script-v4-1/

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How do I add a library path in cmake?

The simplest way of doing this would be to add

include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)

add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib

The modern CMake version that doesn't add the -I and -L flags to every compiler invocation would be to use imported libraries:

add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
  IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
  INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)

set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path

If setting the INTERFACE_INCLUDE_DIRECTORIES doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include). However, this no longer works with CMake 3.6 or newer.

Check if all values of array are equal

You can convert array to a Set and check its size

In case of primitive array entries, i.e. number, string:

const isArrayWithEqualEntries = array => new Set(array).size === 1

In case of array of objects with some field to be tested for equivalence, say id:

const mapper = ({id}) => id
const isArrayWithEqualEntries = array => new Set(array.map(mapper)).size === 1

jQuery Remove string from string

If you just want to remove "username1" you can use a simple replace.

name.replace("username1,", "")

or you could use split like you mentioned.

var name = "username1, username2 and username3 like this post.".split(",")[1];      
$("h1").text(name);

jsfiddle example

Hashing a file in Python

For the correct and efficient computation of the hash value of a file (in Python 3):

  • Open the file in binary mode (i.e. add 'b' to the filemode) to avoid character encoding and line-ending conversion issues.
  • Don't read the complete file into memory, since that is a waste of memory. Instead, sequentially read it block by block and update the hash for each block.
  • Eliminate double buffering, i.e. don't use buffered IO, because we already use an optimal block size.
  • Use readinto() to avoid buffer churning.

Example:

import hashlib

def sha256sum(filename):
    h  = hashlib.sha256()
    b  = bytearray(128*1024)
    mv = memoryview(b)
    with open(filename, 'rb', buffering=0) as f:
        for n in iter(lambda : f.readinto(mv), 0):
            h.update(mv[:n])
    return h.hexdigest()

What's the purpose of SQL keyword "AS"?

In the early days of SQL, it was chosen as the solution to the problem of how to deal with duplicate column names (see below note).

To borrow a query from another answer:

SELECT P.ProductName,
       P.ProductRetailPrice,
       O.Quantity
  FROM Products AS P
       INNER JOIN Orders AS O ON O.ProductID = P.ProductID
 WHERE O.OrderID = 123456

The column ProductID (and possibly others) is common to both tables and since the join condition syntax requires reference to both, the 'dot qualification' provides disambiguation.

Of course, the better solution was to never have allowed duplicate column names in the first place! Happily, if you use the newer NATURAL JOIN syntax, the need for the range variables P and O goes away:

SELECT ProductName, ProductRetailPrice, Quantity
  FROM Products NATURAL JOIN Orders
 WHERE OrderID = 123456

But why is the AS keyword optional? My recollection from a personal discussion with a member of the SQL standard committee (either Joe Celko or Hugh Darwen) was that their recollection was that, at the time of defining the standard, one vendor's product (Microsoft's?) required its inclusion and another vendor's product (Oracle's?) required its omission, so the compromise chosen was to make it optional. I have no citation for this, you either believe me or not!


In the early days of the relational model, the cross product (or theta-join or equi-join) of relations whose headings are not disjoint appeared to produce a relation with two attributes of the same name; Codd's solution to this problem in his relational calculus was the use of dot qualification, which was later emulated in SQL (it was later realised that so-called natural join was primitive without loss; that is, natural join can replace all theta-joins and even cross product.)

Source: Business System 12, Notes keyed to slides of the presentation given at TTM Implementers’ Workshop, University of Northumbria, 2-3 June 2011 by Hugh Darwen

Python 2.7 getting user input and manipulating as string without quotations

The issue seems to be resolved in Python version 3.4.2.

testVar = input("Ask user for something.")

Will work fine.

Create JSON object dynamically via JavaScript (Without concate strings)

This is what you need!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }

Remove the newline character in a list read from a file

You can use the strip() function to remove trailing (and leading) whitespace; passing it an argument will let you specify which whitespace:

for i in range(len(lists)):
    grades.append(lists[i].strip('\n'))

It looks like you can just simplify the whole block though, since if your file stores one ID per line grades is just lists with newlines stripped:

Before

lists = files.readlines()
grades = []

for i in range(len(lists)):
    grades.append(lists[i].split(","))

After

grades = [x.strip() for x in files.readlines()]

(the above is a list comprehension)


Finally, you can loop over a list directly, instead of using an index:

Before

for i in range(len(grades)):
    # do something with grades[i]

After

for thisGrade in grades:
    # do something with thisGrade

How do I use NSTimer?

#import "MyViewController.h"

@interface MyViewController ()

@property (strong, nonatomic) NSTimer *timer;

@end

@implementation MyViewController

double timerInterval = 1.0f;

- (NSTimer *) timer {
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:timerInterval target:self selector:@selector(onTick:) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

-(void)onTick:(NSTimer*)timer
{
    NSLog(@"Tick...");
}

@end

How to use css style in php

I had this problem just now and I tried the require_once trick, but it would just echo the CSS above all my php code without actually applying the styles.

What I did to fix it, though, was wrap all my php in their own plain HTML templates. Just type out html in the first line of the document and pick the suggestion html:5 to get the HTML boilerplate, like you would when you're just starting a plain HTML doc. Then cut the closing body and html tags and paste them all the way down at the bottom, below the closing php tag to wrap your php code without actually changing anything. Finally, you can just put your plain old link to your stylesheet into the head of your HTML. Works just fine.

3D Plotting from X, Y, Z Data, Excel or other Tools

Why not merge the rows that contain the same values? -

         13    21    29     37    45   
  • 1000] -75.2 -- 79.21 -- 80.02

  • 5000] ---------------------87.9---88.54----88.56

  • 10000] -------------------90.11--90.97----90.87

Excel can use that pretty well..

Circular dependency in Spring

Circular dependency in Spring : Dependency of one Bean to other. Bean A ? Bean B ? Bean A

Solutions:

  1. Use @Lazy Annotation
  2. Redesign you class dependency
  3. Use Setter/Field Injection
  4. Use @PostConstruct Annotation

How can I turn a DataTable to a CSV?

Try changing sb.Append(Environment.NewLine); to sb.AppendLine();.

StringBuilder sb = new StringBuilder();          
foreach (DataColumn col in dt.Columns)         
{             
    sb.Append(col.ColumnName + ',');         
}          

sb.Remove(sb.Length - 1, 1);         
sb.AppendLine();          

foreach (DataRow row in dt.Rows)         
{             
    for (int i = 0; i < dt.Columns.Count; i++)             
    {                 
        sb.Append(row[i].ToString() + ",");             
    }              

    sb.AppendLine();         
}          

File.WriteAllText("test.csv", sb.ToString());

replace \n and \r\n with <br /> in java

It works for me. The Java code works exactly as you wrote it. In the tester, the input string should be:

This is a string.
This is a long string.

...with a real linefeed. You can't use:

This is a string.\nThis is a long string.

...because it treats \n as the literal sequence backslash 'n'.

Clear image on picturebox

Its so simple! You can go with your button click event, I used it with a button property Name: "btnClearImage"

// Note 1a:
// after clearing the picture box 
// you can also disable clear button 
// by inserting follwoing one line of code:

btnClearImage.Enabled = false   

// Note 1b:
// you should set your button Enabled property
// to "False"
// after that you will need to Insert 
// the following line to concerned event or button
// that load your image into picturebox1 
// code line is as follows:

btnClearImage.Enabled = true;

RandomForestClassfier.fit(): ValueError: could not convert string to float

LabelEncoding worked for me (basically you've to encode your data feature-wise) (mydata is a 2d array of string datatype):

myData=np.genfromtxt(filecsv, delimiter=",", dtype ="|a20" ,skip_header=1);

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for i in range(*NUMBER OF FEATURES*):
    myData[:,i] = le.fit_transform(myData[:,i])

When using a Settings.settings file in .NET, where is the config actually stored?

Assuming that you're talking about desktop and not web applications:

When you add settings to a project, VS creates a file named app.config in your project directory and stores the settings in that file. It also builds the Settings.cs file that provides the static accessors to the individual settings.

At compile time, VS will (by default; you can change this) copy the app.config to the build directory, changing its name to match the executable (e.g. if your executable is named foo.exe, the file will be named foo.exe.config), which is the name the .NET configuration manager looks for when it retrieves settings at runtime.

If you change a setting through the VS settings editor, it will update both app.config and Settings.cs. (If you look at the property accessors in the generated code in Settings.cs, you'll see that they're marked with an attribute containing the default value of the setting that's in your app.config file.) If you change a setting by editing the app.config file directly, Settings.cs won't be updated, but the new value will still be used by your program when you run it, because app.config gets copied to foo.exe.config at compile time. If you turn this off (by setting the file's properties), you can change a setting by directly editing the foo.exe.config file in the build directory.

Then there are user-scoped settings.

Application-scope settings are read-only. Your program can modify and save user-scope settings, thus allowing each user to have his/her own settings. These settings aren't stored in the foo.exe.config file (since under Vista, at least, programs can't write to any subdirectory of Program Files without elevation); they're stored in a configuration file in the user's application data directory.

The path to that file is %appdata%\%publisher_name%\%program_name%\%version%\user.config, e.g. C:\Users\My Name\AppData\Local\My_Company\My_Program.exe\1.0.0\user.config. Note that if you've given your program a strong name, the strong name will be appended to the program name in this path.

Edit existing excel workbooks and sheets with xlrd and xlwt

Here's another way of doing the code above using the openpyxl module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.

from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')

Using a Python subprocess call to invoke a Python script

First, check if somescript.py is executable and starts with something along the lines of #!/usr/bin/python. If this is done, then you can use subprocess.call('./somescript.py').

Or as another answer points out, you could do subprocess.call(['python', 'somescript.py']).

Can we pass an array as parameter in any function in PHP?

Yes, we can pass arrays to a function.

$arr = array(“a” => “first”, “b” => “second”, “c” => “third”);

function user_defined($item, $key)
{
    echo $key.”-”.$item.”<br/>”;
} 

array_walk($arr, ‘user_defined’);

We can find more array functions here

http://skillrow.com/array-functions-in-php-part1/

Write in body request with HttpClient

Extending your code (assuming that the XML you want to send is in xmlString) :

String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);

call a function in success of datatable ajax call

You can use this:

"drawCallback": function(settings) {
   console.log(settings.json);
   //do whatever  
},

How to get enum value by string or int

Following is the method in C# to get the enum value by string

///
/// Method to get enumeration value from string value.
///
///
///

public T GetEnumValue<T>(string str) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
        throw new Exception("T must be an Enumeration type.");
    }
    T val = ((T[])Enum.GetValues(typeof(T)))[0];
    if (!string.IsNullOrEmpty(str))
    {
        foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
        {
            if (enumValue.ToString().ToUpper().Equals(str.ToUpper()))
            {
                val = enumValue;
                break;
            }
        }
    }

    return val;
}

Following is the method in C# to get the enum value by int.

///
/// Method to get enumeration value from int value.
///
///
///

public T GetEnumValue<T>(int intValue) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
        throw new Exception("T must be an Enumeration type.");
    }
    T val = ((T[])Enum.GetValues(typeof(T)))[0];

    foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
    {
        if (Convert.ToInt32(enumValue).Equals(intValue))
        {
            val = enumValue;
            break;
        }             
    }
    return val;
}

If I have an enum as follows:

public enum TestEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3
}

then I can make use of above methods as

TestEnum reqValue = GetEnumValue<TestEnum>("Value1");  // Output: Value1
TestEnum reqValue2 = GetEnumValue<TestEnum>(2);        // OutPut: Value2

Hope this will help.

Error: unable to verify the first certificate in nodejs

I was using nodemailer npm module. The below code solved the issue

     tls: {
     // do not fail on invalid certs
     rejectUnauthorized: false
     }

How to find length of a string array?

As all the above answers have suggested it will throw a NullPointerException.

Please initialise it with some value(s) and then you can use the length property correctly. For example:

String[] str = { "plastic", "paper", "use", "throw" };
System.out.println("Length is:::" + str.length);

The array 'str' is now defined, and so it's length also has a defined value.

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

Parsing xml using powershell

First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]

$doc = [xml]@'
<xml>
    <Section name="BackendStatus">
        <BEName BE="crust" Status="1" />
        <BEName BE="pizza" Status="1" />
        <BEName BE="pie" Status="1" />
        <BEName BE="bread" Status="1" />
        <BEName BE="Kulcha" Status="1" />
        <BEName BE="kulfi" Status="1" />
        <BEName BE="cheese" Status="1" />
    </Section>
</xml>
'@

Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:

$doc.xml.Section.BEName

Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where

$doc.xml.Section.BEName | ? { $_.Status -eq 1 }

The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).

If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:

$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }

Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.

How to fix "'System.AggregateException' occurred in mscorlib.dll"

As the message says, you have a task which threw an unhandled exception.

Turn on Break on All Exceptions (Debug, Exceptions) and rerun the program.
This will show you the original exception when it was thrown in the first place.


(comment appended): In VS2015 (or above). Select Debug > Options > Debugging > General and unselect the "Enable Just My Code" option.

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

If you're using a newer XAMPP (for example for PHP 5.6, 7) which is built with "Bitnami" installer and it includes Apache 2.4.x then this applies:

https://httpd.apache.org/docs/2.4/upgrading.html#run-time

2.2 configuration:

Order allow,deny
Allow from all

2.4 configuration:

Require all granted

This also applies to VirtualHost sections, if you have any custom virtualhost definitions.

How to open some ports on Ubuntu?

Ubuntu these days comes with ufw - Uncomplicated Firewall. ufw is an easy-to-use method of handling iptables rules.

Try using this command to allow a port

sudo ufw allow 1701

To test connectivity, you could try shutting down the VPN software (freeing up the ports) and using netcat to listen, like this:

nc -l 1701

Then use telnet from your Windows host and see what shows up on your Ubuntu terminal. This can be repeated for each port you'd like to test.

Firebase Storage How to store and Retrieve images

Using Base64 string in JSON will be very heavy. The parser has to do a lot of heavy lifting. Currently, Fresco only supports base supports Base64. Better you put something on Amazon Cloud or Firebase Cloud. And get an image as a URL. So that you can use Picasso or Glide for caching.

Removing duplicate characters from a string

As was mentioned "".join(set(foo)) and collections.OrderedDict will do. A added foo = foo.lower() in case the string has upper and lower case characters and you need to remove ALL duplicates no matter if they're upper or lower characters.

from collections import OrderedDict
foo = "EugeneEhGhsnaWW"
foo = foo.lower()
print "".join(OrderedDict.fromkeys(foo))

prints eugnhsaw

Freeing up a TCP/IP port?

Shutting down the computer always kills the process for me.

CSS Box Shadow Bottom Only

Do this:

box-shadow: 0 4px 2px -2px gray;

It's actually much simpler, whatever you set the blur to (3rd value), set the spread (4th value) to the negative of it.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

There seem to be a lot of solutions for Windows here but this is the simplest:

Tools -> Build System -> New Build System, type in the above, save as Browser.sublime-build:

{
    "cmd": "explorer $file"
}

Then go back to your HTML file. Tools -> Build System -> Browser. Then press CTRL-B and the file will be opened in whatever browser is your system default browser.

How to execute a command in a remote computer?

try
{
    string AppPath = "\\\\spri11U1118\\SampleBatch\\Bin\\";
    string strFilePath = AppPath + "ABCED120D_XXX.bat";
    System.Diagnostics.Process proc = new System.Diagnostics.Process();

    proc.StartInfo.FileName = strFilePath;
    string pwd = "s44erver";

    proc.StartInfo.Domain = "abcd";
    proc.StartInfo.UserName = "sysfaomyulm";

    System.Security.SecureString secret = new System.Security.SecureString();
    foreach (char c in pwd)

        secret.AppendChar(c);

    proc.StartInfo.Password = secret;
    proc.StartInfo.UseShellExecute = false;

    proc.StartInfo.WorkingDirectory = "psexec \\\\spri11U1118\\SampleBatch\\Bin ";

    proc.Start();
    while (!proc.HasExited)
    {
        proc.Refresh();
        // Thread.Sleep(1000);
    }

    proc.Close();
}
catch (Exception ex)
{
    throw ex;
}

Setting custom UITableViewCells height

Your UITableViewDelegate should implement tableView:heightForRowAtIndexPath:

Objective-C

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [indexPath row] * 20;
}

Swift 5

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return indexPath.row * 20
}

You will probably want to use NSString's sizeWithFont:constrainedToSize:lineBreakMode: method to calculate your row height rather than just performing some silly math on the indexPath :)

Passing route control with optional parameter after root in express?

That would work depending on what client.get does when passed undefined as its first parameter.

Something like this would be safer:

app.get('/:key?', function(req, res, next) {
    var key = req.params.key;
    if (!key) {
        next();
        return;
    }
    client.get(key, function(err, reply) {
        if(client.get(reply)) {
            res.redirect(reply);
        }
        else {
            res.render('index', {
                link: null
            });
        }
    });
});

There's no problem in calling next() inside the callback.

According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.

Eliminating duplicate values based on only one column of the table

From your example it seems reasonable to assume that the siteIP column is determined by the siteName column (that is, each site has only one siteIP). If this is indeed the case, then there is a simple solution using group by:

select
  sites.siteName,
  sites.siteIP,
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName,
  sites.siteIP
order by
  sites.siteName;

However, if my assumption is not correct (that is, it is possible for a site to have multiple siteIP), then it is not clear from you question which siteIP you want the query to return in the second column. If just any siteIP, then the following query will do:

select
  sites.siteName,
  min(sites.siteIP),
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName
order by
  sites.siteName;

JQuery select2 set default value from an option in list?

Step 1: You need to append one blank option with a blank value in your select tag.

Step 2: Add data-placeholder attribute in select tag with a placeholder value

HTML

<select class="select2" data-placeholder='--Select--'>
  <option value=''>--Select--</option>
  <option value='1'>Option 1</option>
  <option value='2'>Option 2</option>
  <option value='3'>Option 3</option>
</select>

Jquery

$('.select2').select2({
    placeholder: $(this).data('placeholder')
});

OR

$('.select2').select2({
    placeholder: 'Custom placeholder text'
});

Using group by on two fields and count in SQL

SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup

What is the simplest way to convert array to vector?

Use the vector constructor that takes two iterators, note that pointers are valid iterators, and use the implicit conversion from arrays to pointers:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + sizeof x / sizeof x[0]);
test(v);

or

test(std::vector<int>(x, x + sizeof x / sizeof x[0]));

where sizeof x / sizeof x[0] is obviously 3 in this context; it's the generic way of getting the number of elements in an array. Note that x + sizeof x / sizeof x[0] points one element beyond the last element.