Programs & Examples On #Httpruntime.cache

How to play a sound using Swift?

First import these libraries

import AVFoundation

import AudioToolbox    

set delegate like this

   AVAudioPlayerDelegate

write this pretty code on button action or something action:

guard let url = Bundle.main.url(forResource: "ring", withExtension: "mp3") else { return }
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
        guard let player = player else { return }

        player.play()
    }catch let error{
        print(error.localizedDescription)
    }

100% working in my project and tested

Cannot invoke an expression whose type lacks a call signature

I had the same issue with numeral, a JS library. The fix was to install the typings again with this command:

npm install --save @types/numeral

Sql script to find invalid email addresses

select * from users 
WHERE NOT
(     CHARINDEX(' ',LTRIM(RTRIM([Email]))) = 0 
AND  LEFT(LTRIM([Email]),1) <> '@' 
AND  RIGHT(RTRIM([Email]),1) <> '.' 
AND  CHARINDEX('.',[Email],CHARINDEX('@',[Email])) - CHARINDEX('@',[Email]) > 1 
AND  LEN(LTRIM(RTRIM([Email]))) - LEN(REPLACE(LTRIM(RTRIM([Email])),'@','')) = 1 
AND  CHARINDEX('.',REVERSE(LTRIM(RTRIM([Email])))) >= 3 
AND  (CHARINDEX('.@',[Email]) = 0 AND CHARINDEX('..',[Email]) = 0) 

Prevent PDF file from downloading and printing

Creating a video with QuickTime's screen capture or anything similar kind of defeats all the effort to protect your document file from being copied.

How to delete last character in a string in C#?

Personally I would go with Rob's suggestion, but if you want to remove one (or more) specific trailing character(s) you can use TrimEnd. E.g.

paramstr = paramstr.TrimEnd('&');

How to auto-indent code in the Atom editor?

If you have troubles with hotkeys, try to open Key Binding Resolver Window with Cmd + .. It will show you keys you're pressing in the realtime.

For example, Cmd + Shift + ' is actually Cmd + "

What primitive data type is time_t?

It's platform-specific. But you can cast it to a known type.

printf("%lld\n", (long long) time(NULL));

How to create a new branch from a tag?

My branch list (only master now)

branch list

My tag list (have three tags)

tag list

Switch to new branch feature/codec from opus_codec tag

git checkout -b feature/codec opus_codec

switch to branch

How to write a JSON file in C#?

Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:

  • .Net Core now has the spookily similar System.Text.Json serialiser (see below)
  • The days of the JavaScriptSerializer have thankfully passed and this class isn't even in .Net Core. This invalidates a lot of the comparisons ran by Newtonsoft.
  • It's also recently come to my attention, via some vulnerability scanning software we use in work that Json.Net hasn't had an update in some time. Updates in 2020 have dried up and the latest version, 12.0.3, is over a year old.
  • The speed tests quoted below are comparing an older version of Json.Nt (version 6.0 and like I said the latest is 12.0.3) with an outdated .Net Framework serialiser.

Are Json.Net's days numbered? It's still used a LOT and it's still used by MS librarties. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.


Update since .Net Core 3.0

A new kid on the block since writing this is System.Text.Json which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. as below, I'd advise you to test this yourself .


I would recommend Json.Net, see example below:

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonConvert.SerializeObject(_data.ToArray());

//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);

Or the slightly more efficient version of the above code (doesn't use a string as a buffer):

//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
     JsonSerializer serializer = new JsonSerializer();
     //serialize object directly into file stream
     serializer.Serialize(file, _data);
}

Documentation: Serialize JSON to a file


Why? Here's a feature comparison between common serialisers as well as benchmark tests .

Below is a graph of performance taken from the linked article:

enter image description here

This separate post, states that:

Json.NET has always been memory efficient, streaming the reading and writing large documents rather than loading them entirely into memory, but I was able to find a couple of key places where object allocations could be reduced...... (now) Json.Net (6.0) allocates 8 times less memory than JavaScriptSerializer


Benchmarks appear to be Json.Net 5, the current version (on writing) is 10. What version of standard .Net serialisers used is not mentioned

These tests are obviously from the developers who maintain the library. I have not verified their claims. If in doubt test them yourself.

In log4j, does checking isDebugEnabled before logging improve performance?

In Java 8, you don't have to use isDebugEnabled() to improve the performance.

https://logging.apache.org/log4j/2.0/manual/api.html#Java_8_lambda_support_for_lazy_logging

import java.util.logging.Logger;
...
Logger.getLogger("hello").info(() -> "Hello " + name);

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

Output on Ubuntu 9.10 -> Ubuntu 12.04 with mono 2.10.8.1:

SpecialFolder.ApplicationData: /home/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.ProgramFiles: 
SpecialFolder.DesktopDirectory: /home/$USER/Desktop
SpecialFolder.LocalApplicationData: /home/$USER/.local/share
SpecialFolder.MyDocuments: /home/$USER
SpecialFolder.System: 

SpecialFolder.Personal: /home/$USER

Output on Ubuntu 16.04 with mono 4.2.1

SpecialFolder.ApplicationData: /home/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.ProgramFiles:
SpecialFolder.DesktopDirectory: /home/$USER/Desktop
SpecialFolder.LocalApplicationData: /home/$USER/.local/share
SpecialFolder.MyDocuments: /home/$USER
SpecialFolder.Desktop: /home/$USER/Desktop
SpecialFolder.Personal: /home/$USER

SpecialFolder.System: 
SpecialFolder.Programs: 
SpecialFolder.Favorites: 
SpecialFolder.Startup: 
SpecialFolder.Recent: 
SpecialFolder.SendTo: 
SpecialFolder.StartMenu: 
SpecialFolder.MyMusic: /home/$USER/Music
SpecialFolder.MyVideos: /home/$USER/Videos
SpecialFolder.MyComputer: 
SpecialFolder.NetworkShortcuts: 
SpecialFolder.Fonts: /home/$USER/.fonts
SpecialFolder.Templates: /home/$USER/Templates
SpecialFolder.CommonStartMenu: 
SpecialFolder.CommonPrograms: 
SpecialFolder.CommonStartup: 
SpecialFolder.CommonDesktopDirectory: 
SpecialFolder.PrinterShortcuts: 
SpecialFolder.InternetCache: 
SpecialFolder.Cookies: 
SpecialFolder.History: 
SpecialFolder.Windows: 
SpecialFolder.MyPictures: /home/$USER/Pictures
SpecialFolder.UserProfile: /home/$USER
SpecialFolder.SystemX86: 
SpecialFolder.ProgramFilesX86: 
SpecialFolder.CommonProgramFiles: 
SpecialFolder.CommonProgramFilesX86: 
SpecialFolder.CommonTemplates: /usr/share/templates
SpecialFolder.CommonDocuments: 
SpecialFolder.CommonAdminTools: 
SpecialFolder.AdminTools: 
SpecialFolder.CommonMusic: 
SpecialFolder.CommonPictures: 
SpecialFolder.CommonVideos: 
SpecialFolder.Resources: 
SpecialFolder.LocalizedResources: 
SpecialFolder.CommonOemLinks: 
SpecialFolder.CDBurning: 

where $USER is the current user

Output on Ubuntu 16.04 using dotnet core (3.0.100)

ApplicationData: /home/$USER/.config
CommonApplicationData: /usr/share
ProgramFiles: 
DesktopDirectory: /home/$USER/Desktop
LocalApplicationData: /home/$USER/.local/share
MyDocuments: /home/$USER
System: 
Personal: /home/$USER

Output on Android 6 using Xamarin 7.2

Environment.SpecialFolder.ApplicationData: /data/user/0/$APPNAME/files/.config
Environment.SpecialFolder.CommonApplicationData: /usr/share
Environment.SpecialFolder.ProgramFiles: 
Environment.SpecialFolder.DesktopDirectory: /data/user/0/$APPNAME/files/Desktop
Environment.SpecialFolder.LocalApplicationData: /data/user/0/$APPNAME/files/.local/share
Environment.SpecialFolder.MyDocuments: /data/user/0/$APPNAME/files
Environment.SpecialFolder.Desktop: /data/user/0/$APPNAME/files/Desktop
Environment.SpecialFolder.Personal: /data/user/0/$APPNAME/files

Environment.SpecialFolder.Startup: 
Environment.SpecialFolder.Recent: 
Environment.SpecialFolder.SendTo: 
Environment.SpecialFolder.StartMenu: 
Environment.SpecialFolder.MyMusic: /data/user/0/$APPNAME/files/Music
Environment.SpecialFolder.MyVideos: /data/user/0/$APPNAME/files/Videos
Environment.SpecialFolder.MyComputer: 
Environment.SpecialFolder.NetworkShortcuts: 
Environment.SpecialFolder.Fonts: /data/user/0/$APPNAME/files/.fonts
Environment.SpecialFolder.Templates: /data/user/0/$APPNAME/files/Templates
Environment.SpecialFolder.CommonStartMenu: 
Environment.SpecialFolder.CommonPrograms: 
Environment.SpecialFolder.CommonStartup: 
Environment.SpecialFolder.CommonDesktopDirectory: 
Environment.SpecialFolder.PrinterShortcuts: 
Environment.SpecialFolder.InternetCache: 
Environment.SpecialFolder.Cookies: 
Environment.SpecialFolder.History: 
Environment.SpecialFolder.Windows: 
Environment.SpecialFolder.MyPictures: /data/user/0/$APPNAME/files/Pictures
Environment.SpecialFolder.UserProfile: /data/user/0/$APPNAME/files
Environment.SpecialFolder.SystemX86: 
Environment.SpecialFolder.ProgramFilesX86: 
Environment.SpecialFolder.CommonProgramFiles: 
Environment.SpecialFolder.CommonProgramFilesX86: 
Environment.SpecialFolder.CommonTemplates: /usr/share/templates
Environment.SpecialFolder.CommonDocuments: 
Environment.SpecialFolder.CommonAdminTools: 
Environment.SpecialFolder.AdminTools: 
Environment.SpecialFolder.CommonMusic: 
Environment.SpecialFolder.CommonPictures: 
Environment.SpecialFolder.CommonVideos: 
Environment.SpecialFolder.Resources: 
Environment.SpecialFolder.LocalizedResources: 
Environment.SpecialFolder.CommonOemLinks: 
Environment.SpecialFolder.CDBurning: 

Where $APPNAME is the name of your Xamarin application (eg. MyApp.Droid)

Output on iOS Simulator 10.3 using Xamarin 7.2

ApplicationData: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/.config
CommonApplicationData: /usr/share
ProgramFiles: /Applications
DesktopDirectory: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Desktop
LocalApplicationData: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
MyDocuments: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
Desktop: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Desktop
MyDocuments: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
Startup: 
Recent: 
SendTo: 
StartMenu: 
MyMusic: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Music
MyVideos: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Videos
MyComputer: 
NetworkShortcuts: 
Fonts: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/.fonts
Templates: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Templates
CommonStartMenu: 
CommonPrograms: 
CommonStartup: 
CommonDesktopDirectory: 
PrinterShortcuts: 
InternetCache: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Library/Caches
Cookies: 
History: 
Windows: 
MyPictures: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Pictures
UserProfile: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID
SystemX86: 
ProgramFilesX86: 
CommonProgramFiles: 
CommonProgramFilesX86: 
CommonTemplates: /usr/share/templates
CommonDocuments: 
CommonAdminTools: 
AdminTools: 
CommonMusic: 
CommonPictures: 
CommonVideos: 
Resources: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Library
LocalizedResources: 
CommonOemLinks: 
CDBurning: 

Where $DEVICEGUID is the simulator GUID (depending on the selected simulator)

Output on ipad 10.3 using Xamarin 7.2

SpecialFolder.MyDocuments: /var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents

Output on ipad 13.3 using Xamarin 16.4

SpecialFolder.MyDocuments: /var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents
SpecialFolder.UserProfile: /private/var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents

Output on windows 10 using .net core 3.1

SpecialFolder.MyDocuments: C:\Users\$USER\Documents

Output on Ubuntu 18.04 using .net core 3.1

SpecialFolder.MyDocuments: /home/$USER

Output on MacOS Catalina using .net core 3.1

SpecialFolder.MyDocuments: /Users/$USER

How to retrieve absolute path given relative

What they said, except find $PWD or (in bash) find ~+ is a bit more convenient.

How to remove an element from the flow?

position: fixed; will also "pop" an element out of the flow, as you say. :)

position: absolute must be accompanied by a position. e.g. top: 1rem; left: 1rem

position: fixed however, will place the element where it would normally appear according to the document flow, but prevent it from moving after that. It also effectively set's the height to 0px (with regards to the dom) so that the next element shifts up over it.

This can be pretty cool, because you can set position: fixed; z-index: 1 (or whatever z-index you need) so that it "pops" over the next element.

This is especially useful for fixed position headers that stay at the top when you scroll, for example.

Auto Scale TextView Text to Fit within Bounds

Providing this version of top answer rewritten on C# for those who codes on Xamarin.Android. Worked for me well.

 /**
 *               DO WHAT YOU WANT TO PUBLIC LICENSE
 *                    Version 2, December 2004
 * 
 * Copyright (C) 2004 Sam Hocevar <[email protected]>
 * 
 * Everyone is permitted to copy and distribute verbatim or modified
 * copies of this license document, and changing it is allowed as long
 * as the name is changed.
 * 
 *            DO WHAT YOU WANT TO PUBLIC LICENSE
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 * 
 *  0. You just DO WHAT YOU WANT TO.
 */


using System;
using Android.Content;
using Android.Runtime;
using Android.Text;
using Android.Util;
using Android.Widget;
using Java.Lang;

namespace App.GuestGuide.Droid.Controls
{
    public class OnTextResizeEventArgs : EventArgs
    {
        public TextView TextView { get; set; }
        public float OldSize { get; set; }
        public float NewSize { get; set; }
    }

    /// <inheritdoc />
    /// <summary>
    /// Text view that auto adjusts text size to fit within the view.
    /// If the text size equals the minimum text size and still does not
    /// fit, append with an ellipsis.
    /// </summary>
    public class AutoResizeTextView : TextView
    {
        /// <summary>
        /// Minimum text size for this text view
        /// </summary>
        public static float MIN_TEXT_SIZE = 10;

        /// <summary>
        /// Our ellipse string
        /// </summary>
        private const string Ellipsis = "...";


        private float _mMaxTextSize;

        private float _mMinTextSize = MIN_TEXT_SIZE;

        /// <summary>
        /// Register subscriber to receive resize notifications
        /// </summary>
        public event EventHandler<OnTextResizeEventArgs> OnTextResize;

        /// <summary>
        /// Flag for text and/or size changes to force a resize
        /// </summary>
        private bool _needsResize;

        /// <summary>
        /// Text size that is set from code. This acts as a starting point for resizing
        /// </summary>
        private float _textSize;

        /// <summary>
        /// Text view line spacing multiplier
        /// </summary>
        private float _spacingMult = 1.0f;

        /// <summary>
        /// Text view additional line spacing
        /// </summary>
        private float _spacingAdd;

        /// <summary>
        /// Add ellipsis to text that overflows at the smallest text size
        /// </summary>
        public bool ShouldAddEllipsis { get; set; }

        /// <inheritdoc />
        /// <summary>
        /// Override the set text size to update our internal reference values
        /// </summary>
        public override float TextSize
        {
            get => base.TextSize;
            set
            {
                base.TextSize = value;
                _textSize = TextSize;
            }
        }

        /// <summary>
        /// Temporary upper bounds on the starting text size
        /// </summary>
        public float MaxTextSize
        {
            get => _mMaxTextSize;
            // Set the upper text size limit and invalidate the view
            set
            {
                _mMaxTextSize = value;
                RequestLayout();
                Invalidate();
            }
        }

