Programs & Examples On #Modbus

Modbus is a serial communications protocol published by Modicon in 1979 for use with its programmable logic controllers (PLCs). Simple and robust, it has since become a de facto standard communication protocol, and it is now amongst the most commonly available means of connecting industrial electronic devices.

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.

"Invalid signature file" when attempting to run a .jar

For those who have trouble with the accepted solution, there is another way to exclude resource from shaded jar with DontIncludeResourceTransformer:

https://maven.apache.org/plugins/maven-shade-plugin/examples/resource-transformers.html#DontIncludeResourceTransformer

          <transformers>
            <transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
                <resource>BC1024KE.DSA</resource>
            </transformer>
          </transformers>

From Shade 3.0, this transformer accepts a list of resources. Before that you just need to use multiple transformer each with one resource.

How to get base URL in Web API controller?

In the action method of the request to the url "http://localhost:85458/api/ctrl/"

var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) ;

this will get you http://localhost:85458

Dynamic tabs with user-click chosen components

update

Angular 5 StackBlitz example

update

ngComponentOutlet was added to 4.0.0-beta.3

update

There is a NgComponentOutlet work in progress that does something similar https://github.com/angular/angular/pull/11235

RC.7

Plunker example RC.7

// Helper component to add dynamic components
@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;
  @Input() type: Type<Component>;
  cmpRef: ComponentRef<Component>;
  private isViewInitialized:boolean = false;

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      // when the `type` input changes we destroy a previously 
      // created component before creating the new one
      this.cmpRef.destroy();
    }

    let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
    this.cmpRef = this.target.createComponent(factory)
    // to access the created instance use
    // this.compRef.instance.someProperty = 'someValue';
    // this.compRef.instance.someOutput.subscribe(val => doSomething());
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Usage example

// Use dcl-wrapper component
@Component({
  selector: 'my-tabs',
  template: `
  <h2>Tabs</h2>
  <div *ngFor="let tab of tabs">
    <dcl-wrapper [type]="tab"></dcl-wrapper>
  </div>
`
})
export class Tabs {
  @Input() tabs;
}
@Component({
  selector: 'my-app',
  template: `
  <h2>Hello {{name}}</h2>
  <my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
  // The list of components to create tabs from
  types = [C3, C1, C2, C3, C3, C1, C1];
}
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
  entryComponents: [C1, C2, C3],
  bootstrap: [ App ]
})
export class AppModule {}

See also angular.io DYNAMIC COMPONENT LOADER

older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

This changed again in Angular2 RC.5

I will update the example below but it's the last day before vacation.

This Plunker example demonstrates how to dynamically create components in RC.5

Update - use ViewContainerRef.createComponent()

Because DynamicComponentLoader is deprecated, the approach needs to be update again.

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private resolver: ComponentResolver) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
   this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
      this.cmpRef = this.target.createComponent(factory)
      // to access the created instance use
      // this.compRef.instance.someProperty = 'someValue';
      // this.compRef.instance.someOutput.subscribe(val => doSomething());
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Plunker example RC.4
Plunker example beta.17

Update - use loadNextToLocation

export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private dcl:DynamicComponentLoader) {}

  updateComponent() {
    // should be executed every time `type` changes but not before `ngAfterViewInit()` was called 
    // to have `target` initialized
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
    this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Plunker example beta.17

original

Not entirely sure from your question what your requirements are but I think this should do what you want.

The Tabs component gets an array of types passed and it creates "tabs" for each item in the array.

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
  @Input() type;

  ngOnChanges() {
    if(this.cmpRef) {
      this.cmpRef.dispose();
    }
    this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }
}

@Component({
  selector: 'c1',
  template: `<h2>c1</h2>`

})
export class C1 {
}

@Component({
  selector: 'c2',
  template: `<h2>c2</h2>`

})
export class C2 {
}

@Component({
  selector: 'c3',
  template: `<h2>c3</h2>`

})
export class C3 {
}

@Component({
  selector: 'my-tabs',
  directives: [DclWrapper],
  template: `
  <h2>Tabs</h2>
  <div *ngFor="let tab of tabs">
    <dcl-wrapper [type]="tab"></dcl-wrapper>
  </div>
`
})
export class Tabs {
  @Input() tabs;
}


@Component({
  selector: 'my-app',
  directives: [Tabs]
  template: `
  <h2>Hello {{name}}</h2>
  <my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
  types = [C3, C1, C2, C3, C3, C1, C1];
}

Plunker example beta.15 (not based on your Plunker)

There is also a way to pass data along that can be passed to the dynamically created component like (someData would need to be passed like type)

    this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
  cmpRef.instance.someProperty = someData;
  this.cmpRef = cmpRef;
});

There is also some support to use dependency injection with shared services.

For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

Select records from NOW() -1 Day

Be aware that the result may be slightly different than you expect.

NOW() returns a DATETIME.

And INTERVAL works as named, e.g. INTERVAL 1 DAY = 24 hours.

So if your script is cron'd to run at 03:00, it will miss the first three hours of records from the 'oldest' day.

To get the whole day use CURDATE() - INTERVAL 1 DAY. This will get back to the beginning of the previous day regardless of when the script is run.

How to hide element using Twitter Bootstrap and show it using jQuery?

Recently ran into this when upgrading from 2.3 to 3.1; our jQuery animations (slideDown) broke because we were putting hide on the elements in the page template. We went the route of creating name-spaced versions of Bootstrap classes that now carry the ugly !important rule.

.rb-hide { display: none; }
.rb-pull-left { float: left; }
etc...

Maven: Failed to read artifact descriptor

I solved this issue by deleting in the repository folders where this error was shown everything except the .jar and .pom files.

Line break in HTML with '\n'

You could use the <pre> tag

_x000D_
_x000D_
<div class="text">_x000D_
<pre>_x000D_
  abc_x000D_
  def_x000D_
  ghi_x000D_
</pre>_x000D_
  abc_x000D_
  def_x000D_
  ghi_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to close Browser Tab After Submitting a Form?

If you have to use the same page as the action, you cannot use onSubmit="window.close();" as it will close the window before the response is received. You have to dinamycally output a JS snippet that closes the window after the SQL data is processed. It would however be far more elegant to use another page as the form action.

Align Div at bottom on main Div

Please try this:

#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;

-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;

-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}

Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.

How to automatically indent source code?

In Visual Studio 2010

Ctrl +k +d indent the complete page.

Ctrl +k +f indent the selected Code.

For more help visit : http://msdn.microsoft.com/en-us/library/da5kh0wa.aspx

every thing is there.

What are the parameters for the number Pipe - Angular 2

From the DOCS

Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.

SYNTAX:

number_expression | number[:digitInfo[:locale]]

where expression is a number:

digitInfo is a string which has a following format:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
  • minIntegerDigits is the minimum number of integer digits to use.Defaults to 1
  • minFractionDigits is the minimum number of digits
  • after fraction. Defaults to 0. maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.
  • locale is a string defining the locale to use (uses the current LOCALE_ID by default)

DEMO

Handling ExecuteScalar() when no results are returned

Try this code, it appears to solve your problem.

Dim MaxID As Integer = Convert.ToInt32(IIf(IsDBNull(cmd.ExecuteScalar()), 1, cmd.ExecuteScalar()))

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

Create table target_table 
As
Select * 
from source_table 
where 1=2;

Source_table is the table u wanna copy the structure of.

Remove Backslashes from Json Data in JavaScript

Your string is invalid, but assuming it was valid, you'd have to do:

var finalData = str.replace(/\\/g, "");

When you want to replace all the occurences with .replace, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.

Cheers

MaxLength Attribute not generating client-side validation attributes

Try using the [StringLength] attribute:

[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }

That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.

Generate a Hash from string in Javascript

String.prototype.hashCode = function() {
  var hash = 0, i, chr;
  if (this.length === 0) return hash;
  for (i = 0; i < this.length; i++) {
    chr   = this.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
  }
  return hash;
};

Source: http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/

How to do a non-greedy match in grep?

The short answer is using the next regular expression:

(?s)<car .*? model=BMW .*?>.*?</car>
  • (?s) - this makes a match across multiline
  • .*? - matches any character, a number of times in a lazy way (minimal match)

A (little) more complicated answer is:

(?s)<([a-z\-_0-9]+?) .*? model=BMW .*?>.*?</\1>

This will makes possible to match car1 and car2 in the following text

<car1 ... model=BMW ...>
...
...
...
</car1>
<car2 ... model=BMW ...>
...
...
...
</car2>
  • (..) represents a capturing group
  • \1 in this context matches the sametext as most recently matched by capturing group number 1

How to convert local time string to UTC?

First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See its documentation.

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.

Finally, use datetime.astimezone() method to convert the datetime to UTC.

Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":

from datetime import datetime   
import pytz

local = pytz.timezone("America/Los_Angeles")
naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)

From there, you can use the strftime() method to format the UTC datetime as needed:

utc_dt.strftime("%Y-%m-%d %H:%M:%S")

How to read the output from git diff?

Here's the simple example.

diff --git a/file b/file 
index 10ff2df..84d4fa2 100644
--- a/file
+++ b/file
@@ -1,5 +1,5 @@
 line1
 line2
-this line will be deleted
 line4
 line5
+this line is added

Here's an explanation (see details here).

  • --git is not a command, this means it's a git version of diff (not unix)
  • a/ b/ are directories, they are not real. it's just a convenience when we deal with the same file (in my case a/ is in index and b/ is in working directory)
  • 10ff2df..84d4fa2 are blob IDs of these 2 files
  • 100644 is the “mode bits,” indicating that this is a regular file (not executable and not a symbolic link)
  • --- a/file +++ b/file minus signs shows lines in the a/ version but missing from the b/ version; and plus signs shows lines missing in a/ but present in b/ (in my case --- means deleted lines and +++ means added lines in b/ and this the file in the working directory)
  • @@ -1,5 +1,5 @@ in order to understand this it's better to work with a big file; if you have two changes in different places you'll get two entries like @@ -1,5 +1,5 @@; suppose you have file line1 ... line100 and deleted line10 and add new line100 - you'll get:
@@ -7,7 +7,6 @@ line6
 line7
 line8
 line9
-this line10 to be deleted
 line11
 line12
 line13
@@ -98,3 +97,4 @@ line97
 line98
 line99
 line100
+this is new line100

How to add Tomcat Server in eclipse

Most of the time when we download tomcat and extract the file a folder will be created:

C:\Program Files\apache-tomcat-9.0.1-windows-x64

Inside that actual tomcat folder will be there:

C:\Program Files\apache-tomcat-9.0.1-windows-x64\apache-tomcat-9.0.1

so while selecting you need to select inner folder:

C:\Program Files\apache-tomcat-9.0.1-windows-x64\apache-tomcat-9.0.1

instead of the outer.

WPF ListView - detect when selected item is clicked

You can handle the ListView's PreviewMouseLeftButtonUp event. The reason not to handle the PreviewMouseLeftButtonDown event is that, by the time when you handle the event, the ListView's SelectedItem may still be null.

XAML:

<ListView ... PreviewMouseLeftButtonUp="listView_Click"> ...

Code behind:

private void listView_Click(object sender, RoutedEventArgs e)
{
    var item = (sender as ListView).SelectedItem;
    if (item != null)
    {
        ...
    }
}

Multiple radio button groups in MVC 4 Razor

I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.

    @Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes

    @Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No

handle textview link click in my android app

Solution

I have implemented a small class with the help of which you can handle long clicks on TextView itself and Taps on the links in the TextView.

Layout

TextView android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autoLink="all"/>

TextViewClickMovement.java

import android.content.Context;
import android.text.Layout;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Patterns;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;

