Programs & Examples On #Mysqladministrator

0

How to vertical align an inline-block in a line of text?

_x000D_
_x000D_
code {_x000D_
    background: black;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
_x000D_
_x000D_

Tested and works in Safari 5 and IE6+.

Print content of JavaScript object?

You should consider using FireBug for JavaScript debugging. It will let you interactively inspect all of your variables, and even step through functions.

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

To go ahead and get a point out there, instead of repeatedly using these:

[A-Za-z0-9 _]
[A-Za-z0-9]

I have two (hopefully better) replacements for those two:

[\w ]
[^\W_]

The first one matches any word character (alphanumeric and _, as well as Unicode) and the space. The second matches anything that isn't a non-word character or an underscore (alphanumeric only, as well as Unicode).

If you don't want Unicode matching, then stick with the other answers. But these just look easier on the eyes (in my opinion). Taking the "preferred" answer as of this writing and using the shorter regexes gives us:

^[\w ]*[^\W_][\w ]*$

Perhaps more readable, perhaps less. Certainly shorter. Your choice.

EDIT:

Just as a note, I am assuming Perl-style regexes here. Your regex engine may or may not support things like \w and \W.

EDIT 2:

Tested mine with the JS regex tester that someone linked to and some basic examples worked fine. Didn't do anything extensive, just wanted to make sure that \w and \W worked fine in JS.

EDIT 3:

Having tried to test some Unicode with the JS regex tester site, I've discovered the problem: that page uses ISO instead of Unicode. No wonder my Japanese input didn't match. Oh well, that shouldn't be difficult to fix:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Or so. I don't know what should be done as far as JavaScript, but I'm sure it's not hard.

Align inline-block DIVs to top of container element

Add overflow: auto to the container div. http://www.quirksmode.org/css/clearing.html This website shows a few options when having this issue.

How to style input and submit button with CSS?

form element UI is somewhat controlled by browser and operating system, so it is not trivial to style them very reliably in a way that it would look the same in all common browser/OS combinations.

Instead, if you want something specific, I would recommend to use a library that provides you stylable form elements. uniform.js is one such library.

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

If you are in a MySQL shell, exit it by typing exit, which will return you to the command prompt.

Now start MySQL by using exactly the following command:

sudo mysql -u root -p

If your username is something other than root, replace 'root' in the above command with your username:

sudo mysql -u <your-user-name> -p

It will then ask you the MySQL account/password, and your MySQL won't show any access privilege issue then on.

How to assign an exec result to a sql variable?

declare @EventId int

CREATE TABLE #EventId (EventId int)

insert into #EventId exec rptInputEventId

set @EventId = (select * from #EventId)

drop table #EventId 

How do I push a local Git branch to master branch in the remote?

You can also do it this way to reference the previous branch implicitly:

git checkout mainline
git pull
git merge -
git push

How can I get a list of repositories 'apt-get' is checking?

As far as I know, you can't ask apt for what their current sources are. However, you can do what you want using shell tools.

Getting a list of repositories:

grep -h ^deb /etc/apt/sources.list /etc/apt/sources.list.d/* >> current.repos.list

Applying the list:

apt-add-repository << current.repos.list

Regarding getting the repository from a package (installed or available), this will do the trick:

apt-cache policy package_name | grep -m1 http | awk '{ print $2 " " $3 }'

However, that will show you the repository of the latest version available of that package, and you may have more repositories for the same package with older versions. Remove all the grep/awk stuff if you want to see the full list.

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

The correct syntax is:

FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
                                   , LCASE( SUBSTRING( NEW.bname, 2 ) ) )

Running code after Spring Boot starts

Try:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

    @SuppressWarnings("resource")
    public static void main(final String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

        context.getBean(Table.class).fillWithTestdata(); // <-- here
    }
}

Undefined reference to main - collect2: ld returned 1 exit status

You can just add a main function to resolve this problem. Just like:

int main()
{
    return 0;
}

How to declare an ArrayList with values?

You can do like this :

List<String> temp = new ArrayList<String>(Arrays.asList("1", "12"));

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

Your problem arises because you're using a self signed key. The client does not trust this key, nor does the key itself provide a chain to validate or a certificate revocation list.

You have a few options - you can

  1. turn off certificate validation on the client (bad move, man in the middle attacks abound)

  2. use makecert to create a root CA and create certificates from that (ok move, but there is still no CRL)

  3. create an internal root CA using Windows Certificate Server or other PKI solution then trust that root cert (a bit of a pain to manage)

  4. purchase an SSL certificate from one of the trusted CAs (expensive)

Transparent color of Bootstrap-3 Navbar

  1. Go to http://px64.net/
  2. mess around with opacity, add your image or choose color.
  3. copy either html or css(css is easier) the site spits out.
  4. Select your element aka the navbar.

  5. .navbar{ background-image:url(link that the site provides); background-repeat:repeat;

  6. Enjoy.

How to change the timeout on a .NET WebClient object

The first solution did not work for me but here is some code that did work for me.

    private class WebClient : System.Net.WebClient
    {
        public int Timeout { get; set; }

        protected override WebRequest GetWebRequest(Uri uri)
        {
            WebRequest lWebRequest = base.GetWebRequest(uri);
            lWebRequest.Timeout = Timeout;
            ((HttpWebRequest)lWebRequest).ReadWriteTimeout = Timeout;
            return lWebRequest;
        }
    }

    private string GetRequest(string aURL)
    {
        using (var lWebClient = new WebClient())
        {
            lWebClient.Timeout = 600 * 60 * 1000;
            return lWebClient.DownloadString(aURL);
        }
    }

Memory address of variables in Java

What you are getting is the result of the toString() method of the Object class or, more precisely, the identityHashCode() as uzay95 has pointed out.

"When we create an object in java with new keyword, we are getting a memory address from the OS."

It is important to realize that everything you do in Java is handled by the Java Virtual Machine. It is the JVM that is giving this information. What actually happens in the RAM of the host operating system depends entirely on the implementation of the JRE.

What's the difference between SoftReference and WeakReference in Java?

SoftReference is designed for caches. When it is found that a WeakReference references an otherwise unreachable object, then it will get cleared immediately. SoftReference may be left as is. Typically there is some algorithm relating to the amount of free memory and the time last used to determine whether it should be cleared. The current Sun algorithm is to clear the reference if it has not been used in as many seconds as there are megabytes of memory free on the Java heap (configurable, server HotSpot checks against maximum possible heap as set by -Xmx). SoftReferences will be cleared before OutOfMemoryError is thrown, unless otherwise reachable.

Convert JSON array to Python list

Tested on Ideone.


import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

How to create module-wide variables in Python?

Explicit access to module level variables by accessing them explicity on the module


In short: The technique described here is the same as in steveha's answer, except, that no artificial helper object is created to explicitly scope variables. Instead the module object itself is given a variable pointer, and therefore provides explicit scoping upon access from everywhere. (like assignments in local function scope).

Think of it like self for the current module instead of the current instance !

# db.py
import sys

# this is a pointer to the module object instance itself.
this = sys.modules[__name__]

# we can explicitly make assignments on it 
this.db_name = None

def initialize_db(name):
    if (this.db_name is None):
        # also in local function scope. no scope specifier like global is needed
        this.db_name = name
        # also the name remains free for local use
        db_name = "Locally scoped db_name variable. Doesn't do anything here."
    else:
        msg = "Database is already initialized to {0}."
        raise RuntimeError(msg.format(this.db_name))

As modules are cached and therefore import only once, you can import db.py as often on as many clients as you want, manipulating the same, universal state:

# client_a.py
import db

db.initialize_db('mongo')
# client_b.py
import db

if (db.db_name == 'mongo'):
    db.db_name = None  # this is the preferred way of usage, as it updates the value for all clients, because they access the same reference from the same module object
# client_c.py
from db import db_name
# be careful when importing like this, as a new reference "db_name" will
# be created in the module namespace of client_c, which points to the value 
# that "db.db_name" has at import time of "client_c".

if (db_name == 'mongo'):  # checking is fine if "db.db_name" doesn't change
    db_name = None  # be careful, because this only assigns the reference client_c.db_name to a new value, but leaves db.db_name pointing to its current value.

As an additional bonus I find it quite pythonic overall as it nicely fits Pythons policy of Explicit is better than implicit.

Multiple select statements in Single query

I know this is an old stack but i will post this Multi-SQL select case

    SELECT bp.bizid, bp.usrid, bp.website, 
ROUND((SELECT SUM(rating) FROM ratings WHERE bizid=bp.bizid)/(SELECT COUNT(*) FROM ratings WHERE bizid=bp.bizid), 1) AS 'ratings', 
(SELECT COUNT(*) FROM bzreviews WHERE bizid=bp.bizid) AS 'ttlreviews', 
bp.phoneno, als.bizname, 
(SELECT COUNT(*) FROM endorsment WHERE bizid=bp.bizid) AS 'endorses'
, als.imgname, bp.`location`, bp.`ownership`, 
(SELECT COUNT(*) FROM follows WHERE bizid=bp.bizid) AS 'followers', 
bp.categories, bp.openhours, bp.bizdecri FROM bizprofile AS bp 
INNER JOIN alluser AS als ON bp.usrid=als.userid 
WHERE als.usertype='Business'

How to make git mark a deleted and a new file as a file move?

When I edit, rename, and move a file at the same time, none of these solutions work. The solution is to do it in two commits (edit and rename/move seperate) and then fixup the second commit via git rebase -i to have it in one commit.

How to make a class JSON serializable

If you're using Python3.5+, you could use jsons. It will convert your object (and all its attributes recursively) to a dict.

import jsons

a_dict = jsons.dump(your_object)

Or if you wanted a string:

a_str = jsons.dumps(your_object)

Or if your class implemented jsons.JsonSerializable:

a_dict = your_object.json

What is the difference between os.path.basename() and os.path.dirname()?

Both functions use the os.path.split(path) function to split the pathname path into a pair; (head, tail).

The os.path.dirname(path) function returns the head of the path.

E.g.: The dirname of '/foo/bar/item' is '/foo/bar'.

The os.path.basename(path) function returns the tail of the path.

E.g.: The basename of '/foo/bar/item' returns 'item'

From: http://docs.python.org/2/library/os.path.html#os.path.basename

Parsing XML with namespace in Python via 'ElementTree'

I've been using similar code to this and have found it's always worth reading the documentation... as usual!

findall() will only find elements which are direct children of the current tag. So, not really ALL.

It might be worth your while trying to get your code working with the following, especially if you're dealing with big and complex xml files so that that sub-sub-elements (etc.) are also included. If you know yourself where elements are in your xml, then I suppose it'll be fine! Just thought this was worth remembering.

root.iter()

ref: https://docs.python.org/3/library/xml.etree.elementtree.html#finding-interesting-elements "Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the element’s text content. Element.get() accesses the element’s attributes:"

Implement Validation for WPF TextBoxes

There a 3 ways to implement validation:

  1. Validation Rule
  2. Implementation of INotifyDataErrorInfo
  3. Implementation of IDataErrorInfo

Validation rule example:

public class NumericValidationRule : ValidationRule
{
    public Type ValidationType { get; set; }
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string strValue = Convert.ToString(value);

        if (string.IsNullOrEmpty(strValue))
            return new ValidationResult(false, $"Value cannot be coverted to string.");
        bool canConvert = false;
        switch (ValidationType.Name)
        {

            case "Boolean":
                bool boolVal = false;
                canConvert = bool.TryParse(strValue, out boolVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of boolean");
            case "Int32":
                int intVal = 0;
                canConvert = int.TryParse(strValue, out intVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int32");
            case "Double":
                double doubleVal = 0;
                canConvert = double.TryParse(strValue, out doubleVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Double");
            case "Int64":
                long longVal = 0;
                canConvert = long.TryParse(strValue, out longVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int64");
            default:
                throw new InvalidCastException($"{ValidationType.Name} is not supported");
        }
    }
}

XAML:

Very important: don't forget to set ValidatesOnTargetUpdated="True" it won't work without this definition.

 <TextBox x:Name="Int32Holder"
         IsReadOnly="{Binding IsChecked,ElementName=CheckBoxEditModeController,Converter={converters:BooleanInvertConverter}}"
         Style="{StaticResource ValidationAwareTextBoxStyle}"
         VerticalAlignment="Center">
    <!--Text="{Binding Converter={cnv:TypeConverter}, ConverterParameter='Int32', Path=ValueToEdit.Value, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"-->
    <TextBox.Text>
        <Binding Path="Name"
                 Mode="TwoWay"
                 UpdateSourceTrigger="PropertyChanged"
                 Converter="{cnv:TypeConverter}"
                 ConverterParameter="Int32"
                 ValidatesOnNotifyDataErrors="True"
                 ValidatesOnDataErrors="True"
                 NotifyOnValidationError="True">
            <Binding.ValidationRules>
                <validationRules:NumericValidationRule ValidationType="{x:Type system:Int32}"
                                                       ValidatesOnTargetUpdated="True" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
    <!--NumericValidationRule-->
</TextBox>

INotifyDataErrorInfo example:

public abstract class ViewModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
{

    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        ValidateAsync();
    }
    #endregion


    public virtual void OnLoaded()
    {
    }

    #region INotifyDataErrorInfo
    private ConcurrentDictionary<string, List<string>> _errors = new ConcurrentDictionary<string, List<string>>();

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

    public void OnErrorsChanged(string propertyName)
    {
        var handler = ErrorsChanged;
        if (handler != null)
            handler(this, new DataErrorsChangedEventArgs(propertyName));
    }

    public IEnumerable GetErrors(string propertyName)
    {
        List<string> errorsForName;
        _errors.TryGetValue(propertyName, out errorsForName);
        return errorsForName;
    }

    public bool HasErrors
    {
        get { return _errors.Any(kv => kv.Value != null && kv.Value.Count > 0); }
    }

    public Task ValidateAsync()
    {
        return Task.Run(() => Validate());
    }

    private object _lock = new object();
    public void Validate()
    {
        lock (_lock)
        {
            var validationContext = new ValidationContext(this, null, null);
            var validationResults = new List<ValidationResult>();
            Validator.TryValidateObject(this, validationContext, validationResults, true);

            foreach (var kv in _errors.ToList())
            {
                if (validationResults.All(r => r.MemberNames.All(m => m != kv.Key)))
                {
                    List<string> outLi;
                    _errors.TryRemove(kv.Key, out outLi);
                    OnErrorsChanged(kv.Key);
                }
            }

            var q = from r in validationResults
                    from m in r.MemberNames
                    group r by m into g
                    select g;

            foreach (var prop in q)
            {
                var messages = prop.Select(r => r.ErrorMessage).ToList();

                if (_errors.ContainsKey(prop.Key))
                {
                    List<string> outLi;
                    _errors.TryRemove(prop.Key, out outLi);
                }
                _errors.TryAdd(prop.Key, messages);
                OnErrorsChanged(prop.Key);
            }
        }
    }
    #endregion

}

View Model Implementation:

public class MainFeedViewModel : BaseViewModel//, IDataErrorInfo
{
    private ObservableCollection<FeedItemViewModel> _feedItems;
    [XmlIgnore]
    public ObservableCollection<FeedItemViewModel> FeedItems
    {
        get
        {
            return _feedItems;
        }
        set
        {
            _feedItems = value;
            OnPropertyChanged("FeedItems");
        }
    }
    [XmlIgnore]
    public ObservableCollection<FeedItemViewModel> FilteredFeedItems
    {
        get
        {
            if (SearchText == null) return _feedItems;

            return new ObservableCollection<FeedItemViewModel>(_feedItems.Where(x => x.Title.ToUpper().Contains(SearchText.ToUpper())));
        }
    }

    private string _title;
    [Required]
    [StringLength(20)]
    //[CustomNameValidationRegularExpression(5, 20)]
    [CustomNameValidationAttribute(3, 20)]
    public string Title
    {
        get { return _title; }
        set
        {
            _title = value;
            OnPropertyChanged("Title");
        }
    }
    private string _url;
    [Required]
    [StringLength(200)]
    [Url]
    //[CustomValidation(typeof(MainFeedViewModel), "UrlValidation")]
    /// <summary>
    /// Validation of URL should be with custom method like the one that implemented below, or with 
    /// </summary>
    public string Url
    {
        get { return _url; }
        set
        {
            _url = value;
            OnPropertyChanged("Url");
        }
    }

    public MainFeedViewModel(string url, string title)
    {
        Title = title;
        Url = url;
    }
    /// <summary>
    /// 
    /// </summary>
    public MainFeedViewModel()
    {

    }
    public MainFeedViewModel(ObservableCollection<FeedItemViewModel> feeds)
    {
        _feedItems = feeds;
    }


    private string _searchText;
    [XmlIgnore]
    public string SearchText
    {
        get { return _searchText; }
        set
        {
            _searchText = value;

            OnPropertyChanged("SearchText");
            OnPropertyChanged("FilteredFeedItems");
        }
    }

    #region Data validation local
    /// <summary>
    /// Custom URL validation method
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public static ValidationResult UrlValidation(object obj, ValidationContext context)
    {
        var vm = (MainFeedViewModel)context.ObjectInstance;
        if (!Uri.IsWellFormedUriString(vm.Url, UriKind.Absolute))
        {
            return new ValidationResult("URL should be in valid format", new List<string> { "Url" });
        }
        return ValidationResult.Success;
    }

    #endregion
}

XAML:

<UserControl x:Class="RssReaderTool.Views.AddNewFeedDialogView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300"
             d:DesignWidth="300">
    <FrameworkElement.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate x:Name="TextErrorTemplate">
                        <DockPanel LastChildFill="True">
                            <AdornedElementPlaceholder>
                                <Border BorderBrush="Red"
                                        BorderThickness="2" />
                            </AdornedElementPlaceholder>
                            <TextBlock FontSize="20"
                                       Foreground="Red">*?*</TextBlock>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError"
                         Value="True">
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource=
            {x:Static RelativeSource.Self},
            Path=(Validation.Errors)[0].ErrorContent}"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
        <!--<Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError"
                         Value="true">
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                        Path=(Validation.Errors)[0].ErrorContent}" />
                </Trigger>
            </Style.Triggers>
        </Style>-->
    </FrameworkElement.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="5" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="5" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBlock Text="Feed Name"
                   ToolTip="Display" />
        <TextBox Text="{Binding MainFeedViewModel.Title,UpdateSourceTrigger=PropertyChanged,ValidatesOnNotifyDataErrors=True,ValidatesOnDataErrors=True}"
                 Grid.Column="2" />

        <TextBlock Text="Feed Url"
                   Grid.Row="2" />
        <TextBox Text="{Binding MainFeedViewModel.Url,UpdateSourceTrigger=PropertyChanged,ValidatesOnNotifyDataErrors=True,ValidatesOnDataErrors=True}"
                 Grid.Column="2"
                 Grid.Row="2" />
    </Grid>
</UserControl>

IDataErrorInfo:

View Model:

public class OperationViewModel : ViewModelBase, IDataErrorInfo
{
    private const int ConstCodeMinValue = 1;
    private readonly IEventAggregator _eventAggregator;
    private OperationInfoDefinition _operation;
    private readonly IEntityFilterer _contextFilterer;
    private OperationDescriptionViewModel _description;

    public long Code
    {
        get { return _operation.Code; }
        set
        {
            if (SetProperty(value, _operation.Code, o => _operation.Code = o))
            {
                UpdateDescription();
            }
        }
    }

    public string Description
    {
        get { return _operation.Description; }
        set
        {
            if (SetProperty(value, _operation.Description, o => _operation.Description = o))
            {
                UpdateDescription();
            }
        }
    }

    public string FriendlyName
    {
        get { return _operation.FriendlyName; }
        set
        {
            if (SetProperty(value, _operation.FriendlyName, o => _operation.FriendlyName = o))
            {
                UpdateDescription();
            }
        }
    }

    public int Timeout
    {
        get { return _operation.Timeout; }
        set
        {
            if (SetProperty(value, _operation.Timeout, o => _operation.Timeout = o))
            {
                UpdateDescription();
            }
        }
    }

    public string Category
    {
        get { return _operation.Category; }
        set
        {
            if (SetProperty(value, _operation.Category, o => _operation.Category = o))
            {
                UpdateDescription();
            }
        }
    }

    public bool IsManual
    {
        get { return _operation.IsManual; }
        set
        {
            if (SetProperty(value, _operation.IsManual, o => _operation.IsManual = o))
            {
                UpdateDescription();
            }
        }
    }


    void UpdateDescription()
    {
        //some code
    }




    #region Validation




    #region IDataErrorInfo

    public ValidationResult Validate()
    {
        return ValidationService.Instance.ValidateNumber(Code, ConstCodeMinValue, long.MaxValue);
    }

    public string this[string columnName]
    {
        get
        {
            var validation = ValidationService.Instance.ValidateNumber(Code, ConstCodeMinValue, long.MaxValue);

            return validation.IsValid ? null : validation.ErrorContent.ToString();
        }
    }

    public string Error
    {
        get
        {
            var result = Validate();
            return result.IsValid ? null : result.ErrorContent.ToString();
        }
    }
    #endregion

    #endregion
}

XAML:

<controls:NewDefinitionControl x:Class="DiagnosticsDashboard.EntityData.Operations.Views.NewOperationView"
                               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                               xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                               xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                               xmlns:views="clr-namespace:DiagnosticsDashboard.EntityData.Operations.Views"
                               xmlns:controls="clr-namespace:DiagnosticsDashboard.Core.Controls;assembly=DiagnosticsDashboard.Core"
                               xmlns:c="clr-namespace:DiagnosticsDashboard.Core.Validation;assembly=DiagnosticsDashboard.Core"
                               mc:Ignorable="d">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Label Grid.Column="0"
               Grid.Row="0"
               Margin="5">Code:</Label>
        <Label Grid.Column="0"
               Grid.Row="1"
               Margin="5">Description:</Label>
        <Label Grid.Column="0"
               Grid.Row="2"
               Margin="5">Category:</Label>
        <Label Grid.Column="0"
               Grid.Row="3"
               Margin="5">Friendly Name:</Label>
        <Label Grid.Column="0"
               Grid.Row="4"
               Margin="5">Timeout:</Label>
        <Label Grid.Column="0"
               Grid.Row="5"
               Margin="5">Is Manual:</Label>
        <TextBox Grid.Column="1"
                 Text="{Binding Code,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
                 Grid.Row="0"
                 Margin="5"/>
        <TextBox Grid.Column="1"
                 Grid.Row="1"
                 Margin="5"
                 Text="{Binding Description}" />
        <TextBox Grid.Column="1"
                 Grid.Row="2"
                 Margin="5"
                 Text="{Binding Category}" />
        <TextBox Grid.Column="1"
                 Grid.Row="3"
                 Margin="5"
                 Text="{Binding FriendlyName}" />
        <TextBox Grid.Column="1"
                 Grid.Row="4"
                 Margin="5"
                 Text="{Binding Timeout}" />
        <CheckBox Grid.Column="1"
                  Grid.Row="5"
                  Margin="5"
                  IsChecked="{Binding IsManual}"
                  VerticalAlignment="Center" />


    </Grid>
</controls:NewDefinitionControl>

How to convert file to base64 in JavaScript?

Building up on Dmitri Pavlutin and joshua.paling answers, here's an extended version that extracts the base64 content (removes the metadata at the beginning) and also ensures padding is done correctly.

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      let encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
      if ((encoded.length % 4) > 0) {
        encoded += '='.repeat(4 - (encoded.length % 4));
      }
      resolve(encoded);
    };
    reader.onerror = error => reject(error);
  });
}

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

How do I append to a table in Lua

foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"

This works because the # operator computes the length of the list. The empty list has length 0, etc.

If you're using Lua 5.3+, then you can do almost exactly what you wanted:

foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"

Expressions are not statements in Lua and they need to be used somehow.

How to use a switch case 'or' in PHP

Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

Make a phone call programmatically

Tried the Swift 3 option above, but it didnt work. I think you need the following if you are to run against iOS 10+ on Swift 3:

Swift 3 (iOS 10+):

let phoneNumber = mymobileNO.titleLabel.text       
UIApplication.shared.open(URL(string: phoneNumber)!, options: [:], completionHandler: nil)

How to get character for a given ascii value

It can also be done in some other manner

byte[] pass_byte = Encoding.ASCII.GetBytes("your input value");

and then print result. by using foreach loop.

error: member access into incomplete type : forward declaration of

Move doSomething definition outside of its class declaration and after B and also make add accessible to A by public-ing it or friend-ing it.

class B;

class A
{
    void doSomething(B * b);
};

class B
{
public:
    void add() {}
};

void A::doSomething(B * b)
{
    b->add();
}

How can I get a process handle by its name in C++?

If you don't mind using system(), doing system("taskkill /f /im process.exe") would be significantly easier than these other methods.

How to easily initialize a list of Tuples?

One technique I think is a little easier and that hasn't been mentioned before here:

var asdf = new [] { 
    (Age: 1, Name: "cow"), 
    (Age: 2, Name: "bird")
}.ToList();

I think that's a little cleaner than:

var asdf = new List<Tuple<int, string>> { 
    (Age: 1, Name: "cow"), 
    (Age: 2, Name: "bird")
};

How to view UTF-8 Characters in VIM or Gvim

this work for me and do not need change any config file

vim --cmd "set encoding=utf8" --cmd "set fileencoding=utf8" fileToOpen

JOptionPane Input to int

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

I don't like all the solutions that use magic numbers like 97 or 36.

const A = 'A'.charCodeAt(0);

let numberToCharacter = number => String.fromCharCode(A + number);

let characterToNumber = character => character.charCodeAt(0) - A;

this assumes uppercase letters and starts 'A' at 0.

How to create a list of objects?

I have some hacky answers that are likely to be terrible... but I have very little experience at this point.

a way:

class myClass():
    myInstances = []
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02
        self.__class__.myInstances.append(self)

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

for thisObj in myClass.myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

A hack way to get this done:

import sys
class myClass():
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
    thisStep += 1
    if "myClass object at" in thisLocalsLine:
        print(thisLocalsLine)
        print(myLocals[(thisStep - 2)])
        #myInstances.append(myLocals[(thisStep - 2)])
        print(myInstances)
        myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))

for thisObj in myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

Another more 'clever' hack:

import sys
class myClass():
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02

myInstances = []
myClasses = {
    "myObj01": ["Foo", "Bar"],
    "myObj02": ["FooBar",  "Baz"]
    }

for thisClass in myClasses.keys():
    exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
    myInstances.append(getattr(sys.modules[__name__], thisClass))

for thisObj in myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

How to add a new schema to sql server 2008?

Use the CREATE SCHEMA syntax or, in SSMS, drill down through Databases -> YourDatabaseName -> Security -> Schemas. Right-click on the Schemas folder and select "New Schema..."

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

Received the following error

Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.

com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Landroid/support/constraint/ConstraintSet$1

Fix : go to Build -> Clean Project

What is the difference between children and childNodes in JavaScript?

Understand that .children is a property of an Element. 1 Only Elements have .children, and these children are all of type Element. 2

However, .childNodes is a property of Node. .childNodes can contain any node. 3

A concrete example would be:

let el = document.createElement("div");
el.textContent = "foo";

el.childNodes.length === 1; // Contains a Text node child.
el.children.length === 0;   // No Element children.

Most of the time, you want to use .children because generally you don't want to loop over Text or Comment nodes in your DOM manipulation.

If you do want to manipulate Text nodes, you probably want .textContent instead. 4


1. Technically, it is an attribute of ParentNode, a mixin included by Element.
2. They are all elements because .children is a HTMLCollection, which can only contain elements.
3. Similarly, .childNodes can hold any node because it is a NodeList.
4. Or .innerText. See the differences here or here.

Changing the resolution of a VNC session in linux

I'm running TigerVNC on my Linux server, which has basic randr support. I just start vncserver without any -randr or multiple -geometry options.

When I run xrandr in a terminal, it displays all the available screen resolutions:

bash> xrandr
 SZ:    Pixels          Physical       Refresh
 0   1920 x 1200   ( 271mm x 203mm )   60
 1   1920 x 1080   ( 271mm x 203mm )   60
 2   1600 x 1200   ( 271mm x 203mm )   60
 3   1680 x 1050   ( 271mm x 203mm )   60
 4   1400 x 1050   ( 271mm x 203mm )   60
 5   1360 x 768    ( 271mm x 203mm )   60
 6   1280 x 1024   ( 271mm x 203mm )   60
 7   1280 x 960    ( 271mm x 203mm )   60
 8   1280 x 800    ( 271mm x 203mm )   60
 9   1280 x 720    ( 271mm x 203mm )   60
*10  1024 x 768    ( 271mm x 203mm )  *60
 11   800 x 600    ( 271mm x 203mm )   60
 12   640 x 480    ( 271mm x 203mm )   60
Current rotation - normal
Current reflection - none
Rotations possible - normal
Reflections possible - none

I can then easily switch to another resolution (f.e. switch to 1360x768):

bash> xrandr -s 5

I'm using TightVnc viewer as the client and it automatically adapts to the new resolution.

How to use SqlClient in ASP.NET Core?

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

Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:

System.Data.Common and System.Data.SqlClient.

Currently this creates dependency in project.json –> aspnetcore50 section to these two libraries.

"aspnetcore50": {
       "dependencies": {
           "System.Runtime": "4.0.20-beta-22523",
           "System.Data.Common": "4.0.0.0-beta-22605",
           "System.Data.SqlClient": "4.0.0.0-beta-22605"
       }
}

Try getting System.Data.Common and System.Data.SqlClient via Nuget and see if this adds the above dependencies for you, but in a nutshell you are missing System.Runtime.

Edit: As per Mozarts answer, if you are using .NET Core 3+, reference Microsoft.Data.SqlClient instead.

Reading my own Jar's Manifest

A simpler way to do this is to use getPackage(). For example, to get Implementation-Version:

Application.class.getPackage().getImplementationVersion()

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

Proper way to restrict text input values (e.g. only numbers)

After did lot of research finally I create a function which full fill the requirement. The function which I created restrict all special character and allow only alphabets and number.. and that function works fine for both either you did copy paste and typing both. Hope it works :)

 public inputValidator(event: any) {
    //console.log(event.target.value);
    const pattern = /^[a-zA-Z0-9]*$/;   
    //let inputChar = String.fromCharCode(event.charCode)
    if (!pattern.test(event.target.value)) {
      event.target.value = event.target.value.replace(/[^a-zA-Z0-9]/g, "");
      // invalid character, prevent input

    }
  }

     <input type="text" [(ngModel)]="abc.abc" (input)="inputValidator($event)" />

How you use -
1) Add above method in your class component of ts file.
2) Call method inputValidator($event) on input event..

React Native fetch() Network Request Failed

For Android devices, go to your project root folder and run the command:

adb reverse tcp:[your_own_server_port] tcp:[your_own_server_port]

e.g., adb reverse tcp:8088 tcp:8088

This will make your physical device(i.e. Android phone) listen to the localhost server running on your development machine (i.e. your computer) on address http://localhost:[your_own_server_port].

After that, you can directly use http:localhost:[your_port] /your_api in your react-native fetch() call.

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

Please check this jsFiddle. (The code is basically the same you posted but I use an element instead of the window to bind the scroll events).

As far as I can see, there is no problem with the code you posted. The error you mentioned normally occurs when you create a loop of changes over a property. For example, like when you watch for changes on a certain property and then change the value of that property on the listener:

$scope.$watch('users', function(value) {
  $scope.users = [];
});

This will result on an error message:

Uncaught Error: 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: ...

Make sure that your code doesn't have this kind of situations.

update:

This is your problem:

<div ng-init="user.score=user.id+1"> 

You shouldn't change objects/models during the render or otherwise, it will force a new render (and consequently a loop, which causes the 'Error: 10 $digest() iterations reached. Aborting!').

If you want to update the model, do it on the Controller or on a Directive, never on the view. angularjs documentation recommends not to use the ng-init exactly to avoid these kinds of situations:

Use ngInit directive in templates (for toy/example apps only, not recommended for real applications)

Here's a jsFiddle with a working example.

How to generate a simple popup using jQuery

Check out jQuery UI Dialog. You would use it like this:

The jQuery:

$(document).ready(function() {
    $("#dialog").dialog();
});

The markup:

<div id="dialog" title="Dialog Title">I'm in a dialog</div>

Done!

Bear in mind that's about the simplest use-case there is, I would suggest reading the documentation to get a better idea of just what can be done with it.

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

$(document).click() not working correctly on iPhone. jquery

try this, applies only to iPhone and iPod so you're not making everything turn blue on chrome or firefox mobile;

/iP/i.test(navigator.userAgent) && $('*').css('cursor', 'pointer');

basically, on iOS, things aren't "clickable" by default -- they're "touchable" (pfffff) so you make them "clickable" by giving them a pointer cursor. makes total sense, right??

Getting the thread ID from a thread

To find the current thread Id use - `Thread.CurrentThread.ManagedThreadId'. But in this case you might need the current win32 thread id - use pInvoke to get it with this function:

[DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
public static extern Int32 GetCurrentWin32ThreadId();

First you'll need to save the managed thread id and win32 thread id connection - use a dictionary that maps a win32 id to managed thread.

Then to find a thread by it's id iterate over the process's thread using Process.GetCurrentProcess().Threads and find the thread with that id:

foreach (ProcessThread thread in Process.GetCurrentProcess().Threads)
{
     var managedThread = win32ToManagedThread[thread.id];
     if((managedThread.ManagedThreadId == threadId)
     {
         return managedThread;
     }
}

Frequency table for a single variable

Maybe .value_counts()?

>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0       1
1       2
2       2
3       3
4       3
5       3
6    fred
7     1.8
8     1.8
>>> counts = my_series.value_counts()
>>> counts
3       3
2       2
1.8     2
fred    1
1       1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

Apply style to cells of first row

Below works for first tr of the table under thead

table thead tr:first-child {
   background: #f2f2f2;
}

And this works for the first tr of thead and tbody both:

table thead tbody tr:first-child {
   background: #f2f2f2;
}

SQL Bulk Insert with FIRSTROW parameter skips the following line

Given how mangled some data can look after BCP importing into SQL Server from non-SQL data sources, I'd suggest doing all the BCP import into some scratch tables first.

For example

truncate table Address_Import_tbl

BULK INSERT dbo.Address_Import_tbl FROM 'E:\external\SomeDataSource\Address.csv' WITH ( FIELDTERMINATOR = '|', ROWTERMINATOR = '\n', MAXERRORS = 10 )

Make sure all the columns in Address_Import_tbl are nvarchar(), to make it as agnostic as possible, and avoid type conversion errors.

Then apply whatever fixes you need to Address_Import_tbl. Like deleting the unwanted header.

Then run a INSERT SELECT query, to copy from Address_Import_tbl to Address_tbl, along with any datatype conversions you need. For example, to cast imported dates to SQL DATETIME.

regex with space and letters only?

$('#input').on('keyup', function() {
     var RegExpression = /^[a-zA-Z\s]*$/;  
     ...

});

\s will allow the space

How to finish current activity in Android

If you are doing a loading screen, just set the parameter to not keep it in activity stack. In your manifest.xml, where you define your activity do:

<activity android:name=".LoadingScreen" android:noHistory="true" ... />

And in your code there is no need to call .finish() anymore. Just do startActivity(i);

There is also no need to keep a instance of your current activity in a separate field. You can always access it like LoadingScreen.this.doSomething() instead of private LoadingScreen loadingScreen;

Git refusing to merge unrelated histories on rebase

Try git pull --rebase development

How to detect if javascript files are loaded?

I don't have a reference for it handy, but script tags are processed in order, and so if you put your $(document).ready(function1) in a script tag after the script tags that define function1, etc., you should be good to go.

<script type='text/javascript' src='...'></script>
<script type='text/javascript' src='...'></script>
<script type='text/javascript'>
$(document).ready(function1);
</script>

Of course, another approach would be to ensure that you're using only one script tag, in total, by combining files as part of your build process. (Unless you're loading the other ones from a CDN somewhere.) That will also help improve the perceived speed of your page.

EDIT: Just realized that I didn't actually answer your question: I don't think there's a cross-browser event that's fired, no. There is if you work hard enough, see below. You can test for symbols and use setTimeout to reschedule:

<script type='text/javascript'>
function fireWhenReady() {
    if (typeof function1 != 'undefined') {
        function1();
    }
    else {
        setTimeout(fireWhenReady, 100);
    }
}
$(document).ready(fireWhenReady);
</script>

...but you shouldn't have to do that if you get your script tag order correct.


Update: You can get load notifications for script elements you add to the page dynamically if you like. To get broad browser support, you have to do two different things, but as a combined technique this works:

function loadScript(path, callback) {

    var done = false;
    var scr = document.createElement('script');

    scr.onload = handleLoad;
    scr.onreadystatechange = handleReadyStateChange;
    scr.onerror = handleError;
    scr.src = path;
    document.body.appendChild(scr);

    function handleLoad() {
        if (!done) {
            done = true;
            callback(path, "ok");
        }
    }

    function handleReadyStateChange() {
        var state;

        if (!done) {
            state = scr.readyState;
            if (state === "complete") {
                handleLoad();
            }
        }
    }
    function handleError() {
        if (!done) {
            done = true;
            callback(path, "error");
        }
    }
}

In my experience, error notification (onerror) is not 100% cross-browser reliable. Also note that some browsers will do both mechanisms, hence the done variable to avoid duplicate notifications.

How do you get the list of targets in a makefile?

This is a modification to jsp's very helpful answer (https://stackoverflow.com/a/45843594/814145). I like the idea of getting not only a list of targets but also their descriptions. jsp's Makefile puts the description as the comment, which I found often will be repeated in the target's description echo command. So instead, I extract the description from the echo command for each target.

Example Makefile:

.PHONY: all
all: build
        : "same as 'make build'"

.PHONY: build
build:
        @echo "Build the project"

.PHONY: clean
clean:
        @echo "Clean the project"

.PHONY: help
help:
        @echo -n "Common make targets"
        @echo ":"
        @cat Makefile | sed -n '/^\.PHONY: / h; /\(^\t@*echo\|^\t:\)/ {H; x; /PHONY/ s/.PHONY: \(.*\)\n.*"\(.*\)"/    make \1\t\2/p; d; x}'| sort -k2,2 |expand -t 20

Output of make help:

$ make help
Common make targets:
    make all        same as 'make build'
    make build      Build the project
    make clean      Clean the project
    make help       Common make targets

Notes:

  • Same as jsp's answer, only PHONY targets may be listed, which may or may not work for your case
  • In addition, it only lists those PHONY targets that have a echo or : command as the first command of the recipe. : means "do nothing". I use it here for those targets that no echo is needed, such as all target above.
  • There is an additional trick for the help target to add the ":" in the make help output.

Select columns from result set of stored procedure

To achieve this, first you create a #test_table like below:

create table #test_table(
    col1 int,
    col2 int,
   .
   .
   .
    col80 int
)

Now execute procedure and put value in #test_table:

insert into #test_table
EXEC MyStoredProc 'param1', 'param2'

Now you fetch the value from #test_table:

select col1,col2....,col80 from #test_table

adb not finding my device / phone (MacOS X)

I had to enable USB debugging (Security settings) developer option in addition to USB debugging in Redmi Note 4.

Convert java.util.Date to String

In single shot ;)

To get the Date

String date = new SimpleDateFormat("yyyy-MM-dd",   Locale.getDefault()).format(new Date());

To get the Time

String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());

To get the date and time

String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());

Happy coding :)

How to put text in the upper right, or lower right corner of a "box" using css

You need to put "here" into a <div> or <span> with style="float: right".

Get all validation errors from Angular 2 FormGroup

// IF not populated correctly - you could get aggregated FormGroup errors object
let getErrors = (formGroup: FormGroup, errors: any = {}) {
  Object.keys(formGroup.controls).forEach(field => {
    const control = formGroup.get(field);
    if (control instanceof FormControl) {
      errors[field] = control.errors;
    } else if (control instanceof FormGroup) {
      errors[field] = this.getErrors(control);
    }
  });
  return errors;
}

// Calling it:
let formErrors = getErrors(this.form);

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

Add shadow to custom shape on Android

This is my version of a drop shadow. I was going for a hazy shadow all around the shape and used this answer by Joakim Lundborg as my starting point. What I changed is to add corners to all the shadow items and to increase the radius of the corner for each subsequent shadow item. So here is the xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#02000000" />
            <corners android:radius="8dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#05000000" />
            <corners android:radius="7dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#10000000" />
            <corners android:radius="6dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#15000000" />
            <corners android:radius="5dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#20000000" />
            <corners android:radius="4dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#25000000" />
            <corners android:radius="3dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#30000000" />
            <corners android:radius="3dp" />
        </shape>
    </item>

    <!-- Background -->
    <item>
    <shape>
            <solid android:color="#0099CC" />
        <corners android:radius="3dp" />
    </shape>
   </item>
</layer-list>

How do I perform a JAVA callback between classes?

Define an interface, and implement it in the class that will receive the callback.

Have attention to the multi-threading in your case.

Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html

interface CallBack {                   //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
    void methodToCallBack();
}

class CallBackImpl implements CallBack {          //class that implements the method to callback defined in the interface
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();       //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
        caller.register(callBack);
    }
} 

In your case, apart from multi-threading you could do like this:

interface ServerInterface {
    void newSeverConnection(Socket socket);
}

public class Server implements ServerInterface {

    public Server(int _address) {
        System.out.println("Starting Server...");
        serverConnectionHandler = new ServerConnections(_address, this);
        workers.execute(serverConnectionHandler);
        System.out.println("Do something else...");
    }

    void newServerConnection(Socket socket) {
        System.out.println("A function of my child class was called.");
    }

}

public class ServerConnections implements Runnable {

    private ServerInterface serverInterface;

    public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
      serverPort = _serverPort;
      serverInterface = _serverInterface;
    }

    @Override
    public void run() {
        System.out.println("Starting Server Thread...");

        if (serverInterface == null) {
            System.out.println("Server Thread error: callback null");
        }

        try {
            mainSocket = new ServerSocket(serverPort);

            while (true) {
                serverInterface.newServerConnection(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Multi-threading

Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.

The observer-pattern

The observer-pattern does nearly this, the major difference is the use of an ArrayList for adding more than one listener. Where this is not needed, you get better performance with one reference.

SQL to add column and comment in table in single command

No, you can't.

There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.

If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.


In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.

SQL> desc sys.com$
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OBJ#                                      NOT NULL NUMBER
 COL#                                               NUMBER
 COMMENT$                                           VARCHAR2(4000)

SQL>

The column is optional and sys.col$ does not contain comment information.

I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.

Practical uses for AtomicInteger

For example, I have a library that generates instances of some class. Each of these instances must have a unique integer ID, as these instances represent commands being sent to a server, and each command must have a unique ID. Since multiple threads are allowed to send commands concurrently, I use an AtomicInteger to generate those IDs. An alternative approach would be to use some sort of lock and a regular integer, but that's both slower and less elegant.

Left align and right align within div in Bootstrap

<div class="row">
  <div class="col-xs-6 col-sm-4">Total cost</div>
  <div class="col-xs-6 col-sm-4"></div>
  <div class="clearfix visible-xs-block"></div>
  <div class="col-xs-6 col-sm-4">$42</div>
</div>

That should do the job just ok

How to prevent form from being submitted?

The following works as of now (tested in chrome and firefox):

<form onsubmit="event.preventDefault(); return validateMyForm();">

where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()

Gradle failed to resolve library in Android Studio

For me follwing steps helped.

It seems to be bug of Android Studio 3.4/3.5 and it was "fixed" by disabling:

File ? Settings ? Experimental ? Gradle ? Only sync the active variant

Angular 2 optional route parameter

The suggested answers here, including the accepted answer from rerezz which suggest adding multiple route entries work fine.

However the component will be recreated when changing between the route entries, i.e. between the route entry with the parameter and the entry without the parameter.

If you want to avoid this, you can create your own route matcher which will match both routes:

export function userPageMatcher(segments: UrlSegment[]): UrlMatchResult {
    if (segments.length > 0 && segments[0].path === 'user') {
        if (segments.length === 1) {
            return {
                consumed: segments,
                posParams: {},
            };
        }
        if (segments.length === 2) {
            return {
                consumed: segments,
                posParams: { id: segments[1] },
            };
        }
        return <UrlMatchResult>(null as any);
    }
    return <UrlMatchResult>(null as any);
 }

Then use the matcher in your route config:

const routes: Routes = [
    {
        matcher: userPageMatcher,
        component: User,
    }
];

OwinStartup not firing

In my case, the IIS application pool was not set to v4. It was v2.

Changed the AppPool to v4 and everything was okay.

Programmatically stop execution of python script?

The exit() and quit() built in functions do just what you want. No import of sys needed.

Alternatively, you can raise SystemExit, but you need to be careful not to catch it anywhere (which shouldn't happen as long as you specify the type of exception in all your try.. blocks).

tsconfig.json: Build:No inputs were found in config file

When using Visual Studio Code, building the project (i.e. pressing Ctrl + Shift + B), moves your .ts file into the .vscode folder (I don't know why it does this), then generates the TS18003 error. What I did was move my .ts file out of the .vscode folder, back into the root folder and build the project again.

The project built successfully!

Send POST data via raw json with postman

meda's answer is completely legit, but when I copied the code I got an error!

Somewhere in the "php://input" there's an invalid character (maybe one of the quotes?).

When I typed the "php://input" code manually, it worked. Took me a while to figure out!

SQL Server 2008 - Case / If statements in SELECT Clause

The most obvious solutions are already listed. Depending on where the query is sat (i.e. in application code) you can't always use IF statements and the inline CASE statements can get painful where lots of columns become conditional. Assuming Col1 + Col3 + Col7 are the same type, and likewise Col2, Col4 + Col8 you can do this:

SELECT Col1, Col2 FROM tbl WHERE @Var LIKE 'xyz'
UNION ALL
SELECT Col3, Col4 FROM tbl WHERE @Var LIKE 'zyx'
UNION ALL
SELECT Col7, Col8 FROM tbl WHERE @Var NOT LIKE 'xyz' AND @Var NOT LIKE 'zyx'

As this is a single command there are several performance benefits with regard to plan caching. Also the Query Optimiser will quickly eliminate those statements where @Var doesn't match the appropriate value without touching the storage engine.

Google API authentication: Not valid origin for the client

Trying on a different browser(chrome) worked for me and clearing cache on firefox cleared the issue.

(PS: Not add the hosting URIs to Authorized JavaScript origins in API credentials would give you Error:redirect_uri_mismatch)

failed to load ad : 3

There could be one of the reasons that You might have created your advertise from adMob console by clicking yes that your app is already in playstore and giving url of your live app.Now in that case you wont able to run your ads in any other projects which is having diff package id then the live one(not even test advertise).You have to implement the ads in live project containing same package id and in other case will be getting ad failed to load ad : 3.

Thanks! Happy coding!

Bootstrap: add margin/padding space between columns

I would keep an extra column in the middle for larger displays and reset to default when the columns collapse on smaller displays. Something like this:

    <div class="row">
        <div class="text-center col-md-5 col-sm-6">
            Widget 1
        </div>
        <div class="col-md-2">
            <!-- Gap between columns -->
        </div>
        <div class="text-center col-md-5 col-sm-6">
            Widget 2
        </div>
    </div>

Run Java Code Online

I found this online java compiler and runner. It work also with threads and showing results immediately. http://www.browxy.com

Get the number of rows in a HTML table

Try:

var count = $('#gvPerformanceResult tr').length;

How to fix a header on scroll

If you are using React I recently published a custom hook which enables you to do this. You need to supply a ref to the sticky element as well as a ref to the element you want it to stick to the top of. It handles the screen "jump" (as mentioned in other responses) for you as well.

const sticky = useRef<HTMLDivElement>(null)
const container = useRef<HTMLDivElement>(null)

useStickyScroll({
    element: sticky,
    container: container
})

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

Putty on ubuntu There is no need to install the driver for PL2303 So only type the command to enable the putty Sudo chmod 666 /dev/ttyUSB0 Done Open the putty.

git checkout tag, git pull fails in branch

This command is deprecated: git branch --set-upstream master origin/master

So, when trying to set up tracking, this is the command that worked for me:

git branch --set-upstream-to=origin/master master

How do I delete an entity from symfony2

Symfony is smart and knows how to make the find() by itself :

public function deleteGuestAction(Guest $guest)
{
    if (!$guest) {
        throw $this->createNotFoundException('No guest found');
    }

    $em = $this->getDoctrine()->getEntityManager();
    $em->remove($guest);
    $em->flush();

    return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}

To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

INSERT VALUES WHERE NOT EXISTS

Ingnoring the duplicated unique constraint isn't a solution?

INSERT IGNORE INTO tblSoftwareTitles...

JPA Native Query select and cast object

When your native query is based on joins, in that case you can get the result as list of objects and process it.

one simple example.

@Autowired
EntityManager em;

    String nativeQuery = "select name,age from users where id=?";   
    Query query = em.createNativeQuery(nativeQuery);
    query.setParameter(1,id);

    List<Object[]> list = query.getResultList();

    for(Object[] q1 : list){

        String name = q1[0].toString();
        //..
        //do something more on 
     }

PHP Sort a multidimensional array by element containing date

http://us2.php.net/manual/en/function.array-multisort.php see third example:

<?php

$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);

?>

fyi, using a unix (seconds from 1970) or mysql timestamp (YmdHis - 20100526014500) would be be easier for the parser but i think in your case it makes no difference.

Reading an integer from user input

You need to typecast the input. try using the following

int input = Convert.ToInt32(Console.ReadLine()); 

It will throw exception if the value is non-numeric.

Edit

I understand that the above is a quick one. I would like to improve my answer:

String input = Console.ReadLine();
int selectedOption;
if(int.TryParse(input, out selectedOption))
{
      switch(selectedOption) 
      {
           case 1:
                 //your code here.
                 break;
           case 2:
                //another one.
                break;
           //. and so on, default..
      }

} 
else
{
     //print error indicating non-numeric input is unsupported or something more meaningful.
}

Google Maps API v3: Can I setZoom after fitBounds?

If I'm not mistaken, I'm assuming you want all your points to be visible on the map with the highest possible zoom level. I accomplished this by initializing the zoom level of the map to 16(not sure if it's the highest possible zoom level on V3).

var map = new google.maps.Map(document.getElementById('map_canvas'), {
  zoom: 16,
  center: marker_point,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

Then after that I did the bounds stuff:

var bounds = new google.maps.LatLngBounds();

// You can have a loop here of all you marker points
// Begin loop
bounds.extend(marker_point);
// End loop

map.fitBounds(bounds);

Result: Success!

How to change int into int64?

This is probably obvious, but simplest:

i64 := int64(23)

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

For me, my issue was that I was

android:background="?attr/selectableItemBackground"

To a LinearLayout background, once I removed it the test passed.

Rotate an image in image source in html

You can do this:

<img src="your image" style="transform:rotate(90deg);">

it is much easier.

React Native: How to select the next TextInput after pressing the "next" keyboard button?

Set the second TextInput focus, when the previous TextInput's onSubmitEditing is triggered.

Try this

  1. Adding a Ref to second TextInput
    ref={(input) => { this.secondTextInput = input; }}

  2. Bind focus function to first TextInput's onSubmitEditing event.
    onSubmitEditing={() => { this.secondTextInput.focus(); }}

  3. Remember to set blurOnSubmit to false, to prevent keyboard flickering.
    blurOnSubmit={false}

When all done, it should looks like this.

<TextInput
    placeholder="FirstTextInput"
    returnKeyType="next"
    onSubmitEditing={() => { this.secondTextInput.focus(); }}
    blurOnSubmit={false}
/>

<TextInput
    ref={(input) => { this.secondTextInput = input; }}
    placeholder="secondTextInput"
/>

Animate background image change with jQuery

Ok, I figured it out, this is pretty simple with a little html trick:

http://jsfiddle.net/kRjrn/8/

HTML

<body>
    <div id="background">.
    </div>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>    
</body>?

javascript

$(document).ready(function(){
    $('#background').animate({ opacity: 1 }, 3000);
});?

CSS

#background {
    background-image: url("http://media.noupe.com//uploads/2009/10/wallpaper-pattern.jpg");
    opacity: 0;
    margin: 0;
    padding: 0;
    z-index: -1;
    position: absolute;
    width: 100%;
    height: 100%;
}?

How to iterate (keys, values) in JavaScript?

You can use JavaScript forEach Loop:

myMap.forEach((value, key) => {
    console.log('value: ', value);
    console.log('key: ', key);
});

How to create a zip archive of a directory in Python?

Function to create zip file.

def CREATEZIPFILE(zipname, path):
    #function to create a zip file
    #Parameters: zipname - name of the zip file; path - name of folder/file to be put in zip file

    zipf = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
    zipf.setpassword(b"password") #if you want to set password to zipfile

    #checks if the path is file or directory
    if os.path.isdir(path):
        for files in os.listdir(path):
            zipf.write(os.path.join(path, files), files)

    elif os.path.isfile(path):
        zipf.write(os.path.join(path), path)
    zipf.close()

Upgrading Node.js to latest version

You don't need to worry about an upgrading process.

You can just install the newest version using the official documentation as if you didn't have it installed and it will work like a charm. > https://nodejs.org/en/download/package-manager/ ;)

Remove characters from NSString?

Taken from NSString

stringByReplacingOccurrencesOfString:withString:

Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement

Parameters

target

The string to replace.

replacement

The string with which to replace target.

Return Value

A new string in which all occurrences of target in the receiver are replaced by replacement.

How do I get interactive plots again in Spyder/IPython/matplotlib?

As said in the comments, the problem lies in your script. Actually, there are 2 problems:

  • There is a matplotlib error, I guess that you're passing an argument as None somewhere. Maybe due to the defaultdict ?
  • You call show() after each subplot. show() should be called once at the end of your script. The alternative is to use interactive mode, look for ion in matplotlib's documentation.

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

You're looking for the MemoryStream.Write method.

For example, the following code will write the contents of a byte[] array into a memory stream:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);

Alternatively, you could create a new, non-resizable MemoryStream object based on the byte array:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);

Allow a div to cover the whole page instead of the area within the container

Try this

#dimScreen {
    width: 100%;
    height: 100%;
    background:rgba(255,255,255,0.5);
    position: fixed;
    top: 0;
    left: 0;
}

Superscript in CSS only?

.superscript {
  position: relative;
  top: 5px;
  font-size: 90%;
  vertical-align: super;
}

XML parsing of a variable string in JavaScript

I've always used the approach below which works in IE and Firefox.

Example XML:

<fruits>
  <fruit name="Apple" colour="Green" />
  <fruit name="Banana" colour="Yellow" />
</fruits>

JavaScript:

function getFruits(xml) {
  var fruits = xml.getElementsByTagName("fruits")[0];
  if (fruits) {
    var fruitsNodes = fruits.childNodes;
    if (fruitsNodes) {
      for (var i = 0; i < fruitsNodes.length; i++) {
        var name = fruitsNodes[i].getAttribute("name");
        var colour = fruitsNodes[i].getAttribute("colour");
        alert("Fruit " + name + " is coloured " + colour);
      }
    }
  }
}

How to handle checkboxes in ASP.NET MVC forms?

this is what i did to loose the double values when using the Html.CheckBox(...

Replace("true,false","true").Split(',')

with 4 boxes checked, unchecked, unchecked, checked it turns true,false,false,false,true,false into true,false,false,true. just what i needed

Can I change the checkbox size using CSS?

My understanding is that this isn't easy at all to do cross-browser. Instead of trying to manipulate the checkbox control, you could always build your own implementation using images, javascript, and hidden input fields. I'm assuming this is similar to what niceforms is (from Staicu lonut's answer above), but wouldn't be particularly difficult to implement. I believe jQuery has a plugin to allow for this custom behavior as well (will look for the link and post here if I can find it).

Dynamically changing font size of UILabel

Here is the fill code of a UILabel subclass that implements animated font size change:

@interface SNTextLayer : CATextLayer

@end

@implementation SNTextLayer

- (void)drawInContext:(CGContextRef)ctx {
    // We override this to make text appear at the same vertical positon as in UILabel
    // (otherwise it's shifted tdown)
    CGFloat height = self.bounds.size.height;
    float fontSize = self.fontSize;
    // May need to adjust this somewhat if it's not aligned perfectly in your implementation
    float yDiff = (height-fontSize)/2 - fontSize/10;

    CGContextSaveGState(ctx);
    CGContextTranslateCTM(ctx, 0.0, yDiff);
    [super drawInContext:ctx];
     CGContextRestoreGState(ctx);
}

@end

@interface SNAnimatableLabel ()

@property CATextLayer* textLayer;

@end

@interface SNAnimatableLabel : UILabel

- (void)animateFontToSize:(CGFloat)fontSize withDuration:(double)duration;

@end



@implementation SNAnimatableLabel


- (void)awakeFromNib {
    [super awakeFromNib];
    _textLayer = [SNTextLayer new];
    _textLayer.backgroundColor = self.backgroundColor.CGColor;
    _textLayer.foregroundColor = self.textColor.CGColor;
    _textLayer.font = CGFontCreateWithFontName((CFStringRef)self.font.fontName);
    _textLayer.frame = self.bounds;
    _textLayer.string = self.text;
    _textLayer.fontSize = self.font.pointSize;
    _textLayer.contentsScale = [UIScreen mainScreen].scale;
    [_textLayer setPosition: CGPointMake(CGRectGetMidX(_textLayer.frame), CGRectGetMidY(_textLayer.frame))];
    [_textLayer setAnchorPoint: CGPointMake(0.5, 0.5)];
    [_textLayer setAlignmentMode: kCAAlignmentCenter];
    self.textColor = self.backgroundColor;
    // Blend text with background, so that it doens't interfere with textlayer text
    [self.layer addSublayer:_textLayer];
    self.layer.masksToBounds = NO;
}

- (void)setText:(NSString *)text {
    _textLayer.string = text;
    super.text = text;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    // Need to enlarge the frame, otherwise the text may get clipped for bigger font sizes
    _textLayer.frame = CGRectInset(self.bounds, -5, -5);
}

- (void)animateFontToSize:(CGFloat)fontSize withDuration:(double)duration {
    [CATransaction begin];
    [CATransaction setAnimationDuration:duration];
    _textLayer.fontSize = fontSize;
    [CATransaction commit];
}

Converting Pandas dataframe into Spark dataframe error

You need to make sure your pandas dataframe columns are appropriate for the type spark is inferring. If your pandas dataframe lists something like:

pd.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5062 entries, 0 to 5061
Data columns (total 51 columns):
SomeCol                    5062 non-null object
Col2                       5062 non-null object

And you're getting that error try:

df[['SomeCol', 'Col2']] = df[['SomeCol', 'Col2']].astype(str)

Now, make sure .astype(str) is actually the type you want those columns to be. Basically, when the underlying Java code tries to infer the type from an object in python it uses some observations and makes a guess, if that guess doesn't apply to all the data in the column(s) it's trying to convert from pandas to spark it will fail.

ZIP file content type for HTTP request

If you want the MIME type for a file, you can use the following code:

- (NSString *)mimeTypeForPath:(NSString *)path
{
    // get a mime type for an extension using MobileCoreServices.framework

    CFStringRef extension = (__bridge CFStringRef)[path pathExtension];
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
    assert(UTI != NULL);

    NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType));
    assert(mimetype != NULL);

    CFRelease(UTI);

    return mimetype;
}

In the case of a ZIP file, this will return application/zip.

What is the lifetime of a static variable in a C++ function?

Motti is right about the order, but there are some other things to consider:

Compilers typically use a hidden flag variable to indicate if the local statics have already been initialized, and this flag is checked on every entry to the function. Obviously this is a small performance hit, but what's more of a concern is that this flag is not guaranteed to be thread-safe.

If you have a local static as above, and foo is called from multiple threads, you may have race conditions causing plonk to be initialized incorrectly or even multiple times. Also, in this case plonk may get destructed by a different thread than the one which constructed it.

Despite what the standard says, I'd be very wary of the actual order of local static destruction, because it's possible that you may unwittingly rely on a static being still valid after it's been destructed, and this is really difficult to track down.

Run an Ansible task only when the variable contains a specific string

None of the above answers worked for me in ansible 2.3.0.0, but the following does:

when: variable1 | search("value")

In ansible 2.9 this is deprecated in favor of using ~ concatenation for variable replacement:

when: "variable1.find('v=' ~ value) == -1"

http://jinja.pocoo.org/docs/dev/templates/#other-operators

Other options:

when: "inventory_hostname in groups[sync_source]"

'cannot find or open the pdb file' Visual Studio C++ 2013

It worked for me. Go to Tools-> Options -> Debugger -> Native and check the Load DLL exports. Hope this helps

Where is HttpContent.ReadAsAsync?

Having hit this one a few times and followed a bunch of suggestions, if you don't find it available after installing the NuGet Microsoft.AspNet.WebApi.Client manually add a reference from the packages folder in the solution to:

\Microsoft.AspNet.WebApi.Client.5.2.6\lib\net45\System.Net.Http.Formatting.dll

And don't get into the trap of adding older references to the System.Net.Http.Formatting.dll NuGet

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

How can I add a box-shadow on one side of an element?

Here is a codepen to demonstrate for each side, or a working snippet:

_x000D_
_x000D_
.boxes {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.box {_x000D_
  margin: 20px;_x000D_
  border: 1px solid #ccc;_x000D_
  font-family: Helvetica Neue, Arial, sans-serif;_x000D_
  font-weight: 100;_x000D_
  letter-spacing: 2px;_x000D_
  color: #999;_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  text-align: center;_x000D_
  flex: 1;_x000D_
  padding: 40px;_x000D_
  line-height: 1.4em;_x000D_
}_x000D_
_x000D_
.top {_x000D_
  box-shadow: 0 -5px 5px -5px #333;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  box-shadow: 5px 0 5px -5px #333;_x000D_
}_x000D_
_x000D_
.bottom {_x000D_
  box-shadow: 0 5px 5px -5px #333;_x000D_
}_x000D_
_x000D_
.left {_x000D_
  box-shadow: -5px 0 5px -5px #333;_x000D_
}
_x000D_
<div class="boxes">_x000D_
  <div class="box top">Top Only</div>_x000D_
  <div class="box right">Right Only</div>_x000D_
  <div class="box bottom">Bottom Only</div>_x000D_
  <div class="box left">Left Only</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to upload files to server using Putty (ssh)

You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.

Laravel 5.4 Specific Table Migration

php artisan migrate --path=database/migrations/2020_04_10_130703_create_test_table.php

note: after --path no / before

Split varchar into separate columns in Oracle

Simple way is to convert into column

SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))

CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);

CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
   RETURN split_tbl
   PIPELINED IS
   l_idx PLS_INTEGER;
   l_list VARCHAR2 (32767) := p_list;
   l_value VARCHAR2 (32767);
BEGIN
   LOOP
      l_idx := INSTR (l_list, p_del);

      IF l_idx > 0 THEN
         PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
         l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
      ELSE
         PIPE ROW (l_list);
         EXIT;
      END IF;
   END LOOP;

   RETURN;
END split;

ImportError: No Module Named bs4 (BeautifulSoup)

Just tagging onto Balthazar's answer. Running

pip install BeautifulSoup4

did not work for me. Instead use

pip install beautifulsoup4

Self Join to get employee manager name

Try this one.

SELECT Employee.emp_id, Employee.emp_name,Manager.emp_id as Mgr_Id, Manager.emp_name as Mgr_Name 
FROM tblEmployeeDetails Employee 
LEFT JOIN tblEmployeeDetails Manager ON Employee.emp_mgr_id = Manager.emp_id

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

I think @tsatiz's answer is mostly right (programming to an interface rather than an implementation). However, by programming to the interface you won't lose any functionality. Let me explain.

If you declare your variable as a List<type> list = new ArrayList<type> you do not actually lose any functionality of the ArrayList. All you need to do is to cast your list down to an ArrayList. Here's an example:

List<String> list = new ArrayList<String>();
((ArrayList<String>) list).ensureCapacity(19);

Ultimately I think tsatiz is correct as once you cast to an ArrayList you're no longer coding to an interface. However, it's still a good practice to initially code to an interface and, if it later becomes necessary, code to an implementation if you must.

Hope that helps!

Automatically start a Windows Service on install

You can use the GetServices method of ServiceController class to get an array of all the services. Then, find your service by checking the ServiceName property of each service. When you've found your service, call the Start method to start it.

You should also check the Status property to see what state it is already in before calling start (it may be running, paused, stopped, etc..).

What is the difference between for and foreach?

foreach is almost equivalent to :

var enumerator = list.GetEnumerator();
var element;
while(enumerator.MoveNext()){
  element = enumerator.Current;
}

and in order to implemetn a "foreach" compliant pattern, this need to provide a class that have a method GetEnumerator() which returns an object that have a MoveNext() method, a Reset() method and a Current property.

Indeed, you do not need to implement neither IEnumerable nor IEnumerator.

Some derived points:

  • foreach does not need to know the collection length so allows to iterate through a "stream" or a kind of "elements producer".
  • foreach calls virtual methods on the iterator (the most of the time) so can perform less well than for.

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

How can I send an Ajax Request on button click from a form with 2 buttons?

function sendAjaxRequest(element,urlToSend) {
             var clickedButton = element;
              $.ajax({type: "POST",
                  url: urlToSend,
                  data: { id: clickedButton.val(), access_token: $("#access_token").val() },
                  success:function(result){
                    alert('ok');
                  },
                 error:function(result)
                  {
                  alert('error');
                 }
             });
     }

       $(document).ready(function(){
          $("#button_1").click(function(e){
              e.preventDefault();
              sendAjaxRequest($(this),'/pages/test/');
          });

          $("#button_2").click(function(e){
              e.preventDefault();
              sendAjaxRequest($(this),'/pages/test/');
          });
        });
  1. created as separate function for sending the ajax request.
  2. Kept second parameter as URL because in future you want to send data to different URL

How to get tf.exe (TFS command line client)?

Following on from the earlier answers above but based on a VS 2019 install ;
I needed to run "tf git permission" commands, and copied the following files from:

C:\Program Files (x86)\Microsoft Visual Studio\2019\TeamExplorer\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer

Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Core.WebApi.dll
Microsoft.TeamFoundation.Diff.dll
Microsoft.TeamFoundation.Git.Client.dll
Microsoft.TeamFoundation.Git.Contracts.dll
Microsoft.TeamFoundation.Git.Controls.dll
Microsoft.TeamFoundation.Git.CoreServices.dll
Microsoft.TeamFoundation.Git.dll
Microsoft.TeamFoundation.Git.Graph.dll
Microsoft.TeamFoundation.Git.HostingProvider.AzureDevOps.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.imagemanifest
Microsoft.TeamFoundation.Git.Provider.dll
Microsoft.TeamFoundation.SourceControl.WebApi.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.TeamFoundation.VersionControl.Common.dll
Microsoft.TeamFoundation.VersionControl.Common.Integration.dll
Microsoft.TeamFoundation.VersionControl.Controls.dll
Microsoft.VisualStudio.Services.Client.Interactive.dll
Microsoft.VisualStudio.Services.Common.dll
Microsoft.VisualStudio.Services.WebApi.dll
TF.exe
TF.exe.config

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

If Folder getting from other, and host file is already generated on ProjectName\.vs\config folder, then it conflicts with a new one and gets this error.
So delete host file from ProjectName\.vs\config and restart project once again. It was worked for me

How do I check if file exists in Makefile so I can delete it?

It may need a backslash on the end of the line for continuation (although perhaps that depends on the version of make):

if [ -a myApp ] ; \
then \
     rm myApp ; \
fi;

How to run a program automatically as admin on Windows 7 at startup?

I think the task scheduler would be overkill (imho). There is a startup folder for win7.

C:\Users\miliu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Just create a shortcut for your autostart Applicaton, edit the properties of the shortcut and have it always run as administrator.

Your kids could close it of course, but if they are tech-savvy they always find a way to keep you out. I know i did when i was younger.

Good luck!

modal View controllers - how to display and dismiss

I think you misunderstood some core concepts about iOS modal view controllers. When you dismiss VC1, any presented view controllers by VC1 are dismissed as well. Apple intended for modal view controllers to flow in a stacked manner - in your case VC2 is presented by VC1. You are dismissing VC1 as soon as you present VC2 from VC1 so it is a total mess. To achieve what you want, buttonPressedFromVC1 should have the mainVC present VC2 immediately after VC1 dismisses itself. And I think this can be achieved without delegates. Something along the lines:

UIViewController presentingVC = [self presentingViewController];
[self dismissViewControllerAnimated:YES completion:
 ^{
    [presentingVC presentViewController:vc2 animated:YES completion:nil];
 }];

Note that self.presentingViewController is stored in some other variable, because after vc1 dismisses itself, you shouldn't make any references to it.

Convert string into integer in bash script - "Leading Zero" number error

You could also use bc

hour=8
result=$(echo "$hour + 1" | bc)
echo $result
9

How to unset (remove) a collection element after fetching it?

You would want to use ->forget()

$collection->forget($key);

Link to the forget method documentation

Difference between try-catch and throw in java

If you execute the following example, you will know the difference between a Throw and a Catch block.

In general terms:

The catch block will handle the Exception

throws will pass the error to his caller.

In the following example, the error occurs in the throwsMethod() but it is handled in the catchMethod().

public class CatchThrow {

private static void throwsMethod() throws NumberFormatException {
    String  intNumber = "5A";

    Integer.parseInt(intNumber);
}

private static void catchMethod() {
    try {

        throwsMethod();

    } catch (NumberFormatException e) {
        System.out.println("Convertion Error");
    }

}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    catchMethod();
}

}

MySQL: How to set the Primary Key on phpMyAdmin?

You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go

ORA-12154 could not resolve the connect identifier specified

I had this error in Visual Studio 2013, with an SSIS project. I set Project, Properties, Debugging, Run64BitRuntime = false and then the SSIS package ran. However, when I deployed the package to the server I had to set the value to true (Server is 64 bit Windows 2012 / Sql 2014 ).

I think the reasoning behind this is that Visual Studio is a 32 bit application.

Importing Excel files into R, xlsx or xls

As stated by many here, I am writing the same thing but with an additional point!

At first we need to make sure that our R Studio has these two packages installed:

  1. "readxl"
  2. "XLConnect"

In order to load a package in R you can use the below function:

install.packages("readxl/XLConnect")
library(XLConnect)
search()

search will display the list of current packages being available in your R Studio.

Now another catch, even though you might have these two packages but still you may encounter problem while reading "xlsx" file and the error could be like "error: more columns than column name"

To solve this issue you can simply resave your excel sheet "xlsx" in to

"CSV (Comma delimited)"

and your life will be super easy....

Have fun!!

PDO with INSERT INTO through prepared statements

Please add try catch also in your code so that you can be sure that there in no exception.

try {
    $hostname = "servername";
    $dbname = "dbname";
    $username = "username";
    $pw = "password";
    $pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }

Show "loading" animation on button click

The best loading and blocking that particular div for ajax call until it succeeded is Blockui

go through this link http://www.malsup.com/jquery/block/#element

example usage:

 <span class="no-display smallLoader"><img src="/images/loader-small.png" /></span>

script

jQuery.ajax(
{   
 url: site_path+"/restaurantlist/addtocart",
 type: "POST",
 success: function (data) {
   jQuery("#id").unblock(); 
},
beforeSend:function (data){
    jQuery("#id").block({ 
    message: jQuery(".smallLoader").html(), 
    css: { 
         border: 'none', 
         backgroundColor: 'none'
    },
    overlayCSS: { backgroundColor: '#afafaf' } 
    });

}
});

hope this helps really it is very interactive.

Pad a number with leading zeros in JavaScript

You did say you had a number-

String.prototype.padZero= function(len, c){
    var s= '', c= c || '0', len= (len || 2)-this.length;
    while(s.length<len) s+= c;
    return s+this;
}
Number.prototype.padZero= function(len, c){
    return String(this).padZero(len,c);
}

What is the difference between const int*, const int * const, and int const *?

Just for the sake of completeness for C following the others explanations, not sure for C++.

  • pp - pointer to pointer
  • p - pointer
  • data - the thing pointed, in examples x
  • bold - read-only variable

Pointer

  • p data - int *p;
  • p data - int const *p;
  • p data - int * const p;
  • p data - int const * const p;

Pointer to pointer

  1. pp p data - int **pp;
  2. pp p data - int ** const pp;
  3. pp p data - int * const *pp;
  4. pp p data - int const **pp;
  5. pp p data - int * const * const pp;
  6. pp p data - int const ** const pp;
  7. pp p data - int const * const *pp;
  8. pp p data - int const * const * const pp;
// Example 1
int x;
x = 10;
int *p = NULL;
p = &x;
int **pp = NULL;
pp = &p;
printf("%d\n", **pp);

// Example 2
int x;
x = 10;
int *p = NULL;
p = &x;
int ** const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);

// Example 3
int x;
x = 10;
int * const p = &x; // Definition must happen during declaration
int * const *pp = NULL;
pp = &p;
printf("%d\n", **pp);

// Example 4
int const x = 10; // Definition must happen during declaration
int const * p = NULL;
p = &x;
int const **pp = NULL;
pp = &p;
printf("%d\n", **pp);

// Example 5
int x;
x = 10;
int * const p = &x; // Definition must happen during declaration
int * const * const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);

// Example 6
int const x = 10; // Definition must happen during declaration
int const *p = NULL;
p = &x;
int const ** const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);

// Example 7
int const x = 10; // Definition must happen during declaration
int const * const p = &x; // Definition must happen during declaration
int const * const *pp = NULL;
pp = &p;
printf("%d\n", **pp);

// Example 8
int const x = 10; // Definition must happen during declaration
int const * const p = &x; // Definition must happen during declaration
int const * const * const pp = &p; // Definition must happen during declaration
printf("%d\n", **pp);

N-levels of Dereference

Just keep going, but may the humanity excommunicate you.

int x = 10;
int *p = &x;
int **pp = &p;
int ***ppp = &pp;
int ****pppp = &ppp;

printf("%d \n", ****pppp);

How to center a "position: absolute" element

If you have set a width you may use:

position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
text-align: center;

Add URL link in CSS Background Image?

Try wrapping the spans in an anchor tag and apply the background image to that.

HTML:

<div class="header">
    <a href="/">
        <span class="header-title">My gray sea design</span><br />
        <span class="header-title-two">A beautiful design</span>
    </a>
</div>

CSS:

.header {
    border-bottom:1px solid #eaeaea;
}

.header a {
    display: block;
    background-image: url("./images/embouchure.jpg");
    background-repeat: no-repeat;
    height:160px;
    padding-left:280px;
    padding-top:50px;
    width:470px;
    color: #eaeaea;
}

Using 'sudo apt-get install build-essentials'

In my case, simply "dropping the s" was not the problem (although it is of course a step in the right direction to use the correct package name).

I had to first update the package manager indexes like this:

sudo apt-get update

Then after that the installation worked fine:

sudo apt-get install build-essential

LaTeX table positioning

If you want to have two tables next to each other you can use: (with float package loaded)

\begin{table}[H]
 \begin{minipage}{.5\textwidth}
  %first table
 \end{minipage}
 \begin{minipage}{.5\textwidth}
  %second table
 \end{minipage}
\end{table}

Each one will have own caption and number. Another option is subfigure package.

Cross Domain Form POSTing

Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).

It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).

But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.

A good example: here

And a good documentation from Mozilla: here

How to read string from keyboard using C?

When reading input from any file (stdin included) where you do not know the length, it is often better to use getline rather than scanf or fgets because getline will handle memory allocation for your string automatically so long as you provide a null pointer to receive the string entered. This example will illustrate:

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {

    char *line = NULL;  /* forces getline to allocate with malloc */
    size_t len = 0;     /* ignored when line = NULL */
    ssize_t read;

    printf ("\nEnter string below [ctrl + d] to quit\n");

    while ((read = getline(&line, &len, stdin)) != -1) {

        if (read > 0)
            printf ("\n  read %zd chars from stdin, allocated %zd bytes for line : %s\n", read, len, line);

        printf ("Enter string below [ctrl + d] to quit\n");
    }

    free (line);  /* free memory allocated by getline */

    return 0;
}

The relevant parts being:

char *line = NULL;  /* forces getline to allocate with malloc */
size_t len = 0;     /* ignored when line = NULL */
/* snip */
read = getline (&line, &len, stdin);

Setting line to NULL causes getline to allocate memory automatically. Example output:

$ ./getline_example

Enter string below [ctrl + d] to quit
A short string to test getline!

  read 32 chars from stdin, allocated 120 bytes for line : A short string to test getline!

Enter string below [ctrl + d] to quit
A little bit longer string to show that getline will allocated again without resetting line = NULL

  read 99 chars from stdin, allocated 120 bytes for line : A little bit longer string to show that getline will allocated again without resetting line = NULL

Enter string below [ctrl + d] to quit

So with getline you do not need to guess how long your user's string will be.

Converting Array to List

Old way but still working!

 int[] values = {1,2,3,4};
 List<Integer> list = new ArrayList<>(values.length);

 for(int valor : values) {
     list.add(valor);
 }

VMWare Player vs VMWare Workstation

One main reason we went with Workstation over Player at my job is because we need to run VMs that use a physical disk as their hard drive instead of a virtual disk. Workstation supports using physical disks while Player does not.

Diff files present in two different directories

You can use the diff command for that:

diff -bur folder1/ folder2/

This will output a recursive diff that ignore spaces, with a unified context:

  • b flag means ignoring whitespace
  • u flag means a unified context (3 lines before and after)
  • r flag means recursive

segmentation fault : 11

What system are you running on? Do you have access to some sort of debugger (gdb, visual studio's debugger, etc.)?

That would give us valuable information, like the line of code where the program crashes... Also, the amount of memory may be prohibitive.

Additionally, may I recommend that you replace the numeric limits by named definitions?

As such:

#define DIM1_SZ 1000
#define DIM2_SZ 1000000

Use those whenever you wish to refer to the array dimension limits. It will help avoid typing errors.

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

There's been a lot of good examples of how to attack this problem. The original question was about using the substringWithRange, but as has been pointed out that's a harder way to go than just doing your own extension.

The above range solution is good. You can also do this a dozen other ways. Here's yet another example of how you could do this:

extension String{
    func sub(start: Int, length: Int) -> String {
        assert(start >= 0, "Cannot extract from a negative starting index")
        assert(length >= 0, "Cannot extract a negative length string")
        assert(start <= countElements(self) - 1, "cannot start beyond the end")
        assert(start + length <= countElements(self), "substring goes past the end of the original")
        var a = self.substringFromIndex(start)
        var b = a.substringToIndex(length)
        return b
    }
}
var s = "apple12345"
println(s.sub(6, length: 4))
// prints "2345"

Arduino Tools > Serial Port greyed out

In my case this turned out to be a bad USB hub.

The 'lsusb' command can be used to display all recognized devices. If the unit is not plugged in the option to set the speed will be disabled.

The lsusb command should output something like the string 'Future Technology Devices International, Ltd Bridge(I2C/SPI/UART/FIFO)' if your device is recognized. Mine was an RFDuino

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

I got this problem because i uninstalled the jdk version 13 and reinstall the jdk version 8

Even though i have updated the path variables eclipse still pick the old configuration.

You need to edit the eclipse.ini file which is in your folder where eclipse.exe is placed.

enter image description here

Just update this file with the latest path so eclipse can pick it up

enter image description here

switch() statement usage

In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:

http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/

Personally, when I have 3 or more cases, I usually just go with case/switch.

jQuery datepicker set selected date, on the fly

please Find below one it helps me a lot to set data function

$('#datepicker').datepicker({dateFormat: 'yy-mm-dd'}).datepicker('setDate', '2010-07-25');

What are -moz- and -webkit-?

These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit for Chrome, Safari; -moz for Firefox, -o for Opera, -ms for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.

This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.

To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:

.elementClass {
    -moz-border-radius: 2em;
    -ms-border-radius: 2em;
    -o-border-radius: 2em;
    -webkit-border-radius: 2em;
    border-radius: 2em;
}

Specifically, to address the CSS in your question, the lines you quote:

-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;

Specify the column-count, column-gap and column-fill properties for Webkit browsers and Firefox.

References:

CSS text-transform capitalize on all caps

JavaScript:

var links = document.getElementsByClassName("link");
for (var i = 0; i < links.length; i++) {
  links[i].innerHTML = links[i].innerHTML.toLowerCase();
}

CSS:

.link { text-transform: capitalize; }

What Khan "ended up doing" (which is cleaner and worked for me) is down in the comments of the post marked as the answer.

Detect if a Form Control option button is selected in VBA

If you are using a Form Control, you can get the same property as ActiveX by using OLEFormat.Object property of the Shape Object. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.

Dim opt As OptionButton

With Sheets("Sheet1") ' Try to be always explicit
    Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
    Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With

But then again, you really don't need to know the value.
If you use Form Control, you associate a Macro or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.

For example you have 2 Form Control Option Buttons.

Sub CheckOptions()
    Select Case Application.Caller
    Case "Option Button 1"
    ' Action for option button 1
    Case "Option Button 2"
    ' Action for option button 2
    End Select
End Sub

In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller.
This way, no need to check whether the option button value is true or false.

Reading from text file until EOF repeats last line

Just follow closely the chain of events.

  • Grab 10
  • Grab 20
  • Grab 30
  • Grab EOF

Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.

Try this:

while (true) {
    int x;
    iFile >> x;
    if( iFile.eof() ) break;
    cerr << x << endl;
}

By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.

Creating Unicode character from its number

String st="2202";
int cp=Integer.parseInt(st,16);// it convert st into hex number.
char c[]=Character.toChars(cp);
System.out.println(c);// its display the character corresponding to '\u2202'.

How to catch all exceptions in c# using try and catch?

Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex is declared but not used.

But note that some exceptions are special and will be rethrown automatically.

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx


As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:

  • Catch and ignore a specific exception that you know is not fatal.

    catch (SomeSpecificException)
    {
        // Ignore this exception.
    }
    
  • Catch and log all exceptions.

    catch (Exception e)
    {
        // Something unexpected went wrong.
        Log(e);
        // Maybe it is also necessary to terminate / restart the application.
    }
    
  • Catch all exceptions, do some cleanup, then rethrow the exception.

    catch
    {
        SomeCleanUp();
        throw;
    }
    

Note that in the last case the exception is rethrown using throw; and not throw ex;.

How do you generate a random double uniformly distributed between 0 and 1 from C++?

This is what I ended up using for my needs:

int range_upper_bound = 12345;
int random_number =((double)rand()/(double)range_upper_bound);

Case statement with multiple values in each 'when' block

Another nice way to put your logic in data is something like this:

# Initialization.
CAR_TYPES = {
  foo_type: ['honda', 'acura', 'mercedes'],
  bar_type: ['toyota', 'lexus']
  # More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }

case @type_for_name[car]
when :foo_type
  # do foo things
when :bar_type
  # do bar things
end

Adding a css class to select using @Html.DropDownList()

Try This

 @Html.DropDownList("Id", null, new { @class = "ct-js-select ct-select-lg" })

Creating CSS Global Variables : Stylesheet theme management

You will either need LESS or SASS for the same..

But here is another alternative which I believe will work out in CSS3..

http://css3.bradshawenterprises.com/blog/css-variables/

Example :

 :root {
    -webkit-var-beautifulColor: rgba(255,40,100, 0.8);
    -moz-var-beautifulColor: rgba(255,40,100, 0.8);
    -ms-var-beautifulColor: rgba(255,40,100, 0.8);
    -o-var-beautifulColor: rgba(255,40,100, 0.8);
    var-beautifulColor: rgba(255,40,100, 0.8);
 }
  .example1 h1 {
    color: -webkit-var(beautifulColor);
    color: -moz-var(beautifulColor);
    color: -ms-var(beautifulColor);
    color: -o-var(beautifulColor);
    color: var(beautifulColor);
 }

Convert comma separated string to array in PL/SQL

Simple Code

    create or replace function get_token(text_is varchar2, token_in number, delim_is varchar2 := ';') return varchar2 is
       text_ls varchar2(2000);
       spos_ln number;
       epos    _ln number;
    begin
       text_ls := delim_is || text_is || rpad(delim_is, token_in, delim_is);
       spos_ln := instr(text_ls, delim_is, 1, token_in);
       epos_ln := instr(text_ls, delim_is, 1, token_in+1);
       return substr(text_ls, spos_ln+1, epos_ln-spos_ln-1);
    end get_token;

Detecting the onload event of a window opened with window.open

The core problem seems to be you are opening a window to show a page whose content is already cached in the browser. Therefore no loading happens and therefore no load-event happens.

One possibility could be to use the 'pageshow' -event instead, as described in:

https://support.microsoft.com/en-us/help/3011939/onload-event-does-not-occur-when-clicking-the-back-button-to-a-previou

How do I find the last column with data?

I know this is old, but I've tested this in many ways and it hasn't let me down yet, unless someone can tell me otherwise.

Row number

Row = ws.Cells.Find(What:="*", After:=[A1] , SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Column Letter

ColumnLetter = Split(ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Cells.Address(1, 0), "$")(0)

Column Number

ColumnNumber = ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

For similar assembly binding errors , following steps may help:

  1. Right click on your Solution and click Manage Nuget Packages for Solution ...
  2. go to Consolidate Tab (last tab) and check if any any differences between packages installed in different projects inside your solution. specially pay attention to your referenced projects which may have lower versions because they usually are less noticed)
  3. consolidate specially packages related to your assembly error and note that many packages are dependent on some other packages like *.code & *.api & ...
  4. after resolving all suspected consolidations , rebuild and rerun the app and see if the assembly bindings are resolved.

cor shows only NA or 1 for correlations - Why?

Tell the correlation to ignore the NAs with use argument, e.g.:

cor(data$price, data$exprice, use = "complete.obs")

Finding height in Binary Search Tree

    public void HeightRecursive()
    {
        Console.WriteLine( HeightHelper(root) ); 
    }

    private int HeightHelper(TreeNode node)
    {
        if (node == null)
        {
            return -1;
        }
        else
        {
            return 1 + Math.Max(HeightHelper(node.LeftNode),HeightHelper(node.RightNode));           
        }
    }

C# code. Include these two methods in your BST class. you need two method to calculate height of tree. HeightHelper calculate it, & HeightRecursive print it in main().

How to clear form after submit in Angular 2?

Here's how I do it Angular 8:

Get a local reference of your form:

<form name="myForm" #myForm="ngForm"></form>
@ViewChild('myForm', {static: false}) myForm: NgForm;

And whenever you need to reset the form, call resetForm method:

this.myForm.resetForm();

You will need FormsModule from @angular/forms for it to work. Be sure to add it to your module imports.

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

I faced the same problem when import C++ Dll in .Net Framework +4, I unchecked Project->Properties->Build->Prefer 32-bit and it solved for me.

How to loop an object in React?

const tifOptions = [];

for (const [key, value] of Object.entries(tifs)) {
    tifOptions.push(<option value={key} key={key}>{value}</option>);
}

return (
   <select id="tif" name="tif" onChange={this.handleChange}>  
      { tifOptions }          
   </select>
)

How to convert string values from a dictionary, into int/float datatypes?

To handle the possibility of int, float, and empty string values, I'd use a combination of a list comprehension, dictionary comprehension, along with conditional expressions, as shown:

dicts = [{'a': '1' , 'b': '' , 'c': '3.14159'},
         {'d': '4' , 'e': '5' , 'f': '6'}]

print [{k: int(v) if v and '.' not in v else float(v) if v else None
            for k, v in d.iteritems()}
               for d in dicts]

# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]

However dictionary comprehensions weren't added to Python 2 until version 2.7. It can still be done in earlier versions as a single expression, but has to be written using the dict constructor like the following:

# for pre-Python 2.7

print [dict([k, int(v) if v and '.' not in v else float(v) if v else None]
            for k, v in d.iteritems())
                for d in dicts]

# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]

Note that either way this creates a new dictionary of lists, instead of modifying the original one in-place (which would need to be done differently).

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

I found elegant work around for me to remove symbols and continue to keep string as string in follows:

yourstring = yourstring.encode('ascii', 'ignore').decode('ascii')

It's important to notice that using the ignore option is dangerous because it silently drops any unicode(and internationalization) support from the code that uses it, as seen here (convert unicode):

>>> u'City: Malmö'.encode('ascii', 'ignore').decode('ascii')
'City: Malm'

Swift: print() vs println() vs NSLog()

A few differences:

  1. print vs println:

    The print function prints messages in the Xcode console when debugging apps.

    The println is a variation of this that was removed in Swift 2 and is not used any more. If you see old code that is using println, you can now safely replace it with print.

    Back in Swift 1.x, print did not add newline characters at the end of the printed string, whereas println did. But nowadays, print always adds the newline character at the end of the string, and if you don't want it to do that, supply a terminator parameter of "".

  2. NSLog:

    • NSLog adds a timestamp and identifier to the output, whereas print will not;

    • NSLog statements appear in both the device’s console and debugger’s console whereas print only appears in the debugger console.

    • NSLog in iOS 10-13/macOS 10.12-10.x uses printf-style format strings, e.g.

        NSLog("%0.4f", CGFloat.pi)
      

      that will produce:

      2017-06-09 11:57:55.642328-0700 MyApp[28937:1751492] 3.1416

    • NSLog from iOS 14/macOS 11 can use string interpolation. (Then, again, in iOS 14 and macOS 11, we would generally favor Logger over NSLog. See next point.)

    Nowadays, while NSLog still works, we would generally use “unified logging” (see below) rather than NSLog.

  3. Effective iOS 14/macOS 11, we have Logger interface to the “unified logging” system. For an introduction to Logger, see WWDC 2020 Explore logging in Swift.

    • To use Logger, you must import os:

      import os
      
    • Like NSLog, unified logging will output messages to both the Xcode debugging console and the device console, too

    • Create a Logger and log a message to it:

      let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "network")
      logger.log("url = \(url)")
      

      When you observe the app via the external Console app, you can filter on the basis of the subsystem and category. It is very useful to differentiate your debugging messages from (a) those generated by other subsystems on behalf of your app, or (b) messages from other categories or types.

    • You can specify different types of logging messages, either .info, .debug, .error, .fault, .critical, .notice, .trace, etc.:

      logger.error("web service did not respond \(error.localizedDescription)")
      

      So, if using the external Console app, you can choose to only see messages of certain categories (e.g. only show debugging messages if you choose “Include Debug Messages” on the Console “Action” menu). These settings also dictate many subtle issues details about whether things are logged to disk or not. See WWDC video for more details.

    • By default, non-numeric data is redacted in the logs. In the example where you logged the URL, if the app were invoked from the device itself and you were watching from your macOS Console app, you would see the following in the macOS Console:

      url = <private>

      If you are confident that this message will not include user confidential data and you wanted to see the strings in your macOS console, you would have to do:

      os_log("url = \(url, privacy: .public)")
      
  4. Prior to iOS 14/macOS 11, iOS 10/macOS 10.12 introduced os_log for “unified logging”. For an introduction to unified logging in general, see WWDC 2016 video Unified Logging and Activity Tracing.

    • Import os.log:

      import os.log
      
    • You should define the subsystem and category:

      let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "network")
      

      When using os_log, you would use a printf-style pattern rather than string interpolation:

      os_log("url = %@", log: log, url.absoluteString)
      
    • You can specify different types of logging messages, either .info, .debug, .error, .fault (or .default):

      os_log("web service did not respond", type: .error)
      
    • You cannot use string interpolation when using os_log. For example with print and Logger you do:

      logger.log("url = \(url)")
      

      But with os_log, you would have to do:

      os_log("url = %@", url.absoluteString)
      
    • The os_log enforces the same data privacy, but you specify the public visibility in the printf formatter (e.g. %{public}@ rather than %@). E.g., if you wanted to see it from an external device, you'd have to do:

      os_log("url = %{public}@", url.absoluteString)
      
    • You can also use the “Points of Interest” log if you want to watch ranges of activities from Instruments:

      let pointsOfInterest = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: .pointsOfInterest)
      

      And start a range with:

      os_signpost(.begin, log: pointsOfInterest, name: "Network request")
      

      And end it with:

      os_signpost(.end, log: pointsOfInterest, name: "Network request")
      

      For more information, see https://stackoverflow.com/a/39416673/1271826.

