Programs & Examples On #Styles

DO NOT USE THIS TAG. This tag does not currently have a single, well-defined meaning. It is often used in place of, or in conjunction with, [css]. It is also used on questions about the appearance of user interfaces and questions about source code formatting.

How to style icon color, size, and shadow of Font Awesome Icons

Please refer to the link http://www.w3schools.com/icons/fontawesome_icons_intro.asp

<i class="fa fa-car"></i>
<i class="fa fa-car" style="font-size:48px;"></i>
<i class="fa fa-car" style="font-size:60px;color:red;"></i>

<i class="fa fa-car fa-lg"></i>
<i class="fa fa-car fa-2x"></i>
<i class="fa fa-car fa-3x"></i>
<i class="fa fa-car fa-4x"></i>
<i class="fa fa-car fa-5x"></i>

How to change DatePicker dialog color for Android 5.0

Create a new style

<!-- Theme.AppCompat.Light.Dialog -->
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">@color/blue_500</item>
</style>

Java code:

The parent theme is the key here. Choose your colorAccent

DatePickerDialog = new DatePickerDialog(context,R.style.DialogTheme,this,now.get(Calendar.YEAR),now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH);

Result:

enter image description here

React Native Border Radius with background color

Try moving the button styling to the TouchableHighlight itself:

Styles:

  submit:{
    marginRight:40,
    marginLeft:40,
    marginTop:10,
    paddingTop:20,
    paddingBottom:20,
    backgroundColor:'#68a0cf',
    borderRadius:10,
    borderWidth: 1,
    borderColor: '#fff'
  },
  submitText:{
      color:'#fff',
      textAlign:'center',
  }

Button (same):

<TouchableHighlight
  style={styles.submit}
  onPress={() => this.submitSuggestion(this.props)}
  underlayColor='#fff'>
    <Text style={[this.getFontSize(),styles.submitText]}>Submit</Text>
</TouchableHighlight>

enter image description here

removing html element styles via javascript

you can just do:

element.removeAttribute("style")

How to bind inverse boolean properties in WPF?

I did something very similar. I created my property behind the scenes that enabled the selection of a combobox ONLY if it had finished searching for data. When my window first appears, it launches an async loaded command but I do not want the user to click on the combobox while it is still loading data (would be empty, then would be populated). So by default the property is false so I return the inverse in the getter. Then when I'm searching I set the property to true and back to false when complete.

private bool _isSearching;
public bool IsSearching
{
    get { return !_isSearching; }
    set
    {
        if(_isSearching != value)
        {
            _isSearching = value;
            OnPropertyChanged("IsSearching");
        }
    }
}

public CityViewModel()
{
    LoadedCommand = new DelegateCommandAsync(LoadCity, LoadCanExecute);
}

private async Task LoadCity(object pArg)
{
    IsSearching = true;

    //**Do your searching task here**

    IsSearching = false;
}

private bool LoadCanExecute(object pArg)
{
    return IsSearching;
}

Then for the combobox I can bind it directly to the IsSearching:

<ComboBox ItemsSource="{Binding Cities}" IsEnabled="{Binding IsSearching}" DisplayMemberPath="City" />

Overriding css style?

You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important.

#zoomTarget .slikezamenjanje img {
    max-height: auto;
    padding-right: 0px;
}

Hatting

I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.

For example, all CSS height and width attributes default to auto.

Set HTML element's style property in javascript

The DOM element style "property" is a readonly collection of all the style attributes defined on the element. (The collection property is readonly, not necessarily the items within the collection.)

You would be better off using the className "property" on the elements.

Override body style for content in an iframe

I have a blog and I had a lot of trouble finding out how to resize my embedded gist. Post manager only allows you to write text, place images and embed HTML code. Blog layout is responsive itself. It's built with Wix. However, embedded HTML is not. I read a lot about how it's impossible to resize components inside body of generated iFrames. So, here is my suggestion:

If you only have one component inside your iFrame, i.e. your gist, you can resize only the gist. Forget about the iFrame.

I had problems with viewport, specific layouts to different user agents and this is what solved my problem:

<script language="javascript" type="text/javascript" src="https://gist.github.com/roliveiravictor/447f994a82238247f83919e75e391c6f.js"></script>

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

function windowSize() {
  let gist = document.querySelector('#gist92442763');

  let isMobile = {
    Android: function() {
        return /Android/i.test(navigator.userAgent)
    },
    BlackBerry: function() {
        return /BlackBerry/i.test(navigator.userAgent)
    },
    iOS: function() {
        return /iPhone|iPod/i.test(navigator.userAgent)
    },
    Opera: function() {
        return /Opera Mini/i.test(navigator.userAgent)
    },
    Windows: function() {
        return /IEMobile/i.test(navigator.userAgent) || /WPDesktop/i.test(navigator.userAgent)
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

  if(isMobile.any()) {
    gist.style.width = "36%";
    gist.style.WebkitOverflowScrolling = "touch"
    gist.style.position = "absolute"
  } else {
    gist.style.width = "auto !important";
  }
}

windowSize();

window.addEventListener('onresize', function() {
    windowSize();
});

</script>

<style type="text/css">

.gist-data {
  max-height: 300px;
}

.gist-meta {
  display: none;
}

</style>

The logic is to set gist (or your component) css based on user agent. Make sure to identify your component first, before applying to query selector. Feel free to take a look how responsiveness is working.

How to programmatically set style attribute in a view

I made a helper interface for this using the holder pattern.

public interface StyleHolder<V extends View> {
    void applyStyle(V view);
}

Now for every style you want to use pragmatically just implement the interface, for example:

public class ButtonStyleHolder implements StyleHolder<Button> {

    private final Drawable background;
    private final ColorStateList textColor;
    private final int textSize;

    public ButtonStyleHolder(Context context) {
        TypedArray ta = context.obtainStyledAttributes(R.style.button, R.styleable.ButtonStyleHolder);

        Resources resources = context.getResources();

        background = ta.getDrawable(ta.getIndex(R.styleable.ButtonStyleHolder_android_background));

        textColor = ta.getColorStateList(ta.getIndex(R.styleable.ButtonStyleHolder_android_textColor));

        textSize = ta.getDimensionPixelSize(
                ta.getIndex(R.styleable.ButtonStyleHolder_android_textSize),
                resources.getDimensionPixelSize(R.dimen.standard_text_size)
        );

        // Don't forget to recycle!
        ta.recycle();
    }

    @Override
    public void applyStyle(Button btn) {
        btn.setBackground(background);
        btn.setTextColor(textColor);
        btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
    }
}

Declare a stylable in your attrs.xml, the styleable for this example is:

<declare-styleable name="ButtonStyleHolder">
    <attr name="android:background" />
    <attr name="android:textSize" />
    <attr name="android:textColor" />
</declare-styleable>

Here is the style declared in styles.xml:

<style name="button">
    <item name="android:background">@drawable/button</item>
    <item name="android:textColor">@color/light_text_color</item>
    <item name="android:textSize">@dimen/standard_text_size</item>
</style>

And finally the implementation of the style holder:

Button btn = new Button(context);    
StyleHolder<Button> styleHolder = new ButtonStyleHolder(context);
styleHolder.applyStyle(btn);

I found this very helpful as it can be easily reused and keeps the code clean and verbose, i would recommend using this only as a local variable so we can allow the garbage collector to do its job once we're done with setting all the styles.

Android checkbox style

The correct way to do it for Material design is :

Style :

<style name="MyCheckBox" parent="Theme.AppCompat.Light">  
    <item name="colorControlNormal">@color/foo</item>
    <item name="colorControlActivated">@color/bar</item>
</style>  

Layout :

<CheckBox  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Check Box"
    android:theme="@style/MyCheckBox"/>

It will preserve Material animations on Lollipop+.

WPF C# button style

In this day and age of mouse driven computers and tablets with touch screens etc, it is often forgotten to cater for input via keyboard only. A button should support a focus rectangle (the dotted rectangle when the button has focus) or another shape matching the button shape.

To add a focus rectangle to the button, use this XAML (from this site). Focus rectangle style:

<Style x:Key="ButtonFocusVisual">
  <Setter Property="Control.Template">
    <Setter.Value>
      <ControlTemplate>
        <Border>
          <Rectangle Margin="2" StrokeThickness="1" Stroke="#60000000" StrokeDashArray="1 2" />
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Applying the style to the button:

<Style TargetType="Button">
  <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}" />
  ...

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

I think the best and cleanest solution you can imagine is this:

@Component( {
  selector: 'app-my-component',
  template: `<p>{{ myData?.anyfield }}</p>`,
  styles: [ '' ]
} )
export class MyComponent implements OnInit {
  private myData;

  constructor( private myService: MyService ) { }

  ngOnInit( ) {
    /* 
      async .. await 
      clears the ExpressionChangedAfterItHasBeenCheckedError exception.
    */
    this.myService.myObservable.subscribe(
      async (data) => { this.myData = await data }
    );
  }
}

Tested with Angular 5.2.9

Styling HTML5 input type number

HTML5 number input doesn't have styles attributes like width or size, but you can style it easily with CSS.

input[type="number"] {
   width:50px;
}

CSS align images and text on same line

You can simply center the image and text in the parent tag by setting

div {
     text-align: center;
}

vertical center the img and span

img {
     vertical-align:middle;
}
span {
     vertical-align:middle;
}

You can just add second set below, and one thing to mention is that h4 has block display attribute, so you might want to set

h4 {
    display: inline-block
}

to set the h4 "inline".

The full example is shown here.

_x000D_
_x000D_
<div id="photo" style="text-align: center">_x000D_
  <img style="vertical-align:middle" src="https://via.placeholder.com/22x22" alt="">_x000D_
  <span style="vertical-align:middle">Take a photo</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to create/make rounded corner buttons in WPF?

This is an adapted version of @Kishore Kumar 's answer that is simpler and more closely matches the default button style and colours. It also fixes the issue that his "IsPressed" trigger is in the wrong order and will never be executed since the "MouseOver" will take precedent:

<Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid x:Name="grid">
                        <Border x:Name="border" CornerRadius="2" BorderBrush="#707070" BorderThickness="1" Background="LightGray">
                            <ContentPresenter HorizontalAlignment="Center"
                                      VerticalAlignment="Center"
                                      TextElement.FontWeight="Normal">
                            </ContentPresenter>
                        </Border>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" TargetName="border" Value="#BEE6FD"/>
                            <Setter Property="BorderBrush" TargetName="border" Value="#3C7FB1"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="True">
                            <Setter Property="BorderBrush" TargetName="border" Value="#2C628B"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Opacity" TargetName="grid" Value="0.25"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

I would use this in HTML 5... Just sayin

#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #f5f5f5;
}

Is it possible to have multiple styles inside a TextView?

As stated, use TextView.setText(Html.fromHtml(String))

And use these tags in your Html formatted string:

<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font size="..." color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>

http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html

Change background color for selected ListBox item

You need to use ListBox.ItemContainerStyle.

ListBox.ItemTemplate specifies how the content of an item should be displayed. But WPF still wraps each item in a ListBoxItem control, which by default gets its Background set to the system highlight colour if it is selected. You can't stop WPF creating the ListBoxItem controls, but you can style them -- in your case, to set the Background to always be Transparent or Black or whatever -- and to do so, you use ItemContainerStyle.

juFo's answer shows one possible implementation, by "hijacking" the system background brush resource within the context of the item style; another, perhaps more idiomatic technique is to use a Setter for the Background property.

How to set TextView textStyle such as bold, italic

You can try like this:

<string name="title"><u><b><i>Your Text</i></b></u></string>

Valid values for android:fontFamily and what they map to?

As far as I'm aware, you can't declare custom fonts in xml or themes. I usually just make custom classes extending textview that set their own font on instantiation and use those in my layout xml files.

ie:

public class Museo500TextView extends TextView {
    public Museo500TextView(Context context, AttributeSet attrs) {
        super(context, attrs);      
        this.setTypeface(Typeface.createFromAsset(context.getAssets(), "path/to/font.ttf"));
    }
}