        /// <summary>
        /// Lower bounds for text size
        /// </summary>
        public float MinTextSize
        {
            get => _mMinTextSize;
            //Set the lower text size limit and invalidate the view
            set
            {
                _mMinTextSize = value;
                RequestLayout();
                Invalidate();
            }
        }

        public AutoResizeTextView(Context context) : this(context, null)
        {
        }

        public AutoResizeTextView(Context context, IAttributeSet attrs) : this(context, attrs, 0)
        {
        }

        public AutoResizeTextView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
        {
            _textSize = TextSize;
        }

        public AutoResizeTextView(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes)
        {
            _textSize = TextSize;
        }

        protected AutoResizeTextView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
        {
            _textSize = TextSize;
        }

        /// <inheritdoc />
        /// <summary>
        /// When text changes, set the force resize flag to true and reset the text size.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="start"></param>
        /// <param name="lengthBefore"></param>
        /// <param name="lengthAfter"></param>
        protected override void OnTextChanged(ICharSequence text, int start, int lengthBefore, int lengthAfter)
        {
            _needsResize = true;
            // Since this view may be reused, it is good to reset the text size
            ResetTextSize();
        }

        /// <inheritdoc />
        /// <summary>
        /// If the text view size changed, set the force resize flag to true
        /// </summary>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <param name="oldw"></param>
        /// <param name="oldh"></param>
        protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
        {
            if (w != oldw || h != oldh)
            {
                _needsResize = true;
            }
        }

        public override void SetTextSize([GeneratedEnum] ComplexUnitType unit, float size)
        {
            base.SetTextSize(unit, size);
            _textSize = TextSize;
        }

        /// <inheritdoc />
        /// <summary>
        /// Override the set line spacing to update our internal reference values
        /// </summary>
        /// <param name="add"></param>
        /// <param name="mult"></param>
        public override void SetLineSpacing(float add, float mult)
        {
            base.SetLineSpacing(add, mult);
            _spacingMult = mult;
            _spacingAdd = add;
        }

        /// <summary>
        /// Reset the text to the original size
        /// </summary>
        public void ResetTextSize()
        {
            if (_textSize > 0)
            {
                base.SetTextSize(ComplexUnitType.Px, _textSize);
                _mMaxTextSize = _textSize;
            }
        }

        /// <inheritdoc />
        /// <summary>
        /// Resize text after measuring
        /// </summary>
        /// <param name="changed"></param>
        /// <param name="left"></param>
        /// <param name="top"></param>
        /// <param name="right"></param>
        /// <param name="bottom"></param>
        protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
        {
            if (changed || _needsResize)
            {
                var widthLimit = (right - left) - CompoundPaddingLeft - CompoundPaddingRight;
                var heightLimit = (bottom - top) - CompoundPaddingBottom - CompoundPaddingTop;
                ResizeText(widthLimit, heightLimit);
            }

            base.OnLayout(changed, left, top, right, bottom);
        }

        /// <summary>
        /// Resize the text size with default width and height
        /// </summary>
        public void ResizeText()
        {
            var heightLimit = Height - PaddingBottom - PaddingTop;
            var widthLimit = Width - PaddingLeft - PaddingRight;
            ResizeText(widthLimit, heightLimit);
        }

        /// <summary>
        /// Resize the text size with specified width and height
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public void ResizeText(int width, int height)
        {
            ICharSequence text = null;

            if (!string.IsNullOrEmpty(Text))
            {
                text = new Java.Lang.String(Text);
            }

            // Do not resize if the view does not have dimensions or there is no text
            if (text == null || text.Length() == 0 || height <= 0 || width <= 0 || _textSize == 0)
            {
                return;
            }

            if (TransformationMethod != null)
            {
                text = TransformationMethod.GetTransformationFormatted(text, this);
            }

            // Get the text view's paint object
            var textPaint = Paint;
            // Store the current text size
            var oldTextSize = textPaint.TextSize;
            // If there is a max text size set, use the lesser of that and the default text size
            var targetTextSize = _mMaxTextSize > 0 ? System.Math.Min(_textSize, _mMaxTextSize) : _textSize;

            // Get the required text height
            var textHeight = GetTextHeight(text, textPaint, width, targetTextSize);

            // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
            while (textHeight > height && targetTextSize > _mMinTextSize)
            {
                targetTextSize = System.Math.Max(targetTextSize - 2, _mMinTextSize);
                textHeight = GetTextHeight(text, textPaint, width, targetTextSize);
            }

            // If we had reached our minimum text size and still don't fit, append an ellipsis
            if (ShouldAddEllipsis && targetTextSize == _mMinTextSize && textHeight > height)
            {
                // Draw using a static layout
                // modified: use a copy of TextPaint for measuring
                var paint = new TextPaint(textPaint);
                // Draw using a static layout
                var layout = new StaticLayout(text, paint, width, Layout.Alignment.AlignNormal, _spacingMult, _spacingAdd, false);

                // Check that we have a least one line of rendered text
                if (layout.LineCount > 0)
                {
                    // Since the line at the specific vertical position would be cut off,
                    // we must trim up to the previous line
                    var lastLine = layout.GetLineForVertical(height) - 1;
                    // If the text would not even fit on a single line, clear it
                    if (lastLine < 0)
                    {
                        Text = string.Empty;
                    }
                    // Otherwise, trim to the previous line and add an ellipsis
                    else
                    {
                        var start = layout.GetLineStart(lastLine);
                        var end = layout.GetLineEnd(lastLine);
                        var lineWidth = layout.GetLineWidth(lastLine);
                        var ellipseWidth = textPaint.MeasureText(Ellipsis);

                        // Trim characters off until we have enough room to draw the ellipsis
                        while (width < lineWidth + ellipseWidth)
                        {
                            lineWidth = textPaint.MeasureText(text.SubSequence(start, --end + 1));
                        }

                        Text = text.SubSequence(0, end) + Ellipsis;
                    }
                }
            }

            // Some devices try to auto adjust line spacing, so force default line spacing
            // and invalidate the layout as a side effect
            SetTextSize(ComplexUnitType.Px, targetTextSize);
            SetLineSpacing(_spacingAdd, _spacingMult);

            var notifyArgs = new OnTextResizeEventArgs
            {
                TextView = this,
                NewSize = targetTextSize,
                OldSize = oldTextSize
            };

            // Notify the listener if registered
            OnTextResize?.Invoke(this, notifyArgs);

            // Reset force resize flag
            _needsResize = false;
        }

        /// <summary>
        /// Set the text size of the text paint object and use a static layout to render text off screen before measuring
        /// </summary>
        /// <param name="source"></param>
        /// <param name="paint"></param>
        /// <param name="width"></param>
        /// <param name="textSize"></param>
        /// <returns></returns>
        private int GetTextHeight(ICharSequence source, TextPaint paint, int width, float textSize)
        {
            // modified: make a copy of the original TextPaint object for measuring
            // (apparently the object gets modified while measuring, see also the
            // docs for TextView.getPaint() (which states to access it read-only)
            // Update the text paint object
            var paintCopy = new TextPaint(paint)
            {
                TextSize = textSize
            };

            // Measure using a static layout
            var layout = new StaticLayout(source, paintCopy, width, Layout.Alignment.AlignNormal, _spacingMult, _spacingAdd, true);

            return layout.Height;
        }
    }
}

Basic authentication for REST API using spring restTemplate

Use setBasicAuth to define credentials

HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("myUsername", myPassword);

Then create the request like you prefer.

Example:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, 
request, String.class);
String body = response.getBody();

Use Ant for running program with command line arguments

Extending Richard Cook's answer.

Here's the ant task to run any program (including, but not limited to Java programs):

<target name="run">
   <exec executable="name-of-executable">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </exec>
</target>

Here's the task to run a Java program from a .jar file:

<target name="run-java">
   <java jar="path for jar">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </java>
</target>

You can invoke either from the command line like this:

ant -Darg0=Hello -Darg1=World run

Make sure to use the -Darg syntax; if you ran this:

ant run arg0 arg1

then ant would try to run targets arg0 and arg1.

Web link to specific whatsapp contact

********* UPDATE ADDED AT THE END *********

I've tried many approaches and I have a winner (see Test 3), here is the result of each one:

(I think the Test 3 will also work for you because if the person visiting your site doesn't have you on their contact list, it's the only option that will allow it.)

In all tests, the number had to be complete, with country and location code without any initial zeros. Example:

  • +55(011) 99999-9999 (NOT)
  • +5511999999999 (YES)

On tests 1 and 2, it only worked with a plus sign on the country code: +5511999999999

Test 1:

<a href="whatsapp://send?abid=phonenumber&text=Hello%2C%20World!">Send Message</a>

This way you must have the phonenumber on your contact list. It doesn't work for me because I wanted to be able to send a message to a number which I may not have on my contact list.

If you don't have the number on your contact list, it opens the Whatsapp listing all your registered contacts, so you can choose one.

It's a good option for sharing stuff.

Test 2:

<a href="intent://send/phonenumber#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">Send Message</a>

This approach only works on Android AND if you have the number on your contact list. If you don't have it, Android opens your SMS app, so you can invite the contact to use Whatsapp.

Test 3 (The Winner):

<a href="https://api.whatsapp.com/send?phone=15551234567">Send Message</a>

This was the only way that worked fully for me.

  • It works on Android, iOS and Web app on the desktop,
  • You can start a conversation with a number that you don't have on your contact list
  • You can create a link with one pre-built message adding &text=[message-url-encoded] like:

https://api.whatsapp.com/send?phone=15551234567&text=Send20%a20%quote

And if you wish to have a bookmarklet for additional ease of use, you may use this one:

javascript: (function() { var val= prompt("Enter phone number",""); if (val) location="https://api.whatsapp.com/send?phone="+escape('972' + val)+""; })()

Youll need to change the country code(or remove it) to you.r target country and paste it in the address field in a chrome/firefox link

Worth notice:

***************** UPDATE (START) *****************

Whatsapp made available other option, now you can create one link to a conversation like this:

https://wa.me/[phonenumber]

The phone number should be in international format:

Like this:

https://wa.me/552196312XXXX

NOT like this:

https://wa.me/+55(021)96312-XXXX

And if you want to add one pre-built message to your link, you can add ?text= at the end with the text URL Encoded:

https://wa.me/552196312XXXX?text=[message-url-encoded]

Exemple:

https://wa.me/552196312XXXX?text=Send20%a20%quote

More info here:

https://faq.whatsapp.com/general/chats/how-to-use-click-to-chat

***************** UPDATE (END) *****************

How to generate javadoc comments in Android Studio

Javadoc comments can be automatically appended by using your IDE's autocomplete feature. Try typing /** and hitting Enter to generate a sample Javadoc comment.

 /**
 *
 * @param action          The action to execute.
 * @param args            The exec() arguments.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return
 * @throws JSONException
 */

In oracle, how do I change my session to display UTF8?

Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:

NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.

Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:

export NLS_LANG=AMERICAN_AMERICA.UTF8

Oracle gets a big fat F for usability.

Does overflow:hidden applied to <body> work on iPhone Safari?

I had a similar issue and found that applying overflow: hidden; to both html and body solved my problem.

html,
body {
    overflow: hidden;
} 

For iOS 9, you may need to use this instead: (Thanks chaenu!)

html,
body {
    overflow: hidden;
    position: relative;
    height: 100%;
}

Angular and debounce

Solution with initialization subscriber directly in event function:

import {Subject} from 'rxjs';
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';

class MyAppComponent {
    searchTermChanged: Subject<string> = new Subject<string>();

    constructor() {
    }

    onFind(event: any) {
        if (this.searchTermChanged.observers.length === 0) {
            this.searchTermChanged.pipe(debounceTime(1000), distinctUntilChanged())
                .subscribe(term => {
                    // your code here
                    console.log(term);
                });
        }
        this.searchTermChanged.next(event);
    }
}

And html:

<input type="text" (input)="onFind($event.target.value)">

How can I know when an EditText loses focus?

Its Working Properly

EditText et_mobile= (EditText) findViewById(R.id.edittxt);

et_mobile.setOnFocusChangeListener(new OnFocusChangeListener() {          
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            // code to execute when EditText loses focus
            if (et_mobile.getText().toString().trim().length() == 0) {
                CommonMethod.showAlert("Please enter name", FeedbackSubmtActivity.this);
            }
        }
    }
});



public static void showAlert(String message, Activity context) {

    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(message).setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                }
            });
    try {
        builder.show();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

With MySQL, how can I generate a column containing the record index in a table?

I know the OP is asking for a mysql answer but since I found the other answers not working for me,

  • Most of them fail with order by
  • Or they are simply very inefficient and make your query very slow for a fat table

So to save time for others like me, just index the row after retrieving them from database

example in PHP:

$users = UserRepository::loadAllUsersAndSortByScore();

foreach($users as $index=>&$user){
    $user['rank'] = $index+1;
}

example in PHP using offset and limit for paging:

$limit = 20; //page size
$offset = 3; //page number

$users = UserRepository::loadAllUsersAndSortByScore();

foreach($users as $index=>&$user){
    $user['rank'] = $index+1+($limit*($offset-1));
}

What is the difference between DTR/DSR and RTS/CTS flow control?

The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.

java: use StringBuilder to insert at the beginning

Difference Between String, StringBuilder And StringBuffer Classes
String
String is immutable ( once created can not be changed )object. The object created as a
String is stored in the Constant String Pool.
Every immutable object in Java is thread-safe, which implies String is also thread-safe. String
can not be used by two threads simultaneously.
String once assigned can not be changed.
StringBuffer
StringBuffer is mutable means one can change the value of the object. The object created
through StringBuffer is stored in the heap. StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread
safe .
Due to this, it does not allow two threads to simultaneously access the same method. Each
method can be accessed by one thread at a time.
But being thread-safe has disadvantages too as the performance of the StringBuffer hits due
to thread-safe property. Thus StringBuilder is faster than the StringBuffer when calling the
same methods of each class.
String Buffer can be converted to the string by using
toString() method.

    StringBuffer demo1 = new StringBuffer("Hello") ;

// The above object stored in heap and its value can be changed.
/
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder is the same as the StringBuffer, that is it stores the object in heap and it can also
be modified. The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread-safe.
StringBuilder is fast as it is not thread-safe.
/
// The above object is stored in the heap and its value can be modified
/
// Above statement is right as it modifies the value which is allowed in the StringBuilder

Date difference in years using C#

int Age = new DateTime((DateTime.Now - BirthDateTime).Ticks).Year;

To calculate the elapsed years (age), the result will be minus one.

var timeSpan = DateTime.Now - birthDateTime;
int age = new DateTime(timeSpan.Ticks).Year - 1;

Split string on whitespace in Python

The str.split() method without an argument splits on whitespace:

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

Java Webservice Client (Best way)

Some ideas in the following answer:

Steps in creating a web service using Axis2 - The client code

Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.

There are lots of web service frameworks out there...

Python: Figure out local timezone

Here's a way to get the local timezone using only the standard library, (only works in a *nix environment):

>>> '/'.join(os.path.realpath('/etc/localtime').split('/')[-2:])
'Australia/Sydney'

You can use this to create a pytz timezone:

>>> import pytz
>>> my_tz_name = '/'.join(os.path.realpath('/etc/localtime').split('/')[-2:])
>>> my_tz = pytz.timezone(my_tz_name)
>>> my_tz
<DstTzInfo 'Australia/Sydney' LMT+10:05:00 STD>

...which you can then apply to a datetime:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2014, 9, 3, 9, 23, 24, 139059)

>>> now.replace(tzinfo=my_tz)
>>> now
datetime.datetime(2014, 9, 3, 9, 23, 24, 139059, tzinfo=<DstTzInfo 'Australia/Sydney' LMT+10:05:00 STD>)