Bottom line, print is sufficient for simple logging with Xcode, but unified logging (whether Logger or os_log) achieves the same thing but offers far greater capabilities.

The power of unified logging comes into stark relief when debugging iOS apps that have to be tested outside of Xcode. For example, when testing background iOS app processes like background fetch, being connected to the Xcode debugger changes the app lifecycle. So, you frequently will want to test on a physical device, running the app from the device itself, not starting the app from Xcode’s debugger. Unified logging lets you still watch your iOS device log statements from the macOS Console app.

How do I loop through rows with a data reader in C#?

That's the way the DataReader works, it's designed to read the database rows one at a time.

while(reader.Read()) 
{
  var value1 = reader.GetValue(0); // On first iteration will be hello
  var value2 = reader.GetValue(1); // On first iteration will be hello2
  var value3 = reader.GetValue(2); // On first iteration will be hello3
}

How can I get argv[] as int?

You can use the function int atoi (const char * str);.
You need to include #include <stdlib.h> and use the function in this way:
int x = atoi(argv[1]);
Here more information if needed: atoi - C++ Reference

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

In Visual Studio 2012 enabling the "Managed" option from Tools > Debugging > Just-In-Time worked for me.

enter image description here

PHP - Debugging Curl

You can enable the CURLOPT_VERBOSE option:

curl_setopt($curlhandle, CURLOPT_VERBOSE, true);

When CURLOPT_VERBOSE is set, output is written to STDERR or the file specified using CURLOPT_STDERR. The output is very informative.

You can also use tcpdump or wireshark to watch the network traffic.

How do I reformat HTML code using Sublime Text 2?

There are half a dozen or so ways to format HTML in Sublime. I've tested each of the most popular plugins (see the writeup I did on my blog for full details), but here's a quick overview of some of the most popular options:

Reindent command

Pros:

  • Ships with Sublime, so no plugin install needed

Cons:

  • Doesn't delete extra blank lines
  • Can't handle minified HTML, lines with multiple open tags
  • Doesn't properly format <script> blocks

Tag

Pros:

  • Supports ST2/ST3
  • Removes extra blank lines
  • No binary dependencies

Cons:

  • Chokes on PHP tags
  • Doesn't handle <script> blocks correctly

HTMLTidy

Pros:

  • Handles PHP tags
  • Some settings to tweak formatting

Cons:

  • Requires PHP (falls back to web service)
  • ST2 only
  • Abandoned?

HTMLBeautify

Pros:

  • Supports ST2/ST3
  • Simple and no binaray dependencies
  • Support for OS X, Win and Linux

Cons:

  • Chokes a bit with inline comments
  • Does expand minimized/compressed code