public class TextViewClickMovement extends LinkMovementMethod {

    private final String TAG = TextViewClickMovement.class.getSimpleName();

    private final OnTextViewClickMovementListener mListener;
    private final GestureDetector                 mGestureDetector;
    private TextView                              mWidget;
    private Spannable                             mBuffer;

    public enum LinkType {

        /** Indicates that phone link was clicked */
        PHONE,

        /** Identifies that URL was clicked */
        WEB_URL,

        /** Identifies that Email Address was clicked */
        EMAIL_ADDRESS,

        /** Indicates that none of above mentioned were clicked */
        NONE
    }

    /**
     * Interface used to handle Long clicks on the {@link TextView} and taps
     * on the phone, web, mail links inside of {@link TextView}.
     */
    public interface OnTextViewClickMovementListener {

        /**
         * This method will be invoked when user press and hold
         * finger on the {@link TextView}
         *
         * @param linkText Text which contains link on which user presses.
         * @param linkType Type of the link can be one of {@link LinkType} enumeration
         */
        void onLinkClicked(final String linkText, final LinkType linkType);

        /**
         *
         * @param text Whole text of {@link TextView}
         */
        void onLongClick(final String text);
    }


    public TextViewClickMovement(final OnTextViewClickMovementListener listener, final Context context) {
        mListener        = listener;
        mGestureDetector = new GestureDetector(context, new SimpleOnGestureListener());
    }

    @Override
    public boolean onTouchEvent(final TextView widget, final Spannable buffer, final MotionEvent event) {

        mWidget = widget;
        mBuffer = buffer;
        mGestureDetector.onTouchEvent(event);

        return false;
    }

    /**
     * Detects various gestures and events.
     * Notify users when a particular motion event has occurred.
     */
    class SimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent event) {
            // Notified when a tap occurs.
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            // Notified when a long press occurs.
            final String text = mBuffer.toString();

            if (mListener != null) {
                Log.d(TAG, "----> Long Click Occurs on TextView with ID: " + mWidget.getId() + "\n" +
                                  "Text: " + text + "\n<----");

                mListener.onLongClick(text);
            }
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent event) {
            // Notified when tap occurs.
            final String linkText = getLinkText(mWidget, mBuffer, event);

            LinkType linkType = LinkType.NONE;

            if (Patterns.PHONE.matcher(linkText).matches()) {
                linkType = LinkType.PHONE;
            }
            else if (Patterns.WEB_URL.matcher(linkText).matches()) {
                linkType = LinkType.WEB_URL;
            }
            else if (Patterns.EMAIL_ADDRESS.matcher(linkText).matches()) {
                linkType = LinkType.EMAIL_ADDRESS;
            }

            if (mListener != null) {
                Log.d(TAG, "----> Tap Occurs on TextView with ID: " + mWidget.getId() + "\n" +
                                  "Link Text: " + linkText + "\n" +
                                  "Link Type: " + linkType + "\n<----");

                mListener.onLinkClicked(linkText, linkType);
            }

            return false;
        }

        private String getLinkText(final TextView widget, final Spannable buffer, final MotionEvent event) {

            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

            if (link.length != 0) {
                return buffer.subSequence(buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0])).toString();
            }

            return "";
        }
    }
}

Usage

TextView tv = (TextView) v.findViewById(R.id.textview);
tv.setText(Html.fromHtml("<a href='test'>test</a>"));
textView.setMovementMethod(new TextViewClickMovement(this, context));

Links

Hope this helps! You can find code here.

Windows equivalent of the 'tail' command

set /p line= < file.csv 
echo %line%

it will return first line of your file in cmd Windows in variable %line%.

Direct method from SQL command text to DataSet

Just finish it up.

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
    DataSet ds = new DataSet();
    using (SqlCommand cmd = new SqlCommand(
        sqlCommand, new SqlConnection(connectionString)))
    {
        cmd.Connection.Open();
        DataTable table = new DataTable();
        table.Load(cmd.ExecuteReader());
        ds.Tables.Add(table);
    }
    return ds;
}

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

Make sure you verify your setting for "Prefer 32-bit". In my case Visual Studio 2012 had this setting checked by default. Trying to use anything from an external DLL failed until I unchecked "Prefer 32-bit".

enter image description here

The split() method in Java does not work on a dot (.)

The method takes a regular expression, not a string, and the dot has a special meaning in regular expressions. Escape it like so split("\\."). You need a double backslash, the second one escapes the first.

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Using the old mysql_native_password works:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YourRootPassword';
-- or
CREATE USER 'foo'@'%' IDENTIFIED WITH mysql_native_password BY 'bar';
-- then
FLUSH PRIVILEGES;

This is because caching_sha2_password is introduced in MySQL 8.0, but the Node.js version is not implemented yet. You can see this pull request and this issue for more information. Probably a fix will come soon!

What is the difference between call and apply?

While this is an old topic, I just wanted to point out that .call is slightly faster than .apply. I can't tell you exactly why.

See jsPerf, http://jsperf.com/test-call-vs-apply/3


[UPDATE!]

Douglas Crockford mentions briefly the difference between the two, which may help explain the performance difference... http://youtu.be/ya4UHuXNygM?t=15m52s

Apply takes an array of arguments, while Call takes zero or more individual parameters! Ah hah!

.apply(this, [...])

.call(this, param1, param2, param3, param4...)

TypeError: 'str' object is not callable (Python)

In my case, I had a Class with a method in it. The method did not have 'self' as the first parameter and the error was being thrown when I made a call to the method. Once I added 'self,' to the method's parameter list, it was fine.

How to find MAC address of an Android device programmatically

See this post where I have submitted Utils.java example to provide pure-java implementations and works without WifiManager. Some android devices may not have wifi available or are using ethernet wiring.

Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6 

How can I set up an editor to work with Git on Windows?

Building on Darren's answer, to use Notepad++ you can simply do this (all on one line):

git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

Obviously, the C:/Program Files/Notepad++/notepad++.exe part should be the path to the Notepad++ executable on your system. For example, it might be C:/Program Files (x86)/Notepad++/notepad++.exe.

It works like a charm for me.

"elseif" syntax in JavaScript

Actually, technically when indented properly, it would be:

if (condition) {
    ...
} else {
    if (condition) {
        ...
    } else {
        ...
    }
}

There is no else if, strictly speaking.

(Update: Of course, as pointed out, the above is not considered good style.)

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

With these two steps we can check if it LL(1) or not. Both of them have to be satisfied.

1.If we have the production:A->a1|a2|a3|a4|.....|an. Then,First(a(i)) intersection First(a(j)) must be phi(empty set)[a(i)-a subscript i.]

2.For every non terminal 'A',if First(A) contains epsilon Then First(A) intersection Follow(A) must be phi(empty set).

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

Passing no-sandbox to exec seems important for jenkins on windows in foreground or as service. Here's my solution

chromedriver fails on windows jenkins slave running in foreground

Python coding standards/best practices

To add to bhadra's list of idiomatic guides:

Checkout Anthony Baxter's presentation on Effective Python Programming (from OSON 2005).

An excerpt:

# dict's setdefault method turns this:
if key in dictobj:
    dictobj[key].append(val)
else:
    dictobj[key] = [val]
# into this:
dictobj.setdefault(key,[]).append(val)

Mount current directory as a volume in Docker on Windows 10

This command should fix it.

docker run --rm -it -v ${PWD}:c:\data mirkohaaser/docker-clitools

{PWD} is the host current folder. after the : is the container folder. If the mounting is correct then files will be listed in the director c:\data in the container.

Required maven dependencies for Apache POI to work

For an excel writer you might need the following:

            <dependency>
              <groupId>org.apache.poi</groupId>
              <artifactId>poi</artifactId>
              <version>3.10-FINAL</version>
           </dependency>


        <dependency>
             <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${apache.poi.version}</version>
       </dependency>

How to read Data from Excel sheet in selenium webdriver

i have used following method to use input data from excel sheet: Need to import following as well

import jxl.Workbook;

then