Why do I get access denied to data folder when using adb?

The problem could be that we need to specifically give adb root access in the developnent options in the latest CMs.. Here is what i did.

abc@abc-L655:~$ sudo adb kill-server
abc@abc-L655:~$ sudo adb root start-server * daemon not running. starting it now on port 5037 * * daemon started successfully * root access is disabled by system setting - enable in settings -> development options

after altering the development options...

abc@abc-L655:~$ sudo adb kill-server
abc@abc-L655:~$ sudo adb root start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
restarting adbd as root
abc@abc-L655:~$ adb shell
root@android:/ # ls /data/ .... good to go.. 

What causes the Broken Pipe Error?

It can take time for the network close to be observed - the total time is nominally about 2 minutes (yes, minutes!) after a close before the packets destined for the port are all assumed to be dead. The error condition is detected at some point. With a small write, you are inside the MTU of the system, so the message is queued for sending. With a big write, you are bigger than the MTU and the system spots the problem quicker. If you ignore the SIGPIPE signal, then the functions will return EPIPE error on a broken pipe - at some point when the broken-ness of the connection is detected.

WPF - add static items to a combo box

Here is the code from MSDN and the link - Article Link, which you should check out for more detail.

<ComboBox Text="Is not open">
    <ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
    <ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
    <ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

Android Material Design Button Styles

Beside android.support.design.button.MaterialButton (which mentioned by Gabriele Mariotti),

There is also another Button widget called com.google.android.material.button.MaterialButton which has different styles and extends from AppCompatButton:

style="@style/Widget.MaterialComponents.Button"
style="@style/Widget.MaterialComponents.Button.UnelevatedButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
style="@style/Widget.MaterialComponents.Button.Icon"
style="@style/Widget.MaterialComponents.Button.TextButton.Icon"

Filled, elevated Button (default): enter image description here

style="@style/Widget.MaterialComponents.Button"

Filled, unelevated Button: enter image description here

style="@style/Widget.MaterialComponents.Button.UnelevatedButton"

Text Button: enter image description here

style="@style/Widget.MaterialComponents.Button.TextButton"

Icon Button: enter image description here

style="@style/Widget.MaterialComponents.Button.Icon"
app:icon="@drawable/icon_24px" // Icons can be added from this

A text Button with an icon:: enter image description here


Read: https://material.io/develop/android/components/material-button/

A convenience class for creating a new Material button.

This class supplies updated Material styles for the button in the constructor. The widget will display the correct default Material styles without the use of the style flag.

Configure nginx with multiple locations with different root folders on subdomain

A little more elaborate example.

Setup: You have a website at example.com and you have a web app at example.com/webapp

...
server {
  listen 443 ssl;
  server_name example.com;

  root   /usr/share/nginx/html/website_dir;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html;

  location /webapp/ {
    alias  /usr/share/nginx/html/webapp_dir/;
    index  index.html index.htm;
    try_files $uri $uri/ /webapp/index.html;
  }
}
...

I've named webapp_dir and website_dir on purpose. If you have matching names and folders you can use the root directive.

This setup works and is tested with Docker.

NB!!! Be careful with the slashes. Put them exactly as in the example.

How to download a file using a Java REST service and a data stream

"How can I directly (without saving the file on 2nd server) download the file from 1st server to client's machine?"

Just use the Client API and get the InputStream from the response

Client client = ClientBuilder.newClient();
String url = "...";
final InputStream responseStream = client.target(url).request().get(InputStream.class);

There are two flavors to get the InputStream. You can also use

Response response = client.target(url).request().get();
InputStream is = (InputStream)response.getEntity();

Which one is the more efficient? I'm not sure, but the returned InputStreams are different classes, so you may want to look into that if you care to.

From 2nd server I can get a ByteArrayOutputStream to get the file from 1st server, can I pass this stream further to the client using the REST service?

So most of the answers you'll see in the link provided by @GradyGCooper seem to favor the use of StreamingOutput. An example implementation might be something like