HTML-CSS-JS Prettify

Pros:

  • Supports ST2/ST3
  • Handles HTML, CSS, JS
  • Great integration with Sublime's menus
  • Highly customizable
  • Per-project settings
  • Format on save option

Cons:

  • Requires Node.js
  • Not great for embedded PHP

Which is best?

HTML-CSS-JS Prettify is the winner in my book. Lots of great features, not much to complain about.

How to write dynamic variable in Ansible playbook

my_var: the variable declared

VAR: the variable, whose value is to be checked

param_1, param_2: values of the variable VAR

value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var

my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"

How do I use extern to share variables between source files?

I like to think of an extern variable as a promise that you make to the compiler.

When encountering an extern, the compiler can only find out its type, not where it "lives", so it can't resolve the reference.

You are telling it, "Trust me. At link time this reference will be resolvable."

How to access to the parent object in c#

something like this:

  public int PowerRating
    {
       get { return base.PowerRating; } // if power inherits from meter...
    }

Node.js: Python not found exception due to node-sass and node-gyp

I found the same issue with Node 12.19.0 and yarn 1.22.5 on Windows 10. I fixed the problem by installing latest stable python 64-bit with adding the path to Environment Variables during python installation. After python installation, I restarted my machine for env vars.

Can I execute a function after setState is finished updating?

when new props or states being received (like you call setState here), React will invoked some functions, which are called componentWillUpdate and componentDidUpdate

in your case, just simply add a componentDidUpdate function to call this.drawGrid()

here is working code in JS Bin

as I mentioned, in the code, componentDidUpdate will be invoked after this.setState(...)

then componentDidUpdate inside is going to call this.drawGrid()

read more about component Lifecycle in React https://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate

How do I append a node to an existing XML file in java

If you need to insert node/element in some specific place , you can to do next steps

  1. Divide original xml into two parts
  2. Append your new node/element as child to first first(the first part should ended with element after wich you wanna add your element )
  3. Append second part to the new document.

It is simple algorithm but should works...