Workbook wBook = Workbook.getWorkbook(new File("E:\\Testdata\\ShellData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0); 
//Now in application i have given my Username and Password input in following way
driver.findElement(By.xpath("//input[@id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[@name='Login']")).click();

it will Work

setting content between div tags using javascript

See Creating and modifying HTML at what used to be called the Web Standards Curriculum.

Use the createElement, createTextNode and appendChild methods.

How can I save application settings in a Windows Forms application?

Other options, instead of using a custom XML file, we can use a more user friendly file format: JSON or YAML file.

  • If you use .NET 4.0 dynamic, this library is really easy to use (serialize, deserialize, nested objects support and ordering output as you wish + merging multiple settings to one) JsonConfig (usage is equivalent to ApplicationSettingsBase)
  • For .NET YAML configuration library... I haven't found one that is as easy to use as JsonConfig

You can store your settings file in multiple special folders (for all users and per user) as listed here Environment.SpecialFolder Enumeration and multiple files (default read only, per role, per user, etc.)

If you choose to use multiple settings, you can merge those settings: For example, merging settings for default + BasicUser + AdminUser. You can use your own rules: the last one overrides the value, etc.

Organizing a multiple-file Go project

I have studied a number of Go projects and there is a fair bit of variation. You can kind of tell who is coming from C and who is coming from Java, as the former dump just about everything in the projects root directory in a main package, and the latter tend to put everything in a src directory. Neither is optimal however. Each have consequences because they affect import paths and how others can reuse them.

To get the best results I have worked out the following approach.

myproj/
  main/
    mypack.go
  mypack.go

Where mypack.go is package mypack and main/mypack.go is (obviously) package main.

If you need additional support files you have two choices. Either keep them all in the root directory, or put private support files in a lib subdirectory. E.g.

myproj/
  main/
    mypack.go
  myextras/
    someextra.go
  mypack.go
  mysupport.go

Or

myproj.org/
  lib/
    mysupport.go
    myextras/
      someextra.go
  main/
    mypack.go
  mypage.go

Only put the files in a lib directory if they are not intended to be imported by another project. In other words, if they are private support files. That's the idea behind having lib --to separate public from private interfaces.

Doing things this way will give you a nice import path, myproj.org/mypack to reuse the code in other projects. If you use lib then internal support files will have an import path that is indicative of that, myproj.org/lib/mysupport.

When building the project, use main/mypack, e.g. go build main/mypack. If you have more than one executable you can also separate those under main without having to create separate projects. e.g. main/myfoo/myfoo.go and main/mybar/mybar.go.

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

Make element fixed on scroll

Here you go, no frameworks, short and simple:

var el = document.getElementById('elId');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;

window.addEventListener('scroll', function(){
    if (document.documentElement.scrollTop > elTop){
        el.style.position = 'fixed';
        el.style.top = '0px';
    }
    else
    {
        el.style.position = 'static';
        el.style.top = 'auto';
    }
});

CSS /JS to prevent dragging of ghost image?

Handle the dragstart event and return false.

How to edit .csproj file

in vs 2019 Version 16.8.2 right click on you project name and click on "Edit Project File" enter image description here

Get user input from textarea

Remove the spaces around your =:

<div>    
  <input type="text" [(ngModel)]="str" name="str">
</div>

But you need to have the variable named str on back-end, than its should work fine.

MySQL LIKE IN()?

Just a little tip:

I prefer to use the variant RLIKE (exactly the same command as REGEXP) as it sounds more like natural language, and is shorter; well, just 1 char.

The "R" prefix is for Reg. Exp., of course.

React: Expected an assignment or function call and instead saw an expression

The return statements should place in one line. Or the other option is to remove the curly brackets that bound the HTML statement.

example:

return posts.map((post, index) =>
    <div key={index}>
      <h3>{post.title}</h3>
      <p>{post.body}</p>
    </div>
);

How to run SUDO command in WinSCP to transfer files from Windows to linux

I know this is old, but it is actually very possible.

  • Go to your WinSCP profile (Session > Sites > Site Manager)

  • Click on Edit > Advanced... > Environment > SFTP

  • Insert sudo su -c /usr/lib/sftp-server in "SFTP Server" (note this path might be different in your system)

  • Save and connect

Source

AWS Ubuntu 18.04: enter image description here

Quick easy way to migrate SQLite3 to MySQL?

This script is ok except for this case that of course, I've met :

INSERT INTO "requestcomparison_stopword" VALUES(149,'f');
INSERT INTO "requestcomparison_stopword" VALUES(420,'t');

The script should give this output :

INSERT INTO requestcomparison_stopword VALUES(149,'f');
INSERT INTO requestcomparison_stopword VALUES(420,'t');

But gives instead that output :

INSERT INTO requestcomparison_stopword VALUES(1490;
INSERT INTO requestcomparison_stopword VALUES(4201;

with some strange non-ascii characters around the last 0 and 1.

This didn't show up anymore when I commented the following lines of the code (43-46) but others problems appeared:


    line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
    line = line.replace('THIS_IS_TRUE', '1')
    line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
    line = line.replace('THIS_IS_FALSE', '0')

This is just a special case, when we want to add a value being 'f' or 't' but I'm not really comfortable with regular expressions, I just wanted to spot this case to be corrected by someone.

Anyway thanks a lot for that handy script !!!

Multi-dimensional arrays in Bash

Lots of answers found here for creating multidimensional arrays in bash.

And without exception, all are obtuse and difficult to use.

If MD arrays are a required criteria, it is time to make a decision:

Use a language that supports MD arrays

My preference is Perl. Most would probably choose Python. Either works.

Store the data elsewhere

JSON and jq have already been suggested. XML has also been suggested, though for your use JSON and jq would likely be simpler.

It would seem though that Bash may not be the best choice for what you need to do.

Sometimes the correct question is not "How do I do X in tool Y?", but rather "Which tool would be best to do X?"

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

Cannot find R.layout.activity_main

In my case , i accidentally imported my library's R. class not my app module's R. After editing this, it is resolved.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

#1071 - Specified key was too long; max key length is 767 bytes

Just changing utf8mb4 to utf8 when creating tables solved my problem. For example: CREATE TABLE ... DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; to CREATE TABLE ... DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;.

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

This should make it work in both cases

function onDateChange() {
   // Do something here
}

$('#dpd1').bind('changeDate', onDateChange);
$('#dpd1').bind('input', onDateChange);

How to ping multiple servers and return IP address and Hostnames using batch script?

This worked great I just add the -a option to ping to resolve the hostname. Thanks https://stackoverflow.com/users/4447323/wombat

@echo off setlocal enabledelayedexpansion set OUTPUT_FILE=result.csv

>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
    set SERVER_ADDRESS_I=UNRESOLVED
    set SERVER_ADDRESS_L=UNRESOLVED
    for /f "tokens=1,2,3" %%x in ('ping -n 1 -a %%i ^&^& echo SERVER_IS_UP') do (
    if %%x==Pinging set SERVER_ADDRESS_L=%%y
    if %%x==Pinging set SERVER_ADDRESS_I=%%z
        if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
    )
    echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
    echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

You use this command in phpMyAdmin SQL Part:

GRANT SELECT , INSERT , UPDATE , DELETE ON phpmyadmin.* TO  `pma`@`localhost` IDENTIFIED BY  ''

How to change fonts in matplotlib (python)?

The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):

import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')

plt.show()

print(fpath) will show you where you should put the .ttf.

You can see the output here: https://matplotlib.org/gallery/api/font_file.html

Declare variable in SQLite and use it

Try using Binding Values. You cannot use variables as you do in T-SQL but you can use "parameters". I hope the following link is usefull.Binding Values

How to set the maximum memory usage for JVM?

You shouldn't have to worry about the stack leaking memory (it is highly uncommon). The only time you can have the stack get out of control is with infinite (or really deep) recursion.

This is just the heap. Sorry, didn't read your question fully at first.

You need to run the JVM with the following command line argument.

-Xmx<ammount of memory>

Example:

-Xmx1024m

That will allow a max of 1GB of memory for the JVM.

What is mod_php?

This answer is taken from TuxRadar:

When running PHP through your web server, there are two distinct options: running it using PHP's CGI SAPI, or running it as a module for the web server. Each have their own benefits, but, overall, the module is generally preferred.

Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable, giving it the script you called, each time you visit a page. That means each time you load a page, PHP needs to read php.ini and set its settings, it needs to load all its extensions, and then it needs to start work parsing the script - there is a lot of repeated work.

When you run PHP as a module, PHP literally sits inside your web server - it starts only once, loads its settings and extensions only once, and can also store information across sessions. For example, PHP accelerators rely on PHP being able to save cached data across requests, which is impossible using the CGI version.

The obvious advantage of using PHP as a module is speed - you will see a big speed boost if you convert from CGI to a module. Many people, particularly Windows users, do not realise this, and carry on using the php.exe CGI SAPI, which is a shame - the module is usually three to five times faster.

There is one key advantage to using the CGI version, though, and that is that PHP reads its settings every time you load a page. With PHP running as a module, any changes you make in the php.ini file do not kick in until you restart your web server, which makes the CGI version preferable if you are testing a lot of new settings and want to see instant responses.

How do you configure HttpOnly cookies in tomcat / java webapps?

also it should be noted that turning on HttpOnly will break applets that require stateful access back to the jvm.

the Applet http requests will not use the jsessionid cookie and may get assigned to a different tomcat.

How to set image button backgroundimage for different state?

what you are trying to do is more a segmentedbutton than an imagebutton list.

here http://blog.bookworm.at/2010/10/segmented-controls-in-android.html is an example on how to do so. The basic idea is to customize RadioButton instead of ImageButton, since the RadioButton will have the checked state you need

Setting DEBUG = False causes 500 Error

I know this is late but I ended up here with a search for my error 500 with DEBUG=False, in my case it did turn out to be the ALLOWED_HOSTS but I was using os.environ.get('variable') to populate the hosts, I did not notice this until I enabled logging, you can log all errors to file with the below and it will log even when DEBUG=False:

# settings.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers':['file'],
            'propagate': True,
            'level':'DEBUG',
        },
        'MYAPP': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }
}

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Great Explanation from the link : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx

Let's First look at MVC

The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.

There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.

There is one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.

The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.

MVP – Model View Presenter

Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:

The input begins with the View, not the Presenter.

There is a one-to-one mapping between the View and the associated Presenter.

The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.

The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.

MVVM – Model View View Model

So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:

The input begins with the View, not the View Model.

While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View could share the same View Model.

Base64: java.lang.IllegalArgumentException: Illegal character

The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.

For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.

static String getBase64EncodedCipherText(String cipherText) {
    byte[] cText = cipherText.getBytes();
    // return an ISO-8859-1 encoded String
    return Base64.getEncoder().encodeToString(cText);
}

static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
    return new String((Base64.getDecoder().decode(encodedCipherText)));
}

public static void main(String[] args) {
    try {
        String cText = getRawCipherText(null, "Hello World of Encryption...");

        System.out.println("Text to encrypt/encode: Hello World of Encryption...");
        // This output is a simple sanity check to display that the text
        // has indeed been converted to a cipher text which 
        // is unreadable by all but the most intelligent of programmers.
        // It is absolutely inhuman of me to do such a thing, but I am a
        // rebel and cannot be trusted in any way.  Please look away.
        System.out.println("RAW CIPHER TEXT: " + cText);
        cText = getBase64EncodedCipherText(cText);
        System.out.println("BASE64 ENCODED: " + cText);
        // There he goes again!!
        System.out.println("BASE64 DECODED:  " + getBase64DecodedCipherText(cText));
        System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

The output looks like:

Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED:  q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...

How does one create an InputStream from a String?

You could do this:

InputStream in = new ByteArrayInputStream(string.getBytes("UTF-8"));

Note the UTF-8 encoding. You should specify the character set that you want the bytes encoded into. It's common to choose UTF-8 if you don't specifically need anything else. Otherwise if you select nothing you'll get the default encoding that can vary between systems. From the JavaDoc:

The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

SQLite select where empty?

There are several ways, like:

where some_column is null or some_column = ''

or

where ifnull(some_column, '') = ''

or

where coalesce(some_column, '') = ''

of

where ifnull(length(some_column), 0) = 0

How to merge two json string in Python?

You can load both json strings into Python Dictionaries and then combine. This will only work if there are unique keys in each json string.

import json

a = json.loads(jsonStringA)
b = json.loads(jsonStringB)
c = dict(a.items() + b.items())
# or c =  dict(a, **b)

When to use references vs. pointers

It is not a matter of taste. Here are some definitive rules.

If you want to refer to a statically declared variable within the scope in which it was declared then use a C++ reference, and it will be perfectly safe. The same applies to a statically declared smart pointer. Passing parameters by reference is an example of this usage.

If you want to refer to anything from a scope that is wider than the scope in which it is declared then you should use a reference counted smart pointer for it to be perfectly safe.

You can refer to an element of a collection with a reference for syntactic convenience, but it is not safe; the element can be deleted at anytime.

To safely hold a reference to an element of a collection you must use a reference counted smart pointer.

SQL select statements with multiple tables

Like that:

SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299'

How do I get the last character of a string?

The other answers are very complete, and you should definitely use them if you're trying to find the last character of a string. But if you're just trying to use a conditional (e.g. is the last character 'g'), you could also do the following:

if (str.endsWith("g")) {

or, strings

if (str.endsWith("bar")) {

Get User's Current Location / Coordinates

Import library like:

import CoreLocation

set Delegate:

CLLocationManagerDelegate

Take variable like:

var locationManager:CLLocationManager!

On viewDidLoad() write this pretty code:

 locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

    if CLLocationManager.locationServicesEnabled(){
        locationManager.startUpdatingLocation()
    }

Write CLLocation delegate methods:

    //MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation :CLLocation = locations[0] as CLLocation

    print("user latitude = \(userLocation.coordinate.latitude)")
    print("user longitude = \(userLocation.coordinate.longitude)")

    self.labelLat.text = "\(userLocation.coordinate.latitude)"
    self.labelLongi.text = "\(userLocation.coordinate.longitude)"

    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
        if (error != nil){
            print("error in reverseGeocode")
        }
        let placemark = placemarks! as [CLPlacemark]
        if placemark.count>0{
            let placemark = placemarks![0]
            print(placemark.locality!)
            print(placemark.administrativeArea!)
            print(placemark.country!)

            self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
        }
    }

}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Error \(error)")
}

Now set permission for access the location, so add these key value into your info.plist file

 <key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location?</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>

enter image description here

100% working without any issue. TESTED

How to display HTML in TextView?

Use below code to get the solution:

textView.setText(fromHtml("<Your Html Text>"))

Utitilty Method

public static Spanned fromHtml(String text)
{
    Spanned result;
    if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        result = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);
    } else {
        result = Html.fromHtml(text);
    }
    return result;
}

Regex AND operator

It is impossible for both (?=foo) and (?=baz) to match at the same time. It would require the next character to be both f and b simultaneously which is impossible.

Perhaps you want this instead:

(?=.*foo)(?=.*baz)