final InputStream responseStream = client.target(url).request().get(InputStream.class);
System.out.println(responseStream.getClass());
StreamingOutput output = new StreamingOutput() {
    @Override
    public void write(OutputStream out) throws IOException, WebApplicationException {  
        int length;
        byte[] buffer = new byte[1024];
        while((length = responseStream.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
        responseStream.close();
    }   
};
return Response.ok(output).header(
        "Content-Disposition", "attachment, filename=\"...\"").build();

But if we look at the source code for StreamingOutputProvider, you'll see in the writeTo, that it simply writes the data from one stream to another. So with our implementation above, we have to write twice.

How can we get only one write? Simple return the InputStream as the Response

final InputStream responseStream = client.target(url).request().get(InputStream.class);
return Response.ok(responseStream).header(
        "Content-Disposition", "attachment, filename=\"...\"").build();

If we look at the source code for InputStreamProvider, it simply delegates to ReadWriter.writeTo(in, out), which simply does what we did above in the StreamingOutput implementation

 public static void writeTo(InputStream in, OutputStream out) throws IOException {
    int read;
    final byte[] data = new byte[BUFFER_SIZE];
    while ((read = in.read(data)) != -1) {
        out.write(data, 0, read);
    }
}

Asides:

  • Client objects are expensive resources. You may want to reuse the same Client for request. You can extract a WebTarget from the client for each request.

    WebTarget target = client.target(url);
    InputStream is = target.request().get(InputStream.class);
    

    I think the WebTarget can even be shared. I can't find anything in the Jersey 2.x documentation (only because it is a larger document, and I'm too lazy to scan through it right now :-), but in the Jersey 1.x documentation, it says the Client and WebResource (which is equivalent to WebTarget in 2.x) can be shared between threads. So I'm guessing Jersey 2.x would be the same. but you may want to confirm for yourself.

  • You don't have to make use of the Client API. A download can be easily achieved with the java.net package APIs. But since you're already using Jersey, it doesn't hurt to use its APIs

  • The above is assuming Jersey 2.x. For Jersey 1.x, a simple Google search should get you a bunch of hits for working with the API (or the documentation I linked to above)


UPDATE

I'm such a dufus. While the OP and I are contemplating ways to turn a ByteArrayOutputStream to an InputStream, I missed the simplest solution, which is simply to write a MessageBodyWriter for the ByteArrayOutputStream

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

@Provider
public class OutputStreamWriter implements MessageBodyWriter<ByteArrayOutputStream> {

    @Override
    public boolean isWriteable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return ByteArrayOutputStream.class == type;
    }

    @Override
    public long getSize(ByteArrayOutputStream t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(ByteArrayOutputStream t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {
        t.writeTo(entityStream);
    }
}

Then we can simply return the ByteArrayOutputStream in the response

return Response.ok(baos).build();

D'OH!

UPDATE 2

Here are the tests I used (

Resource class

@Path("test")
public class TestResource {

    final String path = "some_150_mb_file";

    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response doTest() throws Exception {
        InputStream is = new FileInputStream(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        byte[] buffer = new byte[4096];
        while ((len = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, len);
        }
        System.out.println("Server size: " + baos.size());
        return Response.ok(baos).build();
    }
}

Client test

public class Main {
    public static void main(String[] args) throws Exception {
        Client client = ClientBuilder.newClient();
        String url = "http://localhost:8080/api/test";
        Response response = client.target(url).request().get();
        String location = "some_location";
        FileOutputStream out = new FileOutputStream(location);
        InputStream is = (InputStream)response.getEntity();
        int len = 0;
        byte[] buffer = new byte[4096];
        while((len = is.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        is.close();
    }
}

UPDATE 3

So the final solution for this particular use case was for the OP to simply pass the OutputStream from the StreamingOutput's write method. Seems the third-party API, required a OutputStream as an argument.

StreamingOutput output = new StreamingOutput() {
    @Override
    public void write(OutputStream out) {
        thirdPartyApi.downloadFile(.., .., .., out);
    }
}
return Response.ok(output).build();

Not quite sure, but seems the reading/writing within the resource method, using ByteArrayOutputStream`, realized something into memory.

The point of the downloadFile method accepting an OutputStream is so that it can write the result directly to the OutputStream provided. For instance a FileOutputStream, if you wrote it to file, while the download is coming in, it would get directly streamed to the file.

It's not meant for us to keep a reference to the OutputStream, as you were trying to do with the baos, which is where the memory realization comes in.

So with the way that works, we are writing directly to the response stream provided for us. The method write doesn't actually get called until the writeTo method (in the MessageBodyWriter), where the OutputStream is passed to it.

You can get a better picture looking at the MessageBodyWriter I wrote. Basically in the writeTo method, replace the ByteArrayOutputStream with StreamingOutput, then inside the method, call streamingOutput.write(entityStream). You can see the link I provided in the earlier part of the answer, where I link to the StreamingOutputProvider. This is exactly what happens

python - checking odd/even numbers and changing outputs on number size

This is simple code. You can try it and grab the knowledge easily.

n = int(input('Enter integer : '))
    if n % 2 == 3`8huhubuiiujji`:
        print('digit entered is ODD')
    elif n % 2 == 0 and 2 < n < 5:
        print('EVEN AND in between [2,5]')
    elif n % 2 == 0 and 6 < n < 20:
        print('EVEN and in between [6,20]')
    elif n % 2 == 0 and n > 20:
       print('Even and greater than 20')

and so on...

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

After the long time research i have found the solution for above:

  1. Firstly you change the wp-config.php> Database DB_CHARSET default to "utf8"

  2. Click the "Export" tab for the database

  3. Click the "Custom" radio button

  4. Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.

  5. Scroll to the bottom and click go

Then you are on.

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

Equals(=) vs. LIKE

If you search for an exact match, you can use both, = and LIKE.

Using "=" is a tiny bit faster in this case (searching for an exact match) - you can check this yourself by having the same query twice in SQL Server Management Studio, once using "=", once using "LIKE", and then using the "Query" / "Include actual execution plan".

Execute the two queries and you should see your results twice, plus the two actual execution plans. In my case, they were split 50% vs. 50%, but the "=" execution plan has a smaller "estimated subtree cost" (displayed when you hover over the left-most "SELECT" box) - but again, it's really not a huge difference.

But when you start searching with wildcards in your LIKE expression, search performance will dimish. Search "LIKE Mill%" can still be quite fast - SQL Server can use an index on that column, if there is one. Searching "LIKE %expression%" is horribly slow, since the only way SQL Server can satisfy this search is by doing a full table scan. So be careful with your LIKE's !

Marc

"undefined" function declared in another file?

I ran into the same issue with Go11, just wanted to share how I did solve it for helping others just in case they run into the same issue.

I had my Go project outside $GOPATH, so I had to turned on GO111MODULE=on without this option turned on, it will give you this issue; even if you you try to build or test the whole package or directory it won't be solved without GO111MODULE=on

jQuery get an element by its data-id

Yes, you can find out element by data attribute.

element = $('a[data-item-id="stand-out"]');

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

How do I get time of a Python program's execution?

Later answer, but I use the built-in timeit:

import timeit
code_to_test = """
a = range(100000)
b = []
for i in a:
    b.append(i*2)
"""
elapsed_time = timeit.timeit(code_to_test, number=500)
print(elapsed_time)
# 10.159821493085474

  • Wrap all your code, including any imports you may have, inside code_to_test.
  • number argument specifies the amount of times the code should repeat.
  • Demo

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

select command denied to user ''@'' for table ''

This problem is a basically generated after join condition are wrong database name in your join query. So please check the your select query in join table name after database.

Then solve it for example its correct ans ware

string g = " SELECT `emptable`.`image` , `applyleave`.`id` , `applyleave`.`empid` , `applyleave`.`empname` , `applyleave`.`dateapply` , `applyleave`.`leavename` , `applyleave`.`fromdate` , `applyleave`.`todate` , `applyleave`.`resion` , `applyleave`.`contact` , `applyleave`.`leavestatus` , `applyleave`.`username` , `applyleave`.`noday` FROM `DataEMP_ems`.`applyleave` INNER JOIN `DataEMP_ems`.`emptable` ON ( `applyleave`.`empid` = `emptable`.`empid` ) WHERE ( `applyleave`.`leavestatus` = 'panding' ) ";

The join table is imputable and applyleave on the same database but online database name is diffrent then given error on this problem.

Disable/Enable Submit Button until all forms have been filled

<form name="theform">
    <input type="text" />
    <input type="text" />`enter code here`
    <input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>

<script type="text/javascript" language="javascript">

    let txt = document.querySelectorAll('[type="text"]');
    for (let i = 0; i < txt.length; i++) {
        txt[i].oninput = () => {
            if (!(txt[0].value == '') && !(txt[1].value == '')) {
                submitbutton.removeAttribute('disabled')
            }
        }
    }
</script>

How can I check if a string contains ANY letters from the alphabet?

How about:

>>> string_1 = "(555).555-5555"
>>> string_2 = "(555) 555 - 5555 ext. 5555"
>>> any(c.isalpha() for c in string_1)
False
>>> any(c.isalpha() for c in string_2)
True

Attach (open) mdf file database with SQL Server Management Studio

I don't know about the older versions but for SSMS 2016 you can go to the Object Explorer and right click on the Databases entry. Then select Attach... in the context menu. Here you can browse to the .mdf file and open it. screenshot

Retrieve filename from file descriptor in C

In Windows, with GetFileInformationByHandleEx, passing FileNameInfo, you can retrieve the file name.

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

X is a dataframe and can't be accessed via slice terminology like X[:, 3]. You must access via iloc or X.values. However, the way you constructed X made it a copy... so. I'd use values

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
# dataset = pd.read_csv('50_Startups.csv')

dataset = pd.DataFrame(np.random.rand(10, 10))
y=dataset.iloc[:, 4]
X=dataset.iloc[:, 0:4]

# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()

#  I changed this line
X.values[:, 3] = labelencoder_X.fit_transform(X.values[:, 3])

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

How do I use ROW_NUMBER()?

If you absolutely want to use ROW_NUMBER for this (instead of count(*)) you can always use:

SELECT TOP 1 ROW_NUMBER() OVER (ORDER BY Id)   
FROM USERS  
ORDER BY ROW_NUMBER() OVER (ORDER BY Id) DESC

Select count(*) from multiple tables

select @count = sum(data) from
(
select count(*)  as data from #tempregion
union 
select count(*)  as data from #tempmetro
union
select count(*)  as data from #tempcity
union
select count(*)  as data from #tempzips
) a

Using quotation marks inside quotation marks

This worked for me in IDLE Python 3.8.2

print('''"A word with quotation marks"''')

Triple single quotes seem to allow you to include your double quotes as part of the string.

Using %f with strftime() in Python to get microseconds

If you want an integer, try this code:

import datetime
print(datetime.datetime.now().strftime("%s%f")[:13])

Output:

1545474382803

Using Server.MapPath in external C# Classes in ASP.NET

I use this too:

System.Web.HTTPContext.Current.Server.MapPath

How to get logged-in user's name in Access vba?

Public Declare Function GetUserName Lib "advapi32.dll" 
    Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

....

Dim strLen As Long
Dim strtmp As String * 256
Dim strUserName As String

strLen = 255
GetUserName strtmp, strLen
strUserName = Trim$(TrimNull(strtmp))

Turns out question has been asked before: How can I get the currently logged-in windows user in Access VBA?

Importing a function from a class in another file?

from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME

FILENAME is w/o the suffix

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

Line Break in HTML Select Option?

If you just want a line break in the dropdown list use this:

<option label="" value="" disabled=""> </option>

Mockito: List Matchers with generics

In addition to anyListOf above, you can always specify generics explicitly using this syntax:

when(mock.process(Matchers.<List<Bar>>any(List.class)));

Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:

when(mock.process(Matchers.any()));

Remember that neither any() nor anyList() will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class) was changed to mean "any instanceof Foo", but any() still means "any value including null".

NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers. Older versions of Mockito will need to keep using org.mockito.Matchers as above.

Using BETWEEN in CASE SQL statement

You do not specify why you think it is wrong but I can se two dangers:

BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.

Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.

How to convert a string to an integer in JavaScript?

Try parseInt function:

var number = parseInt("10");

But there is a problem. If you try to convert "010" using parseInt function, it detects as octal number, and will return number 8. So, you need to specify a radix (from 2 to 36). In this case base 10.

parseInt(string, radix)

Example:

var result = parseInt("010", 10) == 10; // Returns true

var result = parseInt("010") == 10; // Returns false

Note that parseInt ignores bad data after parsing anything valid.
This guid will parse as 51:

var result = parseInt('51e3daf6-b521-446a-9f5b-a1bb4d8bac36', 10) == 51; // Returns true

How to edit default dark theme for Visual Studio Code?

I came here to find a way to edit the theme, but could not find it on my Mac. After a deep dive, finally I found the install place:

~/.vscode/extensions

All extensions in there!

Transition of background-color

To me, it is better to put the transition codes with the original/minimum selectors than with the :hover or any other additional selectors:

_x000D_
_x000D_
#content #nav a {_x000D_
    background-color: #FF0;_x000D_
    _x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -moz-transition: background-color 1000ms linear;_x000D_
    -o-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
}_x000D_
_x000D_
#content #nav a:hover {_x000D_
    background-color: #AD310B;_x000D_
}
_x000D_
<div id="content">_x000D_
    <div id="nav">_x000D_
        <a href="#link1">Link 1</a>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

the bast way i use i bind the textblock and combobox to same property and this property should support notifyPropertyChanged.

i used relativeresource to bind to parent view datacontext which is usercontrol to go up datagrid level in binding because in this case the datagrid will search in object that you used in datagrid.itemsource

<DataGridTemplateColumn Header="your_columnName">
     <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
             <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.SelectedUnit.Name, Mode=TwoWay}" />
           </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
     <DataGridTemplateColumn.CellEditingTemplate>
           <DataTemplate>
            <ComboBox DisplayMemberPath="Name"
                      IsEditable="True"
                      ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.UnitLookupCollection}"
                       SelectedItem="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.SelectedUnit, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                      SelectedValue="{Binding UnitId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                      SelectedValuePath="Id" />
            </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

Bash mkdir and subfolders

To create multiple sub-folders

mkdir -p parentfolder/{subfolder1,subfolder2,subfolder3}

SQL statement to get column type

For IBM DB2 :

SELECT TYPENAME FROM SYSCAT.COLUMNS WHERE TABSCHEMA='your_schema_name' AND TABNAME='your_table_name' AND COLNAME='your_column_name'

How to split a dos path into its components in Python

In Python >=3.4 this has become much simpler. You can now use pathlib.Path.parts to get all the parts of a path.

Example:

>>> from pathlib import Path
>>> Path('C:/path/to/file.txt').parts
('C:\\', 'path', 'to', 'file.txt')
>>> Path(r'C:\path\to\file.txt').parts
('C:\\', 'path', 'to', 'file.txt')

On a Windows install of Python 3 this will assume that you are working with Windows paths, and on *nix it will assume that you are working with posix paths. This is usually what you want, but if it isn't you can use the classes pathlib.PurePosixPath or pathlib.PureWindowsPath as needed:

>>> from pathlib import PurePosixPath, PureWindowsPath
>>> PurePosixPath('/path/to/file.txt').parts
('/', 'path', 'to', 'file.txt')
>>> PureWindowsPath(r'C:\path\to\file.txt').parts
('C:\\', 'path', 'to', 'file.txt')
>>> PureWindowsPath(r'\\host\share\path\to\file.txt').parts
('\\\\host\\share\\', 'path', 'to', 'file.txt')

Edit: There is also a backport to python 2 available: pathlib2

How to redirect to the same page in PHP

I just tried using header("Location: "); (without any value) and it redirected to the current page.

An existing connection was forcibly closed by the remote host - WCF

The issue I had was also with serialization. The cause was some of my DTO/business classes and properties were renamed or deleted without updating the service reference. I'm surprised I didn't get a contract filter mismatch error instead. But updating the service ref fixed the error for me (same error as OP).

How to specify different Debug/Release output directories in QMake .pro file

1. Find Debug/Release in CONFIG

Get the current (debug | release).

specified_configs=$$find(CONFIG, "\b(debug|release)\b")
build_subdir=$$last(specified_configs)

(May be multiple, so keep only last specified in the build):

2. Set DESTDIR

Use it has the build subdir name

DESTDIR = $$PWD/build/$$build_subdir

how to implement login auth in node.js

_x000D_
_x000D_
======authorization====== MIDDLEWARE_x000D_
_x000D_
const jwt = require('../helpers/jwt')_x000D_
const User = require('../models/user')_x000D_
_x000D_
module.exports = {_x000D_
  authentication: function(req, res, next) {_x000D_
    try {_x000D_
      const user = jwt.verifyToken(req.headers.token, process.env.JWT_KEY)_x000D_
      User.findOne({ email: user.email }).then(result => {_x000D_
        if (result) {_x000D_
          req.body.user = result_x000D_
          req.params.user = result_x000D_
          next()_x000D_
        } else {_x000D_
          throw new Error('User not found')_x000D_
        }_x000D_
      })_x000D_
    } catch (error) {_x000D_
      console.log('langsung dia masuk sini')_x000D_
_x000D_
      next(error)_x000D_
    }_x000D_
  },_x000D_
_x000D_
  adminOnly: function(req, res, next) {_x000D_
    let loginUser = req.body.user_x000D_
    if (loginUser && loginUser.role === 'admin') {_x000D_
      next()_x000D_
    } else {_x000D_
      next(new Error('Not Authorized'))_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
====error handler==== MIDDLEWARE_x000D_
const errorHelper = require('../helpers/errorHandling')_x000D_
_x000D_
module.exports = function(err, req, res, next) {_x000D_
  //   console.log(err)_x000D_
  let errorToSend = errorHelper(err)_x000D_
  // console.log(errorToSend)_x000D_
  res.status(errorToSend.statusCode).json(errorToSend)_x000D_
}_x000D_
_x000D_
_x000D_
====error handling==== HELPER_x000D_
var nodeError = ["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]_x000D_
var mongooseError = ["MongooseError","DisconnectedError","DivergentArrayError","MissingSchemaError","DocumentNotFoundError","MissingSchemaError","ObjectExpectedError","ObjectParameterError","OverwriteModelError","ParallelSaveError","StrictModeError","VersionError"]_x000D_
var mongooseErrorFromClient = ["CastError","ValidatorError","ValidationError"];_x000D_
var jwtError = ["TokenExpiredError","JsonWebTokenError","NotBeforeError"]_x000D_
_x000D_
function nodeErrorMessage(message){_x000D_
    switch(message){_x000D_
        case "Token is undefined":{_x000D_
            return 403;_x000D_
        }_x000D_
        case "User not found":{_x000D_
            return 403;_x000D_
        }_x000D_
        case "Not Authorized":{_x000D_
            return 401;_x000D_
        }_x000D_
        case "Email is Invalid!":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Password is Invalid!":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Incorrect password for register as admin":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Item id not found":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Email or Password is invalid": {_x000D_
            return 400_x000D_
        }_x000D_
        default :{_x000D_
            return 500;_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
module.exports = function(errorObject){_x000D_
    // console.log("===ERROR OBJECT===")_x000D_
    // console.log(errorObject)_x000D_
    // console.log("===ERROR STACK===")_x000D_
    // console.log(errorObject.stack);_x000D_
_x000D_
    let statusCode = 500;  _x000D_
    let returnObj = {_x000D_
        error : errorObject_x000D_
    }_x000D_
    if(jwtError.includes(errorObject.name)){_x000D_
        statusCode = 403;_x000D_
        returnObj.message = "Token is Invalid"_x000D_
        returnObj.source = "jwt"_x000D_
    }_x000D_
    else if(nodeError.includes(errorObject.name)){_x000D_
        returnObj.error = JSON.parse(JSON.stringify(errorObject, ["message", "arguments", "type", "name"]))_x000D_
        returnObj.source = "node";_x000D_
        statusCode = nodeErrorMessage(errorObject.message);_x000D_
        returnObj.message = errorObject.message;_x000D_
    }else if(mongooseError.includes(errorObject.name)){_x000D_
        returnObj.source = "database"_x000D_
        returnObj.message = "Error from server"_x000D_
    }else if(mongooseErrorFromClient.includes(errorObject.name)){_x000D_
        returnObj.source = "database";_x000D_
        errorObject.message ? returnObj.message = errorObject.message : returnObj.message = "Bad Request"_x000D_
        statusCode = 400;_x000D_
    }else{_x000D_
        returnObj.source = "unknown error";_x000D_
        returnObj.message = "Something error";_x000D_
    }_x000D_
    returnObj.statusCode = statusCode;_x000D_
    _x000D_
    return returnObj;_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
===jwt====_x000D_
const jwt = require('jsonwebtoken')_x000D_
_x000D_
function generateToken(payload) {_x000D_
    let token = jwt.sign(payload, process.env.JWT_KEY)_x000D_
    return token_x000D_
}_x000D_
_x000D_
function verifyToken(token) {_x000D_
    let payload = jwt.verify(token, process.env.JWT_KEY)_x000D_
    return payload_x000D_
}_x000D_
_x000D_
module.exports = {_x000D_
    generateToken, verifyToken_x000D_
}_x000D_
_x000D_
===router index===_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
_x000D_
// router.get('/', )_x000D_
router.use('/users', require('./users'))_x000D_
router.use('/products', require('./product'))_x000D_
router.use('/transactions', require('./transaction'))_x000D_
_x000D_
module.exports = router_x000D_
_x000D_
====router user ====_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
const User = require('../controllers/userController')_x000D_
const auth = require('../middlewares/auth')_x000D_
_x000D_
/* GET users listing. */_x000D_
router.post('/register', User.register)_x000D_
router.post('/login', User.login)_x000D_
router.get('/', auth.authentication, User.getUser)_x000D_
router.post('/logout', auth.authentication, User.logout)_x000D_
module.exports = router_x000D_
_x000D_
_x000D_
====app====_x000D_
require('dotenv').config()_x000D_
const express = require('express')_x000D_
const cookieParser = require('cookie-parser')_x000D_
const logger = require('morgan')_x000D_
const cors = require('cors')_x000D_
const indexRouter = require('./routes/index')_x000D_
const errorHandler = require('./middlewares/errorHandler')_x000D_
const mongoose = require('mongoose')_x000D_
const app = express()_x000D_
_x000D_
mongoose.connect(process.env.DB_URI, {_x000D_
  useNewUrlParser: true,_x000D_
  useUnifiedTopology: true,_x000D_
  useCreateIndex: true,_x000D_
  useFindAndModify: false_x000D_
})_x000D_
_x000D_
app.use(cors())_x000D_
app.use(logger('dev'))_x000D_
app.use(express.json())_x000D_
app.use(express.urlencoded({ extended: false }))_x000D_
app.use(cookieParser())_x000D_
_x000D_
app.use('/', indexRouter)_x000D_
app.use(errorHandler)_x000D_
_x000D_
module.exports = app
_x000D_
_x000D_
_x000D_

Concat all strings inside a List<string> using LINQ

String.Join(delimiter, list);

is sufficient.

select records from postgres where timestamp is in certain range

Search till the seconds for the timestamp column in postgress

select * from "TableName" e
    where timestamp >= '2020-08-08T13:00:00' and timestamp < '2020-08-08T17:00:00';

CSS Auto hide elements after 5 seconds

YES!

But you can't do it in the way you may immediately think, because you cant animate or create a transition around the properties you'd otherwise rely on (e.g. display, or changing dimensions and setting to overflow:hidden) in order to correctly hide the element and prevent it from taking up visible space.

Therefore, create an animation for the elements in question, and simply toggle visibility:hidden; after 5 seconds, whilst also setting height and width to zero to prevent the element from still occupying space in the DOM flow.

FIDDLE

CSS

html, body {
    height:100%;
    width:100%;
    margin:0;
    padding:0;
}
#hideMe {
    -moz-animation: cssAnimation 0s ease-in 5s forwards;
    /* Firefox */
    -webkit-animation: cssAnimation 0s ease-in 5s forwards;
    /* Safari and Chrome */
    -o-animation: cssAnimation 0s ease-in 5s forwards;
    /* Opera */
    animation: cssAnimation 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}
@keyframes cssAnimation {
    to {
        width:0;
        height:0;
        overflow:hidden;
    }
}
@-webkit-keyframes cssAnimation {
    to {
        width:0;
        height:0;
        visibility:hidden;
    }
}

HTML

<div id='hideMe'>Wait for it...</div>

How to convert a string to character array in c (or) how to extract a single char form string?

In C, a string is actually stored as an array of characters, so the 'string pointer' is pointing to the first character. For instance,

char myString[] = "This is some text";

You can access any character as a simple char by using myString as an array, thus:

char myChar = myString[6];
printf("%c\n", myChar); // Prints s

Hope this helps! David

sql set variable using COUNT

You just need parentheses around your select:

SET @times = (SELECT COUNT(DidWin) FROM ...)

Or you can do it like this:

SELECT @times = COUNT(DidWin) FROM ...

React.js: Wrapping one component into another

In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:

var ListView = React.createClass({
    render: function() {
        var items = this.props.data.map(function(item) {
            return this.props.delegate({data:item});
        }.bind(this));
        return <ul>{items}</ul>;
    }
});

var ItemDelegate = React.createClass({
    render: function() {
        return <li>{this.props.data}</li>
    }
});

var Wrapper = React.createClass({    
    render: function() {
        return <ListView delegate={ItemDelegate} data={someListOfData} />
    }
});

jQuery: more than one handler for same event

Both handlers get called.

You may be thinking of inline event binding (eg "onclick=..."), where a big drawback is only one handler may be set for an event.

jQuery conforms to the DOM Level 2 event registration model:

The DOM Event Model allows registration of multiple event listeners on a single EventTarget. To achieve this, event listeners are no longer stored as attribute values

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

What kind of computer are you using? It may not have any other "normal" local storage, but does it have video RAM, for example? 1 megapixel x 32 bits per pixel (say) is pretty close to your required data input size.

(I largely ask in memory of the old Acorn RISC PC, which could 'borrow' VRAM to expand the available system RAM, if you chose a low resolution or low colour-depth screen mode!). This was rather useful on a machine with only a few MB of normal RAM.

Python argparse: default value or specified value

The difference between:

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)

and

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)

is thus:

myscript.py => debug is 7 (from default) in the first case and "None" in the second

myscript.py --debug => debug is 1 in each case

myscript.py --debug 2 => debug is 2 in each case

How to change the order of DataFrame columns?

You could do the following (borrowing parts from Aman's answer):

cols = df.columns.tolist()
cols.insert(0, cols.pop(-1))

cols
>>>['mean', 0L, 1L, 2L, 3L, 4L]

df = df[cols]

How to convert Blob to File in JavaScript

Use saveAs on FileSaver.js github project.

FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it.

SQL query to find third highest salary in company

The most simple way that should work in any database is to do following:

SELECT * FROM `employee` ORDER BY `salary` DESC LIMIT 1 OFFSET 2;

Which orders employees by salary and then tells db to return a single result (1 in LIMIT) counting from third row in result set (2 in OFFSET). It may be OFFSET 3 if your DB counts result rows from 1 and not from 0.

This example should work in MySQL and PostgreSQL.

Foreach value from POST from form

Use array-like fields:

<input name="name_for_the_items[]"/>

You can loop through the fields:

foreach($_POST['name_for_the_items'] as $item)
{
  //do something with $item
}

Unnamed/anonymous namespaces vs. static functions

Use of static keyword for that purpose is deprecated by the C++98 standard. The problem with static is that it doesn't apply to type definition. It's also an overloaded keyword used in different ways in different contexts, so unnamed namespaces simplify things a bit.

AngularJS. How to call controller function from outside of controller component

Dmitry's answer works fine. I just made a simple example using the same technique.

jsfiddle: http://jsfiddle.net/o895a8n8/5/

<button onclick="call()">Call Controller's method from outside</button>
<div  id="container" ng-app="" ng-controller="testController">
</div>

.

function call() {
    var scope = angular.element(document.getElementById('container')).scope();
      scope.$apply(function(){
        scope.msg = scope.msg + ' I am the newly addded message from the outside of the controller.';
    })
    alert(scope.returnHello());
}

function testController($scope) {
    $scope.msg = "Hello from a controller method.";
    $scope.returnHello = function() {
        return $scope.msg ; 
    }
}

How to set the default value for radio buttons in AngularJS?

Set a default value for people with ngInit

<div ng-app>
    <div ng-init="people=1" />
        <input type="radio" ng-model="people" value="1"><label>1</label>
        <input type="radio" ng-model="people" value="2"><label>2</label>
        <input type="radio" ng-model="people" value="3"><label>3</label>
    <ul>
        <li>{{10*people}}€</li>
        <li>{{8*people}}€</li>
        <li>{{30*people}}€</li>
    </ul>
</div>

Demo: Fiddle

Override default Spring-Boot application.properties settings in Junit Test

TLDR:

So what I did was to have the standard src/main/resources/application.properties and also a src/test/resources/application-default.properties where i override some settings for ALL my tests.

Whole Story

I ran into the same problem and was not using profiles either so far. It seemed to be bothersome to have to do it now and remember declaring the profile -- which can be easily forgotten.

The trick is, to leverage that a profile specific application-<profile>.properties overrides settings in the general profile. See https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties.

Post parameter is always null

With Angular, I was able to pass data in this format:

 data: '=' + JSON.stringify({ u: $scope.usrname1, p: $scope.pwd1 }),
 headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' }

And in Web API Controler:

    [HttpPost]
    public Hashtable Post([FromBody]string jsonString)
    {
        IDictionary<string, string> data = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonString);
        string username = data["u"];
        string pwd = data["p"];
   ......

Alternatively, I could also post JSON data like this:

    data: { PaintingId: 1, Title: "Animal show", Price: 10.50 } 

And, in the controller, accept a class type like this:

    [HttpPost]
    public string POST(Models.PostModel pm)
    {

     ....
    }

Either way works, if you have an established public class in the API then post JSON, otherwise post '=' + JSON.stringify({..: ..., .. : ... })

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

Answer in swift:

Add the following method in your TableViewController:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return indexPathOfCellYouWantToHide == indexPath ? 0 : super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}

if the tableView tries to draw the cell you wish to hide, then it won't display it because its height will be set to 0pt thanks to the method above, everything else stays unaltered.

Please note that indexPathOfCellYouWantToHide can be changed at anytime :)

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

SELECT convert(datetime, '23/07/2009', 103)

Select query with date condition

select Qty, vajan, Rate,Amt,nhamali,ncommission,ntolai from SalesDtl,SalesMSt where SalesDtl.PurEntryNo=1 and SalesMST.SaleDate=  (22/03/2014) and SalesMST.SaleNo= SalesDtl.SaleNo;

That should work.

Excel VBA - How to Redim a 2D array?

Here ya go.

Public Function ReDimPreserve(ByRef Arr, ByVal idx1 As Integer, ByVal idx2 As Integer)

    Dim newArr()
    Dim x As Integer
    Dim y As Integer

    ReDim newArr(idx1, idx2)

    For x = 0 To UBound(Arr, 1)
        For y = 0 To UBound(Arr, 2)
            newArr(x, y) = Arr(x, y)
        Next
    Next

    Arr = newArr

End Function

How do I create an executable in Visual Studio 2013 w/ C++?

All executable files from Visual Studio should be located in the debug folder of your project, e.g:

Visual Studio Directory: c:\users\me\documents\visual studio

Then the project which was called 'hello world' would be in the directory:

c:\users\me\documents\visual studio\hello world

And your exe would be located in:

c:\users\me\documents\visual studio\hello world\Debug\hello world.exe

Note the exe being named the same as the project.

Otherwise, you could publish it to a specified folder of your choice which comes with an installation, which would be good if you wanted to distribute it quickly

EDIT:

Everytime you build your project in VS, the exe is updated with the new one according to the code (as long as it builds without errors). When you publish it, you can choose the location, aswell as other factors, and the setup exe will be in that location, aswell as some manifest files and other files about the project.

MySQL "Or" Condition

Use brackets to group the OR statements.

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");

You can also use IN

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo','$Date_ThreeDaysAgo','$Date_FourDaysAgo','$Date_FiveDaysAgo','$Date_SixDaysAgo','$Date_SevenDaysAgo')");

Trigger change event <select> using jquery

Use val() to change to the value (not the text) and trigger() to manually fire the event.

The change event handler must be declared before the trigger.

Here's a sample

$('.check').change(function(){
  var data= $(this).val();
  alert(data);            
});

$('.check')
    .val('two')
    .trigger('change');

UIButton action in table view cell

Swift 4 & Swift 5:

You need to add target for that button.

myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

To get the tag in the connected function:

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}

Understanding unique keys for array children in React.js

I had a unique key, just had to pass it as a prop like this:

<CompName key={msg._id} message={msg} />

This page was helpful:

https://reactjs.org/docs/lists-and-keys.html#keys

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I would rather use plt.clf() after every plt.show() to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.

Similarly, you could do plt.cla() to just clear the current axes.

To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:

fig, axes = plt.subplots(nrows=2, ncols=2)

axes[0, 1].clear()

Scroll to a div using jquery

Add this little function and use it as so: $('div').scrollTo(500);

jQuery.fn.extend(
{
  scrollTo : function(speed, easing)
  {
    return this.each(function()
    {
      var targetOffset = $(this).offset().top;
      $('html,body').animate({scrollTop: targetOffset}, speed, easing);
    });
  }
});

How to use shared memory with Linux in C

try this code sample, I tested it, source: http://www.makelinux.net/alp/035

#include <stdio.h> 
#include <sys/shm.h> 
#include <sys/stat.h> 

int main () 
{
  int segment_id; 
  char* shared_memory; 
  struct shmid_ds shmbuffer; 
  int segment_size; 
  const int shared_segment_size = 0x6400; 

  /* Allocate a shared memory segment.  */ 
  segment_id = shmget (IPC_PRIVATE, shared_segment_size, 
                 IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR); 
  /* Attach the shared memory segment.  */ 
  shared_memory = (char*) shmat (segment_id, 0, 0); 
  printf ("shared memory attached at address %p\n", shared_memory); 
  /* Determine the segment's size. */ 
  shmctl (segment_id, IPC_STAT, &shmbuffer); 
  segment_size  =               shmbuffer.shm_segsz; 
  printf ("segment size: %d\n", segment_size); 
  /* Write a string to the shared memory segment.  */ 
  sprintf (shared_memory, "Hello, world."); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Reattach the shared memory segment, at a different address.  */ 
  shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0); 
  printf ("shared memory reattached at address %p\n", shared_memory); 
  /* Print out the string from shared memory.  */ 
  printf ("%s\n", shared_memory); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Deallocate the shared memory segment.  */ 
  shmctl (segment_id, IPC_RMID, 0); 

  return 0; 
} 

Passing Javascript variable to <a href >

JAVASCRIPT CODE:

<script>

    function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

var user = getUrlVars()["user"];
var pass = getUrlVars()["pass"];
var sub  = getUrlVars()["sub"];
</script>

<script>
    var myApp = angular.module('myApp',[]);

myApp.controller('dropdownCtrl', ['$scope','$window','$http', function($scope, $window, $http) {

 $http.get('http://dummy.com/app/chapter.php?user='+user+'&pass='+pass)

     .then(function (response) {$scope.names = response.data.admin;});
    $scope.names = [];

        $http.get('http://dummy.com/app/chapter.php?user='+user+'&pass='+pass+'&sub='+sub)

            .then(function (response) {$scope.chapter = response.data.chp;});
           $scope.chapter = [];

};


}]);
    </script>

HTML:

<div ng-controller="dropdownCtrl">
<div ng-repeat="a in chapter">
<a href="topic.html?ch={{a.chapter}}" onClick="location.href=this.href+'&user='+user+'&pass='+pass+'&sub='+sub;return false;">{{a.chapter}}</a>
</div>

How to create SPF record for multiple IPs?

Yes the second syntax is fine.

Have you tried using the SPF wizard? https://www.spfwizard.net/

It can quickly generate basic and complex SPF records.

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

Sometimes the exception will not stop after you increase the memory in eclipse ini file. then try below option

Go to Window >> Preferences >> MyEclipse >> Java Enterprise Project >> Web Project >> Deployment Tab Under -> Under Library Deployment Policies UnCheck -> Jars from User Libraries

How to force a line break in a long word in a DIV?

This could be added to the accepted answer for a 'cross-browser' solution.

Sources:

.your_element{
    -ms-word-break: break-all;
    word-break: break-all;

 /* Non standard for webkit */
     word-break: break-word;

    -webkit-hyphens: auto;
       -moz-hyphens: auto;
        -ms-hyphens: auto;
            hyphens: auto;
}

android.widget.Switch - on/off event listener?

Define your XML layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.neoecosystem.samplex.SwitchActivity">

    <Switch
        android:id="@+id/myswitch"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

</RelativeLayout> 

Then create an Activity

public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {

    Switch mySwitch = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_switch);


        mySwitch = (Switch) findViewById(R.id.myswitch);
        mySwitch.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // do something when check is selected
        } else {
            //do something when unchecked
        }
    }

    ****
}

======== For below API 14 use SwitchCompat =========

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.neoecosystem.samplex.SwitchActivity">

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/myswitch"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

</RelativeLayout>

Activity

public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {

    SwitchCompat mySwitch = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_switch);


        mySwitch = (SwitchCompat) findViewById(R.id.myswitch);
        mySwitch.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // do something when checked is selected
        } else {
            //do something when unchecked
        }
    }
   *****
}

How do I make bootstrap table rows clickable?

That code transforms any bootstrap table row that has data-href attribute set into a clickable element

Note: data-href attribute is a valid tr attribute (HTML5), href attributes on tr element are not.

$(function(){
    $('.table tr[data-href]').each(function(){
        $(this).css('cursor','pointer').hover(
            function(){ 
                $(this).addClass('active'); 
            },  
            function(){ 
                $(this).removeClass('active'); 
            }).click( function(){ 
                document.location = $(this).attr('data-href'); 
            }
        );
    });
});

How to set initial value and auto increment in MySQL?

First you need to add column for auto increment

alter table users add column id int(5) NOT NULL AUTO_INCREMENT FIRST

This query for add column at first. Now you have to reset auto increment initial value. So use this query

alter table users AUTO_INCREMENT=1001

Now your table started with 1001

Jquery UI datepicker. Disable array of Dates

beforeShowDate didn't work for me, so I went ahead and developed my own solution:

$('#embeded_calendar').datepicker({
               minDate: date,
                localToday:datePlusOne,
               changeDate: true,
               changeMonth: true,
               changeYear: true,
               yearRange: "-120:+1",
               onSelect: function(selectedDateFormatted){

                     var selectedDate = $("#embeded_calendar").datepicker('getDate');

                    deactivateDates(selectedDate);
                   }

           });


              var excludedDates = [ "10-20-2017","10-21-2016", "11-21-2016"];

              deactivateDates(new Date());

            function deactivateDates(selectedDate){
                setTimeout(function(){ 
                      var thisMonthExcludedDates = thisMonthDates(selectedDate);
                      thisMonthExcludedDates = getDaysfromDate(thisMonthExcludedDates);
                       var excludedTDs = page.find('td[data-handler="selectDay"]').filter(function(){
                           return $.inArray( $(this).text(), thisMonthExcludedDates) >= 0
                       });

                       excludedTDs.unbind('click').addClass('ui-datepicker-unselectable');
                   }, 10);
            }

            function thisMonthDates(date){
              return $.grep( excludedDates, function( n){
                var dateParts = n.split("-");
                return dateParts[0] == date.getMonth() + 1  && dateParts[2] == date.getYear() + 1900;
            });
            }

            function getDaysfromDate(datesArray){
                  return  $.map( datesArray, function( n){
                    return n.split("-")[1]; 
                });
             }

How do I use 'git reset --hard HEAD' to revert to a previous commit?

First, it's always worth noting that git reset --hard is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status is clean (that is, empty) before using it.

Initially you say the following:

So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:

That's incorrect. Git only records the state of the files when you stage them (with git add) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)

In your question you then go on to ask the following:

When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro

How do I then revert the files on my hard drive back to that previous commit?

If you do git reset --hard <SOME-COMMIT> then Git will:

  • Make your current branch (typically master) back to point at <SOME-COMMIT>.
  • Then make the files in your working tree and the index ("staging area") the same as the versions committed in <SOME-COMMIT>.

HEAD points to your current branch (or current commit), so all that git reset --hard HEAD will do is to throw away any uncommitted changes you have.

So, suppose the good commit that you want to go back to is f414f31. (You can find that via git log or any history browser.) You then have a few different options depending on exactly what you want to do:

  • Change your current branch to point to the older commit instead. You could do that with git reset --hard f414f31. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31 will no longer be in the history of your master branch.
  • Create a new commit that represents exactly the same state of the project as f414f31, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:

    git reset --hard f414f31
    git reset --soft HEAD@{1}
    git commit -m "Reverting to the state of the project at f414f31"
    

Convert a PHP script into a stand-alone windows executable

I tried most of solution given in the 1st answer, the only one that worked for me and is non-commercial is php-desktop.

I simply put my php files in the www/ folder, changed the name of .exe and was able to run my php as an exe !!

Also there is a complete documentation, up to date support, windows and linux (and soon mac) compatibility and options can easily be changed.

Error: fix the version conflict (google-services plugin)

For fire base to install properly all the versions of the fire base compiles must be in same version so

compile 'com.google.firebase:firebase-messaging:11.0.4' 
compile 'com.google.android.gms:play-services-maps:11.0.4' 
compile 'com.google.android.gms:play-services-location:11.0.4'

this is the correct way to do it.

How to select an item in a ListView programmatically?

I think that the problem and the solution was descripted by cody gray! I've an additional note.

Please check the focus of the specified listview item (and the control!). I could set the focus and the selection with the following lines of code :

this.listView1.Items[1].Selected = true;
this.listView1.Items[1].Focused = true;

But the focused control was a condition!

Is there any difference between a GUID and a UUID?

GUID is Microsoft's implementation of the UUID standard.

Per Wikipedia:

The term GUID usually refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.

An updated quote from that same Wikipedia article:

RFC 4122 itself states that UUIDs "are also known as GUIDs". All this suggests that "GUID", while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…

Altering user-defined table types in SQL Server

Here are simple steps that minimize tedium and don't require error-prone semi-automated scripts or pricey tools.

Keep in mind that you can generate DROP/CREATE statements for multiple objects from the Object Explorer Details window (when generated this way, DROP and CREATE scripts are grouped, which makes it easy to insert logic between Drop and Create actions):

Drop and Create To

  1. Back up you database in case anything goes wrong!
  2. Automatically generate the DROP/CREATE statements for all dependencies (or generate for all "Programmability" objects to eliminate the tedium of finding dependencies).
  3. Between the DROP and CREATE [dependencies] statements (after all DROP, before all CREATE), insert generated DROP/CREATE [table type] statements, making the changes you need with CREATE TYPE.
  4. Run the script, which drops all dependencies/UDTTs and then recreates [UDTTs with alterations]/dependencies.

If you have smaller projects where it might make sense to change the infrastructure architecture, consider eliminating user-defined table types. Entity Framework and similar tools allow you to move most, if not all, of your data logic to your code base where it's easier to maintain.

How to link C++ program with Boost using CMake

The following is my configuration:

cmake_minimum_required(VERSION 2.8)
set(Boost_INCLUDE_DIR /usr/local/src/boost_1_46_1)
set(Boost_LIBRARY_DIR /usr/local/src/boost_1_46_1/stage/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})

add_executable(main main.cpp)
target_link_libraries( main ${Boost_LIBRARIES} )

How to have EditText with border in Android Lollipop

For correct work your shape should be with selector and item tags

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ffffff" />
            <stroke android:width="1dp"
                    android:color="@color/shape_border_active"/>
        </shape>
    </item>

</selector>

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

'any' vs 'Object'

Object appears to be a more specific declaration than any. From the TypeScript spec (section 3):

All types in TypeScript are subtypes of a single top type called the Any type. The any keyword references this type. The Any type is the one type that can represent any JavaScript value with no constraints. All other types are categorized as primitive types, object types, or type parameters. These types introduce various static constraints on their values.

Also:

The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list.

Objects do not allow the same flexibility.

For example:

var myAny : any;

myAny.Something(); // no problemo

var myObject : Object;

myObject.Something(); // Error: The property 'Something' does not exist on value of type 'Object'.

How to duplicate a git repository? (without forking)

If you just want to create a new repository using all or most of the files from an existing one (i.e., as a kind of template), I find the easiest approach is to make a new repo with the desired name etc, clone it to your desktop, then just add the files and folders you want in it.

You don't get all the history etc, but you probably don't want that in this case.

How to set Spring profile from system variable?

If i run the command line : java -Dspring.profiles.active=development -jar yourApplication.jar from my webapplication directory it states that the path is incorrect. So i just defined the profile in manualy in the application.properties file like this :

spring.profiles.active=mysql 

or

spring.profiles.active=postgres

or

spring.profiles.active=mongodb

Date only from TextBoxFor()

For me, I needed to keep the TextboxFor() because using EditorFor() changes the input type to date. Which, in Chrome, adds a built in date picker, which screwed up the jQuery datepicker that I was already using. So, to continue using TextboxFor() AND only output the date, you can do this:

<tr>
    <td class="Label">@Html.LabelFor(model => model.DeliveryDate)</td>
    @{
        string deliveryDate = Model.DeliveryDate.ToShortDateString();
    }
    <td>@Html.TextBoxFor(model => model.DeliveryDate, new { @Value = deliveryDate }) *</td>
    <td style="color: red;">@Html.ValidationMessageFor(model => model.DeliveryDate)</td>
</tr>

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

I wouldn't bother doing it in Linq2SQL. Create a stored Procedure for the query you want and understand and then create the object to the stored procedure in the framework or just connect direct to it.

Delete files or folder recursively on Windows CMD

Use the Windows rmdir command

That is, rmdir /S /Q C:\Temp

I'm also using the ones below for some years now, flawlessly.

Check out other options with: forfiles /?

Delete SQM/Telemetry in windows folder recursively

forfiles /p %SYSTEMROOT%\system32\LogFiles /s /m *.* /d -1 /c "cmd /c del @file"

Delete windows TMP files recursively

forfiles /p %SYSTEMROOT%\Temp /s /m *.* /d -1 /c "cmd /c del @file"

Delete user TEMP files and folders recursively

forfiles /p %TMP% /s /m *.* /d -1 /c "cmd /c del @file"

How can I generate a random number in a certain range?

You can use If Random. For example, this generates a random number between 75 to 100.

final int random = new Random().nextInt(26) + 75;

Which characters make a URL invalid?

In general URIs as defined by RFC 3986 (see Section 2: Characters) may contain any of the following 84 characters:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=

Note that this list doesn't state where in the URI these characters may occur.

Any other character needs to be encoded with the percent-encoding (%hh). Each part of the URI has further restrictions about what characters need to be represented by an percent-encoded word.

Private pages for a private Github repo

There is an article with a working idea on how to request oAuth authorization before loading static content dynamically:

Securing Site That Runs on Github Pages With JSON Backend In Private Repository

Content should be stored in a secret GitHub repository with a viewer having read access to it. GitHub pages stores only the serving JS code.

How do I move a table into a schema in T-SQL

ALTER SCHEMA TargetSchema 
    TRANSFER SourceSchema.TableName;

If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable stored procedure:

exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"

Ref.: ALTER SCHEMA

SQL 2008: How do I change db schema to dbo

git remote prune – didn't show as many pruned branches as I expected

When you use git push origin :staleStuff, it automatically removes origin/staleStuff, so when you ran git remote prune origin, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune to get rid of branches you have removed.


So what exactly git remote prune does? Main idea: local branches (not tracking branches) are not touched by git remote prune command and should be removed manually.

Now, a real-world example for better understanding:

You have a remote repository with 2 branches: master and feature. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):

  • refs/heads/master (short name master)
  • refs/heads/feature (short name feature)
  • refs/remotes/origin/master (short name origin/master)
  • refs/remotes/origin/feature (short name origin/feature)

Now, a typical scenario:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including refs/heads/feature, because git remote prune does not remove any refs/heads/* references.

It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge configuration parameter. This parameter is not really required for anything to work (probably except git pull), so it might be missing.

(updated with example & useful info from comments)

How do I create a singleton service in Angular 2?

Parent and child services

I was having trouble with a parent service and its child using different instances. To force one instance to be used, you can alias the parent with reference to the child in your app module providers. The parent will not be able to access the child's properties, but the same instance will be used for both services. https://angular.io/guide/dependency-injection-providers#aliased-class-providers

app.module.ts

providers: [
  ChildService,
  // Alias ParentService w/ reference to ChildService
  { provide: ParentService, useExisting: ChildService}
]

Services used by components outside of your app modules scope

When creating a library consisting of a component and a service, I ran into an issue where two instances would be created. One by my Angular project and one by the component inside of my library. The fix:

my-outside.component.ts

@Component({...})
export class MyOutsideComponent {
  @Input() serviceInstance: MyOutsideService;
  ...
}

my-inside.component.ts

  constructor(public myService: MyOutsideService) { }

my-inside.component.hmtl

<app-my-outside [serviceInstance]="myService"></app-my-outside>

Generic type conversion FROM string

I used lobos answer and it works. But I had a problem with the conversion of doubles because of the culture settings. So I added

return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture);

Append values to a set in Python

You can also use the | operator to concatenate two sets (union in set theory):

>>> my_set = {1}
>>> my_set = my_set | {2}
>>> my_set
{1, 2}

Or a shorter form using |=:

>>> my_set = {1}
>>> my_set |= {2}
>>> my_set
{1, 2}

Note: In versions prior to Python 2.7, use set([...]) instead of {...}.

"Insert if not exists" statement in SQLite

insert into bookmarks (users_id, lessoninfo_id)

select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;

This is the fastest way.

For some other SQL engines, you can use a Dummy table containing 1 record. e.g:

select 1, 167 from ONE_RECORD_DUMMY_TABLE

How to use Class<T> in Java?

Just use the beef class:

public <T> T beefmarshal( Class<beef> beefClass, InputBeef inputBeef )
     throws JAXBException {
     String packageName = docClass.getPackage().getBeef();
     JAXBContext beef = JAXBContext.newInstance( packageName );
     Unmarshaller u = beef.createBeef();
     JAXBElement<T> doc = (JAXBElement<T>)u.beefmarshal( inputBeef );
     return doc.getBeef();
}

What does "atomic" mean in programming?

It's something that "appears to the rest of the system to occur instantaneously", and falls under categorisation of Linearizability in computing processes. To quote that linked article further:

Atomicity is a guarantee of isolation from concurrent processes. Additionally, atomic operations commonly have a succeed-or-fail definition — they either successfully change the state of the system, or have no apparent effect.

So, for instance, in the context of a database system, one can have 'atomic commits', meaning that you can push a changeset of updates to a relational database and those changes will either all be submitted, or none of them at all in the event of failure, in this way data does not become corrupt, and consequential of locks and/or queues, the next operation will be a different write or a read, but only after the fact. In the context of variables and threading this is much the same, applied to memory.

Your quote highlights that this need not be expected behaviour in all instances.

C# "internal" access modifier when doing unit testing

If you want to test private methods, have a look at PrivateObject and PrivateType in the Microsoft.VisualStudio.TestTools.UnitTesting namespace. They offer easy to use wrappers around the necessary reflection code.

Docs: PrivateType, PrivateObject

For VS2017 & 2019, you can find these by downloading the MSTest.TestFramework nuget

react-router getting this.props.location in child components

If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';


Using this you can export your child class as -

class MyApp extends Component{
    // your code
}

export default withRouter(MyApp);

And your class with Router -

// your code
<Router>
      ...
      <Route path="/myapp" component={MyApp} />
      // or if you are sending additional fields
      <Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>

Take a screenshot via a Python script on Linux

for ubuntu this work for me, you can take a screenshot of select window with this:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gdk
from gi.repository import GdkPixbuf
import numpy as np
from Xlib.display import Display

#define the window name
window_name = 'Spotify'

#define xid of your select 'window'
def locate_window(stack,window):
    disp = Display()
    NET_WM_NAME = disp.intern_atom('_NET_WM_NAME')
    WM_NAME = disp.intern_atom('WM_NAME') 
    name= []
    for i, w in enumerate(stack):
        win_id =w.get_xid()
        window_obj = disp.create_resource_object('window', win_id)
        for atom in (NET_WM_NAME, WM_NAME):
            window_name=window_obj.get_full_property(atom, 0)
            name.append(window_name.value)
    for l in range(len(stack)):
        if(name[2*l]==window):
            return stack[l]

window = Gdk.get_default_root_window()
screen = window.get_screen()
stack = screen.get_window_stack()
myselectwindow = locate_window(stack,window_name)
img_pixbuf = Gdk.pixbuf_get_from_window(myselectwindow,*myselectwindow.get_geometry()) 

to transform pixbuf into array

def pixbuf_to_array(p):
    w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channels(), p.get_rowstride())
    assert p.get_colorspace() == GdkPixbuf.Colorspace.RGB
    assert p.get_bits_per_sample() == 8
    if  p.get_has_alpha():
        assert c == 4
    else:
        assert c == 3
    assert r >= w * c
    a=np.frombuffer(p.get_pixels(),dtype=np.uint8)
    if a.shape[0] == w*c*h:
        return a.reshape( (h, w, c) )
    else:
        b=np.zeros((h,w*c),'uint8')
        for j in range(h):
            b[j,:]=a[r*j:r*j+w*c]
        return b.reshape( (h, w, c) )

beauty_print = pixbuf_to_array(img_pixbuf)

Java multiline string

If you like google's guava as much as I do, it can give a fairly clean representation and a nice, easy way to not hardcode your newline characters too:

String out = Joiner.on(newline).join(ImmutableList.of(
    "line1",
    "line2",
    "line3"));

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

If you are simply testing a local dev version of WordPress as I was an hitting timeouts when WordPress tries to update itself you can always disable updates for your local version like so: https://www.wpbeginner.com/wp-tutorials/how-to-disable-automatic-updates-in-wordpress/

Don't do this for a production site!

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

You just need to divide each element by the sum of the values in its column.

Doing this should suffice:

data.perc <- apply(data, 2, function(x){x/sum(x)})

Note that the second parameter tells apply to apply the provided function to columns (using 1 you would apply it to rows). The anonymous function, then, gets passed each data column, one at a time.

Parsing date string in Go

As answered but to save typing out "2006-01-02T15:04:05.000Z" for the layout, you could use the package's constant RFC3339.

str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(time.RFC3339, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

https://play.golang.org/p/Dgu2ZvHwTh

Loop through JSON in EJS

JSON.stringify(data).length return string length not Object length, you can use Object.keys.

<% for(var i=0; i < Object.keys(data).length ; i++) {%>

https://stackoverflow.com/a/14379528/3224296

Is 'bool' a basic datatype in C++?

C is meant to be a step above assembly language. The C if-statement is really just syntactical sugar for "branch-if-zero", so the idea of booleans as an independent datatype was a foreign concept at the time. (1)

Even now, C/C++ booleans are usually little more than an alias for a single byte data type. As such, it's really more of a purposing label than an independent datatype.

(1) Of course, modern compilers are a bit more advanced in their handling of if statements. This is from the standpoint of C as a new language.

ERROR 1049 (42000): Unknown database

Its a common error which happens when we try to access a database which doesn't exist. So create the database using

CREATE DATABASE blog_development;

The error commonly occours when we have dropped the database using

DROP DATABASE blog_development;

and then try to access the database.

Retrieve CPU usage and memory usage of a single process on Linux?

To get the memory usage of just your application (as opposed to the shared libraries it uses, you need to use the Linux smaps interface). This answer explains it well.

How to convert string to IP address and vice versa

This example shows how to convert from string to ip, and viceversa:

struct sockaddr_in sa;
char ip_saver[INET_ADDRSTRLEN];

// store this IP address in sa:
inet_pton(AF_INET, "192.0.1.10", &(sa.sin_addr));

// now get it back 
sprintf(ip_saver, "%s", sa.sin_addr));

// prints "192.0.2.10"
printf("%s\n", ip_saver); 

HTML img onclick Javascript

here you go.

<img src="https://i.imgur.com/7KpCS0Y.jpg" onclick="window.open(this.src)">

How to Get the HTTP Post data in C#?

This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.

string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++) 
{
   Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}

Sending string via socket (python)

client.py

import socket

s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
    str = raw_input("S: ")
    s.send(str.encode());
    if(str == "Bye" or str == "bye"):
        break
    print "N:",s.recv(1024).decode()
s.close()

server.py

import socket

s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
    rcvdData = c.recv(1024).decode()
    print "S:",rcvdData
    sendData = raw_input("N: ")
    c.send(sendData.encode())
    if(sendData == "Bye" or sendData == "bye"):
        break
c.close()

This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.

How to enable PHP's openssl extension to install Composer?

Wamp works with another php.ini that is in C:\wamp\bin\apache\Apache2.4.4\bin\php.ini. So you need to manualy find the correct file, that is in C:\wamp\bin\php\php5.4.12\php.ini. Uncomment the extension=php_openssl.dll line and just try to install Composer again.

ORA-00972 identifier is too long alias column name

As others have referred, names in Oracle SQL must be less or equal to 30 characters. I would add that this rule applies not only to table names but to field names as well. So there you have it.

Maven: Non-resolvable parent POM

Alternative reason also might be the parent artifact comes from repository which is not accessible from pom.xml, typically private repository. The solution was to provide that repository in pom.xml:

<repositories>
    <repository>
        <id>internal-repo</id>
        <name>internal repository</name>
        <url>https://my/private/repo</url>
        <layout>default</layout>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

In my case the problem was even more complicated due to Eclipse: the repository was active only in special profile (<profiles><profile><id>activate-private-repo</id><repositories>...) and Maven GUI in Eclipse didn't allow to set this profile through Ctrl+Alt+P shortcut.

The solution was to temporarily declare repository outside profile (unconditionally), launch Alt+F5 Maven Update Project, activate profile and put repository declaration back into profile. This is rather Eclipse bug, not Maven bug.

Byte and char conversion in Java

new String(byteArray, Charset.defaultCharset())

This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.

Use Expect in a Bash script to provide a password to an SSH command

Another way that I found useful to use a small Expect script from a Bash script is as follows.

...
Bash script start
Bash commands
...
expect - <<EOF
spawn your-command-here
expect "some-pattern"
send "some-command"
...
...
EOF
...
More Bash commands
...

This works because ...If the string "-" is supplied as a filename, standard input is read instead...

best practice font size for mobile

Based on my comment to the accepted answer, there are a lot potential pitfalls that you may encounter by declaring font-sizes smaller than 12px. By declaring styles that lead to computed font-sizes of less than 12px, like so:

html {
  font-size: 8px;
}
p {
  font-size: 1.4rem;
}
// Computed p size: 11px.

You'll run into issues with browsers, like Chrome with a Chinese language pack that automatically renders any font sizes computed under 12px as 12px. So, the following is true:

h6 {
    font-size: 12px;
}
p {
   font-size: 8px;
}
// Both render at 12px in Chrome with a Chinese language pack.   
// How unpleasant of a surprise.

I would also argue that for accessibility reasons, you generally shouldn't use sizes under 12px. You might be able to make a case for captions and the like, but again--prepare to be surprised under some browser setups, and prepared to make your grandma squint when she's trying to read your content.

I would instead, opt for something like this:

h1 {
    font-size: 2.5rem;
}

h2 {
    font-size: 2.25rem;
}

h3 {
    font-size: 2rem;
}

h4 {
    font-size: 1.75rem;
}

h5 {
    font-size: 1.5rem;
}

h6 {
    font-size: 1.25rem;
}

p {
    font-size: 1rem;
}

@media (max-width: 480px) {
    html {
        font-size: 12px;
    }
}

@media (min-width: 480px) {
    html {
        font-size: 13px;
    }
}

@media (min-width: 768px) {
    html {
        font-size: 14px;
    }
}

@media (min-width: 992px) {
    html {
        font-size: 15px;
    }
}

@media (min-width: 1200px) {
    html {
        font-size: 16px;
    }
}

You'll find that tons of sites that have to focus on accessibility use rather large font sizes, even for p elements.

As a side note, setting margin-bottom equal to the font-size usually also tends to be attractive, i.e.:

h1 {
    font-size: 2.5rem;
    margin-bottom: 2.5rem;
}

Good luck.

Why use double indirection? or Why use pointers to pointers?

One thing I use them for constantly is when I have an array of objects and I need to perform lookups (binary search) on them by different fields.
I keep the original array...

int num_objects;
OBJECT *original_array = malloc(sizeof(OBJECT)*num_objects);

Then make an array of sorted pointers to the objects.

int compare_object_by_name( const void *v1, const void *v2 ) {
  OBJECT *o1 = *(OBJECT **)v1;
  OBJECT *o2 = *(OBJECT **)v2;
  return (strcmp(o1->name, o2->name);
}

OBJECT **object_ptrs_by_name = malloc(sizeof(OBJECT *)*num_objects);
  int i = 0;
  for( ; i<num_objects; i++)
    object_ptrs_by_name[i] = original_array+i;
  qsort(object_ptrs_by_name, num_objects, sizeof(OBJECT *), compare_object_by_name);

You can make as many sorted pointer arrays as you need, then use a binary search on the sorted pointer array to access the object you need by the data you have. The original array of objects can stay unsorted, but each pointer array will be sorted by their specified field.

INNER JOIN vs LEFT JOIN performance in SQL Server

Try both queries (the one with inner and left join) with OPTION (FORCE ORDER) at the end and post the results. OPTION (FORCE ORDER) is a query hint that forces the optimizer to build the execution plan with the join order you provided in the query.

If INNER JOIN starts performing as fast as LEFT JOIN, it's because:

  • In a query composed entirely by INNER JOINs, the join order doesn't matter. This gives freedom for the query optimizer to order the joins as it sees fit, so the problem might rely on the optimizer.
  • With LEFT JOIN, that's not the case because changing the join order will alter the results of the query. This means the engine must follow the join order you provided on the query, which might be better than the optimized one.

Don't know if this answers your question but I was once in a project that featured highly complex queries making calculations, which completely messed up the optimizer. We had cases where a FORCE ORDER would reduce the execution time of a query from 5 minutes to 10 seconds.

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

How to open up a form from another form in VB.NET?

You could use:

Dim MyForm As New Form1
MyForm.Show()

or rather:

MyForm.ShowDialog()

to open the form as a dialog box to ensure that user interacts with the new form or closes it.

C++ String Concatenation operator<<

For string concatenation in C++, you should use the + operator.

nametext = "Your name is" + name;

Regular expression to extract text between square brackets

To match a substring between the first [ and last ], you may use

\[.*\]            # Including open/close brackets
\[(.*)\]          # Excluding open/close brackets (using a capturing group)
(?<=\[).*(?=\])   # Excluding open/close brackets (using lookarounds)

See a regex demo and a regex demo #2.

Use the following expressions to match strings between the closest square brackets:

  • Including the brackets:

    • \[[^][]*] - PCRE, Python re/regex, .NET, Golang, POSIX (grep, sed, bash)
    • \[[^\][]*] - ECMAScript (JavaScript, C++ std::regex, VBA RegExp)
    • \[[^\]\[]*] - Java regex
    • \[[^\]\[]*\] - Onigmo (Ruby, requires escaping of brackets everywhere)
  • Excluding the brackets:

    • (?<=\[)[^][]*(?=]) - PCRE, Python re/regex, .NET (C#, etc.), ICU (R stringr), JGSoft Software
    • \[([^][]*)] - Bash, Golang - capture the contents between the square brackets with a pair of unescaped parentheses, also see below
    • \[([^\][]*)] - JavaScript, C++ std::regex, VBA RegExp
    • (?<=\[)[^\]\[]*(?=]) - Java regex
    • (?<=\[)[^\]\[]*(?=\]) - Onigmo (Ruby, requires escaping of brackets everywhere)

NOTE: * matches 0 or more characters, use + to match 1 or more to avoid empty string matches in the resulting list/array.

Whenever both lookaround support is available, the above solutions rely on them to exclude the leading/trailing open/close bracket. Otherwise, rely on capturing groups (links to most common solutions in some languages have been provided).

If you need to match nested parentheses, you may see the solutions in the Regular expression to match balanced parentheses thread and replace the round brackets with the square ones to get the necessary functionality. You should use capturing groups to access the contents with open/close bracket excluded:

Creating an array of objects in Java

You are correct. Aside from that if we want to create array of specific size filled with elements provided by some "factory", since Java 8 (which introduces stream API) we can use this one-liner:

A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);
  • Stream.generate(() -> new A()) is like factory for separate A elements created in a way described by lambda, () -> new A() which is implementation of Supplier<A> - it describe how each new A instances should be created.
  • limit(4) sets amount of elements which stream will generate
  • toArray(A[]::new) (can also be rewritten as toArray(size -> new A[size])) - it lets us decide/describe type of array which should be returned.

For some primitive types you can use DoubleStream, IntStream, LongStream which additionally provide generators like range rangeClosed and few others.

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

PHP Pass by reference in foreach

I got here just by accident and the OP's question got my attention. Unfortunately I do not understand any of the explanations from the top. Seems to me like everybody knows it, gets it, accetps it, just cannot explain.

Luckily, a pure sentence from PHP documentation on foreach makes this completely clear:

Warning: Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

jQuery: keyPress Backspace won't fire?

According to the jQuery documentation for .keypress(), it does not catch non-printable characters, so backspace will not work on keypress, but it is caught in keydown and keyup:

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser. (https://api.jquery.com/keypress/)

In some instances keyup isn't desired or has other undesirable effects and keydown is sufficient, so one way to handle this is to use keydown to catch all keystrokes then set a timeout of a short interval so that the key is entered, then do processing in there after.

jQuery(el).keydown( function() { 
    var that = this; setTimeout( function(){ 
           /** Code that processes backspace, etc. **/ 
     }, 100 );  
 } );

Is it possible to play music during calls so that the partner can hear it ? Android

I think it's not possible. Though I found an app from google play called PHONE MUSIC which claims to : "Thus whenver someone puts you on hold just hit the hovering musical note and start playing music. Or play music while someones on the phone with you. "

What is WEB-INF used for in a Java EE web application?

You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.

WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.

Generally speaking, many configurations files also go into WEB-INF.

As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

If this occurs IE intranet only, check compatibility settings and uncheck "Display intranet sites in Compatibility mode" .

IE-->settings-->compatibility

enter image description here

Propagate all arguments in a bash shell script

Use "$@" instead of plain $@ if you actually wish your parameters to be passed the same.

Observe:

$ cat no_quotes.sh
#!/bin/bash
echo_args.sh $@

$ cat quotes.sh
#!/bin/bash
echo_args.sh "$@"

$ cat echo_args.sh
#!/bin/bash
echo Received: $1
echo Received: $2
echo Received: $3
echo Received: $4

$ ./no_quotes.sh first second
Received: first
Received: second
Received:
Received:

$ ./no_quotes.sh "one quoted arg"
Received: one
Received: quoted
Received: arg
Received:

$ ./quotes.sh first second
Received: first
Received: second
Received:
Received:

$ ./quotes.sh "one quoted arg"
Received: one quoted arg
Received:
Received:
Received:

PHP Using RegEx to get substring of a string

$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);

This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.

php.net/preg-match

Type Checking: typeof, GetType, or is?

Type t = typeof(obj1);
if (t == typeof(int))
    // Some code here

This is an error. The typeof operator in C# can only take type names, not objects.

if (obj1.GetType() == typeof(int))
    // Some code here

This will work, but maybe not as you would expect. For value types, as you've shown here, it's acceptable, but for reference types, it would only return true if the type was the exact same type, not something else in the inheritance hierarchy. For instance:

class Animal{}
class Dog : Animal{}

static void Foo(){
    object o = new Dog();

    if(o.GetType() == typeof(Animal))
        Console.WriteLine("o is an animal");
    Console.WriteLine("o is something else");
}

This would print "o is something else", because the type of o is Dog, not Animal. You can make this work, however, if you use the IsAssignableFrom method of the Type class.

if(typeof(Animal).IsAssignableFrom(o.GetType())) // note use of tested type
    Console.WriteLine("o is an animal");

This technique still leaves a major problem, though. If your variable is null, the call to GetType() will throw a NullReferenceException. So to make it work correctly, you'd do:

if(o != null && typeof(Animal).IsAssignableFrom(o.GetType()))
    Console.WriteLine("o is an animal");

With this, you have equivalent behavior of the is keyword. Hence, if this is the behavior you want, you should use the is keyword, which is more readable and more efficient.

if(o is Animal)
    Console.WriteLine("o is an animal");

In most cases, though, the is keyword still isn't what you really want, because it's usually not enough just to know that an object is of a certain type. Usually, you want to actually use that object as an instance of that type, which requires casting it too. And so you may find yourself writing code like this:

if(o is Animal)
    ((Animal)o).Speak();

But that makes the CLR check the object's type up to two times. It will check it once to satisfy the is operator, and if o is indeed an Animal, we make it check again to validate the cast.

It's more efficient to do this instead:

Animal a = o as Animal;
if(a != null)
    a.Speak();

The as operator is a cast that won't throw an exception if it fails, instead returning null. This way, the CLR checks the object's type just once, and after that, we just need to do a null check, which is more efficient.

But beware: many people fall into a trap with as. Because it doesn't throw exceptions, some people think of it as a "safe" cast, and they use it exclusively, shunning regular casts. This leads to errors like this:

(o as Animal).Speak();

In this case, the developer is clearly assuming that o will always be an Animal, and as long as their assumption is correct, everything works fine. But if they're wrong, then what they end up with here is a NullReferenceException. With a regular cast, they would have gotten an InvalidCastException instead, which would have more correctly identified the problem.

Sometimes, this bug can be hard to find:

class Foo{
    readonly Animal animal;

    public Foo(object o){
        animal = o as Animal;
    }

    public void Interact(){
        animal.Speak();
    }
}

This is another case where the developer is clearly expecting o to be an Animal every time, but this isn't obvious in the constructor, where the as cast is used. It's not obvious until you get to the Interact method, where the animal field is expected to be positively assigned. In this case, not only do you end up with a misleading exception, but it isn't thrown until potentially much later than when the actual error occurred.

In summary:

  • If you only need to know whether or not an object is of some type, use is.

  • If you need to treat an object as an instance of a certain type, but you don't know for sure that the object will be of that type, use as and check for null.

  • If you need to treat an object as an instance of a certain type, and the object is supposed to be of that type, use a regular cast.

How to change facebook login button with my custom image

The method which you are using is rendering login button from the Facebook Javascript code. However, you can write your own Javascript code function to mimic the functionality. Here is how to do it -

  1. Create a simple anchor tag link with the image you want to show. Have a onclick method on anchor tag which would actually do the real job.
<a href="#" onclick="fb_login();"><img src="images/fb_login_awesome.jpg" border="0" alt=""></a>
  1. Next, we create the Javascript function which will show the actual popup and will fetch the complete user information, if user allows. We also handle the scenario if user disallows our facebook app.
window.fbAsyncInit = function() {
    FB.init({
        appId   : 'YOUR_APP_ID',
        oauth   : true,
        status  : true, // check login status
        cookie  : true, // enable cookies to allow the server to access the session
        xfbml   : true // parse XFBML
    });

  };

function fb_login(){
    FB.login(function(response) {

        if (response.authResponse) {
            console.log('Welcome!  Fetching your information.... ');
            //console.log(response); // dump complete info
            access_token = response.authResponse.accessToken; //get access token
            user_id = response.authResponse.userID; //get FB UID

            FB.api('/me', function(response) {
                user_email = response.email; //get user email
          // you can store this data into your database             
            });

        } else {
            //user hit cancel button
            console.log('User cancelled login or did not fully authorize.');

        }
    }, {
        scope: 'public_profile,email'
    });
}
(function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}());
  1. We are done.

Please note that the above function is fully tested and works. You just need to put your facebook APP ID and it will work.

call a function in success of datatable ajax call

  "success" : function(data){
       //do stuff here
        fnCallback(data);
   }

how to set background image in submit button?

.button {
    border: none;
    background: url('/forms/up.png') no-repeat top left;
    padding: 2px 8px;
}

What is the best way to know if all the variables in a Class are null?

How about streams?

public boolean checkFieldsIsNull(Object instance, List<String> fieldNames) {

    return fieldNames.stream().allMatch(field -> {
        try {
            return Objects.isNull(instance.getClass().getDeclaredField(field).get(instance));
        } catch (IllegalAccessException | NoSuchFieldException e) {
            return true;//You can throw RuntimeException if need.
        }
    });
}

how to use free cloud database with android app?

Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.

Here are some providers which have a "free-tier" (may change in future):

  1. Firebase (Google) - https://firebase.google.com/
  2. AWS Mobile (Amazon) - https://aws.amazon.com/mobile/
  3. Azure Mobile (Microsoft) - https://azure.microsoft.com/en-in/services/app-service/mobile/
  4. MongoDB Realm (MongoDB) - https://www.mongodb.com/realm
  5. Back4app (Popular) - https://www.back4app.com/

Open source solutions:

  1. Parse - http://parseplatform.org/
  2. Apache User Grid - https://usergrid.apache.org/
  3. SupaBase (under development) - https://supabase.io/

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

It is a runtime error that is caused by Dynamic Linker

dyld: Library not loaded: @rpath/...
...
Reason: image not found

The error Library not loaded with @rpath indicates that Dynamic Linker cannot find the binary.

  1. Check if the dynamic framework was added to General -> Embedded Binaries

  2. Check the @rpath setup between consumer(application) and producer(dynamic framework):

    • Dynamic framework:
      • Build Settings -> Dynamic Library Install Name
    • Application:
      • Build Settings -> Runpath Search Paths
      • Build Phases -> Embed Frameworks -> Destination, Subpath

Dynamic linker

Dynamic Library Install Name(LD_DYLIB_INSTALL_NAME) which is used by loadable bundle(Dynamic framework as a derivative) where dyld come into play
Dynamic Library Install Name - path to binary file(not .framework). Yes, they have the same name, but MyFramework.framework is a packaged bundle with MyFramework binary file and resources inside.
This path to directory can be absolute or relative(e.g. @executable_path, @loader_path, @rpath). Relative path is more preferable because it is changed together with an anchor that is useful when you distribute your bundle as a single directory

absolute path - Framework1 example

//Framework1 Dynamic Library Install Name
/some_path/Framework1.framework/subfolder1

@executable_path

@executable_path - relative to entry binary - Framework2 example
use case: embed a Dynamic framework into an application

//Application bundle(`.app` package) absolute path
/some_path/Application.?pp

//Application binary absolute path 
/some_path/Application.?pp/subfolder1

//Framework2 binary absolute path
/some_path/Application.?pp/Frameworks/Framework2.framework/subfolder1

//Framework2 @executable_path == Application binary absolute path
/some_path/Application.?pp/subfolder1

//Framework2 Dynamic Library Install Name 
@executable_path/../Frameworks/Framework2.framework/subfolder1

//Framework2 binary resolved absolute path by dyld
/some_path/Application.?pp/subfolder1/../Frameworks/Framework2.framework/subfolder1
/some_path/Application.?pp/Frameworks/Framework2.framework/subfolder1

@loader_path

@loader_path - relative to bundle which is an owner of this binary
use case: framework with embedded framework - Framework3_1 with Framework3_2 inside

//Framework3_1 binary absolute path
/some_path/Application.?pp/Frameworks/Framework3_1.framework/subfolder1

//Framework3_2 binary absolute path
/some_path/Application.?pp/Frameworks/Framework3_1.framework/Frameworks/Framework3_2.framework/subfolder1

//Framework3_1 @executable_path == Application binary absolute path
/some_path/Application.?pp/subfolder1

//Framework3_1 @loader_path == Framework3_1 @executable_path
/some_path/Application.?pp/subfolder1

//Framework3_2 @executable_path == Application binary absolute path
/some_path/Application.?pp/subfolder1

//Framework3_2 @loader_path == Framework3_1 binary absolute path
/some_path/Application.?pp/Frameworks/Framework3_1.framework/subfolder1

//Framework3_2 Dynamic Library Install Name 
@loader_path/../Frameworks/Framework3_2.framework/subfolder1

//Framework3_2 binary resolved absolute path by dyld
/some_path/Application.?pp/Frameworks/Framework3_1.framework/subfolder1/../Frameworks/Framework3_2.framework/subfolder1
/some_path/Application.?pp/Frameworks/Framework3_1.framework/Frameworks/Framework3_2.framework/subfolder1

@rpath - Runpath Search Path

Framework2 example

Previously we had to setup a Framework to work with dyld. It is not convenient because the same Framework can not be used with a different configurations

@rpath is a compound concept that relies on outer(Application) and nested(Dynamic framework) parts:

  • Application:

    • Runpath Search Paths(LD_RUNPATH_SEARCH_PATHS) - defines a list of templates which be substituted with @rpath.
       @executable_path/../Frameworks
      
    • Review Build Phases -> Embed Frameworks -> Destination, Subpath to be shire where exactly the embed framework is located
  • Dynamic Framework:

    • Dynamic Library Install Name(LD_DYLIB_INSTALL_NAME) - point that @rpath is used together with local bundle path to a binary
      @rpath/Framework2.framework/subfolder1
      
//Application Runpath Search Paths
@executable_path/../Frameworks

//Framework2 Dynamic Library Install Name
@rpath/Framework2.framework/subfolder1

//Framework2 binary resolved absolute path by dyld
//Framework2 @rpath is replaced by each element of Application Runpath Search Paths
@executable_path/../Frameworks/Framework2.framework/subfolder1
/some_path/Application.?pp/Frameworks/Framework2.framework/subfolder1

*../ - go to the parent of the current directory

otool - object file displaying tool

//-L print shared libraries used
//Application otool -L
@rpath/Framework2.framework/subfolder1/Framework2

//Framework2 otool -L
@rpath/Framework2.framework/subfolder1/Framework2

//-l print the load commands
//Application otool -l
LC_LOAD_DYLIB
@rpath/Framework2.framework/subfolder1/Framework2

LC_RPATH
@executable_path/../Frameworks

//Framework2 otool -l
LC_ID_DYLIB
@rpath/Framework2.framework/subfolder1/Framework2

install_name_tool change dynamic shared library install names using -rpath

CocoaPods uses use_frameworks![About] to regulate a Dynamic Linker

[Vocabulary]

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

There are two ways to do that:

<li{!!(Request::is('your_url')) ? ' class="active"' : '' !!}>

or

<li @if(Request::is('your_url'))class="active"@endif>

How to apply box-shadow on all four sides?

You can different combinations at the following link.
https://www.cssmatic.com/box-shadow

The results which you need can be achieved by the following CSS

-webkit-box-shadow: 0px 0px 11px 1px rgba(0,0,0,1);
-moz-box-shadow: 0px 0px 11px 1px rgba(0,0,0,1);
box-shadow: 0px 0px 11px 1px rgba(0,0,0,1);

How to set a value of a variable inside a template code?

The best solution for this is to write a custom assignment_tag. This solution is more clean than using a with tag because it achieves a very clear separation between logic and styling.

Start by creating a template tag file (eg. appname/templatetags/hello_world.py):

from django import template

register = template.Library()

@register.assignment_tag
def get_addressee():
    return "World"

Now you may use the get_addressee template tag in your templates:

{% load hello_world %}

{% get_addressee as addressee %}

<html>
    <body>
        <h1>hello {{addressee}}</h1>
    </body>
</html>

Cannot open Windows.h in Microsoft Visual Studio

For my case, I had to right click the solution and click "Retarget Projects". In my case I retargetted to Windows SDK version 10.0.1777.0 and Platform Toolset v142. I also had to change "Windows.h"to<windows.h>

I am running Visual Studio 2019 version 16.25 on a windows 10 machine

Can JavaScript connect with MySQL?

Yes you can. MySQL connectors use TCP for connection, and in JS there is an little modified version of TCP client called Websocket. But you can't directly connect to MySQL server with websocket. You will need some 3rd party bridge between websocket and mysql. It receive query from websocket, send it to mysql, response result and resend to JS.

And this is my example bridge written in C# with websocket-sharp library:

class JSQLBridge : WebSocketBehavior
{
    MySqlConnection conn;

    protected override void OnMessage(MessageEventArgs e)
    {
        if (conn == null)
        {
            try
            {
                conn = new MySqlConnection(e.Data);
                conn.Open();
            }
            catch (Exception exc)
            {
                Send(exc.Message);
            }
        }
        else
        {
            try
            {
                MySqlCommand cmd = new MySqlCommand(e.Data, conn);
                cmd.ExecuteNonQuery();
                Send("success");
            }
            catch (Exception exc)
            {
                Send(exc.Message);
            }
        }
    }

    protected override void OnClose(CloseEventArgs e)
    {
        if (conn != null)
            conn.Close();
    }
}

JS side:

var ws = new WebSocket("ws://localhost/");

ws.send("server=localhost;user=root;database=mydb;");

ws.send("select * from users");

How to match "anything up until this sequence of characters" in a regular expression?

The $ marks the end of a string, so something like this should work: [[^abc]*]$ where you're looking for anything NOT ENDING in any iteration of abc, but it would have to be at the end

Also if you're using a scripting language with regex (like php or js), they have a search function that stops when it first encounters a pattern (and you can specify start from the left or start from the right, or with php, you can do an implode to mirror the string).

How to convert binary string value to decimal

public static int integerfrmbinary(String str){
    double j=0;
    for(int i=0;i<str.length();i++){
        if(str.charAt(i)== '1'){
         j=j+ Math.pow(2,str.length()-1-i);
     }

    }
    return (int) j;
}

This piece of code I have written manually. You can also use parseInt as mentioned above . This function will give decimal value corresponding to the binary string :)

Cygwin Make bash command not found

While instaling (updating) check 'Devel' to 'Install', it will install a lot of MB but helps. I don't have time to check which exacly I (we) need.

CYGWIN INSTALL STEP

Get only part of an Array in Java?

You can try:

System.arraycopy(sourceArray, 0, targetArray, 0, targetArray.length);// copies whole array

// copies elements 1 and 2 from sourceArray to targetArray
System.arraycopy(sourceArray, 1, targetArray, 0, 2); 

See javadoc for System.

How can I pass a Bitmap object from one activity to another

Compress and Send Bitmap

The accepted answer will crash when the Bitmap is too large. I believe it's a 1MB limit. The Bitmap must be compressed into a different file format such as a JPG represented by a ByteArray, then it can be safely passed via an Intent.

Implementation

The function is contained in a separate thread using Kotlin Coroutines because the Bitmap compression is chained after the Bitmap is created from an url String. The Bitmap creation requires a separate thread in order to avoid Application Not Responding (ANR) errors.

Concepts Used

  • Kotlin Coroutines notes.
  • The Loading, Content, Error (LCE) pattern is used below. If interested you can learn more about it in this talk and video.
  • LiveData is used to return the data. I've compiled my favorite LiveData resource in these notes.
  • In Step 3, toBitmap() is a Kotlin extension function requiring that library to be added to the app dependencies.

Code

1. Compress Bitmap to JPG ByteArray after it has been created.

Repository.kt

suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
    MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
        postValue(Lce.Loading())
        postValue(Lce.Content(ContentResult.ContentBitmap(
            ByteArrayOutputStream().apply {
                try {                     
                    BitmapFactory.decodeStream(URL(url).openConnection().apply {
                        doInput = true
                        connect()
                    }.getInputStream())
                } catch (e: IOException) {
                   postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
                   null
                }?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
           }.toByteArray(), "")))
        }
    }

ViewModel.kt

//Calls bitmapToByteArray from the Repository
private fun bitmapToByteArray(url: String) = liveData {
    emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
        when (lce) {
            is Lce.Loading -> liveData {}
            is Lce.Content -> liveData {
                emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
            }
            is Lce.Error -> liveData {
                Crashlytics.log(Log.WARN, LOG_TAG,
                        "bitmapToByteArray error or null - ${lce.packet.errorMessage}")
            }
        }
    })
}

2. Pass image as ByteArray via an Intent.

In this sample it's passed from a Fragment to a Service. It's the same concept if being shared between two Activities.

Fragment.kt

ContextCompat.startForegroundService(
    context!!,
    Intent(context, AudioService::class.java).apply {
        action = CONTENT_SELECTED_ACTION
        putExtra(CONTENT_SELECTED_BITMAP_KEY, contentPlayer.image)
    })

3. Convert ByteArray back to Bitmap.

Utils.kt

fun ByteArray.byteArrayToBitmap(context: Context) =
    run {
        BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
            if (this != null) this
            // In case the Bitmap loaded was empty or there is an error I have a default Bitmap to return.
            else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
        }
    }

.map() a Javascript ES6 Map?

Maybe this way:

const m = new Map([["a", 1], ["b", 2], ["c", 3]]);
m.map((k, v) => [k, v * 2]); // Map { 'a' => 2, 'b' => 4, 'c' => 6 }

You would only need to monkey patch Map before:

Map.prototype.map = function(func){
    return new Map(Array.from(this, ([k, v]) => func(k, v)));
}

We could have wrote a simpler form of this patch:

Map.prototype.map = function(func){
    return new Map(Array.from(this, func));
}

But we would have forced us to then write m.map(([k, v]) => [k, v * 2]); which seems a bit more painful and ugly to me.

Mapping values only

We could also map values only, but I wouldn't advice going for that solution as it is too specific. Nevertheless it can be done and we would have the following API:

const m = new Map([["a", 1], ["b", 2], ["c", 3]]);
m.map(v => v * 2); // Map { 'a' => 2, 'b' => 4, 'c' => 6 }

Just like before patching this way:

Map.prototype.map = function(func){
    return new Map(Array.from(this, ([k, v]) => [k, func(v)]));
}

Maybe you can have both, naming the second mapValues to make it clear that you are not actually mapping the object as it would probably be expected.

What is the use of style="clear:both"?

When you use float without width, there remains some space in that row. To block this space you can use clear:both; in next element.

Thread-safe List<T> property

If you look at the source code for List of T (https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,c66df6f36c131877) you will notice there is a class there (which is of course internal - why, Microsoft, why?!?!) called SynchronizedList of T. I am copy pasting the code here:

   [Serializable()]
    internal class SynchronizedList : IList<T> {
        private List<T> _list;
        private Object _root;

        internal SynchronizedList(List<T> list) {
            _list = list;
            _root = ((System.Collections.ICollection)list).SyncRoot;
        }

        public int Count {
            get {
                lock (_root) { 
                    return _list.Count; 
                }
            }
        }

        public bool IsReadOnly {
            get {
                return ((ICollection<T>)_list).IsReadOnly;
            }
        }

        public void Add(T item) {
            lock (_root) { 
                _list.Add(item); 
            }
        }

        public void Clear() {
            lock (_root) { 
                _list.Clear(); 
            }
        }

        public bool Contains(T item) {
            lock (_root) { 
                return _list.Contains(item);
            }
        }

        public void CopyTo(T[] array, int arrayIndex) {
            lock (_root) { 
                _list.CopyTo(array, arrayIndex);
            }
        }

        public bool Remove(T item) {
            lock (_root) { 
                return _list.Remove(item);
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            lock (_root) { 
                return _list.GetEnumerator();
            }
        }

        IEnumerator<T> IEnumerable<T>.GetEnumerator() {
            lock (_root) { 
                return ((IEnumerable<T>)_list).GetEnumerator();
            }
        }

        public T this[int index] {
            get {
                lock(_root) {
                    return _list[index];
                }
            }
            set {
                lock(_root) {
                    _list[index] = value;
                }
            }
        }

        public int IndexOf(T item) {
            lock (_root) {
                return _list.IndexOf(item);
            }
        }

        public void Insert(int index, T item) {
            lock (_root) {
                _list.Insert(index, item);
            }
        }

        public void RemoveAt(int index) {
            lock (_root) {
                _list.RemoveAt(index);
            }
        }
    }

Personally I think they knew a better implementation using SemaphoreSlim could be created, but didn't get to it.

Can't bind to 'dataSource' since it isn't a known property of 'table'

I was also breaking my head for a long time with this error message and later I identified that I was using [datasource] instead of [dataSource].

How to count the number of letters in a string without the spaces?

Simply solution using the sum function:

sum(c != ' ' for c in word)

It's a memory efficient solution because it uses a generator rather than creating a temporary list and then calculating the sum of it.

It's worth to mention that c != ' ' returns True or False, which is a value of type bool, but bool is a subtype of int, so you can sum up bool values (True corresponds to 1 and False corresponds to 0)

You can check for an inheretance using the mro method:

>>> bool.mro() # Method Resolution Order
[<type 'bool'>, <type 'int'>, <type 'object'>]

Here you see that bool is a subtype of int which is a subtype of object.

Resize image in the wiki of GitHub using Markdown

Updated:

Markdown syntax for images (external/internal):

![test](https://github.com/favicon.ico)

HTML code for sizing images (internal/external):

<img src="https://github.com/favicon.ico" width="48">

Example:

test


Old Answer:

This should work:

[[ http://url.to/image.png | height = 100px ]]

Source: https://guides.github.com/features/mastering-markdown/

What is this weird colon-member (" : ") syntax in the constructor?

That's constructor initialisation. It is the correct way to initialise members in a class constructor, as it prevents the default constructor being invoked.

Consider these two examples:

// Example 1
Foo(Bar b)
{
   bar = b;
}

// Example 2
Foo(Bar b)
   : bar(b)
{
}

In example 1:

Bar bar;  // default constructor
bar = b;  // assignment

In example 2:

Bar bar(b) // copy constructor

It's all about efficiency.