and

<my.package.views.Museo900TextView
        android:id="@+id/dialog_error_text_header"
        android:layout_width="190dp"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textSize="12sp" />

Binding ConverterParameter

There is also an alternative way to use MarkupExtension in order to use Binding for a ConverterParameter. With this solution you can still use the default IValueConverter instead of the IMultiValueConverter because the ConverterParameter is passed into the IValueConverter just like you expected in your first sample.

Here is my reusable MarkupExtension:

/// <summary>
///     <example>
///         <TextBox>
///             <TextBox.Text>
///                 <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
///                     Converter="{StaticResource TestValueConverter}"
///                     ConverterParameterBinding="{Binding ConcatSign}" />
///             </TextBox.Text>
///         </TextBox>
///     </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
    #region Public Properties

    public Binding Binding { get; set; }
    public BindingMode Mode { get; set; }
    public IValueConverter Converter { get; set; }
    public Binding ConverterParameter { get; set; }

    #endregion

    public ConverterBindableParameter()
    { }

    public ConverterBindableParameter(string path)
    {
        Binding = new Binding(path);
    }

    public ConverterBindableParameter(Binding binding)
    {
        Binding = binding;
    }

    #region Overridden Methods

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var multiBinding = new MultiBinding();
        Binding.Mode = Mode;
        multiBinding.Bindings.Add(Binding);
        if (ConverterParameter != null)
        {
            ConverterParameter.Mode = BindingMode.OneWay;
            multiBinding.Bindings.Add(ConverterParameter);
        }
        var adapter = new MultiValueConverterAdapter
        {
            Converter = Converter
        };
        multiBinding.Converter = adapter;
        return multiBinding.ProvideValue(serviceProvider);
    }

    #endregion

    [ContentProperty(nameof(Converter))]
    private class MultiValueConverterAdapter : IMultiValueConverter
    {
        public IValueConverter Converter { get; set; }

        private object lastParameter;

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (Converter == null) return values[0]; // Required for VS design-time
            if (values.Length > 1) lastParameter = values[1];
            return Converter.Convert(values[0], targetType, lastParameter, culture);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            if (Converter == null) return new object[] { value }; // Required for VS design-time

            return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
        }
    }
}

With this MarkupExtension in your code base you can simply bind the ConverterParameter the following way:

<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
    <Setter.Value>
     <wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
                 Converter="{StaticResource AccessLevelToVisibilityConverter}"
                 ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />          
    </Setter.Value>
</Setter>

Which looks almost like your initial proposal.

How do I style (css) radio buttons and labels?

For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels

input:checked + label {
    color: white;
}  

MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.

How to change line color in EditText

Its pretty simple (Required: Minimum API 21)...

  1. Go to your xml and select the EditText field
  2. On the right side, you can see the 'Attributes' window. Select 'View All Attributes'
  3. Just search for 'tint'
  4. And add/change the 'backgroundTint' to a desired color hex (say #FF0000)

enter image description here

enter image description here

Keep Coding........ :)

How to set the style -webkit-transform dynamically using JavaScript?

The JavaScript style names are WebkitTransformOrigin and WebkitTransform

element.style.webkitTransform = "rotate(-2deg)";

Check the DOM extension reference for WebKit here.

What is the Java equivalent of PHP var_dump?

It is not quite as baked-in in Java, so you don't get this for free. It is done with convention rather than language constructs. In all data transfer classes (and maybe even in all classes you write...), you should implement a sensible toString method. So here you need to override toString() in your Person class and return the desired state.

There are utilities available that help with writing a good toString method, or most IDEs have an automatic toString() writing shortcut.

What is the best way to merge mp3 files?

Instead of using the command line to do

copy /b 1.mp3+2.mp3 3.mp3

you could instead use "The Rename" to rename all the MP3 fragments into a series of names that are in order based on some kind of counter. Then you could just use the same command line format but change it a little to:

copy /b *.mp3 output_name.mp3

That is assuming you ripped all of these fragment MP3's at the same time and they have the same audio settings. Worked great for me when I was converting an Audio book I had in .aa to a single .mp3. I had to burn all the .aa files to 9 CD's then rip all 9 CD's and then I was left with about 90 mp3's. Really a pain in the a55.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

This is possible with a bit of format conversion.

To extract the private key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa

To convert the private key to a public key:

openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8

To extract the public key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8

How to parse XML and count instances of a particular node attribute?

xml.etree.ElementTree vs. lxml

These are some pros of the two most used libraries I would have benefit to know before choosing between them.

xml.etree.ElementTree:

  1. From the standard library: no needs of installing any module

lxml

  1. Easily write XML declaration: for instance do you need to add standalone="no"?
  2. Pretty printing: you can have a nice indented XML without extra code.
  3. Objectify functionality: It allows you to use XML as if you were dealing with a normal Python object hierarchy.node.
  4. sourceline allows to easily get the line of the XML element you are using.
  5. you can use also a built-in XSD schema checker.

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

Maven plugins can not be found in IntelliJ

If problem persist, you can add manually the missing plugins files.

For example if maven-site-plugins is missing, go to https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-site-plugin

Choice your version, and download files associated directly into your .m2 folder, in this example : C:\Users\ {USERNAME} .m2\repository\org\apache\maven\plugins\maven-site-plugin\ {VERSION}

In IntelliJ IDEA, open Maven sidebar, and reload (tooltip : Reimport All Maven projects)

"continue" in cursor.forEach()

Making use of JavaScripts short-circuit evaluation. If el.shouldBeProcessed returns true, doSomeLengthyOperation

elementsCollection.forEach( el => 
  el.shouldBeProcessed && doSomeLengthyOperation()
);

How to get index of object by its property in JavaScript?

var fields = {
teste:
{
    Acess:
    {
        Edit: true,
      View: false

      }
 },
teste1:
{
    Acess:
    {
        Edit: false,
      View: false

      }
  }
};

console.log(find(fields,'teste'));
function find(fields,field){
    for(key in fields){
        if(key == field){
        return true;
    }
}
return false;
}

If you have one Object with multiply objects inside, if you want know if some object are include on Master object, just put find(MasterObject,'Object to Search'), this function will return the response if exist or not (TRUE or FALSE), I hope help with this, can see the exemple on JSFiddle.

How to "pull" from a local branch into another one?

If you are looking for a brand new pull from another branch like from local to master you can follow this.

git commit -m "Initial Commit"
git add .
git pull --rebase git_url
git push origin master

Auto highlight text in a textbox control

In Windows Forms and WPF:

textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;

Calculate date/time difference in java

Joda-Time

Joda-Time 2.3 library offers already-debugged code for this chore.

Joad-Time includes three classes to represent a span of time: Period, Interval, and Duration. Period tracks a span as a number of months, days, hours, etc. (not tied to the timeline).

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

// Specify a time zone rather than rely on default.
// Necessary to handle Daylight Saving Time (DST) and other anomalies.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );

DateTimeFormatter formatter = DateTimeFormat.forPattern( "yy/MM/dd HH:mm:ss" ).withZone( timeZone ); 

DateTime dateTimeStart = formatter.parseDateTime( "11/03/14 09:29:58" );
DateTime dateTimeStop = formatter.parseDateTime( "11/03/14 09:33:43" );
Period period = new Period( dateTimeStart, dateTimeStop );

PeriodFormatter periodFormatter = PeriodFormat.getDefault();
String output = periodFormatter.print( period );

System.out.println( "output: " + output );

When run…

output: 3 minutes and 45 seconds

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:

Documentation

Implementations

Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

Perl

PHP

C#/.NET

Nim/C

The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files

Extensions

Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

Sphinx

The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

rest2web

rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

Pygments

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

Emacs

The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

Vim

The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

Jed

There is a rst mode for the Jed programmers editor.

gedit

gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

Geany

Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

Leo

Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

FTE

The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

PyK

PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

Eclipse

The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

NoTex

NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

Notepad++

Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

TextMate

TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

Intype

Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

PyCharm

PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

Wiki

here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

MediaWiki

MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

MoinMoin

MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.

Trac

Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

rstiki

rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

ikiwiki

Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services

Sandbox

An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks

WordPress

WordPreSt reStructuredText plugin for WordPress. (PHP)

Zine

reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

pelican

Pelican is a static blog generator that supports writing articles in ReST. (Python)

hyde

Hyde is a static website generator that supports ReST. (Python)

Acrylamid

Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

Nikola

Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.

Yozuch

Yozuch is a static blog generator written in Python.

More

How to resolve ambiguous column names when retrieving results?

If you don't feel like aliassing you can also just prefix the tablenames.

This way you can better automate generation of your queries. Also, it's a best-practice to not use select * (it is obviously slower than just selecting the fields you need Furthermore, only explicitly name the fields you want to have.

SELECT
    news.id, news.title, news.author, news.posted, 
    users.id, users.name, users.registered 
FROM 
    news 
LEFT JOIN 
    users 
ON 
    news.user = user.id

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

Finding the max/min value in an array of primitives using Java

You could easily do it with an IntStream and the max() method.

Example

public static int maxValue(final int[] intArray) {
  return IntStream.range(0, intArray.length).map(i -> intArray[i]).max().getAsInt();
}

Explanation

  1. range(0, intArray.length) - To get a stream with as many elements as present in the intArray.

  2. map(i -> intArray[i]) - Map every element of the stream to an actual element of the intArray.

  3. max() - Get the maximum element of this stream as OptionalInt.

  4. getAsInt() - Unwrap the OptionalInt. (You could also use here: orElse(0), just in case the OptionalInt is empty.)

Creating a dynamic choice field

the problem is when you do

def __init__(self, user, *args, **kwargs):
    super(waypointForm, self).__init__(*args, **kwargs)
    self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.filter(user=user)])

in a update request, the previous value will lost!

How to copy text programmatically in my Android app?

So everyone agree on how this should be done, but since no one want to give a complete solution, here goes:

int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText("text to clip");
} else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
    android.content.ClipData clip = android.content.ClipData.newPlainText("text label","text to clip");
    clipboard.setPrimaryClip(clip);
}

I assume you have something like following declared in manifest:

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="14" />

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

In my case, the reason was a simple typo.

<parent>
    <groupId>org.sringframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>

A missing character in the groupId org.s(p)ringframework lead to this error.

MongoDB Aggregation: How to get total records count?

If you don't want to group, then use the following method:

db.collection.aggregate( [ { $match : { score : { $gt : 70, $lte : 90 } } }, { $count: 'count' } ] );

To show only file name without the entire directory path

There are several ways you can achieve this. One would be something like:

for filepath in /path/to/dir/*
do
    filename=$(basename $filepath)

    ... whatever you want to do with the file here
done

How to add parameters to a HTTP GET request in Android?

To build uri with get parameters, Uri.Builder provides a more effective way.

Uri uri = new Uri.Builder()
    .scheme("http")
    .authority("foo.com")
    .path("someservlet")
    .appendQueryParameter("param1", foo)
    .appendQueryParameter("param2", bar)
    .build();

AttributeError: Can only use .dt accessor with datetimelike values

Your problem here is that the dtype of 'Date' remained as str/object. You can use the parse_dates parameter when using read_csv

import pandas as pd
file = '/pathtocsv.csv'
df = pd.read_csv(file, sep = ',', parse_dates= [col],encoding='utf-8-sig', usecols= ['Date', 'ids'],)    
df['Month'] = df['Date'].dt.month

From the documentation for the parse_dates parameter

parse_dates : bool or list of int or names or list of lists or dict, default False

The behavior is as follows:

  • boolean. If True -> try parsing the index.
  • list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
  • list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column.
  • dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’

If a column or index cannot be represented as an array of datetimes, say because of an unparseable value or a mixture of timezones, the column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use pd.to_datetime after pd.read_csv. To parse an index or column with a mixture of timezones, specify date_parser to be a partially-applied pandas.to_datetime() with utc=True. See Parsing a CSV with mixed timezones for more.

Note: A fast-path exists for iso8601-formatted dates.

The relevant case for this question is the "list of int or names" one.

col is the columns index of 'Date' which parses as a separate date column.

SQL Server - SELECT FROM stored procedure

You can cheat a little with OPENROWSET :

SELECT ...fieldlist...
FROM OPENROWSET('SQLNCLI', 'connection string', 'name of sp')
WHERE ...

This would still run the entire SP every time, of course.

How can I use different certificates on specific connections?

Create an SSLSocket factory yourself, and set it on the HttpsURLConnection before connecting.

...
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslFactory);
conn.setMethod("POST");
...

You'll want to create one SSLSocketFactory and keep it around. Here's a sketch of how to initialize it:

/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
KeyStore keyStore = ... 
TrustManagerFactory tmf = 
  TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
sslFactory = ctx.getSocketFactory();

If you need help creating the key store, please comment.


Here's an example of loading the key store:

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(trustStore, trustStorePassword);
trustStore.close();

To create the key store with a PEM format certificate, you can write your own code using CertificateFactory, or just import it with keytool from the JDK (keytool won't work for a "key entry", but is just fine for a "trusted entry").

keytool -import -file selfsigned.pem -alias server -keystore server.jks

How to find if directory exists in Python

So close! os.path.isdir returns True if you pass in the name of a directory that currently exists. If it doesn't exist or it's not a directory, then it returns False.

Why does Git say my master branch is "already up to date" even though it is not?

Just a friendly reminder if you have files locally that aren't in github and yet your git status says

Your branch is up to date with 'origin/master'. nothing to commit, working tree clean

It can happen if the files are in .gitignore

Try running

cat .gitignore 

and seeing if these files show up there. That would explain why git doesn't want to move them to the remote.

'module' object is not callable - calling method in another file

The problem is in the import line. You are importing a module, not a class. Assuming your file is named other_file.py (unlike java, again, there is no such rule as "one class, one file"):

from other_file import findTheRange

if your file is named findTheRange too, following java's convenions, then you should write

from findTheRange import findTheRange

you can also import it just like you did with random:

import findTheRange
operator = findTheRange.findTheRange()

Some other comments:

a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)

b) You can build the list directly:

  randomList = [random.randint(0, 100) for i in range(5)]

c) You can call methods in the same way you do in java:

largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)

d) You can use built in function, and the huge python library:

largestInList = max(randomList)
smallestInList = min(randomList)

e) If you still want to use a class, and you don't need self, you can use @staticmethod:

class findTheRange():
    @staticmethod
    def findLargest(_list):
        #stuff...

How to calculate the sum of the datatable column in asp.net?

To calculate the sum of a column in a DataTable use the DataTable.Compute method.

Example of usage from the linked MSDN article:

DataTable table = dataSet.Tables["YourTableName"];

// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Amount)", string.Empty);

Display the result in your Total Amount Label like so:

lblTotalAmount.Text = sumObject.ToString();

Add vertical whitespace using Twitter Bootstrap?

I tried using <div class="control-group"> and it did not change my layout. It did not add vertical space. The solution that worked for me was:

<ol style="visibility:hidden;"></ol>

If that doesn't give you enough vertical space, you can incrementally get more by adding nested <li>&nbsp;</li> tags.

What is the difference between ELF files and bin files?

I just want to correct a point here. ELF file is produced by the Linker, not the compiler.

The Compiler mission ends after producing the object files (*.o) out of the source code files. Linker links all .o files together and produces the ELF.

How to check whether a str(variable) is empty or not?

How do i make an: if str(variable) == [contains text]: condition?

Perhaps the most direct way is:

if str(variable) != '':
  # ...

Note that the if not ... solutions test the opposite condition.

How can I load storyboard programmatically from class?

Swift 3

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "viewController")
self.navigationController!.pushViewController(vc, animated: true)

Swift 2

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewController")
self.navigationController!.pushViewController(vc, animated: true)

Prerequisite

Assign a Storyboard ID to your view controller.

Storyboard ID

IB > Show the Identity inspector > Identity > Storyboard ID

Swift (legacy)

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewController") as? UIViewController
self.navigationController!.pushViewController(vc!, animated: true)

Edit: Swift 2 suggested in a comment by Fred A.

if you want to use without any navigationController you have to use like following :

    let Storyboard  = UIStoryboard(name: "Main", bundle: nil)
    let vc = Storyboard.instantiateViewController(withIdentifier: "viewController")
    present(vc , animated: true , completion: nil)

Insert data through ajax into mysql database

ajax:

$(document).on('click','#mv_secure_page',function(e) {
    var data = $("#m_form1").serialize();
    $.ajax({
        data: data,
        type: "post",
        url: "adapter.php",
        success: function(data){
        alert("Data: " + data);
        }
    });
});

php code:

<?php
/**
 * Created by PhpStorm.
 * User: Engg Amjad
 * Date: 11/9/16
 * Time: 1:28 PM
 */


if(isset($_REQUEST)){
    include_once('inc/system.php');

    $full_name=$_POST['full_name'];
    $business_name=$_POST['business_name'];
    $email=$_POST['email'];
    $phone=$_POST['phone'];
    $message=$_POST['message'];

    $sql="INSERT INTO mars (f_n,b_n,em,p_n,msg) values('$full_name','$business_name','$email','$phone','$message') ";

    $sql_result=mysqli_query($con,$sql);
    if($sql_result){
       echo "inserted successfully";
    }else{
        echo "Query failed".mysqli_error($con);
    }
}
?>

Inheriting constructors

This is straight from Bjarne Stroustrup's page:

If you so choose, you can still shoot yourself in the foot by inheriting constructors in a derived class in which you define new member variables needing initialization:

struct B1 {
    B1(int) { }
};

struct D1 : B1 {
    using B1::B1; // implicitly declares D1(int)
    int x;
};

void test()
{
    D1 d(6);    // Oops: d.x is not initialized
    D1 e;       // error: D1 has no default constructor
}

CSS scrollbar style cross browser

nanoScrollerJS is simply to use. I always use them...

Browser compatibility:
  • IE7+
  • Firefox 3+
  • Chrome
  • Safari 4+
  • Opera 11.60+
Mobile browsers support:
  • iOS 5+ (iPhone, iPad and iPod Touch)
  • iOS 4 (with a polyfill)
  • Android Firefox
  • Android 2.2/2.3 native browser (with a polyfill)
  • Android Opera 11.6 (with a polyfill)

Code example from the Documentation,

  1. Markup - The following type of markup structure is needed to make the plugin work.
<div id="about" class="nano">
    <div class="nano-content"> ... content here ...  </div>
</div>

Best XML Parser for PHP

the crxml parser is a real easy to parser.

This class has got a search function, which takes a node name with any namespace as an argument. It searches the xml for the node and prints out the access statement to access that node using this class. This class also makes xml generation very easy.

you can download this class at

http://freshmeat.net/projects/crxml

or from phpclasses.org

http://www.phpclasses.org/package/6769-PHP-Manipulate-XML-documents-as-array.html

php convert datetime to UTC

As an improvement on Phill Pafford's answer (I did not understand his 'Y-d-mTG:i:sz' and he suggested to revert timezone). So I propose this (I complicated by changing the HMTL format in plain/text...):

<?php
header('content-type: text/plain;');
$my_timestamp = strtotime("2010-01-19 00:00:00");

// stores timezone
$my_timezone = date_default_timezone_get();
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date)\n";

// changes timezone
date_default_timezone_set("UTC");
echo date("Y-m-d\TH:i:s\Z", $my_timestamp)."\t\t (ISO8601 UTC date)\n";
echo date("Y-m-d H:i:s", $my_timestamp)."\t\t (your UTC date)\n";

// reverts change
date_default_timezone_set($my_timezone);
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date is back)\n"; 
?>

How do I delete multiple rows in Entity Framework (without foreach)

using (var context = new DatabaseEntities())
{
    context.ExecuteStoreCommand("DELETE FROM YOURTABLE WHERE CustomerID = {0}", customerId);
}

jQuery load more data on scroll

You question specifically is about loading data when a div falls into view, and not when the user reaches the end of the page.

Here's the best answer to your question: https://stackoverflow.com/a/33979503/3024226

Add up a column of numbers at the Unix shell

Pure bash

total=0; for i in $(cat files.txt | xargs ls -l | cut -c 23-30); do 
total=$(( $total + $i )); done; echo $total

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

How to make an introduction page with Doxygen

Add any file in the documentation which will include your content, for example toc.h:

@ mainpage Manual SDK
<hr/>
@ section pageTOC Content
  -# @ref Description
  -# @ref License
  -# @ref Item
...

And in your Doxyfile:

INPUT = toc.h \

Example (in Russian):

Length of array in function argument

Best example is here

thanks #define SIZE 10

void size(int arr[SIZE])
{
    printf("size of array is:%d\n",sizeof(arr));
}

int main()
{
    int arr[SIZE];
    size(arr);
    return 0;
}

How can I get query string values in JavaScript?

Try this:

String.prototype.getValueByKey = function(k){
    var p = new RegExp('\\b'+k+'\\b','gi');
    return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p)+k.length+1).substr(0,this.substr(this.search(p)+k.length+1).search(/(&|;|$)/))) : "";
};

Then call it like so:

if(location.search != "") location.search.getValueByKey("id");

You can use this for cookies also:

if(navigator.cookieEnabled) document.cookie.getValueByKey("username");

This only works for strings that have key=value[&|;|$]... will not work on objects/arrays.

If you don't want to use String.prototype... move it to a function and pass the string as an argument

Exit a while loop in VBS/VBA

VBScript's While loops don't support early exit. Use the Do loop for that:

num = 0
do while (num < 10)
  if (status = "Fail") then exit do
  num = num + 1
loop

Insert content into iFrame

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

See here [srcdoc]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

See here [sandbox]: https://www.w3schools.com/tags/att_iframe_sandbox.asp

How to set headers in http get request?

Pay attention that in http.Request header "Host" can not be set via Set method

req.Header.Set("Host", "domain.tld")

but can be set directly:

req.Host = "domain.tld":

req, err := http.NewRequest("GET", "http://10.0.0.1/", nil)
if err != nil {
    ...
}

req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)

How to get SQL from Hibernate Criteria API (*not* for logging)

For anyone wishing to do this in a single line (e.g in the Display/Immediate window, a watch expression or similar in a debug session), the following will do so and "pretty print" the SQL:

new org.hibernate.jdbc.util.BasicFormatterImpl().format((new org.hibernate.loader.criteria.CriteriaJoinWalker((org.hibernate.persister.entity.OuterJoinLoadable)((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),new org.hibernate.loader.criteria.CriteriaQueryTranslator(((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),((org.hibernate.impl.CriteriaImpl)crit),((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),(org.hibernate.impl.CriteriaImpl)crit,((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters())).getSQLString());

...or here's an easier to read version:

new org.hibernate.jdbc.util.BasicFormatterImpl().format(
  (new org.hibernate.loader.criteria.CriteriaJoinWalker(
     (org.hibernate.persister.entity.OuterJoinLoadable)
      ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getEntityPersister(
        ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory().getImplementors(
          ((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName())[0]),
     new org.hibernate.loader.criteria.CriteriaQueryTranslator(
          ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
          ((org.hibernate.impl.CriteriaImpl)crit),
          ((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
          org.hibernate.loader.criteria.CriteriaQueryTranslator.ROOT_SQL_ALIAS),
     ((org.hibernate.impl.CriteriaImpl)crit).getSession().getFactory(),
     (org.hibernate.impl.CriteriaImpl)crit,
     ((org.hibernate.impl.CriteriaImpl)crit).getEntityOrClassName(),
     ((org.hibernate.impl.CriteriaImpl)crit).getSession().getEnabledFilters()
   )
  ).getSQLString()
);

Notes:

  1. The answer is based on the solution posted by ramdane.i.
  2. It assumes the Criteria object is named crit. If named differently, do a search and replace.
  3. It assumes the Hibernate version is later than 3.3.2.GA but earlier than 4.0 in order to use BasicFormatterImpl to "pretty print" the HQL. If using a different version, see this answer for how to modify. Or perhaps just remove the pretty printing entirely as it's just a "nice to have".
  4. It's using getEnabledFilters rather than getLoadQueryInfluencers() for backwards compatibility since the latter was introduced in a later version of Hibernate (3.5???)
  5. It doesn't output the actual parameter values used if the query is parameterized.

How do I specify different layouts for portrait and landscape orientations?

Or use this:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:scrollbars="vertical" 
            android:layout_height="wrap_content" 
            android:layout_width="fill_parent">

  <LinearLayout android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

     <!-- Add your UI elements inside the inner most linear layout -->

  </LinearLayout>
</ScrollView>

How to get the month name in C#?

If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime

//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);

Deleting rows with Python in a CSV file

You should have if row[2] != "0". Otherwise it's not checking to see if the string value is equal to 0.

Go to first line in a file in vim?

Type "gg" in command mode. This brings the cursor to the first line.

How to pad a string with leading zeros in Python 3

Since python 3.6 you can use fstring :

>>> length = 1
>>> print(f'length = {length:03}')
length = 001

How to initialize an array in Java?

Try data = new int[] {10,20,30,40,50,60,71,80,90,91 };

What is token-based authentication?

I think it's well explained here -- quoting just the key sentences of the long article:

The general concept behind a token-based authentication system is simple. Allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource - without using their username and password. Once their token has been obtained, the user can offer the token - which offers access to a specific resource for a time period - to the remote site.

In other words: add one level of indirection for authentication -- instead of having to authenticate with username and password for each protected resource, the user authenticates that way once (within a session of limited duration), obtains a time-limited token in return, and uses that token for further authentication during the session.

Advantages are many -- e.g., the user could pass the token, once they've obtained it, on to some other automated system which they're willing to trust for a limited time and a limited set of resources, but would not be willing to trust with their username and password (i.e., with every resource they're allowed to access, forevermore or at least until they change their password).

If anything is still unclear, please edit your question to clarify WHAT isn't 100% clear to you, and I'm sure we can help you further.

What's the Use of '\r' escape sequence?

The '\r' stands for "Carriage Return" - it's a holdover from the days of typewriters and really old printers. The best example is in Windows and other DOSsy OSes, where a newline is given as "\r\n". These are the instructions sent to an old printer to start a new line: first move the print head back to the beginning, then go down one.

Different OSes will use other newline sequences. Linux and OSX just use '\n'. Older Mac OSes just use '\r'. Wikipedia has a more complete list, but those are the important ones.

Hope this helps!

PS: As for why you get that weird output... Perhaps the console is moving the "cursor" back to the beginning of the line, and then overwriting the first bit with spaces or summat.

How do you run a .bat file from PHP?

You might need to run it via cmd, eg:

system("cmd /c C:[path to file]");

Get gateway ip address in android

Install terminal emulator app, then to see routing table run iproute from the command prompt. Does not require root permissions. I don't know how to get the DNS server. There's no /etc/resolv.conf file. You can try nslookup www.google.com and see what it reports for your server, but on my phone it reports 0.0.0.0 which isn't too helpful.

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 browse localhost on Android device?

You can get a public URL for your server running on a specific port on localhost.

At my work place I could access the local server by using the local IP address of my machine in the app, as most of the other answers suggest. But at home I wasn't able to do that for some reason. After trying many answers and spending many hours, I came across https://ngrok.com. It is pretty straight forward. Just download it from within the folder do:

ngrok portnumber

( from command prompt in windows)

./ngrok portnumber

(from terminal in linux)

This will give you a public URL for your local server running on that port number on localhost. You can include in your app and debug it using that URL.

You can securely expose a local web server to the internet and capture all traffic for detailed inspection. You can share the URL with your colleague developer also who might be working remotely and can debug the App/Server interaction.

Hope this saves someone's time someday.

How to move the cursor word by word in the OS X Terminal

In Bash, these are bound to Esc-B and Esc-F. Bash has many, many more keyboard shortcuts; have a look at the output of bind -p to see what they are.

Checking if an input field is required using jQuery

You don't need jQuery to do this. Here's an ES2015 solution:

// Get all input fields
const inputs = document.querySelectorAll('#register input');

// Get only the required ones
const requiredFields = Array.from(inputs).filter(input => input.required);

// Do your stuff with the required fields
requiredFields.forEach(field => /* do what you want */);

Or you could just use the :required selector:

Array.from(document.querySelectorAll('#register input:required'))
    .forEach(field => /* do what you want */);

npm ERR cb() never called

sudo npm cache clean didn't work out for me. Update to the latest version of node helps.

I had node v.5.91 and updated to v6.9.1

How does one generate a random number in Apple's Swift language?

Swift 4.2

Bye bye to import Foundation C lib arc4random_uniform()

// 1  
let digit = Int.random(in: 0..<10)

// 2
if let anotherDigit = (0..<10).randomElement() {
  print(anotherDigit)
} else {
  print("Empty range.")
}

// 3
let double = Double.random(in: 0..<1)
let float = Float.random(in: 0..<1)
let cgFloat = CGFloat.random(in: 0..<1)
let bool = Bool.random()
  1. You use random(in:) to generate random digits from ranges.
  2. randomElement() returns nil if the range is empty, so you unwrap the returned Int? with if let.
  3. You use random(in:) to generate a random Double, Float or CGFloat and random() to return a random Bool.

More @ Official

Getting a union of two arrays in JavaScript

You can try these:

function union(a, b) {
    return a.concat(b).reduce(function(prev, cur) {
        if (prev.indexOf(cur) === -1) prev.push(cur);
        return prev;
    }, []);    
}

or

function union(a, b) {
    return a.concat(b.filter(function(el) {
        return a.indexOf(el) === -1;
    }));
}

Substring with reverse index

Also you can get the result by using substring and lastIndexOf -

alert("xxx_456".substring("xxx_456".lastIndexOf("_")+1));

How do I check if I'm running on Windows in Python?

in sys too:

import sys
# its win32, maybe there is win64 too?
is_windows = sys.platform.startswith('win')

How do I open a URL from C++?

I was having the exact same problem in Windows.

I noticed that in OP's gist, he uses string("open ") in line 21, however, by using it one comes across this error:

'open' is not recognized as an internal or external command

After researching, I have found that open is MacOS the default command to open things. It is different on Windows or Linux.

Linux: xdg-open <URL>

Windows: start <URL>


For those of you that are using Windows, as I am, you can use the following:

std::string op = std::string("start ").append(url);
system(op.c_str());

How to delete columns that contain ONLY NAs?

One way of doing it:

df[, colSums(is.na(df)) != nrow(df)]

If the count of NAs in a column is equal to the number of rows, it must be entirely NA.

Or similarly

df[colSums(!is.na(df)) > 0]

SSIS Connection not found in package

This solution worked for me:

Go to SQL Server Management Studio, Right click on the failing step and select Properties -> Logging -> Remove the Log Provider, and then re-add it

Hibernate-sequence doesn't exist

When you use

@GeneratedValue(strategy=GenerationType.AUTO)

or

@GeneratedValue which is short hand way of the above, Hibernate starts to decide the best generation strategy for you, in this case it has selected

GenerationType.SEQUENCE as the strategy and that is why it is looking for

schemaName.hibernate_sequence which is a table, for sequence based id generation.

When you use GenerationType.SEQUENCE as the strategy you need to provide the @TableGenerator as follows.

     @Id
     @GeneratedValue(strategy = GenerationType.TABLE, generator = "user_table_generator")
     @TableGenerator(name = "user_table_generator",
                table = "user_keys", pkColumnName = "PK_NAME", valueColumnName = "PK_VALUE")
     @Column(name = "USER_ID")
     private long userId;

When you set the strategy it the to

@GeneratedValue(strategy = GenerationType.IDENTITY) .

original issue get resolved because then Hibernate stop looking for sequence table.

How can I include null values in a MIN or MAX?

It's a bit ugly but because the NULLs have a special meaning to you, this is the cleanest way I can think to do it:

SELECT recordid, MIN(startdate),
   CASE WHEN MAX(CASE WHEN enddate IS NULL THEN 1 ELSE 0 END) = 0
        THEN MAX(enddate)
   END
FROM tmp GROUP BY recordid

That is, if any row has a NULL, we want to force that to be the answer. Only if no rows contain a NULL should we return the MIN (or MAX).

Determining Referer in PHP

The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons.

If you want to verify if a request is coming from your site, well you can't, but you can verify the user has been to your site and/or is authenticated. Cookies are sent in AJAX requests so you can rely on that.

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Documenting in detail for future readers:

The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url) method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request) method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.

The below is the skeleton on how you would accomplish this:

class CustomWebViewClient extends WebViewClient {

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        final Uri uri = Uri.parse(url);
        return handleUri(uri);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        final Uri uri = request.getUrl();
        return handleUri(uri);
    }

    private boolean handleUri(final Uri uri) {
        Log.i(TAG, "Uri =" + uri);
        final String host = uri.getHost();
        final String scheme = uri.getScheme();
        // Based on some condition you need to determine if you are going to load the url 
        // in your web view itself or in a browser. 
        // You can use `host` or `scheme` or any part of the `uri` to decide.
        if (/* any condition */) {
            // Returning false means that you are going to load this url in the webView itself
            return false;
        } else {
            // Returning true means that you need to handle what to do with the url
            // e.g. open web page in a Browser
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        }
    }
}

Just like shouldOverrideUrlLoading, you can come up with a similar approach for shouldInterceptRequest method.

Shortcut to comment out a block of code with sublime text

Just an important note. If you have HTML comment and your uncomment doesn't work
(Maybe it's a PHP file), so don't mark all the comment but just put your cursor at the end or at the beginning of the comment (before ) and try again (Ctrl+/).

My Application Could not open ServletContext resource

Make sure your maven war plugin block in pom.xml includes all files (especially xml files) while building the war. But you don't need to include the .java files though.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.5</version>

  <configuration>
    <webResources>
      <resources>
        <directory>WebContent</directory>
        <includes>
          <include>**/*.*</include> <!--this line includes the xml files into the war, which will be found when it is exploded in server during deployment -->
        </includes>
        <excludes>
          <exclude>*.java</exclude>
        </excludes>
      </resources>
    </webResources>
    <webXml>WebContent/WEB-INF/web.xml</webXml>
  </configuration>
</plugin> 

Making button go full-width?

Bootstrap / CSS

Use col-12, btn-block, w-100, form-control or width:100%

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

         <button class="btn btn-success col-12">
             class="col-12"
         </button>
    
         <button class="btn btn-primary w-100">
             class="w-100"
         </button>

         <button class="btn btn-secondary btn-block">
             class="btn-block"
         </button>
         
         <button class="btn btn-success form-control">
             class="form-control"
         </button>
         
         <button class="btn btn-danger" style="width:100%">
             style="width:100%"
         </button>
_x000D_
_x000D_
_x000D_

How do I write a backslash (\) in a string?

Just escape the "\" by using + "\\Tasks" or use a verbatim string like @"\Tasks"

Print Currency Number Format in PHP

with the intl extension in PHP 5.3+, you can use the NumberFormatter class:

$amount = '12345.67';

$formatter = new NumberFormatter('en_GB',  NumberFormatter::CURRENCY);
echo 'UK: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;

$formatter = new NumberFormatter('de_DE',  NumberFormatter::CURRENCY);
echo 'DE: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;

which prints :

 UK: €12,345.67
 DE: 12.345,67 €

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink

Assuming you have foo.conf in sites-available

Try

cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l

Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf

Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.

If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.

ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf

Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:

lrwxrwxrwx 1 root root  26 Jun 24 21:06 000-default -> ../sites-available/default

See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).

Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.

fork() child and parent processes

It is printing the statement twice because it is printing it for both the parent and the child. The parent has a parent id of 0

Try something like this:

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),getppid());
 else 
    printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), getppid() );

I need to get all the cookies from the browser

Added trim() to the key in object, and name it str, so it would be more clear that we are dealing with string here.

export const getAllCookies = () => document.cookie.split(';').reduce((ac, str) => Object.assign(ac, {[str.split('=')[0].trim()]: str.split('=')[1]}), {});

How to remove element from array in forEach loop?

Use Array.prototype.filter instead of forEach:

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'b', 'c', 'b', 'a', 'e'];
review = review.filter(item => item !== 'a');
log(review);

Twitter Bootstrap - full width navbar

You have to add col-md-12 to your inner-navbar. md is for desktop .you can choose other options from bootstrap's list of options . 12 in col-md-12 is for full width .If you want half-width you can use 6 instead of 12 .for e.g. col-md-6.

Here is the solution to your question

    <div class="container">
       <div class="navbar">
          <div class="navbar-inner col-md-12">
               <!-- nav bar items here -->
          </div>
       </div>
   </div>

Can we update primary key values of a table?

Short answer: yes you can. Of course you'll have to make sure that the new value doesn't match any existing value and other constraints are satisfied (duh).

What exactly are you trying to do?

net::ERR_INSECURE_RESPONSE in Chrome

I was having this issue when testing my Cordova app on android. It just so happens that this android device does not persist its date, and will reset back to its factory date somehow. The API that it calls has a cert that is valid starting this year, while the device date after bootup is in 2017. For now, I have to adb shell and change the date manually.

Uploading files to file server using webclient class

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

How to do multiple conditions for single If statement

As Hogan notes above, use an AND instead of &. See this tutorial for more info.

How to hide command output in Bash

>/dev/null 2>&1 will mute both stdout and stderr

yum install nano >/dev/null 2>&1

SQL Server Linked Server Example Query

select name from drsql01.test.dbo.employee
  • drslq01 is servernmae --linked serer
  • test is database name
  • dbo is schema -default schema
  • employee is table name

I hope it helps to understand, how to execute query for linked server

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

Open a good text editor (I'd recommend TextMate, but the free TextWrangler or vi or nano will do too), and open:

/etc/apache2/httpd.conf

Find the line:

"#LoadModule php5_module        libexec/apache2/libphp5.so"

And uncomment it (remove the #).

Download and install the latest MySQL version from mysql.com. Choose the x86_64 version for Intel (unless your Intel Mac is the original Macbook Pro or Macbook, which are not 64 bit chips. In those cases, use the 32 bit x86 version).

Install all the MySQL components. Using the pref pane, start MySQL.

In the Sharing System Pref, turn on (or if it was already on, turn off/on) Web Sharing.

You should now have Apache/PHP/MySQL running.

In 10.4 and 10.5 it was necessary to modify the php.ini file to point to the correct location of mysql.sock. There are reports that this is fixed in 10.6, but that doesn't appear to be the case for all of us, given some of the comments below.

Get names of all keys in the collection

You could do this with MapReduce:

mr = db.runCommand({
  "mapreduce" : "my_collection",
  "map" : function() {
    for (var key in this) { emit(key, null); }
  },
  "reduce" : function(key, stuff) { return null; }, 
  "out": "my_collection" + "_keys"
})

Then run distinct on the resulting collection so as to find all the keys:

db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]

No converter found capable of converting from type to type

Turns out, when the table name is different than the model name, you have to change the annotations to:

@Entity
@Table(name = "table_name")
class WhateverNameYouWant {
    ...

Instead of simply using the @Entity annotation.

What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.

Using Mysql in the command line in osx - command not found?

for me the following commands worked:

$ brew install mysql

$ brew services start mysql

How can I check if the current date/time is past a set date/time?

date_default_timezone_set('Asia/Kolkata');

$curDateTime = date("Y-m-d H:i:s");
$myDate = date("Y-m-d H:i:s", strtotime("2018-06-26 16:15:33"));
if($myDate < $curDateTime){
    echo "active";exit;
}else{
    echo "inactive";exit;
}

Best dynamic JavaScript/JQuery Grid

My suggestion for dynamic JQuery Grid are below.

http://reconstrukt.com/ingrid/

https://github.com/mleibman/SlickGrid

http://www.datatables.net/index

Best one is :

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.

Variable length pagination

On-the-fly filtering

Multi-column sorting with data type detection

Smart handling of column widths

Display data from almost any data source

DOM, Javascript array, Ajax file and server-side processing (PHP, C#, Perl, Ruby, AIR, Gears etc)

Scrolling options for table viewport

Fully internationalisable

jQuery UI ThemeRoller support

Rock solid - backed by a suite of 2600+ unit tests

Wide variety of plug-ins inc. TableTools, FixedColumns, KeyTable and more

Dynamic creation of tables

Ajax auto loading of data

Custom DOM positioning

Single column filtering

Alternative pagination types

Non-destructive DOM interaction

Sorting column(s) highlighting

Advanced data source options

Extensive plug-in support

Sorting, type detection, API functions, pagination and filtering

Fully themeable by CSS

Solid documentation

110+ pre-built examples

Full support for Adobe AIR

Establish a VPN connection in cmd

I know this is a very old thread but I was looking for a solution to the same problem and I came across this before eventually finding the answer and I wanted to just post it here so somebody else in my shoes would have a shorter trek across the internet.

****Note that you probably have to run cmd.exe as an administrator for this to work**

So here we go, open up the prompt (as an adminstrator) and go to your System32 directory. Then run

C:\Windows\System32>cd ras

Now you'll be in the ras directory. Now it's time to create a temporary file with our connection info that we will then append onto the rasphone.pbk file that will allow us to use the rasdial command.

So to create our temp file run:

C:\Windows\System32\ras>copy con temp.txt

Now it will let you type the contents of the file, which should look like this:

[CONNECTION NAME]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=vpn.server.address.com

So replace CONNECTION NAME and vpn.server.address.com with the desired connection name and the vpn server address you want.

Make a new line and press Ctrl+Z to finish and save.

Now we will append this onto the rasphone.pbk file that may or may not exist depending on if you already have network connections configured or not. To do this we will run the following command:

C:\Windows\System32\ras>type temp.txt >> rasphone.pbk

This will append the contents of temp.txt to the end of rasphone.pbk, or if rasphone.pbk doesn't exist it will be created. Now we might as well delete our temp file:

C:\Windows\System32\ras>del temp.txt

Now we can connect to our newly configured VPN server with the following command:

C:\Windows\System32\ras>rasdial "CONNECTION NAME" myUsername myPassword

When we want to disconnect we can run:

C:\Windows\System32\ras>rasdial /DISCONNECT

That should cover it! I've included a direct copy and past from the command line of me setting up a connection for and connecting to a canadian vpn server with this method:

Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.

C:\Windows\system32>cd ras

C:\Windows\System32\ras>copy con temp.txt
[Canada VPN Connection]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=ca.justfreevpn.com
^Z
        1 file(s) copied.

C:\Windows\System32\ras>type temp.txt >> rasphone.pbk

C:\Windows\System32\ras>del temp.txt

C:\Windows\System32\ras>rasdial "Canada VPN Connection" justfreevpn 2932
Connecting to Canada VPN Connection...
Verifying username and password...
Connecting to Canada VPN Connection...
Connecting to Canada VPN Connection...
Verifying username and password...
Registering your computer on the network...
Successfully connected to Canada VPN Connection.
Command completed successfully.

C:\Windows\System32\ras>rasdial /DISCONNECT
Command completed successfully.

C:\Windows\System32\ras>

Hope this helps.

How to paste into a terminal?

On windows 7:

Ctrl + Shift + Ins

works for me!

Error: package or namespace load failed for ggplot2 and for data.table

I also faced the same problem and

remove.packages(c("ggplot2", "data.table"))
install.packages('Rcpp', dependencies = TRUE)
install.packages('ggplot2', dependencies = TRUE)

these commands did not work for me. What I found was that it was showing a warning message that it could not move temporary installation C:\Users\User_name\Documents\R\win-library\3.3\abcd1234\Rcpp to C:\Users\User_name\Documents\R\win-library\3.3\Rcpp.

I downloaded the Rcpp zip file from the link given and unziped it and copied it inside C:\Users\User_name\Documents\R\win-library\3.3 and then

library(Rcpp)
library(ggplot2) 

worked. I did not have to uninstall R. Hope this helps.

How to calculate growth with a positive and negative number?

Use this formula:

=100% + (Year 2/Year 1)

The logic is that you recover 100% of the negative in year 1 (hence the initial 100%) plus any excess will be a ratio against year 1.

What is python's site-packages directory?

site-packages is the target directory of manually built Python packages. When you build and install Python packages from source (using distutils, probably by executing python setup.py install), you will find the installed modules in site-packages by default.

There are standard locations:

  • Unix (pure)1: prefix/lib/pythonX.Y/site-packages
  • Unix (non-pure): exec-prefix/lib/pythonX.Y/site-packages
  • Windows: prefix\Lib\site-packages

1 Pure means that the module uses only Python code. Non-pure can contain C/C++ code as well.

site-packages is by default part of the Python search path, so modules installed there can be imported easily afterwards.


Useful reading

Program to find largest and second largest number in array

There is no need to use the Third loop to check the second largest number in the array. You can only use two loops(one for insertion and another is for checking.

Refer this code.

#include <stdio.h>

int main()

{
int a[10], n;

int i;

printf("enter number of elements you want in array");

scanf("%d", &n);

printf("enter elements");

for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
}

int largest1 = a[0],largest2 = a[0];

for (i = 0; i < n; i++) 
{
    if (a[i] > largest1) 
    {
         largest2=largest1;
         largest1 = a[i];
    }
}

printf("First and second largest number is %d and %d ", largest1, largest2);
}

Hope this code will work for you.

Enjoy Coding :)

Multiline text in JLabel

It is possible to use (basic) CSS in the HTML.


This question was linked from Multiline JLabels - Java.

Want to upgrade project from Angular v5 to Angular v6

simply run the following command:

ng update

note: this will not update globally.

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

CodeIgniter 500 Internal Server Error

Make sure your root index.php file has the correct permission, its permission must be 0755 or 0644

CSS background image URL failing to load

Source location should be the URL (relative to the css file or full web location), not a file system full path, for example:

background: url("http://localhost/media/css/static/img/sprites/buttons-v3-10.png");
background: url("static/img/sprites/buttons-v3-10.png");

Alternatively, you can try to use file:/// protocol prefix.

Python "expected an indented block"

in python .....intendation matters, e.g.:

if a==1:
    print("hey")

if a==2:
   print("bye")

print("all the best")

In this case "all the best" will be printed if either of the two conditions executes, but if it would have been like this

if a==2:
   print("bye")
   print("all the best")

then "all the best" will be printed only if a==2

Explanation of <script type = "text/template"> ... </script>

It's legit and very handy!

Try this:

<script id="hello" type="text/template">
  Hello world
</script>
<script>
  alert($('#hello').html());
</script>

Several Javascript templating libraries use this technique. Handlebars.js is a good example.

C++ Double Address Operator? (&&)

As other answers have mentioned, the && token in this context is new to C++0x (the next C++ standard) and represent an "rvalue reference".

Rvalue references are one of the more important new things in the upcoming standard; they enable support for 'move' semantics on objects and permit perfect forwarding of function calls.

It's a rather complex topic - one of the best introductions (that's not merely cursory) is an article by Stephan T. Lavavej, "Rvalue References: C++0x Features in VC10, Part 2"

Note that the article is still quite heavy reading, but well worthwhile. And even though it's on a Microsoft VC++ Blog, all (or nearly all) the information is applicable to any C++0x compiler.

Insert all values of a table into another table in SQL

From here:

SELECT *
INTO new_table_name [IN externaldatabase] 
FROM old_tablename

scrollable div inside container

Adding position: relative to the parent, and a max-height:100%; on div2 works.

_x000D_
_x000D_
<body>_x000D_
  <div id="div1" style="height: 500px;position:relative;">_x000D_
    <div id="div2" style="max-height:100%;overflow:auto;border:1px solid red;">_x000D_
      <div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</body>?
_x000D_
_x000D_
_x000D_


Update: The following shows the "updated" example and answer. http://jsfiddle.net/Wcgvt/181/

The secret there is to use box-sizing: border-box, and some padding to make the second div height 100%, but move it's content down 50px. Then wrap the content in a div with overflow: auto to contain the scrollbar. Pay attention to z-indexes to keep all the text selectable - hope this helps, several years later.

Why is a "GRANT USAGE" created the first time I grant a user privileges?

As you said, in MySQL USAGE is synonymous with "no privileges". From the MySQL Reference Manual:

The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.

USAGE is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE. It corresponds to a row in the `mysql`.`user` table with no privileges set.

The IDENTIFIED BY clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.

A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user` table. If the user does not have any other privileges ON *.*, they are granted USAGE ON *.* and their password hash is displayed there. This is often a side effect of a CREATE USER statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE.

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

I got the same error. My mistake was that the enablejsapi=1 parameter was not present in the iframe src.

Enter key pressed event handler

In WPF, TextBox element will not get opportunity to use "Enter" button for creating KeyUp Event until you will not set property: AcceptsReturn="True".

But, it would`t solve the problem with handling KeyUp Event in TextBox element. After pressing "ENTER" you will get a new text line in TextBox.

I had solved problem of using KeyUp Event of TextBox element by using Bubble event strategy. It's short and easy. You have to attach a KeyUp Event handler in some (any) parent element:

XAML:

<Window x:Class="TextBox_EnterButtomEvent.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TextBox_EnterButtomEvent"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid KeyUp="Grid_KeyUp">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height ="0.3*"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Row="1" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
        Input text end press ENTER:
    </TextBlock>
    <TextBox Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch"/>
    <TextBlock Grid.Row="4" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow">
        You have entered:
    </TextBlock>
    <TextBlock Name="txtBlock" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Stretch"/>
</Grid></Window>

C# logical part (KeyUp Event handler is attached to a grid element):

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Grid_KeyUp(object sender, KeyEventArgs e)
    {
        if(e.Key == Key.Enter)
        {
            TextBox txtBox = e.Source as TextBox;
            if(txtBox != null)
            {
                this.txtBlock.Text = txtBox.Text;
                this.txtBlock.Background = new SolidColorBrush(Colors.LightGray);
            }
        }
    }
}

Result:

Image with result

Table 'mysql.user' doesn't exist:ERROR

 show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| datapass_schema    |
| mysql              |
| test               |
+--------------------+
4 rows in set (0.05 sec)

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables
    -> ;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| event                     |
| func                      |
| general_log               |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| host                      |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| servers                   |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
23 rows in set (0.00 sec)

mysql> create user m identified by 'm';
Query OK, 0 rows affected (0.02 sec)

check for the database mysql and table user as shown above if that dosent work, your mysql installation is not proper.

use the below command as mention in other post to install tables again

mysql_install_db

How can I remove a specific item from an array?

You have 1 to 9 in the array, and you want remove 5. Use the below code:

_x000D_
_x000D_
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];_x000D_
_x000D_
var newNumberArray = numberArray.filter(m => {_x000D_
  return m !== 5;_x000D_
});_x000D_
_x000D_
console.log("new Array, 5 removed", newNumberArray);
_x000D_
_x000D_
_x000D_


If you want to multiple values. Example:- 1,7,8

_x000D_
_x000D_
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];_x000D_
_x000D_
var newNumberArray = numberArray.filter(m => {_x000D_
  return (m !== 1) && (m !== 7) && (m !== 8);_x000D_
});_x000D_
_x000D_
console.log("new Array, 1,7 and 8 removed", newNumberArray);
_x000D_
_x000D_
_x000D_


If you want to remove an array value in an array. Example: [3,4,5]

_x000D_
_x000D_
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];_x000D_
var removebleArray = [3,4,5];_x000D_
_x000D_
var newNumberArray = numberArray.filter(m => {_x000D_
    return !removebleArray.includes(m);_x000D_
});_x000D_
_x000D_
console.log("new Array, [3,4,5] removed", newNumberArray);
_x000D_
_x000D_
_x000D_

Includes supported browser is link.

ssl.SSLError: tlsv1 alert protocol version

As of July 2018, Pypi now requires that clients connecting to it use TLS 1.2. This is an issue if you're using the version of python shipped with MacOS (2.7.10) because it only supports TLS 1.0. You can change the version of ssl that python is using to fix the problem or upgrade to a newer version of python. Use homebrew to install the new version of python outside of the default library location.

brew install python@2

How to type a new line character in SQL Server Management Studio

Try using MS Access instead. Create a new file and select 'Project using existing data' template. This will create .adp file.

Then simply open your table and press Ctrl+Enter for new line.

Pasting from clipboard also works correctly.

How can I execute a python script from an html button?

you could use text files to trasfer the data using PHP and reading the text file in python

wget: unable to resolve host address `http'

If using Vagrant try reloading your box. This solved my issue.

python: how to identify if a variable is an array or a scalar

Another alternative approach (use of class name property):

N = [2,3,5]
P = 5

type(N).__name__ == 'list'
True

type(P).__name__ == 'int'
True

type(N).__name__ in ('list', 'tuple')
True

No need to import anything.

How do I avoid the "#DIV/0!" error in Google docs spreadsheet?

Wrap your formula with IFERROR.

=IFERROR(yourformula)

The openssl extension is required for SSL/TLS protection

according to the composer reference there are two relevant options: disable-tls and secure-http.

nano ~/.composer/config.json (If the file does not exist or is empty, then just create it with the following content)

{
    "config": {
        "disable-tls": true,
        "secure-http": false
    }
}

then it complains much:

You are running Composer with SSL/TLS protection disabled.
Warning: Accessing getcomposer.org over http which is an insecure protocol.

but it performs the composer selfupdate (or whatever).

while one cannot simply "enable SSL in the php.ini" on Linux; PHP needs to be compiled with openSSL configured as shared library - in order to be able to access it from the PHP CLI SAPI.

Add a new column to existing table in a migration

You can add new columns within the initial Schema::create method like this:

Schema::create('users', function($table) {
    $table->integer("paied");
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

If you have already created a table you can add additional columns to that table by creating a new migration and using the Schema::table method:

Schema::table('users', function($table) {
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

The documentation is fairly thorough about this, and hasn't changed too much from version 3 to version 4.

How to select an element with 2 classes

You can chain class selectors without a space between them:

.a.b {
     color: #666;
}

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

Vertically centering Bootstrap modal window

This works in BS3, not tested in v2. It centers the modal vertically. Note that it will transition there - if you want it to just appear in position edit CSS transition property for .modal-dialog

centerModal = function() {
    var $dialog = $(this).find(".modal-dialog"),
        offset = ($(window).height() - $dialog.height()) / 2;

    // Center modal vertically in window
    $dialog.css({
        'transform': 'translateY(' + offset + 'px) !important',
    });
};

$('.modal').on('shown.bs.modal', centerModal);
$(window).on("resize", function() {
    $('.modal').each(centerModal);
});

Center the content inside a column in Bootstrap 4

<div class="container">
    <div class="row justify-content-center">
        <div class="col-3 text-center">
            Center text goes here
        </div>
    </div>
</div>

I have used justify-content-center class instead of mx-auto as in this answer.

check at https://jsfiddle.net/sarfarazk/4fsp4ywh/

Change :hover CSS properties with JavaScript

This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I'm a novice, so take it for what it's worth:

$(".hoverCell").bind('mouseover', function() {
    var old_color = $(this).css("background-color");
    $(this)[0].style.backgroundColor = '#ffff00';

    $(".hoverCell").bind('mouseout', function () {
        $(this)[0].style.backgroundColor = old_color;
    });
});

This requires setting the Class for each of the cells you want to highlight to "hoverCell".

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.

< original link no longer active >

http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:

https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"

http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"

How to fix nginx throws 400 bad request headers on any header testing tools?

I had the same issue and tried everything. This 400 happened for an upstream proxy. Debug logged showed absolutely nothing.

The problem was in duplicate proxy_set_header Host $http_host directive, which I didn't notice initially. Removing duplicate one solved the issue immediately. I wish nginx was saying something other than 400 in this scenario, as nginx -t didn't complain at all.

P.S. this happened while migrating from older nginx 1.10 to the newer 1.19. Before it was tolerated apparently.

Clear android application user data

// To delete all the folders and files within folders recursively
File sdDir = new File(sdPath);

if(sdDir.exists())
    deleteRecursive(sdDir);




// Delete any folder on a device if exists
void deleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory())
    for (File child : fileOrDirectory.listFiles())
        deleteRecursive(child);

    fileOrDirectory.delete();
}

Encoding conversion in java

I would just like to add that if the String is originally encoded using the wrong encoding it might be impossible to change it to another encoding without errors. The question does not state that the conversion here is made from wrong encoding to correct encoding but I personally stumbled to this question just because of this situation so just a heads up for others as well.

This answer in other question gives an explanation why the conversion does not always yield correct results https://stackoverflow.com/a/2623793/4702806

How do I apply a diff patch on Windows?

In TortoiseSVN, patch applying does work. You need to apply the patch to the same directory as it was created from. It is always important to keep this in mind. So here's how you do it in TortoiseSVN:

Right click on the folder you want to apply the patch to. It will present a dialog asking for the location of the patch file. Select the file and this should open up a little file list window that lists the changed files, and clicking each item should open a diff window that shows what the patch is about to do to that file.

Good luck.

Opening a folder in explorer and selecting a file

You need to put the arguments to pass ("/select etc") in the second parameter of the Start method.

How to deserialize JS date using Jackson?

I found a work around but with this I'll need to annotate each date's setter throughout the project. Is there a way in which I can specify the format while creating the ObjectMapper?

Here's what I did:

public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
    @Override
    public Date deserialize(JsonParser jsonParser,
            DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String date = jsonParser.getText();
        try {
            return format.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }

}

And annotated each Date field's setter method with this:

@JsonDeserialize(using = CustomJsonDateDeserializer.class)

ActionController::InvalidAuthenticityToken

In rails 5, we need to add 2 lines of code

    skip_before_action :verify_authenticity_token
    protect_from_forgery prepend: true, with: :exception

Disable a link in Bootstrap

I think you need the btn class.
It would be like this:

<a class="btn disabled" href="#">Disabled link</a>

Get the content of a sharepoint folder with Excel VBA

The only way I've found to work with files on SharePoint while having to server rights is to map the WebDAV folder to a drive letter. Here's an example for the implementation.

Add references to the following ActiveX libraries in VBA:

  • Windows Script Host Object Model (wshom.ocx) - for WshNetwork
  • Microsoft Scripting Runtime (scrrun.dll) - for FileSystemObject

Create a new class module, call it DriveMapper and add the following code:

Option Explicit

Private oMappedDrive As Scripting.Drive
Private oFSO As New Scripting.FileSystemObject
Private oNetwork As New WshNetwork

Private Sub Class_Terminate()
  UnmapDrive
End Sub

Public Function MapDrive(NetworkPath As String) As Scripting.Folder
  Dim DriveLetter As String, i As Integer

  UnmapDrive

  For i = Asc("Z") To Asc("A") Step -1
    DriveLetter = Chr(i)
    If Not oFSO.DriveExists(DriveLetter) Then
      oNetwork.MapNetworkDrive DriveLetter & ":", NetworkPath
      Set oMappedDrive = oFSO.GetDrive(DriveLetter)
      Set MapDrive = oMappedDrive.RootFolder
      Exit For
    End If
  Next i
End Function

Private Sub UnmapDrive()
  If Not oMappedDrive Is Nothing Then
    If oMappedDrive.IsReady Then
      oNetwork.RemoveNetworkDrive oMappedDrive.DriveLetter & ":"
    End If
    Set oMappedDrive = Nothing
  End If
End Sub

Then you can implement it in your code:

Sub test()
  Dim dm As New DriveMapper
  Dim sharepointFolder As Scripting.Folder

  Set sharepointFolder = dm.MapDrive("http://your/sharepoint/path")

  Debug.Print sharepointFolder.Path
End Sub

What is the difference between static_cast<> and C style casting?

struct A {};
struct B : A {};
struct C {}; 

int main()
{
    A* a = new A;    

    int i = 10;

    a = (A*) (&i); // NO ERROR! FAIL!

    //a = static_cast<A*>(&i); ERROR! SMART!

    A* b = new B;

    B* b2 = static_cast<B*>(b); // NO ERROR! SMART!

    C* c = (C*)(b); // NO ERROR! FAIL!

    //C* c = static_cast<C*>(b); ERROR! SMART!
}

How can I tell jackson to ignore a property for which I don't have control over the source code?

Mix-in annotations work pretty well here as already mentioned. Another possibility beyond per-property @JsonIgnore is to use @JsonIgnoreType if you have a type that should never be included (i.e. if all instances of GeometryCollection properties should be ignored). You can then either add it directly (if you control the type), or using mix-in, like:

@JsonIgnoreType abstract class MixIn { }
// and then register mix-in, either via SerializationConfig, or by using SimpleModule

This can be more convenient if you have lots of classes that all have a single 'IgnoredType getContext()' accessor or so (which is the case for many frameworks)

ALTER DATABASE failed because a lock could not be placed on database

I managed to reproduce this error by doing the following.

Connection 1 (leave running for a couple of minutes)

CREATE DATABASE TESTING123
GO

USE TESTING123;

SELECT NEWID() AS X INTO FOO
FROM sys.objects s1,sys.objects s2,sys.objects s3,sys.objects s4 ,sys.objects s5 ,sys.objects s6

Connections 2 and 3

set lock_timeout 5;

ALTER DATABASE TESTING123 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

You don't need to muck about with extracting parts of the date. Just cast it to a date using to_date and the format in which its stored, then cast that date to a char in the format you want. Like this:

select to_char(to_date('1/10/2011','mm/dd/yyyy'),'mm-dd-yyyy') from dual

Removing all line breaks and adding them after certain text

You can also try this in Notepad++

  • Highlight the lines you want to join (ctrl + a to select all)
  • Choose Edit -> Line Operations -> Join Lines

How to run two jQuery animations simultaneously?

If you run the above as they are, they will appear to run simultaenously.

Here's some test code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(function () {
    $('#first').animate({ width: 200 }, 200);
    $('#second').animate({ width: 600 }, 200);
});
</script>
<div id="first" style="border:1px solid black; height:50px; width:50px"></div>
<div id="second" style="border:1px solid black; height:50px; width:50px"></div>

how to set value of a input hidden field through javascript?

You need to run your script after the element exists. Move the <input type="hidden" name="checkyear" id="checkyear" value=""> to the beginning.

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

ALTER USER 'mysqlUsername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysqlUsernamePassword';

Remove quotes (') after ALTER USER and keep quote (') after mysql_native_password BY

It is working for me also.

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

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

Here is an example code that you may use:

$ STR="String;1;2;3"
$ for EACH in `echo "$STR" | grep -o -e "[^;]*"`; do
    echo "Found: \"$EACH\"";
done

grep -o -e "[^;]*" will select anything that is not ';', therefore spliting the string by ';'.

Hope that help.

How to get the size of a string in Python?

Python 3:

user225312's answer is correct:

A. To count number of characters in str object, you can use len() function:

>>> print(len('please anwser my question'))
25

B. To get memory size in bytes allocated to store str object, you can use sys.getsizeof() function

>>> from sys import getsizeof
>>> print(getsizeof('please anwser my question'))
50

Python 2:

It gets complicated for Python 2.

A. The len() function in Python 2 returns count of bytes allocated to store encoded characters in a str object.

Sometimes it will be equal to character count:

>>> print(len('abc'))
3

But sometimes, it won't:

>>> print(len('???'))  # String contains Cyrillic symbols
6

That's because str can use variable-length encoding internally. So, to count characters in str you should know which encoding your str object is using. Then you can convert it to unicode object and get character count:

>>> print(len('???'.decode('utf8'))) #String contains Cyrillic symbols 
3

B. The sys.getsizeof() function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string object

>>> print(getsizeof('???'))
27
>>> print(getsizeof('???'.decode('utf8')))
32

Selecting last element in JavaScript array

var last = function( obj, key ) { 
    var a = obj[key];
    return a[a.length - 1];
};

last(loc, 'f096012e-2497-485d-8adb-7ec0b9352c52');

How to vertically align into the center of the content of a div with defined width/height?

I have researched this a little and from what I have found you have four options:

Version 1: Parent div with display as table-cell

If you do not mind using the display:table-cell on your parent div, you can use of the following options:

.area{
    height: 100px;
    width: 100px;
    background: red;
    margin:10px;
    text-align: center;
    display:table-cell;
    vertical-align:middle;
}?

Live DEMO


Version 2: Parent div with display block and content display table-cell

.area{
    height: 100px;
    width: 100px;
    background: red;
    margin:10px;
    text-align: center;
    display:block;
}

.content {
    height: 100px;
    width: 100px;
    display:table-cell;
    vertical-align:middle;    
}?

Live DEMO


Version 3: Parent div floating and content div as display table-cell

.area{
    background: red;
    margin:10px;
    text-align: center;
    display:block;
    float: left;
}

.content {
    display:table-cell;
    vertical-align:middle;
    height: 100px;
    width: 100px;
}?

Live DEMO


Version 4: Parent div position relative with content position absolute

The only problem that I have had with this version is that it seems you will have to create the css for every specific implementation. The reason for this is the content div needs to have the set height that your text will fill and the margin-top will be figured off of that. This issue can be seen in the demo. You can get it to work for every scenario manually by changing the height % of your content div and multiplying it by -.5 to get your margin-top value.

.area{
    position:relative; 
    display:block;
    height:100px;
    width:100px;
    border:1px solid black;
    background:red;
    margin:10px;
}

.content { 
    position:absolute;
    top:50%; 
    height:50%; 
    width:100px;
    margin-top:-25%;
    text-align:center;
}?

Live DEMO

How to include layout inside layout?

Try this

<include
            android:id="@+id/OnlineOffline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            layout="@layout/YourLayoutName" />

How to delete file from public folder in laravel 5.1

Try it :Laravel 5.5

public function destroy($id){  
      $data = User::FindOrFail($id);  
      if(file_exists('backend_assets/uploads/userPhoto/'.$data->photo) AND !empty($data->photo)){ 
            unlink('backend_assets/uploads/userPhoto/'.$data->photo);
         } 
            try{

                $data->delete();
                $bug = 0;
            }
            catch(\Exception $e){
                $bug = $e->errorInfo[1];
            } 
            if($bug==0){
                echo "success";
            }else{
                echo 'error';
            }
        }

How do I truly reset every setting in Visual Studio 2012?

To reset your settings

  • On the Tools menu, click Import and Export Settings.
  • On the Welcome to the Import and Export Settings Wizard page, click Reset all settings and then click Next.
  • If you want to delete your current settings combination, choose No, just reset settings, overwriting all current settings, and then click Next. Select the programming language(s) you want to reset the setting for.

Click Finish.

The Reset Complete page alerts you to any problems encountered during the reset.

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

Remove the content of the folder \.m2\repository\org\apache\maven\plugins\maven-resource-plugin\2.7. The cached info turned out to be the issue.

Clear dropdown using jQuery Select2

This solved my problem in version 3.5.2.

$remote.empty().append(new Option()).trigger('change');

According to this issue you need an empty option inside select tag for the placeholder to show up.

Hibernate: get entity by id

In getUserById you shouldn't create a new object (user1) which isn't used. Just assign it to the already (but null) initialized user. Otherwise Hibernate.initialize(user); is actually Hibernate.initialize(null);

Here's the new getUserById (I haven't tested this ;)):

public User getUserById(Long user_id) {
    Session session = null;
    Object user = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        user = (User)session.load(User.class, user_id);
        Hibernate.initialize(user);
    } catch (Exception e) {
       e.printStackTrace();
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return user;
}

Intercept and override HTTP requests from WebView

Here is my solution I use for my app.

I have several asset folder with css / js / img anf font files.

The application gets all filenames and looks if a file with this name is requested. If yes, it loads it from asset folder.

//get list of files of specific asset folder
        private ArrayList listAssetFiles(String path) {

            List myArrayList = new ArrayList();
            String [] list;
            try {
                list = getAssets().list(path);
                for(String f1 : list){
                    myArrayList.add(f1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return (ArrayList) myArrayList;
        }

        //get mime type by url
        public String getMimeType(String url) {
            String type = null;
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            if (extension != null) {
                if (extension.equals("js")) {
                    return "text/javascript";
                }
                else if (extension.equals("woff")) {
                    return "application/font-woff";
                }
                else if (extension.equals("woff2")) {
                    return "application/font-woff2";
                }
                else if (extension.equals("ttf")) {
                    return "application/x-font-ttf";
                }
                else if (extension.equals("eot")) {
                    return "application/vnd.ms-fontobject";
                }
                else if (extension.equals("svg")) {
                    return "image/svg+xml";
                }
                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            }
            return type;
        }

        //return webresourceresponse
        public WebResourceResponse loadFilesFromAssetFolder (String folder, String url) {
            List myArrayList = listAssetFiles(folder);
            for (Object str : myArrayList) {
                if (url.contains((CharSequence) str)) {
                    try {
                        Log.i(TAG2, "File:" + str);
                        Log.i(TAG2, "MIME:" + getMimeType(url));
                        return new WebResourceResponse(getMimeType(url), "UTF-8", getAssets().open(String.valueOf(folder+"/" + str)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        //@TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @SuppressLint("NewApi")
        @Override
        public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
            //Log.i(TAG2, "SHOULD OVERRIDE INIT");
            //String url = webResourceRequest.getUrl().toString();
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            //I have some folders for files with the same extension
            if (extension.equals("css") || extension.equals("js") || extension.equals("img")) {
                return loadFilesFromAssetFolder(extension, url);
            }
            //more possible extensions for font folder
            if (extension.equals("woff") || extension.equals("woff2") || extension.equals("ttf") || extension.equals("svg") || extension.equals("eot")) {
                return loadFilesFromAssetFolder("font", url);
            }

            return null;
        }

How do I get Month and Date of JavaScript in 2 digit format?

If it might spare some time I was looking to get:

YYYYMMDD

for today, and got along with:

const dateDocumentID = new Date()
  .toISOString()
  .substr(0, 10)
  .replace(/-/g, '');

Uncaught ReferenceError: angular is not defined - AngularJS not working

i forgot to add below line to my HTML code after i add problem has resolved.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>

How do AX, AH, AL map onto EAX?

The below snippet examines EAX using GDB.

    (gdb) info register eax
    eax            0xaa55   43605
    (gdb) info register ax
    ax             0xaa55   -21931
    (gdb) info register ah
    ah             0xaa -86
    (gdb) info register al
    al             0x55 85
  1. EAX - Full 32 bit value
  2. AX - lower 16 bit value
  3. AH - Bits from 8 to 15
  4. AL - lower 8 bits of EAX/AX

How to start an Intent by passing some parameters to it?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.

Syntax: intent.putExtra("key", value);

Eg: intent.putExtra("full_name", "Vishnu Sivan");

Intent intent=getIntent() : It gets the Intent from the previous activity.

fullname = intent.getStringExtra(“full_name”) : This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.

Sample Code:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);

String parsing in Java with delimiter tab "\t" using split

Try this:

String[] columnDetail = column.split("\t", -1);

Read the Javadoc on String.split(java.lang.String, int) for an explanation about the limit parameter of split function:

split

public String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

The string "boo:and:foo", for example, yields the following results with these parameters:

Regex   Limit   Result
:   2   { "boo", "and:foo" }
:   5   { "boo", "and", "foo" }
:   -2  { "boo", "and", "foo" }
o   5   { "b", "", ":and:f", "", "" }
o   -2  { "b", "", ":and:f", "", "" }
o   0   { "b", "", ":and:f" }

When the last few fields (I guest that's your situation) are missing, you will get the column like this:

field1\tfield2\tfield3\t\t

If no limit is set to split(), the limit is 0, which will lead to that "trailing empty strings will be discarded". So you can just get just 3 fields, {"field1", "field2", "field3"}.

When limit is set to -1, a non-positive value, trailing empty strings will not be discarded. So you can get 5 fields with the last two being empty string, {"field1", "field2", "field3", "", ""}.

String array initialization in Java

You mean like:

String names[] = {"Ankit","Bohra","Xyz"};

But you can only do this in the same statement when you declare it

How to size an Android view based on its parent's dimensions

It's something like this:

<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.company.myapp.ActivityOrFragment"
    android:id="@+id/activity_or_fragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/linearLayoutFirst"
    android:weightSum="100">   <!-- Overall weights sum of children elements -->

    <Spinner
        android:layout_width="0dp"   <!-- It's 0dp because is determined by android:layout_weight -->
        android:layout_weight="50"
        android:layout_height="wrap_content"
        android:id="@+id/spinner" />

</LinearLayout>


<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:layout_below="@+id/linearLayoutFirst"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:id="@+id/linearLayoutSecond">

    <EditText
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="75"
        android:inputType="numberDecimal"
        android:id="@+id/input" />

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="25"
        android:id="@+id/result"/>

</LinearLayout>
</RelativeLayout>

How can I create a marquee effect?

The following should do what you want.

@keyframes marquee {
    from  { text-indent:  100% }
    to    { text-indent: -100% }
}

Functional style of Java 8's Optional.ifPresent and if-not-Present?

Supposing that you have a list and avoiding the isPresent() issue (related with optionals) you could use .iterator().hasNext() to check if not present.

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

I have faced this type of error. to call a function from the razor.

public ActionResult EditorAjax(int id, int? jobId, string type = ""){}

solved that by changing the line

from

<a href="/ScreeningQuestion/EditorAjax/5&jobId=2&type=additional" /> 

to

<a href="/ScreeningQuestion/EditorAjax/?id=5&jobId=2&type=additional" />

where my route.config is

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new string[] { "RPMS.Controllers" } // Parameter defaults
        );

How to add anything in <head> through jquery/javascript?

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

Make DOM element like so:

link=document.createElement('link');
link.href='href';
link.rel='rel';

document.getElementsByTagName('head')[0].appendChild(link);

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

In LINQ, select all values of property X where X != null

get one column in the distinct select and ignore null values:

 var items = db.table.Where(p => p.id!=null).GroupBy(p => p.id)
                                .Select(grp => grp.First().id)
                                .ToList();

Remove duplicates in the list using linq

An universal extension method:

public static class EnumerableExtensions
{
    public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> enumerable, Func<T, TKey> keySelector)
    {
        return enumerable.GroupBy(keySelector).Select(grp => grp.First());
    }
}

Example of usage:

var lstDst = lst.DistinctBy(item => item.Key);

XAMPP, Apache - Error: Apache shutdown unexpectedly

Even i had this issue and i resolved it, in my case it was different.

first i tried uninstalling the skype but that didn't work. but in my windows 10 desktop, i had the IIS(Internet Information Server) installed by default which was pointing to port 80.

All i did is i changed the port number to 8081 and just restarted XAMPP, and that worked for me.

however i was not using IIS.

here is the link to https://support.microsoft.com/en-in/help/149605/how-to-change-the-tcp-port-for-iis-services

Checking password match while typing

$('#txtConfirmPassword').keyup(function(){


if($(this).val() != $('#txtNewPassword').val().substr(0,$(this).val().length))
{
 alert('confirm password not match');
}



});

Write string to output stream

By design it is to be done this way:

OutputStream out = ...;
try (Writer w = new OutputStreamWriter(out, "UTF-8")) {
    w.write("Hello, World!");
} // or w.close(); //close will auto-flush

When to use the !important property in CSS

The use of !important is very import in email creation when inline CSS is the correct answer. It is used in conjunction with @media to change the layout when viewing on different platforms. For instance the way the page looks on desktop as compare to smart phones (ie. change the link placement and size. have the whole page fit within a 480px width as apposed to 640px width.

An invalid form control with name='' is not focusable

Not only required field as mentioned in other answers. Its also caused by placing a <input> field in a hidden <div> which holds a invalid value.

Consider below example,

<div style="display:none;">
   <input type="number" name="some" min="1" max="50" value="0">
</div> 

This throws the same error. So make sure the <input> fields inside hidden <div> doesnt hold any invalid value.

How to suppress "unused parameter" warnings in C?

Labelling the attribute is ideal way. MACRO leads to sometime confusion. and by using void(x),we are adding an overhead in processing.

If not using input argument, use

void foo(int __attribute__((unused))key)
{
}

If not using the variable defined inside the function

void foo(int key)
{
   int hash = 0;
   int bkt __attribute__((unused)) = 0;

   api_call(x, hash, bkt);
}

Now later using the hash variable for your logic but doesn’t need bkt. define bkt as unused, otherwise compiler says'bkt set bt not used".

NOTE: This is just to suppress the warning not for optimization.

Run git pull over all subdirectories

I use this one:

find . -name ".git" -type d | sed 's/\/.git//' |  xargs -P10 -I{} git -C {} pull

Universal: Updates all git repositories that are below current directory.

Check if value exists in enum in TypeScript

If you want to use the variable as enum, just add the function:

Enum EVehicle {
    Car = 'car',
    Bike = 'bike',
    Truck = 'truck'
}

const getVehicleAsEnum = (vehicleStr:string) => vehicleStr === 'car' ? EVehicle.Car : vehicleStr === 'bike' ? EVehicle.Bike : vehicleStr === 'truck' ? EVehicle.Truck : undefined

And then test:

const vehicleEnum = getVecicleAsEnum(str)
if(vehicleEnum) {
   // do something
}

Mockito - NullpointerException when stubbing Method

Corner case:
If you're using Scala and you try to create an any matcher on a value class, you'll get an unhelpful NPE.

So given case class ValueClass(value: Int) extends AnyVal, what you want to do is ValueClass(anyInt) instead of any[ValueClass]

when(mock.someMethod(ValueClass(anyInt))).thenAnswer {
   ...
   val v  = ValueClass(invocation.getArguments()(0).asInstanceOf[Int])
   ...
}

This other SO question is more specifically about that, but you'd miss it when you don't know the issue is with value classes.

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

I would use something like this for fixed length, like hashes:

md5sum = String.format("%032x", new BigInteger(1, md.digest()));

The 0 in the mask does the padding...

Git Cherry-pick vs Merge Workflow

In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").

Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).

Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.

HTH.

How to get date representing the first day of a month?

select last_day(add_months(sysdate,-1))+1 from dual;

Is there a command like "watch" or "inotifywait" on the Mac?

My fork of fswatch provides the functionality of inotifywait -m with slightly less (no wait, more! I have a lot more troubles on Linux with inotifywait...) parse-friendly output.

It is an improvement upon the original fswatch because it sends out the actual path of the changed file over STDOUT rather than requiring you to provide a program that it forks.

It's been rock solid as the foundation of a series of scary bash scripts I use to automate stuff.

(this is off-topic) inotifywait on Linux, on the other hand, requires a lot of kludges on top of it and I still haven't figured out a good way to manage it, though I think something based on node.js might be the ticket.

How to download a file from a URL in C#?

Include this namespace

using System.Net;

Download Asynchronously and put a ProgressBar to show the status of the download within the UI Thread Itself

private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadProgressChanged += wc_DownloadProgressChanged;
        wc.DownloadFileAsync (
            // Param1 = Link of file
            new System.Uri("http://www.sayka.com/downloads/front_view.jpg"),
            // Param2 = Path to save
            "D:\\Images\\front_view.jpg"
        );
    }
}
// Event to track the progress
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    progressBar.Value = e.ProgressPercentage;
}

How do I execute a stored procedure in a SQL Agent job?

You just need to add this line to the window there:

exec (your stored proc name) (and possibly add parameters)

What is your stored proc called, and what parameters does it expect?

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

No it doesn't wait and the way you are doing it in that sample is not good practice.

dispatch_async is always asynchronous. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code.

If you want the update to wait you can use dispatch_sync instead.

// This will wait to finish
dispatch_sync(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
});

Another approach would be to nest enqueueing the block. I wouldn't recommend it for multiple levels though.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Background work

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update UI

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // Background work

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update UI
            });
        });
    });
});

If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.

ImageView in circular through xml

Just use the ShapeableImageView provided by the Material Components Library.
Somethig like:

<com.google.android.material.imageview.ShapeableImageView
    app:shapeAppearanceOverlay="@style/roundedImageViewRounded"
    app:strokeColor="@color/....."
    app:strokeWidth="1dp"
    ...
    />

with:

  <style name="roundedImageViewRounded">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
  </style>

enter image description here

Note: it requires at least the version 1.2.0-alpha03.

How to create a Java / Maven project that works in Visual Studio Code?

An alternative way is to install the Maven for Java plugin and create a maven project within Visual Studio. The steps are described in the official documentation:

  1. From the Command Palette (Crtl+Shift+P), select Maven: Generate from Maven Archetype and follow the instructions, or
  2. Right-click on a folder and select Generate from Maven Archetype.

python: changing row index of pandas data frame

When you are not sure of the number of rows, then you can do it this way:

followers_df.index = range(len(followers_df))

Why do we use Base64?

Your first mistake is thinking that ASCII encoding and Base64 encoding are interchangeable. They are not. They are used for different purposes.

  • When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes.
  • When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.

To understand why Base64 was necessary in the first place we need a little history of computing.


Computers communicate in binary - 0s and 1s - but people typically want to communicate with more rich forms data such as text or images. In order to transfer this data between computers it first has to be encoded into 0s and 1s, sent, then decoded again. To take text as an example - there are many different ways to perform this encoding. It would be much simpler if we could all agree on a single encoding, but sadly this is not the case.

Originally a lot of different encodings were created (e.g. Baudot code) which used a different number of bits per character until eventually ASCII became a standard with 7 bits per character. However most computers store binary data in bytes consisting of 8 bits each so ASCII is unsuitable for tranferring this type of data. Some systems would even wipe the most significant bit. Furthermore the difference in line ending encodings across systems mean that the ASCII character 10 and 13 were also sometimes modified.

To solve these problems Base64 encoding was introduced. This allows you to encode arbitrary bytes to bytes which are known to be safe to send without getting corrupted (ASCII alphanumeric characters and a couple of symbols). The disadvantage is that encoding the message using Base64 increases its length - every 3 bytes of data is encoded to 4 ASCII characters.

To send text reliably you can first encode to bytes using a text encoding of your choice (for example UTF-8) and then afterwards Base64 encode the resulting binary data into a text string that is safe to send encoded as ASCII. The receiver will have to reverse this process to recover the original message. This of course requires that the receiver knows which encodings were used, and this information often needs to be sent separately.

Historically it has been used to encode binary data in email messages where the email server might modify line-endings. A more modern example is the use of Base64 encoding to embed image data directly in HTML source code. Here it is necessary to encode the data to avoid characters like '<' and '>' being interpreted as tags.


Here is a working example:

I wish to send a text message with two lines:

Hello
world!

If I send it as ASCII (or UTF-8) it will look like this:

72 101 108 108 111 10 119 111 114 108 100 33

The byte 10 is corrupted in some systems so we can base 64 encode these bytes as a Base64 string:

SGVsbG8Kd29ybGQh

Which when encoded using ASCII looks like this:

83 71 86 115 98 71 56 75 100 50 57 121 98 71 81 104

All the bytes here are known safe bytes, so there is very little chance that any system will corrupt this message. I can send this instead of my original message and let the receiver reverse the process to recover the original message.

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

As it turns out, one should not forget to include jacson dependency into the pom file. This solved the issue for me:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)