This says that foo must appear anywhere and baz must appear anywhere, not necessarily in that order and possibly overlapping (although overlapping is not possible in this specific case because the letters themselves don't overlap).

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

Module not found: Error: Can't resolve 'core-js/es6'

After Migrated to Angular8, core-js/es6 or core-js/es7 Will not work.

You have to simply replace import core-js/es/

For ex.

import 'core-js/es6/symbol'  

to

import 'core-js/es/symbol'

This will work properly.

Github "Updates were rejected because the remote contains work that you do not have locally."

If this is your first push

just change the

git push <repo name> master

change it like this!

git push -f <repo name> master

What's the reason I can't create generic array types in Java?

It is because generics were added on to java after they made it, so its kinda clunky because the original makers of java thought that when making an array the type would be specified in the making of it. So that does not work with generics so you have to do E[] array=(E[]) new Object[15]; This compiles but it gives a warning.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

VS 2010 Express is no longer linked to any VS Express pages (that I found). I did find this link to the ISO which I used and it fixed the errors mentioned here.

http://download.microsoft.com/download/1/E/5/1E5F1C0A-0D5B-426A-A603-1798B951DDAE/VS2010Express1.iso

Note: Also make sure you have x86 everything (Python + Postgresql) or you'll get other errors. I did not try x64 everything.

How to split a string into an array in Bash?

The key to splitting your string into an array is the multi character delimiter of ", ". Any solution using IFS for multi character delimiters is inherently wrong since IFS is a set of those characters, not a string.

If you assign IFS=", " then the string will break on EITHER "," OR " " or any combination of them which is not an accurate representation of the two character delimiter of ", ".

You can use awk or sed to split the string, with process substitution:

#!/bin/bash

str="Paris, France, Europe"
array=()
while read -r -d $'\0' each; do   # use a NUL terminated field separator 
    array+=("$each")
done < <(printf "%s" "$str" | awk '{ gsub(/,[ ]+|$/,"\0"); print }')
declare -p array
# declare -a array=([0]="Paris" [1]="France" [2]="Europe") output

It is more efficient to use a regex you directly in Bash:

#!/bin/bash

str="Paris, France, Europe"

array=()
while [[ $str =~ ([^,]+)(,[ ]+|$) ]]; do
    array+=("${BASH_REMATCH[1]}")   # capture the field
    i=${#BASH_REMATCH}              # length of field + delimiter
    str=${str:i}                    # advance the string by that length
done                                # the loop deletes $str, so make a copy if needed

declare -p array
# declare -a array=([0]="Paris" [1]="France" [2]="Europe") output...

With the second form, there is no sub shell and it will be inherently faster.


Edit by bgoldst: Here are some benchmarks comparing my readarray solution to dawg's regex solution, and I also included the read solution for the heck of it (note: I slightly modified the regex solution for greater harmony with my solution) (also see my comments below the post):

## competitors
function c_readarray { readarray -td '' a < <(awk '{ gsub(/, /,"\0"); print; };' <<<"$1, "); unset 'a[-1]'; };
function c_read { a=(); local REPLY=''; while read -r -d ''; do a+=("$REPLY"); done < <(awk '{ gsub(/, /,"\0"); print; };' <<<"$1, "); };
function c_regex { a=(); local s="$1, "; while [[ $s =~ ([^,]+),\  ]]; do a+=("${BASH_REMATCH[1]}"); s=${s:${#BASH_REMATCH}}; done; };

## helper functions
function rep {
    local -i i=-1;
    for ((i = 0; i<$1; ++i)); do
        printf %s "$2";
    done;
}; ## end rep()

function testAll {
    local funcs=();
    local args=();
    local func='';
    local -i rc=-1;
    while [[ "$1" != ':' ]]; do
        func="$1";
        if [[ ! "$func" =~ ^[_a-zA-Z][_a-zA-Z0-9]*$ ]]; then
            echo "bad function name: $func" >&2;
            return 2;
        fi;
        funcs+=("$func");
        shift;
    done;
    shift;
    args=("$@");
    for func in "${funcs[@]}"; do
        echo -n "$func ";
        { time $func "${args[@]}" >/dev/null 2>&1; } 2>&1| tr '\n' '/';
        rc=${PIPESTATUS[0]}; if [[ $rc -ne 0 ]]; then echo "[$rc]"; else echo; fi;
    done| column -ts/;
}; ## end testAll()

function makeStringToSplit {
    local -i n=$1; ## number of fields
    if [[ $n -lt 0 ]]; then echo "bad field count: $n" >&2; return 2; fi;
    if [[ $n -eq 0 ]]; then
        echo;
    elif [[ $n -eq 1 ]]; then
        echo 'first field';
    elif [[ "$n" -eq 2 ]]; then
        echo 'first field, last field';
    else
        echo "first field, $(rep $[$1-2] 'mid field, ')last field";
    fi;
}; ## end makeStringToSplit()

function testAll_splitIntoArray {
    local -i n=$1; ## number of fields in input string
    local s='';
    echo "===== $n field$(if [[ $n -ne 1 ]]; then echo 's'; fi;) =====";
    s="$(makeStringToSplit "$n")";
    testAll c_readarray c_read c_regex : "$s";
}; ## end testAll_splitIntoArray()

## results
testAll_splitIntoArray 1;
## ===== 1 field =====
## c_readarray   real  0m0.067s   user 0m0.000s   sys  0m0.000s
## c_read        real  0m0.064s   user 0m0.000s   sys  0m0.000s
## c_regex       real  0m0.000s   user 0m0.000s   sys  0m0.000s
##
testAll_splitIntoArray 10;
## ===== 10 fields =====
## c_readarray   real  0m0.067s   user 0m0.000s   sys  0m0.000s
## c_read        real  0m0.064s   user 0m0.000s   sys  0m0.000s
## c_regex       real  0m0.001s   user 0m0.000s   sys  0m0.000s
##
testAll_splitIntoArray 100;
## ===== 100 fields =====
## c_readarray   real  0m0.069s   user 0m0.000s   sys  0m0.062s
## c_read        real  0m0.065s   user 0m0.000s   sys  0m0.046s
## c_regex       real  0m0.005s   user 0m0.000s   sys  0m0.000s
##
testAll_splitIntoArray 1000;
## ===== 1000 fields =====
## c_readarray   real  0m0.084s   user 0m0.031s   sys  0m0.077s
## c_read        real  0m0.092s   user 0m0.031s   sys  0m0.046s
## c_regex       real  0m0.125s   user 0m0.125s   sys  0m0.000s
##
testAll_splitIntoArray 10000;
## ===== 10000 fields =====
## c_readarray   real  0m0.209s   user 0m0.093s   sys  0m0.108s
## c_read        real  0m0.333s   user 0m0.234s   sys  0m0.109s
## c_regex       real  0m9.095s   user 0m9.078s   sys  0m0.000s
##
testAll_splitIntoArray 100000;
## ===== 100000 fields =====
## c_readarray   real  0m1.460s   user 0m0.326s   sys  0m1.124s
## c_read        real  0m2.780s   user 0m1.686s   sys  0m1.092s
## c_regex       real  17m38.208s   user 15m16.359s   sys  2m19.375s
##

Why does an onclick property set with setAttribute fail to work in IE?

to make this work in both FF and IE you must write both ways:


    button_element.setAttribute('onclick','doSomething();'); // for FF
    button_element.onclick = function() {doSomething();}; // for IE

thanks to this post.

UPDATE: This is to demonstrate that sometimes it is necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:

// get old onclick attribute
var onclick = button_element.getAttribute("onclick");  

// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") { 
    button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome

// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
    button_element.onclick = function() { 
        doSomething();
        onclick();
    }; // for IE7
}

Pseudo-terminal will not be allocated because stdin is not a terminal

Try ssh -t -t(or ssh -tt for short) to force pseudo-tty allocation even if stdin isn't a terminal.

See also: Terminating SSH session executed by bash script

From ssh manpage:

-T      Disable pseudo-tty allocation.

-t      Force pseudo-tty allocation.  This can be used to execute arbitrary 
        screen-based programs on a remote machine, which can be very useful,
        e.g. when implementing menu services.  Multiple -t options force tty
        allocation, even if ssh has no local tty.

Using ffmpeg to encode a high quality video

Make sure the PNGs are fully opaque before creating the video

e.g. with imagemagick, give them a black background:

convert 0.png -background black -flatten +matte 0_opaque.png

From my tests, no bitrate or codec is sufficient to make the video look good if you feed ffmpeg PNGs with transparency

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

An alternative that always exists for learning purpose is to build your custom collector through Collector.of() though toMap() JDK collector here is succinct (+1 here) .

Map<String,Integer> newMap = givenMap.
                entrySet().
                stream().collect(Collector.of
               ( ()-> new HashMap<String,Integer>(),
                       (mutableMap,entryItem)-> mutableMap.put(entryItem.getKey(),Integer.parseInt(entryItem.getValue())),
                       (map1,map2)->{ map1.putAll(map2); return map1;}
               ));

Display Back Arrow on Toolbar

Easily you can do it.

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

Credits: https://freakycoder.com/android-notes-24-how-to-add-back-button-at-toolbar-941e6577418e

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

Is it safe to expose Firebase apiKey to the public?

You should not expose this info. in public, specially api keys. It may lead to a privacy leak.

Before making the website public you should hide it. You can do it in 2 or more ways

  1. Complex coding/hiding
  2. Simply put firebase SDK codes at bottom of your website or app thus firebase automatically does all works. you don't need to put API keys anywhere

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

this is how I implement it .

let dictionary = self.convertStringToDictionary(responceString)            
     NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SOCKET_UPDATE"), object: dictionary)

How to get row number from selected rows in Oracle

you can just do

select rownum, l.* from student  l where name like %ram%

this assigns the row number as the rows are fetched (so no guaranteed ordering of course).

if you wanted to order first do:

select rownum, l.*
  from (select * from student l where name like %ram% order by...) l;

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

We're using Jira 6.2 and I use this query:

updatedDate > startOfDay(-1d) AND updatedDate < endOfDay(-1)

to return all of the issues that were updated from the previous day. You can combine with whichever queries you want to return the appropriate issues for the previous day.

Hibernate show real SQL

If you can already see the SQL being printed, that means you have the code below in your hibernate.cfg.xml:

<property name="show_sql">true</property>

To print the bind parameters as well, add the following to your log4j.properties file:

log4j.logger.net.sf.hibernate.type=debug

Java - Change int to ascii

You can convert a number to ASCII in java. example converting a number 1 (base is 10) to ASCII.

char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));

Output:

Character: 1
Character: 49

How to load a resource from WEB-INF directory of a web archive

Here is how it works for me with no Servlet use.

Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml

  1. In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )

  2. Now let's use class loader:

    InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
    

Adding three months to a date in PHP

I assume by "didn't work" you mean that it's giving you a timestamp instead of the formatted date, because you were doing it correctly:

$effectiveDate = strtotime("+3 months", strtotime($effectiveDate)); // returns timestamp
echo date('Y-m-d',$effectiveDate); // formatted version

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

What's your most controversial programming opinion?

Python does everything that other programming languages do in half the dev time... and so does Google!!! Check out Unladen Swallow if you disagree.

Wait, this is a fact. Does it still qualify as an answer to this question?

What is the height of iPhone's onscreen keyboard?

version note: this is no longer value in iOS 9 & 10, as they support custom keyboard sizes.

This depends on the model and the QuickType bar:

enter image description here

http://www.idev101.com/code/User_Interface/sizes.html

file_put_contents(meta/services.json): failed to open stream: Permission denied

Try again with chmod -R 755 /var/www/html/test/app/storage. Use with sudo for Operation not permitted in chmod. Use Check owner permission if still having the error.

React setState not updating state

In case of hooks, you should use useEffect hook.

const [fruit, setFruit] = useState('');

setFruit('Apple');

useEffect(() => {
  console.log('Fruit', fruit);
}, [fruit])

Is there an equivalent to background-size: cover and contain for image elements?

Try setting both min-height and min-width, with display:block:

img {
    display:block;
    min-height:100%;
    min-width:100%;
}

(fiddle)

Provided your image's containing element is position:relative or position:absolute, the image will cover the container. However, it will not be centred.

You can easily centre the image if you know whether it will overflow horizontally (set margin-left:-50%) or vertically (set margin-top:-50%). It may be possible to use CSS media queries (and some mathematics) to figure that out.

Set a button group's width to 100% and make buttons equal width?

Bootstrap 4 Solution

<div class="btn-group w-100">
    <button type="button" class="btn">One</button>
    <button type="button" class="btn">Two</button>
    <button type="button" class="btn">Three</button>
</div>

You basically tell the btn-group container to have width 100% by adding w-100 class to it. The buttons inside will fill in the whole space automatically.

Git reset --hard and push to remote repository

To complement Jakub's answer, if you have access to the remote git server in ssh, you can go into the git remote directory and set:

user@remote$ git config receive.denyNonFastforwards false

Then go back to your local repo, try again to do your commit with --force:

user@local$ git push origin +master:master --force

And finally revert the server's setting in the original protected state:

user@remote$ git config receive.denyNonFastforwards true

For a boolean field, what is the naming convention for its getter/setter?

It should just be get{varname} like every other getter. Changing it to "is" doesn't stop bad variable names, it just makes another unnecessary rule.

Consider program generated code, or reflection derivations.

It's a non-useful convention that should be dropped at the first available opportunity.

Finding what branch a Git commit came from

I deal with the same problem (Jenkins multibranch pipeline) - having only commit information and trying to find a branch name where this commit originally came from. It must work for remote branches, local copies are not available.

This is what I work with:

git rev-parse HEAD | xargs git name-rev

Optionally you can strip the output:

git rev-parse HEAD | xargs git name-rev | cut -d' ' -f2 | sed 's/remotes\/origin\///g'

How to remove element from array in forEach loop?

It looks like you are trying to do this?

Iterate and mutate an array using Array.prototype.splice

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

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

var review = ['a', 'b', 'c', 'b', 'a'];

review.forEach(function(item, index, object) {
  if (item === 'a') {
    object.splice(index, 1);
  }
});

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Which works fine for simple case where you do not have 2 of the same values as adjacent array items, other wise you have this problem.

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

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

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

review.forEach(function(item, index, object) {
  if (item === 'a') {
    object.splice(index, 1);
  }
});

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

So what can we do about this problem when iterating and mutating an array? Well the usual solution is to work in reverse. Using ES3 while but you could use for sugar if preferred

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

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

var review = ['a' ,'a', 'b', 'c', 'b', 'a', 'a'],
  index = review.length - 1;

while (index >= 0) {
  if (review[index] === 'a') {
    review.splice(index, 1);
  }

  index -= 1;
}

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Ok, but you wanted to use ES5 iteration methods. Well and option would be to use Array.prototype.filter but this does not mutate the original array but creates a new one, so while you can get the correct answer it is not what you appear to have specified.

We could also use ES5 Array.prototype.reduceRight, not for its reducing property by rather its iteration property, i.e. iterate in reverse.

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

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

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

review.reduceRight(function(acc, item, index, object) {
  if (item === 'a') {
    object.splice(index, 1);
  }
}, []);

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Or we could use ES5 Array.protoype.indexOf like so.

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

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

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'],
  index = review.indexOf('a');

while (index !== -1) {
  review.splice(index, 1);
  index = review.indexOf('a');
}

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

But you specifically want to use ES5 Array.prototype.forEach, so what can we do? Well we need to use Array.prototype.slice to make a shallow copy of the array and Array.prototype.reverse so we can work in reverse to mutate the original array.

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

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

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

review.slice().reverse().forEach(function(item, index, object) {
  if (item === 'a') {
    review.splice(object.length - 1 - index, 1);
  }
});

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Finally ES6 offers us some further alternatives, where we do not need to make shallow copies and reverse them. Notably we can use Generators and Iterators. However support is fairly low at present.

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

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

function* reverseKeys(arr) {
  var key = arr.length - 1;

  while (key >= 0) {
    yield key;
    key -= 1;
  }
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

for (var index of reverseKeys(review)) {
  if (review[index] === 'a') {
    review.splice(index, 1);
  }
}

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Something to note in all of the above is that, if you were stripping NaN from the array then comparing with equals is not going to work because in Javascript NaN === NaN is false. But we are going to ignore that in the solutions as it it yet another unspecified edge case.

So there we have it, a more complete answer with solutions that still have edge cases. The very first code example is still correct but as stated, it is not without issues.

Symfony 2 EntityManager injection in service

Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.

namespace AppBundle\Service;

use Doctrine\ORM\EntityManagerInterface;

class Someclass {
    protected $em;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->em = $entityManager;
    }

    public function somefunction() {
        $em = $this->em;
        ...
    }
}

Ruby function to remove all white spaces?

Also don't forget:

$ s = "   I have white space   ".split
=> ["I", "have", "white", "space"]

@angular/material/index.d.ts' is not a module

I was also facing the same issue with the latest version of @angular/material i.e. "^9.2.3" So I found out a solution of this. If you go to the folder of @angular/material inside node_modules, you can find a file naming index.d.ts, in that file paste the below code. With this change in the index file you will be able to import the modules using import statements from @angular/material directly. (P.S. If you face error in any of the below statements please comment that.)

export * from '@angular/material/core';
export * from '@angular/material/icon';
export * from '@angular/material/autocomplete';
export * from '@angular/material/badge';
export * from '@angular/material/bottom-sheet';
export * from '@angular/material/button';
export * from '@angular/material/button-toggle';
export * from '@angular/material/card';
export * from '@angular/material/checkbox';
export * from '@angular/material/chips';
export * from '@angular/material/stepper';
export * from '@angular/material/datepicker'
export * from '@angular/material/dialog';
export * from '@angular/material/divider';
export * from '@angular/material/esm2015';
export * from '@angular/material/form-field';
export * from '@angular/material/esm5';
export * from '@angular/material/expansion';
export * from '@angular/material/grid-list';
export * from '@angular/material/icon';
export * from '@angular/material/input';
export * from '@angular/material/list';
export * from '@angular/material/menu';
export * from '@angular/material/paginator';
export * from '@angular/material/progress-bar';
export * from '@angular/material/progress-spinner';
export * from '@angular/material/radio';
export * from '@angular/material/stepper';
export * from '@angular/material/select';
export * from '@angular/material/sidenav';
export * from '@angular/material/slider';
export * from '@angular/material/slide-toggle';
export * from '@angular/material/snack-bar';
export * from '@angular/material/sort';
export * from '@angular/material/table';
export * from '@angular/material/tabs';
export * from '@angular/material/toolbar';
export * from '@angular/material/tooltip';
export * from '@angular/material/tree';

How do I check if a string is valid JSON in Python?

You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.

lexers vs parsers

When is lexing enough, when do you need EBNF?

EBNF really doesn't add much to the power of grammars. It's just a convenience / shortcut notation / "syntactic sugar" over the standard Chomsky's Normal Form (CNF) grammar rules. For example, the EBNF alternative:

S --> A | B

you can achieve in CNF by just listing each alternative production separately:

S --> A      // `S` can be `A`,
S --> B      // or it can be `B`.

The optional element from EBNF:

S --> X?

you can achieve in CNF by using a nullable production, that is, the one which can be replaced by an empty string (denoted by just empty production here; others use epsilon or lambda or crossed circle):

S --> B       // `S` can be `B`,
B --> X       // and `B` can be just `X`,
B -->         // or it can be empty.

A production in a form like the last one B above is called "erasure", because it can erase whatever it stands for in other productions (product an empty string instead of something else).

Zero-or-more repetiton from EBNF:

S --> A*

you can obtan by using recursive production, that is, one which embeds itself somewhere in it. It can be done in two ways. First one is left recursion (which usually should be avoided, because Top-Down Recursive Descent parsers cannot parse it):

S --> S A    // `S` is just itself ended with `A` (which can be done many times),
S -->        // or it can begin with empty-string, which stops the recursion.

Knowing that it generates just an empty string (ultimately) followed by zero or more As, the same string (but not the same language!) can be expressed using right-recursion:

S --> A S    // `S` can be `A` followed by itself (which can be done many times),
S -->        // or it can be just empty-string end, which stops the recursion.

And when it comes to + for one-or-more repetition from EBNF:

S --> A+

it can be done by factoring out one A and using * as before:

S --> A A*

which you can express in CNF as such (I use right recursion here; try to figure out the other one yourself as an exercise):

S --> A S   // `S` can be one `A` followed by `S` (which stands for more `A`s),
S --> A     // or it could be just one single `A`.

Knowing that, you can now probably recognize a grammar for a regular expression (that is, regular grammar) as one which can be expressed in a single EBNF production consisting only from terminal symbols. More generally, you can recognize regular grammars when you see productions similar to these:

A -->        // Empty (nullable) production (AKA erasure).
B --> x      // Single terminal symbol.
C --> y D    // Simple state change from `C` to `D` when seeing input `y`.
E --> F z    // Simple state change from `E` to `F` when seeing input `z`.
G --> G u    // Left recursion.
H --> v H    // Right recursion.

That is, using only empty strings, terminal symbols, simple non-terminals for substitutions and state changes, and using recursion only to achieve repetition (iteration, which is just linear recursion - the one which doesn't branch tree-like). Nothing more advanced above these, then you're sure it's a regular syntax and you can go with just lexer for that.

But when your syntax uses recursion in a non-trivial way, to produce tree-like, self-similar, nested structures, like the following one:

S --> a S b    // `S` can be itself "parenthesized" by `a` and `b` on both sides.
S -->          // or it could be (ultimately) empty, which ends recursion.

then you can easily see that this cannot be done with regular expression, because you cannot resolve it into one single EBNF production in any way; you'll end up with substituting for S indefinitely, which will always add another as and bs on both sides. Lexers (more specifically: Finite State Automata used by lexers) cannot count to arbitrary number (they are finite, remember?), so they don't know how many as were there to match them evenly with so many bs. Grammars like this are called context-free grammars (at the very least), and they require a parser.

Context-free grammars are well-known to parse, so they are widely used for describing programming languages' syntax. But there's more. Sometimes a more general grammar is needed -- when you have more things to count at the same time, independently. For example, when you want to describe a language where one can use round parentheses and square braces interleaved, but they have to be paired up correctly with each other (braces with braces, round with round). This kind of grammar is called context-sensitive. You can recognize it by that it has more than one symbol on the left (before the arrow). For example:

A R B --> A S B

You can think of these additional symbols on the left as a "context" for applying the rule. There could be some preconditions, postconditions etc. For example, the above rule will substitute R into S, but only when it's in between A and B, leaving those A and B themselves unchanged. This kind of syntax is really hard to parse, because it needs a full-blown Turing machine. It's a whole another story, so I'll end here.

td widths, not working?

Width and/or height in tables are not standard anymore; as Ianzz says, they are deprecated. Instead the best way to do this is to have a block element inside your table cell that will hold the cell open to your desired size:

<table>
    <tr>
        <td valign="top">
            <div class="left_menu">
                <div class="menu_item">
                    <a href="#">Home</a>
                </div>
            </div>
        </td>
        <td valign="top" class="content">Content</td>
    </tr>
</table>

CSS

.content {
    width: 1000px;
}

.left_menu {
    background: none repeat scroll 0 0 #333333;
    border-radius: 5px 5px 5px 5px;
    font-family: Arial,Helvetica,sans-serif;
    font-size: 12px;
    font-weight: bold;
    padding: 5px;
    width: 200px;
}

.menu_item {
    background: none repeat scroll 0 0 #CCCCCC;
    border-bottom: 1px solid #999999;
    border-radius: 5px 5px 5px 5px;
    border-top: 1px solid #FFFFCC;
    cursor: pointer;
    padding: 5px;
}

In SQL how to compare date values?

You could add the time component

WHERE mydate<='2008-11-25 23:59:59'

but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:

WHERE mydate < '2008-11-26 00:00:00'

Razor View throwing "The name 'model' does not exist in the current context"

I've found a solution. If you want to update razor version or mvc 4 to 5, change some lines.

Old code in Views/web.config

<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
  <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
  <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>

Replaced with

<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>

sectionGroup must be change, too.

Why does cURL return error "(23) Failed writing body"?

I encountered this error message while trying to install varnish cache on ubuntu. The google search landed me here for the error (23) Failed writing body, hence posting a solution that worked for me.

The bug is encountered while running the command as root curl -L https://packagecloud.io/varnishcache/varnish5/gpgkey | apt-key add -

the solution is to run apt-key add as non root

curl -L https://packagecloud.io/varnishcache/varnish5/gpgkey | apt-key add -

How to show form input fields based on select value?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
function myfun(){
$(document).ready(function(){

    $("#select").click(
    function(){
    var data=$("#select").val();
        $("#disp").val(data);
                     });
});
}
</script>
</head>
<body>

<p>id <input type="text" name="user" id="disp"></p>

<select id="select" onclick="myfun()">
<option name="1"value="1">first</option>
<option name="2"value="2">second</option>
</select>

</body>
</html>

Mockito: InvalidUseOfMatchersException

I had the same problem for a long time now, I often needed to mix Matchers and values and I never managed to do that with Mockito.... until recently ! I put the solution here hoping it will help someone even if this post is quite old.

It is clearly not possible to use Matchers AND values together in Mockito, but what if there was a Matcher accepting to compare a variable ? That would solve the problem... and in fact there is : eq

when(recommendedAccessor.searchRecommendedHolidaysProduct(eq(metas), any(List.class), any(HotelsBoardBasisType.class), any(Config.class)))
            .thenReturn(recommendedResults);

In this example 'metas' is an existing list of values

How can I make Flexbox children 100% height of their parent?

This is my solution using css+.

First of all, if the first child (flex-1) should be 100px, it shouldn't be flex.

In css+ in fact you can set flexible and/or static elements (columns or rows) and your example become as easy as this:

<div class="container">
  <div class="EXTENDER">
    <div class="COLS">
      <div class="CELL _100px" style="background-color:blue">100px</div>
      <div class="CELL _FLEX" style="background-color:red">flex</div>
    </div>
  </div>
</div>

Container CSS:

.container {
    height: 200px;
    width: 500px;
    position: relative;
}

And obviously include css+ 0.2 core.

Here is the fiddle.

The VMware Authorization Service is not running

I followed Telvin's suggestion and it worked on Windows 7:

  1. Run the VMware installer by right clicking on it and selecting "Run as Administrator"
  2. In the resulting popup menu, select "Repair installation"

Could not load file or assembly '' or one of its dependencies

For me rebuilding the unity game without Unity C# Proects Checkmark worked.

Reset git proxy to default configuration

git config --global --unset http.proxy

Using Python String Formatting with Lists

You should take a look to the format method of python. You could then define your formatting string like this :

>>> s = '{0} BLAH BLAH {1} BLAH {2} BLAH BLIH BLEH'
>>> x = ['1', '2', '3']
>>> print s.format(*x)
'1 BLAH BLAH 2 BLAH 3 BLAH BLIH BLEH'

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

check your path ,this error will come if file was not exist into given path.

Bootstrap: wider input field

In bootstrap 4, they have designed a bigger input file.

A simple solution to increase the size input file is to use font-size:

Add you style, for example:

input[type="file"] {
  font-size:35px
}

Otherwise, you can make one custom class and add to input control.

How can you dynamically create variables via a while loop?

vars()['meta_anio_2012'] = 'translate'

Insert picture into Excel cell

just go to google docs and paste this as a formula, where URL is a link to your img

      =image("URL", 1)

afterwards, from google docs options, download for excel and you'll have your image on the cell EDIT Per comments, you dont need to keep the image URL alive that long, just long enough for the excel to download it. Then it will stay embedded on the file.

How can I output leading zeros in Ruby?

Use the % operator with a string:

irb(main):001:0> "%03d" % 5
=> "005"

The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:

irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"

Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C function printf, but similar formating functions are available in perl, ruby, python, java, php, etc.

Is it possible to run a .NET 4.5 app on XP?

Try mono:

http://www.go-mono.com/mono-downloads/download.html

This download works on all versions of Windows XP, 2003, Vista and Windows 7.

How to add manifest permission to an application?

Copy the following line to your application manifest file and paste before the <application> tag.

<uses-permission android:name="android.permission.INTERNET"/>

Placing the permission below the <application/> tag will work, but will give you warning. So take care to place it before the <application/> tag declaration.

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

if you use spring data jpa , spring boot you can add this line in application.properties

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

PHPDoc type hinting for array of objects?

The problem is that @var can just denote a single type - Not contain a complex formula. If you had a syntax for "array of Foo", why stop there and not add a syntax for "array of array, that contains 2 Foo's and three Bar's"? I understand that a list of elements is perhaps more generic than that, but it's a slippery slope.

Personally, I have some times used @var Foo[] to signify "an array of Foo's", but it's not supported by IDE's.

ASP.Net MVC: Calling a method from a view

why You don't use Ajax to

its simple and does not require page refresh and has success and error callbacks

take look at my samlpe

<a id="ResendVerificationCode" >@Resource_en.ResendVerificationCode</a>

and in JQuery

 $("#ResendVerificationCode").on("click", function() {
                getUserbyPhoneIfNotRegisterd($("#phone").val());
 });

and this is my ajax which call my controller and my controller and return object from database

function getUserbyPhoneIfNotRegisterd(userphone) {

              $.ajax({
                    type: "GET",
                    dataType: "Json",
                    url: '@Url.Action("GetUserByPhone", "User")' + '?phone=' + userphone,
                    async: false,
                    success: function(data) {
                        if (data == null || data.data == null) {
                            ErrorMessage("", "@Resource_en.YourPhoneDoesNotExistInOurDatabase");
                        } else {
                            user = data[Object.keys(data)[0]];
                                AddVereCode(user.ID);// anather Ajax call 
                                SuccessMessage("Done", "@Resource_en.VerificationCodeSentSuccessfully", "Done");
                        }
                    },
                    error: function() {
                        ErrorMessage("", '@Resource_en.ErrorOccourd');
                    }
                });
            }

How to have a default option in Angular.js select box

My solution to this was use html to hardcode my default option. Like so:

In HAML:

%select{'ng-model' => 'province', 'ng-options' => "province as province for province in summary.provinces", 'chosen' => "chosen-select", 'data-placeholder' => "BC & ON"}
  %option{:value => "", :selected => "selected"}
    BC &amp; ON

In HTML:

<select ng-model="province" ng-options="province as province for province in summary.provinces" chosen="chosen-select" data-placeholder="BC & ON">
  <option value="" selected="selected">BC &amp; ON</option>
</select>

I want my default option to return all values from my api, that's why I have a blank value. Also excuse my haml. I know this isn't directly an answer to the OP's question, but people find this on Google. Hope this helps someone else.

How to insert strings containing slashes with sed?

Great answer from Anonymous. \ solved my problem when I tried to escape quotes in HTML strings.

So if you use sed to return some HTML templates (on a server), use double backslash instead of single:

var htmlTemplate = "<div style=\\"color:green;\\"></div>";

Specify an SSH key for git push for a given domain

I've cribbed together and tested with github the following approach, based on reading other answers, which combines a few techniques:

  • correct SSH config
  • git URL re-writing

The advantage of this approach is, once set up, it doesn't require any additional work to get it right - for example, you don't need to change remote URLs or remember to clone things differently - the URL rewriting makes it all work.

~/.ssh/config

# Personal GitHub
Host github.com
  HostName github.com
  User git
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/github_id_rsa

# Work GitHub
Host github-work
  HostName github.com
  User git
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/work_github_id_rsa

Host *
  IdentitiesOnly yes

~/.gitconfig

[user]
    name = My Name
    email = [email protected]

[includeIf "gitdir:~/dev/work/"]
    path = ~/dev/work/.gitconfig

[url "github-work:work-github-org/"]
    insteadOf = [email protected]:work-github-org/

~/dev/work/.gitconfig

[user]
    email = [email protected]

As long as you keep all your work repos under ~/dev/work and personal stuff elsewhere, git will use the correct SSH key when doing pulls/clones/pushes to the server, and it will also attach the correct email address to all of your commits.

References:

Where does Anaconda Python install on Windows?

To find where Anaconda was installed I used the "where" command on the command line in Windows.

C:\>where anaconda

which for me returned:

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe

Which allowed me to find the Anaconda Python interpreter at

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\python.exe

to update PyDev

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

In my case I have imported the RouterModule in App module but not imported in my feature module. After import the router module in my EventModule the error goes away.

    import {NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import {EventListComponent} from './EventList.Component';
    import {EventThumbnailComponent} from './EventThumbnail.Component';
    import { EventService } from './shared/Event.Service'
    import {ToastrService} from '../shared/toastr.service';
    import {EventDetailsComponent} from './event-details/event.details.component';
    import { RouterModule } from "@angular/router";
    @NgModule({
      imports:[BrowserModule,RouterModule],
      declarations:[EventThumbnailComponent,EventListComponent,EventDetailsComponent],
      exports: [EventThumbnailComponent,EventListComponent,EventDetailsComponent],
       providers: [EventService,ToastrService]
    })
    export class EventModule {
        
     }

How to get history on react-router v4?

In App.js

 import {useHistory } from "react-router-dom";

 const TheContext = React.createContext(null);

 const App = () => {
   const history = useHistory();

   <TheContext.Provider value={{ history, user }}>

    <Switch>
        <Route exact path="/" render={(props) => <Home {...props} />} />
        <Route
          exact
          path="/sign-up"
          render={(props) => <SignUp {...props} setUser={setUser} />}
        /> ...

Then in a child component :

const Welcome = () => {
    
    const {user, history} = React.useContext(TheContext); 
    ....

SQL query to find Nth highest salary from a salary table

+-------+--------+
|  name | salary |
+-------+--------+
|   A   | 100    |
|   B   | 200    |
|   C   | 300    |
|   D   | 400    |
|   E   | 500    |
|   F   | 500    |
|   G   | 600    |
+-------+--------+

IF YOU WANT TO SELECT ONLY Nth HIGHEST SALARY THEN:

SELECT DISTINCT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET N-1;

IF YOU WANT TO SELECT ALL EMPLOYEE WHO GETTING Nth HIGHEST SALARY THEN:

SELECT * FROM emp WHERE salary = (
   SELECT DISTINCT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET N-1
);

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

For Kotlin, You can use something like this :

object FileUtils {

   fun Context.getFileName(uri: Uri): String?
        = when (uri.scheme) {
            ContentResolver.SCHEME_FILE -> File(uri.path).name
            ContentResolver.SCHEME_CONTENT -> getCursorContent(uri)
            else -> null
        }

    private fun Context.getCursorContent(uri: Uri): String? 
        = try {
            contentResolver.query(uri, null, null, null, null)?.let { cursor ->
                cursor.run {
                    if (moveToFirst()) getString(getColumnIndex(OpenableColumns.DISPLAY_NAME))
                    else null
                }.also { cursor.close() }
            }
        } catch (e : Exception) { null }

How can I rename a conda environment?

conda should have given us a simple tool like cond env rename <old> <new> but it hasn't. Simply renaming the directory, as in this previous answer, of course, breaks the hardcoded hashbangs(#!). Hence, we need to go one more level deeper to achieve what we want.

conda env list
# conda environments:
#
base                  *  /home/tgowda/miniconda3
junkdetect               /home/tgowda/miniconda3/envs/junkdetect
rtg                      /home/tgowda/miniconda3/envs/rtg

Here I am trying to rename rtg --> unsup (please bear with those names, this is my real use case)

$ cd /home/tgowda/miniconda3/envs 
$ OLD=rtg
$ NEW=unsup
$ mv $OLD $NEW   # rename dir

$ conda env list
# conda environments:
#
base                  *  /home/tgowda/miniconda3
junkdetect               /home/tgowda/miniconda3/envs/junkdetect
unsup                    /home/tgowda/miniconda3/envs/unsup


$ conda activate $NEW
$ which python
  /home/tgowda/miniconda3/envs/unsup/bin/python

the previous answer reported upto this, but wait, we are not done yet! the pending task is, $NEW/bin dir has a bunch of executable scripts with hashbangs (#!) pointing to the $OLD env paths.

See jupyter, for example:

$ which jupyter
/home/tgowda/miniconda3/envs/unsup/bin/jupyter

$ head -1 $(which jupyter) # its hashbang is still looking at old
#!/home/tgowda/miniconda3/envs/rtg/bin/python

So, we can easily fix it with a sed

$ sed  -i.bak "s:envs/$OLD/bin:envs/$NEW/bin:" $NEW/bin/*  
# `-i.bak` created backups, to be safe

$ head -1 $(which jupyter) # check if updated
#!/home/tgowda/miniconda3/envs/unsup/bin/python
$ jupyter --version # check if it works
jupyter core     : 4.6.3
jupyter-notebook : 6.0.3

$ rm $NEW/bin/*.bak  # remove backups

Now we are done

I think it should be trivial to write a portable script to do all those and bind it to conda env rename old new.


I tested this on ubuntu. For whatever unforseen reasons, if things break and you wish to revert the above changes:

$ mv $NEW  $OLD
$ sed  -i.bak "s:envs/$NEW/bin:envs/$OLD/bin:" $OLD/bin/*

Difference between "this" and"super" keywords in Java

this refers to a reference of the current class.
super refers to the parent of the current class (which called the super keyword).

By doing this, it allows you to access methods/attributes of the current class (including its own private methods/attributes).

super allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.

Return Result from Select Query in stored procedure to a List

Building on some of the responds here, i'd like to add an alternative way. Creating a generic method using reflection, that can map any Stored Procedure response to a List. That is, a List of any type you wish, as long as the given type contains similarly named members to the Stored Procedure columns in the response. Ideally, i'd probably use Dapper for this - but here goes:

private static SqlConnection getConnectionString() // Should be gotten from config in secure storage.
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = "it.hurts.when.IP";
            builder.UserID = "someDBUser";
            builder.Password = "someDBPassword";
            builder.InitialCatalog = "someDB";
            return new SqlConnection(builder.ConnectionString);
        }

        public static List<T> ExecuteSP<T>(string SPName, List<SqlParameter> Params)
        {
            try
            {
                DataTable dataTable = new DataTable();

                using (SqlConnection Connection = getConnectionString())
                {
                    // Open connection
                    Connection.Open();

                    // Create command from params / SP
                    SqlCommand cmd = new SqlCommand(SPName, Connection);

                    // Add parameters
                    cmd.Parameters.AddRange(Params.ToArray());
                    cmd.CommandType = CommandType.StoredProcedure;

                    // Make datatable for conversion
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dataTable);
                    da.Dispose();

                    // Close connection
                    Connection.Close();
                }

                // Convert to list of T
                var retVal = ConvertToList<T>(dataTable);
                return retVal;
            }
            catch (SqlException e)
            {
                Console.WriteLine("ConvertToList Exception: " + e.ToString());
                return new List<T>();
            }
        }

        /// <summary>
        /// Converts datatable to List<someType> if possible.
        /// </summary>
        public static List<T> ConvertToList<T>(DataTable dt)
        {
            try // Necesarry unfotunately.
            {
                var columnNames = dt.Columns.Cast<DataColumn>()
                    .Select(c => c.ColumnName)
                    .ToList();

                var properties = typeof(T).GetProperties();

                return dt.AsEnumerable().Select(row =>
                    {
                        var objT = Activator.CreateInstance<T>();

                        foreach (var pro in properties)
                        {
                            if (columnNames.Contains(pro.Name))
                            {
                                if (row[pro.Name].GetType() == typeof(System.DBNull)) pro.SetValue(objT, null, null);
                                else pro.SetValue(objT, row[pro.Name], null);
                            }
                        }

                        return objT;
                    }).ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to write data to list. Often this occurs due to type errors (DBNull, nullables), changes in SP's used or wrongly formatted SP output.");
                Console.WriteLine("ConvertToList Exception: " + e.ToString());
                return new List<T>();
            }
        }

Gist: https://gist.github.com/Big-al/4c1ff3ed87b88570f8f6b62ee2216f9f

How to define dimens.xml for every different screen size in android?

You can put dimens.xml in

1) values

2) values-hdpi

3) values-xhdpi

4) values-xxhdpi

And give different sizes in dimens.xml within corresponding folders according to densities.

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

Two options:

char c1 = '\u0001';
char c1 = (char) 1;

How do I get unique elements in this array?

You can just use the method uniq. Assuming your array is ary, call:

ary.uniq{|x| x.user_id}

and this will return a set with unique user_ids.

how to get all child list from Firebase android

Works Like a Charm

final DatabaseReference senderDb = FirebaseDatabase.getInstance().getReference(Constant.NODE_MESSAGE).child(myId + "_" + otherId);

    senderDb.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();

            for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                DatabaseReference objRef = senderDb.child( childDataSnapshot.getKey());
                Map<String,Object> taskMap = new HashMap<String,Object>();
                taskMap.put("is_read", "1");
                objRef.updateChildren(taskMap); //should I use setValue()...?
                Log.v("Testing",""+ childDataSnapshot.getKey()); //displays the key for the node
            }

            //notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

jQuery Validate Required Select

You can write your own rule!

 // add the rule here
 $.validator.addMethod("valueNotEquals", function(value, element, arg){
  return arg !== value;
 }, "Value must not equal arg.");

 // configure your validation
 $("form").validate({
  rules: {
   SelectName: { valueNotEquals: "default" }
  },
  messages: {
   SelectName: { valueNotEquals: "Please select an item!" }
  }  
 });

Your content must have a ListView whose id attribute is 'android.R.id.list'

You should have one listview in your mainlist.xml file with id as @android:id/list

<ListView
    android:id="@android:id/list"
    android:layout_height="wrap_content"
    android:layout_height="fill_parent"/>

NLTK and Stopwords Fail #lookuperror

import nltk

nltk.download()

  • A GUI pops up and in that go the Corpora section, select the required corpus.
  • Verified Result

jQuery show/hide not working

Use this

<script>
$(document).ready(function(){
    $( '.expand' ).click(function() {
        $( '.img_display_content' ).show();
    });
});
</script>

Event assigning always after Document Object Model loaded

How do you beta test an iphone app?

Diawi Alternatives

Since diawi.com have added some limitations for free accounds.

Next best available and easy to use alternative is

Microsoft

https://appcenter.ms

Google

https://firebase.google.com/docs/app-distribution/ios/distribute-console

Others

https://hockeyapp.net/

http://buildtry.com

Happy build sharing!

Convert string to Color in C#

(It would really have been nice if you'd mentioned which Color type you were interested in to start with...)

One simple way of doing this is to just build up a dictionary via reflection:

public static class Colors
{
    private static readonly Dictionary<string, Color> dictionary =
        typeof(Color).GetProperties(BindingFlags.Public | 
                                    BindingFlags.Static)
                     .Where(prop => prop.PropertyType == typeof(Color))
                     .ToDictionary(prop => prop.Name,
                                   prop => (Color) prop.GetValue(null, null)));

    public static Color FromName(string name)
    {
        // Adjust behaviour for lookup failure etc
        return dictionary[name];
    }
}

That will be relatively slow for the first lookup (while it uses reflection to find all the properties) but should be very quick after that.

If you want it to be case-insensitive, you can pass in something like StringComparer.OrdinalIgnoreCase as an extra argument in the ToDictionary call. You can easily add TryParse etc methods should you wish.

Of course, if you only need this in one place, don't bother with a separate class etc :)

How to check if input is numeric in C++

When cin gets input it can't use, it sets failbit:

int n;
cin >> n;
if(!cin) // or if(cin.fail())
{
    // user didn't input a number
    cin.clear(); // reset failbit
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
    // next, request user reinput
}

When cin's failbit is set, use cin.clear() to reset the state of the stream, then cin.ignore() to expunge the remaining input, and then request that the user re-input. The stream will misbehave so long as the failure state is set and the stream contains bad input.

File URL "Not allowed to load local resource" in the Internet Browser

For people do not like to modify chrome's security options, we can simply start a python http server from directory which contains your local file:

python -m SimpleHTTPServer

and for python 3:

python3 -m http.server

Now you can reach any local file directly from your js code or externally with http://127.0.0.1:8000/some_file.txt

How can I set response header on express.js assets

@klode's answer is right.

However, you are supposed to set another response header to make your header accessible to others.


Example:

First, you add 'page-size' in response header

response.set('page-size', 20);

Then, all you need to do is expose your header

response.set('Access-Control-Expose-Headers', 'page-size')

Rails: How to reference images in CSS within Rails 4

Don't know why, but only thing that worked for me was using asset_path instead of image_path, even though my images are under the assets/images/ directory:

Example:

app/assets/images/mypic.png

In Ruby:

asset_path('mypic.png')

In .scss:

url(asset-path('mypic.png'))

UPDATE:

Figured it out- turns out these asset helpers come from the sass-rails gem (which I had installed in my project).

IIS Request Timeout on long ASP.NET operation

Remove ~ character in location so

path="~/Admin/SomePage.aspx"

becomes

path="Admin/SomePage.aspx"

How to close a web page on a button click, a hyperlink or a link button click?

public class Form1 : Form
{
public Form1()
{
    InitializeComponents(); // or whatever that method is called :)
    this.button.Click += new RoutedEventHandler(buttonClick);
}

private void buttonClick(object sender, EventArgs e)
{
    this.Close();
}
}

What does OpenCV's cvWaitKey( ) function do?

The cvWaitKey simply provides something of a delay. For example:

char c = cvWaitKey(33);
if( c == 27 ) break;

Tis was apart of my code in which a video was loaded into openCV and the frames outputted. The 33 number in the code means that after 33ms, a new frame would be shown. Hence, the was a dely or time interval of 33ms between each frame being shown on the screen. Hope this helps.

PostgreSQL "DESCRIBE TABLE"

/dt is the commad which lists you all the tables present in a database. using
/d command and /d+ we can get the details of a table. The sysntax will be like
* /d table_name (or) \d+ table_name

Check if a String contains a special character

What do you exactly call "special character" ? If you mean something like "anything that is not alphanumeric" you can use org.apache.commons.lang.StringUtils class (methods IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable).

If it is not so trivial, you can use a regex that defines the exact character list you accept and match the string against it.

How to split a string in Ruby and get all items except the first one?

ex="test1,test2,test3,test4,test5"
all_but_first=ex.split(/,/)[1..-1]

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

As @Jared Ng and @Issun pointed out, the key to solve this kind of RegEx like "matching everything up to a certain word or substring" or "matching everything after a certain word or substring" is called "lookaround" zero-length assertions. Read more about them here.

In your particular case, it can be solved by a positive look ahead: .+?(?=abc)

A picture is worth a thousand words. See the detail explanation in the screenshot.

Regex101 Screenshot

Scroll to the top of the page after render in react.js

I tried everything, but this is the only thing that worked.

 useLayoutEffect(() => {
  document.getElementById("someID").scrollTo(0, 0);
 });

How to download file in swift?

After trying a few of the above suggestions without success (Swift versions...) I ended up using the official documentation: https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_from_websites

let downloadTask = URLSession.shared.downloadTask(with: url) {
    urlOrNil, responseOrNil, errorOrNil in
    // check for and handle errors:
    // * errorOrNil should be nil
    // * responseOrNil should be an HTTPURLResponse with statusCode in 200..<299
    
    guard let fileURL = urlOrNil else { return }
    do {
        let documentsURL = try
            FileManager.default.url(for: .documentDirectory,
                                    in: .userDomainMask,
                                    appropriateFor: nil,
                                    create: false)
        let savedURL = documentsURL.appendingPathComponent(fileURL.lastPathComponent)
        try FileManager.default.moveItem(at: fileURL, to: savedURL)
    } catch {
        print ("file error: \(error)")
    }
}
downloadTask.resume()

how to get current month and year

If you have following two labels:

<asp:Label ID="MonthLabel" runat="server" />
<asp:Label ID="YearLabel" runat="server" />

Than you can use following code just need to set the Text Property for these labels like:

MonthLabel.Text = DateTime.Now.Month.ToString();
YearLabel.Text = DateTime.Now.Year.ToString();

Update Fragment from ViewPager

Because none of the above answers did the trick for me, here is my solution:

I combined the POSITION_NONE with loading on setUserVisibleHint(boolean isVisibleToUser) instead of onStart()

As seen here: https://stackoverflow.com/a/25676323/497366

In the Fragment:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // load data here
    }else{
       // fragment is no longer visible
    }
}

and in the FragmentStatePagerAdapter as seen in the top answer here from Simon Dorociak https://stackoverflow.com/a/18088509/497366:

@Override
public int getItemPosition(@NonNull Object object) {
    return POSITION_NONE;
}

Now the fragments reload the data into their views everytime they are shown to the user.

Where does this come from: -*- coding: utf-8 -*-

In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.

What is "string[] args" in Main class for?

This is an array of the command line switches pass to the program. E.g. if you start the program with the command "myapp.exe -c -d" then string[] args[] will contain the strings "-c" and "-d".

GROUP_CONCAT comma separator - MySQL

Or, if you are doing a split - join:

GROUP_CONCAT(split(thing, " "), '----') AS thing_name,

You may want to inclue WITHIN RECORD, like this:

GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,

from BigQuery API page

Get the cartesian product of a series of lists?

Just to add a bit to what has already been said: if you use sympy, you can use symbols rather than strings which makes them mathematically useful.

import itertools
import sympy

x, y = sympy.symbols('x y')

somelist = [[x,y], [1,2,3], [4,5]]
somelist2 = [[1,2], [1,2,3], [4,5]]

for element in itertools.product(*somelist):
  print element

About sympy.

Get spinner selected items text?

You have to use the index and the Adapter to find out the text you have

See this example of Spinner

public class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
      Toast.makeText(parent.getContext()), "The planet is " +
          parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
    }

    public void onNothingSelected(AdapterView parent) {
      // Do nothing.
    }
}

How do I make a newline after a twitter bootstrap element?

You're using span6 and span2. Both of these classes are "float:left" meaning, if possible they will always try to sit next to each other. Twitter bootstrap is based on a 12 grid system. So you should generally always get the span**#** to add up to 12.

E.g.: span4 + span4 + span4 OR span6 + span6 OR span4 + span3 + span5.

To force a span down though, without listening to the previous float you can use twitter bootstraps clearfix class. To do this, your code should look like this:

<ul class="nav nav-tabs span2">
  <li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
  <li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
  <li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
  <li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>
</ul>
<!-- Notice this following line -->
<div class="clearfix"></div>
<div class="well span6">
  <h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>
</div>

How to quickly drop a user with existing privileges

How about

DROP USER <username>

This is actually an alias for DROP ROLE.

You have to explicity drop any privileges associated with that user, also to move its ownership to other roles (or drop the object).

This is best achieved by

REASSIGN OWNED BY <olduser> TO <newuser>

and

DROP OWNED BY <olduser>

The latter will remove any privileges granted to the user.

See the postgres docs for DROP ROLE and the more detailed description of this.


Addition:

Apparently, trying to drop a user by using the commands mentioned here will only work if you are executing them while being connected to the same database that the original GRANTS were made from, as discussed here:

https://www.postgresql.org/message-id/83894A1821034948BA27FE4DAA47427928F7C29922%40apde03.APD.Satcom.Local

Set Value of Input Using Javascript Function

The following works in MVC5:

document.getElementById('theID').value = 'new value';

Return value in a Bash function

As an add-on to others' excellent posts, here's an article summarizing these techniques:

  • set a global variable
  • set a global variable, whose name you passed to the function
  • set the return code (and pick it up with $?)
  • 'echo' some data (and pick it up with MYVAR=$(myfunction) )

Returning Values from Bash Functions

How can I make a clickable link in an NSAttributedString?

Use UITextView it supports clickable Links. Create attributed string using the following code

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strSomeTextWithLinks];

Then set UITextView text as follows

NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor redColor],

                                 NSUnderlineColorAttributeName: [UIColor blueColor],

                                 NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

customTextView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;

Make sure that you enable "Selectable" behavior of the UITextView in XIB.

phpMyAdmin on MySQL 8.0

New MySQL 8.0.11 is using caching_sha2_password as default authentication method. I think that phpMyAdmin cannot understand this authentication method. You need to create user with one of the older authentication method, e.g. CREATE USER xyz@localhost IDENTIFIED WITH mysql_native_password BY 'passw0rd'.

More here https://dev.mysql.com/doc/refman/8.0/en/create-user.html and here https://dev.mysql.com/doc/refman/8.0/en/authentication-plugins.html

How do I diff the same file between two different commits on the same branch?

If you want a simple visual comparison on Windows such as you can get in Visual SourceSafe or Team Foundation Server (TFS), try this:

  • right-click on the file in File Explorer
  • select 'Git History'

Note: After upgrading to Windows 10 I have lost the Git context menu options. However, you can achieve the same thing using 'gitk' or 'gitk filename' in a command window.

Once you call 'Git History', the Git GUI tool will start, with a history of the file in the top left pane. Select one of the versions you would like to compare. Then right-click on the second version and choose either

Diff this -> selected

or

Diff selected -> this

Colour-coded differences will appear in the lower left-hand pane.

How to install requests module in Python 3.4, instead of 2.7

while installing python packages in a global environment is doable, it is a best practice to isolate the environment between projects (creating virtual environments). Otherwise, confusion between Python versions will arise, just like your problem.

The simplest method is to use venv library in the project directory:

python3 -m venv venv

Where the first venv is to call the venv package, and the second venv defines the virtual environment directory name. Then activate the virtual environment:

source venv/bin/activate

Once the virtual environment has been activated, your pip install ... commands would not be interfered with any other Python version or pip version anymore. For installing requests:

pip install requests

Another benefit of the virtual environment is to have a concise list of libraries needed for that specific project.

*note: commands only work on Linux and Mac OS

Creating a LinkedList class from scratch

Sure, a Linked List is a bit confusing for programming n00bs, pretty much the temptation is to look at it as Russian Dolls, because that's what it seems like, a LinkedList Object in a LinkedList Object. But that's a touch difficult to visualize, instead look at it like a computer.

LinkedList = Data + Next Member

Where it's the last member of the list if next is NULL

So a 5 member LinkedList would be:

LinkedList(Data1, LinkedList(Data2, LinkedList(Data3, LinkedList(Data4, LinkedList(Data5, NULL)))))

But you can think of it as simply:

Data1 -> Data2 -> Data3 -> Data4 -> Data5 -> NULL

So, how do we find the end of this? Well, we know that the NULL is the end so:

public void append(LinkedList myNextNode) {
  LinkedList current = this; //Make a variable to store a pointer to this LinkedList
  while (current.next != NULL) { //While we're not at the last node of the LinkedList
    current = current.next; //Go further down the rabbit hole.
  }
  current.next = myNextNode; //Now we're at the end, so simply replace the NULL with another Linked List!
  return; //and we're done!
}

This is very simple code of course, and it will infinitely loop if you feed it a circularly linked list! But that's the basics.

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

alternative to "!is.null()" in R

If it's just a matter of easy reading, you could always define your own function :

is.not.null <- function(x) !is.null(x)

So you can use it all along your program.

is.not.null(3)
is.not.null(NULL)

Implicit function declarations in C

To complete the picture, since -Werror might considered too "invasive",
for gcc (and llvm) a more precise solution is to transform just this warning in an error, using the option:

-Werror=implicit-function-declaration

See Make one gcc warning an error?

Regarding general use of -Werror: Of course, having warningless code is recommendable, but in some stage of development it might slow down the prototyping.

How to change the color of an image on hover

Ok, try this:

Get the image with the transparent circle - http://i39.tinypic.com/15s97vd.png Put that image in a html element and change that element's background color via css. This way you get the logo with the circle in the color defined in the stylesheet.

The html

<div class="badassColorChangingLogo">
    <img src="http://i39.tinypic.com/15s97vd.png" /> 
    Or download the image and change the path to the downloaded image in your machine
</div>

The css

div.badassColorChangingLogo{
    background-color:white;
}
div.badassColorChangingLogo:hover{
    background-color:blue;
}

Keep in mind that this wont work on non-alpha capable browsers like ie6, and ie7. for ie you can use a js fix. Google ddbelated png fix and you can get the script.

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

How to get first 5 characters from string

Use substr():

$result = substr($myStr, 0, 5);

How can I create an observable with a delay

It's little late to answer ... but just in case may be someone return to this question looking for an answer

'delay' is property(function) of an Observable

fakeObservable = Observable.create(obs => {
  obs.next([1, 2, 3]);
  obs.complete();
}).delay(3000);

This worked for me ...

Tracking Google Analytics Page Views with AngularJS

app.run(function ($rootScope, $location) {
    $rootScope.$on('$routeChangeSuccess', function(){
        ga('send', 'pageview', $location.path());
    });
});

trying to align html button at the center of the my page

try this it is quite simple and give you cant make changes to your .css file this should work

<p align="center">
<button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%"> mybuttonname</button>
</p>

Where to find the win32api module for Python?

There is a a new option as well: get it via pip! There is a package pypiwin32 with wheels available, so you can just install with: pip install pypiwin32!

Edit: Per comment from @movermeyer, the main project now publishes wheels at pywin32, and so can be installed with pip install pywin32

How to read a specific line using the specific line number from a file in Java?

If you are talking about a text file, then there is really no way to do this without reading all the lines that precede it - After all, lines are determined by the presence of a newline, so it has to be read.

Use a stream that supports readline, and just read the first X-1 lines and dump the results, then process the next one.

Positive Number to Negative Number in JavaScript?

num * -1

This would do it for you.