Programs & Examples On #Messagecontract

Service Reference Error: Failed to generate code for the service reference

If you want to correct this without uncheking the assembly reuse checkbox this is what worked for me:

  • Remove referenced assembly that you want to re-use
  • Delete all the bin folder of the project
  • Update service reference
    • Keep "Reuse types in specified referenced assemblies"
  • Add reference to assembly again to fix the errors
  • Update service reference again

what is the difference between XSD and WSDL

WSDL (Web Services Description Language) describes your service and its operations - what is the service called, which methods does it offer, what kind of in parameters and return values do these methods have?

It's a description of the behavior of the service - it's functionality.

XSD (Xml Schema Definition) describes the static structure of the complex data types being exchanged by those service methods. It describes the types, their fields, any restriction on those fields (like max length or a regex pattern) and so forth.

It's a description of datatypes and thus static properties of the service - it's about data.

How to add an extra source directory for maven to compile and include in the build jar?

You can add the directories for your build process like:

    ...
   <resources>
     <resource>
       <directory>src/bootstrap</directory>
     </resource>
   </resources>
   ...

The src/main/java is the default path which is not needed to be mentioned in the pom.xml

Decode UTF-8 with Javascript

@albert's solution was the closest I think but it can only parse up to 3 byte utf-8 characters

function utf8ArrayToStr(array) {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = 0;

  // XXX: Invalid bytes are ignored
  while(i < len) {
    c = array[i++];
    if (c >> 7 == 0) {
      // 0xxx xxxx
      out += String.fromCharCode(c);
      continue;
    }

    // Invalid starting byte
    if (c >> 6 == 0x02) {
      continue;
    }

    // #### MULTIBYTE ####
    // How many bytes left for thus character?
    var extraLength = null;
    if (c >> 5 == 0x06) {
      extraLength = 1;
    } else if (c >> 4 == 0x0e) {
      extraLength = 2;
    } else if (c >> 3 == 0x1e) {
      extraLength = 3;
    } else if (c >> 2 == 0x3e) {
      extraLength = 4;
    } else if (c >> 1 == 0x7e) {
      extraLength = 5;
    } else {
      continue;
    }

    // Do we have enough bytes in our data?
    if (i+extraLength > len) {
      var leftovers = array.slice(i-1);

      // If there is an invalid byte in the leftovers we might want to
      // continue from there.
      for (; i < len; i++) if (array[i] >> 6 != 0x02) break;
      if (i != len) continue;

      // All leftover bytes are valid.
      return {result: out, leftovers: leftovers};
    }
    // Remove the UTF-8 prefix from the char (res)
    var mask = (1 << (8 - extraLength - 1)) - 1,
        res = c & mask, nextChar, count;

    for (count = 0; count < extraLength; count++) {
      nextChar = array[i++];

      // Is the char valid multibyte part?
      if (nextChar >> 6 != 0x02) {break;};
      res = (res << 6) | (nextChar & 0x3f);
    }

    if (count != extraLength) {
      i--;
      continue;
    }

    if (res <= 0xffff) {
      out += String.fromCharCode(res);
      continue;
    }

    res -= 0x10000;
    var high = ((res >> 10) & 0x3ff) + 0xd800,
        low = (res & 0x3ff) + 0xdc00;
    out += String.fromCharCode(high, low);
  }

  return {result: out, leftovers: []};
}

This returns {result: "parsed string", leftovers: [list of invalid bytes at the end]} in case you are parsing the string in chunks.

EDIT: fixed the issue that @unhammer found.

Get textarea text with javascript or Jquery

As @Darin Dimitrov said, if it is not an iframe on the same domain it is not posible, if it is, check that $("#frame1").contents() returns all it should, and then check if the textbox is found:

$("#frame1").contents().find("#area1").length should be 1.

Edit

If when your textarea is "empty" an empty string is returned and when it has some text entered that text is returned, then it is working perfect!! When the textarea is empty, an empty string is returned!

Edit 2 Ok. Here there is one way, it is not very pretty but it works:

Outside the iframe you will access the textarea like this:

window.textAreaInIframe

And inside the iframe (which I assume has jQuery) in the document ready put this code:

$("#area1").change(function() {
    window.parent.textAreaInIframe = $(this).val();
}).trigger("change");

What generates the "text file busy" message in Unix?

It's a while since I've seen that message, but it used to be prevalent in System V R3 or thereabouts a good couple of decades ago. Back then, it meant that you could not change a program executable while it was running.

For example, I was building a make workalike called rmk, and after a while it was self-maintaining. I would run the development version and have it build a new version. To get it to work, it was necessary to use the workaround:

gcc -g -Wall -o rmk1 main.o -L. -lrmk -L/Users/jleffler/lib/64 -ljl
if [ -f rmk ] ; then mv rmk rmk2 ; else true; fi ; mv rmk1 rmk

So, to avoid problems with the 'text file busy', the build created a new file rmk1, then moved the old rmk to rmk2 (rename wasn't a problem; unlink was), and then moved the newly built rmk1 to rmk.

I haven't seen the error on a modern system in quite a while...but I don't all that often have programs rebuilding themselves.

Reload an iframe with jQuery

Just reciprocating Alex's answer but with jQuery

var currSrc = $("#currentElement").attr("src");
$("#currentElement").attr("src", currSrc);

How to make Java honor the DNS Caching Timeout?

Java has some seriously weird dns caching behavior. Your best bet is to turn off dns caching or set it to some low number like 5 seconds.

networkaddress.cache.ttl (default: -1)
Indicates the caching policy for successful name lookups from the name service. The value is specified as as integer to indicate the number of seconds to cache the successful lookup. A value of -1 indicates "cache forever".

networkaddress.cache.negative.ttl (default: 10)
Indicates the caching policy for un-successful name lookups from the name service. The value is specified as as integer to indicate the number of seconds to cache the failure for un-successful lookups. A value of 0 indicates "never cache". A value of -1 indicates "cache forever".

How to find list intersection?

If, by Boolean AND, you mean items that appear in both lists, e.g. intersection, then you should look at Python's set and frozenset types.

Any reason to prefer getClass() over instanceof when generating .equals()?

This is something of a religious debate. Both approaches have their problems.

  • Use instanceof and you can never add significant members to subclasses.
  • Use getClass and you violate the Liskov substitution principle.

Bloch has another relevant piece of advice in Effective Java Second Edition:

  • Item 17: Design and document for inheritance or prohibit it

Force overwrite of local file with what's in origin repo?

I believe what you are looking for is "git restore".

The easiest way is to remove the file locally, and then execute the git restore command for that file:

$ rm file.txt
$ git restore file.txt 

ng serve not detecting file changes automatically

You can try this too.

sudo ng serve

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

In SQL Developer: Everything was working fine and I had all the permissions to login and there was no password change and I could click the table and see the data tab.

But when I run query (simple select statement) it was showing "ORA-01031: insufficient privileges" message.

The solution is simply disconnect the connection and reconnect. Note: only doing Reconnect did not work for me. SQL Developer Disconnect Snapshot

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

orphan removal has the same effect as ON DELETE CASCADE in the following scenario:- Lets say we have a simple many to one relationship between student entity and a guide entity, where many students can be mapped to the same guide and in database we have a foreign key relation between Student and Guide table such that student table has id_guide as FK.

    @Entity
    @Table(name = "student", catalog = "helloworld")
    public class Student implements java.io.Serializable {
     @Id
     @GeneratedValue(strategy = IDENTITY)
     @Column(name = "id")
     private Integer id;

    @ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
    @JoinColumn(name = "id_guide")
    private Guide guide;

// The parent entity

    @Entity
    @Table(name = "guide", catalog = "helloworld")
    public class Guide implements java.io.Serializable {

/**
 * 
 */
private static final long serialVersionUID = 9017118664546491038L;

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;

@Column(name = "name", length = 45)
private String name;

@Column(name = "salary", length = 45)
private String salary;


 @OneToMany(mappedBy = "guide", orphanRemoval=true) 
 private Set<Student> students = new  HashSet<Student>(0);

In this scenario, the relationship is such that student entity is the owner of the relationship and as such we need to save the student entity in order to persist the whole object graph e.g.

    Guide guide = new Guide("John", "$1500");
    Student s1 = new Student(guide, "Roy","ECE");
    Student s2 = new Student(guide, "Nick", "ECE");
    em.persist(s1);
    em.persist(s2);

Here we are mapping the same guide with two different student objects and since the CASCADE.PERSIST is used , the object graph will be saved as below in the database table(MySql in my case)

STUDENT table:-

ID Name Dept Id_Guide

1     Roy     ECE    1

2    Nick    ECE    1

GUIDE Table:-

ID NAME Salary

1    John     $1500

and Now if I want to remove one of the students, using

      Student student1 = em.find(Student.class,1);
      em.remove(student1);

and when a student record is removed the corresponding guide record should also be removed, that's where CASCADE.REMOVE attribute in the Student entity comes into picture and what it does is ;it removes the student with identifier 1 as well the corresponding guide object(identifier 1). But in this example, there is one more student object which is mapped to the same guide record and unless we use the orphanRemoval=true attribute in the Guide Entity , the remove code above will not work.

Scala: what is the best way to append an element to an Array?

val array2 = array :+ 4
//Array(1, 2, 3, 4)

Works also "reversed":

val array2 = 4 +: array
Array(4, 1, 2, 3)

There is also an "in-place" version:

var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)

Convert MySQL to SQlite

I like the SQLite2009 Pro Enterprise Manager suggested by Jfly. However:

  • The MySQL datatype INT is not converted to SQlite datatype INTEGER (works with DBeaver )

  • It does not import foreign key constaints from MySQL (I could not find any tool that supports the transfer of foreign key constraints from MySQL to SQlite.)

How do the major C# DI/IoC frameworks compare?

Just read this great .Net DI container comparison blog by Philip Mat.

He does some thorough performance comparison tests on;

He recommends Autofac as it is small, fast, and easy to use ... I agree. It appears that Unity and Ninject are the slowest in his tests.

Best way to check for "empty or null value"

If database having large number of records then null check can take more time you can use null check in different ways like : 1) where columnname is null 2) where not exists() 3) WHERE (case when columnname is null then true end)

Why doesn't the height of a container element increase if it contains floated elements?

you can use overflow property to the container div if you don't have any div to show over the container eg:

<div class="cointainer">
    <div class="one">Content One</div>
    <div class="two">Content Two</div>
</div>

Here is the following css:

.container{
    width:100%;/* As per your requirment */
    height:auto;
    float:left;
    overflow:hidden;
}
.one{
    width:200px;/* As per your requirment */
    height:auto;
    float:left;
}

.two{
    width:200px;/* As per your requirment */
    height:auto;
    float:left;
}

-----------------------OR------------------------------

    <div class="cointainer">
        <div class="one">Content One</div>
        <div class="two">Content Two</div>
        <div class="clearfix"></div>
    </div>

Here is the following css:

    .container{
        width:100%;/* As per your requirment */
        height:auto;
        float:left;
        overflow:hidden;
    }
    .one{
        width:200px;/* As per your requirment */
        height:auto;
        float:left;
    }

    .two{
        width:200px;/* As per your requirment */
        height:auto;
        float:left;
    }
    .clearfix:before,
    .clearfix:after{
        display: table;
        content: " ";
    }
    .clearfix:after{
        clear: both;
    }

How to find array / dictionary value using key?

It's as simple as this :

$array[$key];

How to get attribute of element from Selenium?

You are probably looking for get_attribute(). An example is shown here as well

def test_chart_renders_from_url(self):
    url = 'http://localhost:8000/analyse/'
    self.browser.get(url)
    org = driver.find_element_by_id('org')
    # Find the value of org?
    val = org.get_attribute("attribute name")

How to check what version of jQuery is loaded?

You can just check if the jQuery object exists:

if( typeof jQuery !== 'undefined' ) ... // jQuery loaded

jQuery().jquery has the version number.

As for the prefix, jQuery should always work. If you want to use $ you can wrap your code to a function and pass jQuery to it as the parameter:

(function( $ ) {
    $( '.class' ).doSomething();  // works always
})( jQuery )

How do I check if a string contains another string in Swift?

From the docs, it seems that calling containsString() on a String should work:

Swift’s String type is bridged seamlessly to Foundation’s NSString class. If you are working with the Foundation framework in Cocoa or Cocoa Touch, the entire NSString API is available to call on any String value you create, in addition to the String features described in this chapter. You can also use a String value with any API that requires an NSString instance.

However, it doesn't seem to work that way.

If you try to use someString.containsString(anotherString), you will get a compile time error that states 'String' does not contain a member named 'containsString'.

So, you're left with a few options, one of which is to explicitly bridge your String to Objective-C by using bridgeToObjectiveC() other two involve explicitly using an NSString and the final one involves casting the String to an NSString

By bridging, you'd get:

var string = "hello Swift"
if string.bridgeToObjectiveC().containsString("Swift") {
    println("YES")
}

By explicitly typing the string as an NSString, you'd get:

var string: NSString = "hello Swift"
if string.containsString("Swift") {
    println("YES")
}

If you have an existing String, you can initialize an NSString from it by using NSString(string:):

var string = "hello Swift"
if NSString(string: string).containsString("Swift") {
    println("YES")
}

And finally, you can cast an existing String to an NSString as below

var string = "hello Swift"
if (string as NSString).containsString("Swift") {
    println("YES")
}

format a Date column in a Data Frame

This should do it (where df is your dataframe)

df$JoiningDate <- as.Date(df$JoiningDate , format = "%m/%d/%y")

df[order(df$JoiningDate ),]

How to select first parent DIV using jQuery?

Use .closest() to traverse up the DOM tree up to the specified selector.

var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes.

How to convert string to integer in C#

bool result = Int32.TryParse(someString, out someNumeric)

This method will try to convert someString into someNumeric, and return a result depends if the conversion is successful, true if conversion is successful and false if conversion failed. Take note that this method will not throw exception if the conversion failed like how Int32.Parse method did and instead it returns zero for someNumeric.

For more information, you can read here:

https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
&
How to convert string to integer in C#

How can I determine browser window size on server side C#

You can use Javascript to get the viewport width and height. Then pass the values back via a hidden form input or ajax.

At its simplest

var width = $(window).width();
var height = $(window).height();

Complete method using hidden form inputs

Assuming you have: JQuery framework.

First, add these hidden form inputs to store the width and height until postback.

<asp:HiddenField ID="width" runat="server" />
<asp:HiddenField ID="height" runat="server" />

Next we want to get the window (viewport) width and height. JQuery has two methods for this, aptly named width() and height().

Add the following code to your .aspx file within the head element.

<script type="text/javascript">
$(document).ready(function() {

    $("#width").val() = $(window).width();
    $("#height").val() = $(window).height();    

});
</script>

Result

This will result in the width and height of the browser window being available on postback. Just access the hidden form inputs like this:

var TheBrowserWidth = width.Value;
var TheBrowserHeight = height.Value;

This method provides the height and width upon postback, but not on the intial page load.

Note on UpdatePanels: If you are posting back via UpdatePanels, I believe the hidden inputs need to be within the UpdatePanel.

Alternatively you can post back the values via an ajax call. This is useful if you want to react to window resizing.

Update for jquery 3.1.1

I had to change the JavaScript to:

$("#width").val($(window).width());
$("#height").val($(window).height());

add item in array list of android

you can use this add string to list on a button click

final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() 
        {

            @Override
            public void onClick(View v) 
            {
                // TODO Auto-generated method stub
                int k=sp.getCount();
                String a1[]=new String[k+1];
                for(int i=0;i<k;i++)
                    a1[i]=sp.getItemAtPosition(i).toString();
                a1[k]=et.getText().toString();
                ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
                sp.setAdapter(ats);
            }
        });

So on a button click it will get string from edittext and store in listitem. you can change this to your needs.

Plotting in a non-blocking way with Matplotlib

You can avoid blocking execution by writing the plot to an array, then displaying the array in a different thread. Here is an example of generating and displaying plots simultaneously using pf.screen from pyformulas 0.2.8:

import pyformulas as pf
import matplotlib.pyplot as plt
import numpy as np
import time

fig = plt.figure()

canvas = np.zeros((480,640))
screen = pf.screen(canvas, 'Sinusoid')

start = time.time()
while True:
    now = time.time() - start

    x = np.linspace(now-2, now, 100)
    y = np.sin(2*np.pi*x) + np.sin(3*np.pi*x)
    plt.xlim(now-2,now+1)
    plt.ylim(-3,3)
    plt.plot(x, y, c='black')

    # If we haven't already shown or saved the plot, then we need to draw the figure first...
    fig.canvas.draw()

    image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
    image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))

    screen.update(image)

#screen.close()

Result:

Sine animation

Disclaimer: I'm the maintainer for pyformulas.

Reference: Matplotlib: save plot to numpy array

Converting array to list in Java

Using Arrays

This is the simplest way to convert an array to List. However, if you try to add a new element or remove an existing element from the list, an UnsupportedOperationException will be thrown.

Integer[] existingArray = {1, 2, 3};
List<Integer> list1 = Arrays.asList(existingArray);
List<Integer> list2 = Arrays.asList(1, 2, 3);

// WARNING:
list2.add(1);     // Unsupported operation!
list2.remove(1);  // Unsupported operation!

Using ArrayList or Other List Implementations

You can use a for loop to add all the elements of the array into a List implementation, e.g. ArrayList:

List<Integer> list = new ArrayList<>();
for (int i : new int[]{1, 2, 3}) {
  list.add(i);
}

Using Stream API in Java 8

You can turn the array into a stream, then collect the stream using different collectors: The default collector in Java 8 use ArrayList behind the screen, but you can also impose your preferred implementation.

List<Integer> list1, list2, list3;
list1 = Stream.of(1, 2, 3).collect(Collectors.toList());
list2 = Stream.of(1, 2, 3).collect(Collectors.toCollection(ArrayList::new));
list3 = Stream.of(1, 2, 3).collect(Collectors.toCollection(LinkedList::new));

See also:

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

Don't change link color when a link is clicked

I think this suits perfect for any color you have:

a {
    color: inherit;
}

an htop-like tool to display disk activity in linux

You could use iotop. It doesn't rely on a kernel patch. It Works with stock Ubuntu kernel

There is a package for it in the Ubuntu repos. You can install it using

sudo apt-get install iotop

iotop

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

Here is the code of a minimal example showing that you always have to redraw every pixel of the Canvas at each frame.

This activity draw a new Bitmap every second on the SurfaceView, without clearing the screen before. If you test it, you will see that the bitmap is not always written to the same buffer, and the screen will alternate between the two buffers.

I tested it on my phone (Nexus S, Android 2.3.3), and on the emulator (Android 2.2).

public class TestCanvas extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new TestView(this));
    }
}

class TestView extends SurfaceView implements SurfaceHolder.Callback {

    private TestThread mThread;
    private int mWidth;
    private int mHeight;
    private Bitmap mBitmap;
    private SurfaceHolder mSurfaceHolder;

    public TestView(Context context) {
        super(context);
        mThread = new TestThread();
        mBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
        mSurfaceHolder = getHolder();
        mSurfaceHolder.addCallback(this);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        mWidth = width;
        mHeight = height;
        mThread.start();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {/* Do nothing */}

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mThread != null && mThread.isAlive())
            mThread.interrupt();
    }

    class TestThread extends Thread {
        @Override
        public void run() {
            while (!isInterrupted()) {
                Canvas c = null;
                try {
                    c = mSurfaceHolder.lockCanvas(null);
                    synchronized (mSurfaceHolder) {
                        c.drawBitmap(mBitmap, (int) (Math.random() * mWidth), (int) (Math.random() * mHeight), null);
                    }
                } finally {
                    if (c != null)
                        mSurfaceHolder.unlockCanvasAndPost(c);
                }

                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    interrupt();
                }
            }
        }   
    }
}

Origin null is not allowed by Access-Control-Allow-Origin

I was looking for an solution to make an XHR request to a server from a local html file and found a solution using Chrome and PHP. (no Jquery)

Javascripts:

var x = new XMLHttpRequest(); 
if(x) x.onreadystatechange=function(){ 
    if (x.readyState === 4 && x.status===200){
        console.log(x.responseText); //Success
    }else{ 
        console.log(x); //Failed
    }
};
x.open(GET, 'http://example.com/', true);
x.withCredentials = true;
x.send();

My Chrome's request header Origin: null

My PHP response header (Note that 'null' is a string). HTTP_REFERER allow cross-origin from a remote server to another.

header('Access-Control-Allow-Origin: '.(trim($_SERVER['HTTP_REFERER'],'/')?:'null'),true);
header('Access-Control-Allow-Credentials:true',true);

I was able to successfully connect to my server. You can disregards the Credentials headers, but this works for me with Apache's AuthType Basic enabled

I tested compatibility with FF and Opera, It works in many cases such as:

From a VM LAN IP (192.168.0.x) back to the VM'S WAN (public) IP:port
From a VM LAN IP back to a remote server domain name.
From a local .HTML file to the VM LAN IP and/or VM WAN IP:port,
From a local .HTML file to a remote server domain name.
And so on.

Passing data through intent using Serializable

Intent intent = new Intent(getApplicationContext(),SomeClass.class);
intent.putExtra("value",all_thumbs);
startActivity(intent);

In SomeClass.java

Bundle b = getIntent().getExtras();
if(b != null)
thumbs = (List<Thumbnail>) b.getSerializable("value");

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

You can always just export the registry, change the setting, then export the registry again and do a diff.

Convert ASCII TO UTF-8 Encoding

If you know for sure that your current encoding is pure ASCII, then you don't have to do anything because ASCII is already a valid UTF-8.

But if you still want to convert, just to be sure that its UTF-8, then you can use iconv

$string = iconv('ASCII', 'UTF-8//IGNORE', $string);

The IGNORE will discard any invalid characters just in case some were not valid ASCII.

MySQL search and replace some text in a field

In my experience, the fastest method is

UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE field LIKE '%foo%';

The INSTR() way is the second-fastest and omitting the WHERE clause altogether is slowest, even if the column is not indexed.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

The right answer is

Decoupled the build-specific components of the Android SDK from the platform-tools component, so that the build tools can be updated independently of the integrated development environment (IDE) components.

link (expand Revision 17)

How to remove focus border (outline) around text/input boxes? (Chrome)

I've found the solution.
I used: outline:none; in the CSS and it seems to have worked. Thanks for the help anyway. :)

@JsonProperty annotation on field as well as getter/setter

In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.

In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.

With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.

Show current assembly instruction in GDB

You can do

display/i $pc

and every time GDB stops, it will display the disassembly of the next instruction.

GDB-7.0 also supports set disassemble-next-line on, which will disassemble the entire next line, and give you more of the disassembly context.

Can I add color to bootstrap icons only using CSS?

Also works with the style tag:

<span class="glyphicon glyphicon-ok" style="color:#00FF00;"></span>

<span class="glyphicon glyphicon-remove" style="color:#FF0000;"></span>

enter image description here

How does #include <bits/stdc++.h> work in C++?

Unfortunately that approach is not portable C++ (so far).

All standard names are in namespace std and moreover you cannot know which names are NOT defined by including and header (in other words it's perfectly legal for an implementation to declare the name std::string directly or indirectly when using #include <vector>).

Despite this however you are required by the language to know and tell the compiler which standard header includes which part of the standard library. This is a source of portability bugs because if you forget for example #include <map> but use std::map it's possible that the program compiles anyway silently and without warnings on a specific version of a specific compiler, and you may get errors only later when porting to another compiler or version.

In my opinion there are no valid technical excuses because this is necessary for the general user: the compiler binary could have all standard namespace built in and this could actually increase the performance even more than precompiled headers (e.g. using perfect hashing for lookups, removing standard headers parsing or loading/demarshalling and so on).

The use of standard headers simplifies the life of who builds compilers or standard libraries and that's all. It's not something to help users.

However this is the way the language is defined and you need to know which header defines which names so plan for some extra neurons to be burnt in pointless configurations to remember that (or try to find and IDE that automatically adds the standard headers you use and removes the ones you don't... a reasonable alternative).

How do you keep parents of floated elements from collapsing?

Strange no one has come up with a complete answer for this yet, ah well here it is.

Solution one: clear: both

Adding a block element with the style clear:both; onto it will clear the floats past that point and stop the parent of that element from collapsing. http://jsfiddle.net/TVD2X/1/

Pros: Allows you to clear an element and elements you add below will not be effected by the floated elements above and valid css.

Cons: Requires the another tag to clear the floats, bloating markup.

Note: To fall back to IE6 and for it to work on abstinent parents (i.e. the input element) you are not able to use :after.

Solution two: display: table

Adding display:table; to the parent to make it shrug off the floats and display with the correct height. http://jsfiddle.net/h9GAZ/1/

Pros: No extra markup and is a lot neater. Works in IE6+

Cons: Requires invalid css to make sure everything plays nice in IE6 and 7.

Note: The IE6 and 7 width auto is used to prevent the width being 100%+padding, which is not the case in newer browsers.

A note on the other "solutions"

These fixes work back to the lowest supported browser, over 1% usage globally (IE6), which means using :after does not cut it.

Overflow hidden does show the content but does not prevent the element from collapsing and so does not answer the question. Using an inline block can have buggy results, children having strange margins and so on, table is much better.

Setting the height does "prevent" the collapse but it is not a proper fix.

Invalid css

Invalid css never hurt anyone, in fact, it is now the norm. Using browser prefixes is just as invalid as using browser specific hacks and doesn't impact the end user what so ever.

In conclusion

I use both of the above solutions to make elements react correctly and play nicely with each other, I implore you to do the same.

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

What's the difference between Apache's Mesos and Google's Kubernetes

Mesos and Kubernetes can both be used to manage a cluster of machines and abstract away the hardware.

Mesos, by design, doesn't provide you with a scheduler (to decide where and when to run processes and what to do if the process fails), you can use something like Marathon or Chronos, or write your own.

Kubernetes will do scheduling for you out of the box, and can be used as a scheduler for Mesos (please correct me if I'm wrong here!) which is where you can use them together. Mesos can have multiple schedulers sharing the same cluster, so in theory you could run kubernetes and chronos together on the same hardware.

Super simplistically: if you want control over how your containers are scheduled, go for Mesos, otherwise Kubernetes rocks.

How do I use Docker environment variable in ENTRYPOINT array?

After much pain, and great assistance from @vitr et al above, i decided to try

  • standard bash substitution
  • shell form of ENTRYPOINT (great tip from above)

and that worked.

ENV LISTEN_PORT=""

ENTRYPOINT java -cp "app:app/lib/*" hello.Application --server.port=${LISTEN_PORT:-80}

e.g.

docker run --rm -p 8080:8080 -d --env LISTEN_PORT=8080 my-image

and

docker run --rm -p 8080:80 -d my-image

both set the port correctly in my container

Refs

see https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html

How do you pass view parameters when navigating from an action in JSF2?

You can do it using Primefaces like this :

<p:button 
      outcome="/page2.xhtml?faces-redirect=true&amp;id=#{myBean.id}">
</p:button>

This IP, site or mobile application is not authorized to use this API key

I had the same issue and I found this.

On the url, it requires the server key in the end and not the api key for the app.

So Basically, you just add the server key in the end of the URL like this:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=yourlatitude,yourlongitude&radius=5000&sensor=true&key=SERVERKEY

Now, to obtain the server key, just follow these steps:

1) Go to Developer Console https://code.google.com/apis/console/

2) In the Credentials, under Public API Access, Create New key

3) Select the server key from the option.

4) Enter your IP Address on the field and if you have more ip addresses, you can just add on every single line.NOTE: Enter the IP Address only when you want to use it for your testing purpose. Else leave the IP Address section blank.

5) Once you are done, click create and your new Server Key will be generated and you can then add that server key to your URL.

Last thing is that, instead of putting the sensor=true in the middle of the URL, you can add it in the end like this:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=yourlatitude,yourlongitude&radius=5000&key=SERVERKEY&sensor=true

This will definitely solve the issue and just remember to use the server key for Places API.

EDIT

I believe the web URL has changed in the past years. You can access developers console from here now - https://console.developers.google.com/apis/dashboard

  • Navigate to developers console - https://console.developers.google.com/ or use the link from details to navigate directly to API dashboard.
  • Under developer console, find Label from the left navigation panel
  • Select project
  • Choose Credentials from the left Navigation panel
  • You could create credentials type from the Top nav bar as required.

Hope this answer will help you and other viewers. Good Luck .. :)

Parsing XML with namespace in Python via 'ElementTree'

ElementTree is not too smart about namespaces. You need to give the .find(), findall() and iterfind() methods an explicit namespace dictionary. This is not documented very well:

namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed

root.findall('owl:Class', namespaces)

Prefixes are only looked up in the namespaces parameter you pass in. This means you can use any namespace prefix you like; the API splits off the owl: part, looks up the corresponding namespace URL in the namespaces dictionary, then changes the search to look for the XPath expression {http://www.w3.org/2002/07/owl}Class instead. You can use the same syntax yourself too of course:

root.findall('{http://www.w3.org/2002/07/owl#}Class')

If you can switch to the lxml library things are better; that library supports the same ElementTree API, but collects namespaces for you in a .nsmap attribute on elements.

How can I do SELECT UNIQUE with LINQ?

The Distinct() is going to mess up the ordering, so you'll have to the sorting after that.

var uniqueColors = 
               (from dbo in database.MainTable 
                 where dbo.Property == true 
                 select dbo.Color.Name).Distinct().OrderBy(name=>name);

Nginx 403 forbidden for all files

Old question, but I had the same issue. I tried every answer above, nothing worked. What fixed it for me though was removing the domain, and adding it again. I'm using Plesk, and I installed Nginx AFTER the domain was already there.

Did a local backup to /var/www/backups first though. So I could easily copy back the files.

Strange problem....

How do you put an image file in a json object?

public class UploadToServer extends Activity {

TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;

String upLoadServerUri = null;

/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_to_server);

    uploadButton = (Button) findViewById(R.id.uploadButton);
    messageText = (TextView) findViewById(R.id.messageText);

    messageText.setText("Uploading file path :- '/mnt/sdcard/"
            + uploadFileName + "'");

    /************* Php script path ****************/
    upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";

    uploadButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(UploadToServer.this, "",
                    "Uploading file...", true);

            new Thread(new Runnable() {
                public void run() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText.setText("uploading started.....");
                        }
                    });

                    uploadFile(uploadFilePath + "" + uploadFileName);

                }
            }).start();
        }
    });
}

public int uploadFile(String sourceFileUri) {

    String fileName = sourceFileUri;

    HttpURLConnection connection = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
                + uploadFileName);

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :"
                        + uploadFilePath + "" + uploadFileName);
            }
        });

        return 0;

    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP connection to the URL
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true); // Allow Inputs
            connection.setDoOutput(true); // Allow Outputs
            connection.setUseCaches(false); // Don't use a Cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(connection.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            // dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
            // + fileName + "\"" + lineEnd);
            dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                    + URLEncoder.encode(fileName, "UTF-8") + lineEnd);

            dos.writeBytes(lineEnd);

            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {

                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                + " http://www.androidexample.com/media/uploads/"
                                + uploadFileName;

                        messageText.setText(msg);
                        Toast.makeText(UploadToServer.this,
                                "File Upload Complete.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText
                            .setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(UploadToServer.this,
                            "MalformedURLException", Toast.LENGTH_SHORT)
                            .show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Got Exception : see logcat ");
                    Toast.makeText(UploadToServer.this,
                            "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

PHP File

<?php
$target_path  = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).    " has been uploaded";
} else {
    echo "There was an error uploading the file, please try again!";
}

?>

What does "atomic" mean in programming?

In Java reading and writing fields of all types except long and double occurs atomically, and if the field is declared with the volatile modifier, even long and double are atomically read and written. That is, we get 100% either what was there, or what happened there, nor can there be any intermediate result in the variables.

Finding Variable Type in JavaScript

Use typeof:

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

So you can do:

if(typeof bar === 'number') {
   //whatever
}

Be careful though if you define these primitives with their object wrappers (which you should never do, use literals where ever possible):

> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"

The type of an array is still object. Here you really need the instanceof operator.

Update:

Another interesting way is to examine the output of Object.prototype.toString:

> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"

With that you would not have to distinguish between primitive values and objects.

Calling a Sub and returning a value

You should be using a Property:

Private _myValue As String
Public Property MyValue As String
    Get
        Return _myValue
    End Get
    Set(value As String)
        _myValue = value
     End Set
End Property

Then use it like so:

MyValue = "Hello"
Console.write(MyValue)

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Update 2015-06

Based on antoinepairet's comment/example:

Using uib-collapse attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview

<nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">

        <!-- note the ng-init and ng-click here: -->
        <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Brand</a>
    </div>

    <div class="collapse navbar-collapse" uib-collapse="navCollapsed">
        <ul class="nav navbar-nav">
        ...
        </ul>
    </div>
</nav>

Ancient..

I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:

The only variation from the official bootstrap example is the addition of ng- attributes noted by comments, below:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">

    <!-- note the ng-init and ng-click here: -->
    <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- note the ng-class here -->
  <div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">

    <ul class="nav navbar-nav">
    ...

Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)

This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!

Search and replace a line in a file in Python

A more pythonic way would be to use context managers like the code below:

from tempfile import mkstemp
from shutil import move
from os import remove

def replace(source_file_path, pattern, substring):
    fh, target_file_path = mkstemp()
    with open(target_file_path, 'w') as target_file:
        with open(source_file_path, 'r') as source_file:
            for line in source_file:
                target_file.write(line.replace(pattern, substring))
    remove(source_file_path)
    move(target_file_path, source_file_path)

You can find the full snippet here.

Add & delete view from Layout

This is the best way

LinearLayout lp = new LinearLayout(this);
lp.addView(new Button(this));
lp.addView(new ImageButton(this));
// Now remove them 
lp.removeViewAt(0); // and so on

If you have xml layout then no need to add dynamically.just call

lp.removeViewAt(0);

How do I control how Emacs makes backup files?

Another way of configuring backup options is via the Customize interface. Enter:

M-x customize-group

And then at the Customize group: prompt enter backup.

If you scroll to the bottom of the buffer you'll see Backup Directory Alist. Click Show Value and set the first entry of the list as follows:

Regexp matching filename: .*
Backup directory name: /path/to/your/backup/dir

Alternatively, you can turn backups off my setting Make Backup Files to off.

If you don't want Emacs to automatically edit your .emacs file you'll want to set up a customisations file.

How to get C# Enum description from value?

You can't easily do this in a generic way: you can only convert an integer to a specific type of enum. As Nicholas has shown, this is a trivial cast if you only care about one kind of enum, but if you want to write a generic method that can handle different kinds of enums, things get a bit more complicated. You want a method along the lines of:

public static string GetEnumDescription<TEnum>(int value)
{
  return GetEnumDescription((Enum)((TEnum)value));  // error!
}

but this results in a compiler error that "int can't be converted to TEnum" (and if you work around this, that "TEnum can't be converted to Enum"). So you need to fool the compiler by inserting casts to object:

public static string GetEnumDescription<TEnum>(int value)
{
  return GetEnumDescription((Enum)(object)((TEnum)(object)value));  // ugly, but works
}

You can now call this to get a description for whatever type of enum is at hand:

GetEnumDescription<MyEnum>(1);
GetEnumDescription<YourEnum>(2);

size of NumPy array

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape

Python: CSV write by column rather than row

Let's assume that (1) you don't have a large memory (2) you have row headings in a list (3) all the data values are floats; if they're all integers up to 32- or 64-bits worth, that's even better.

On a 32-bit Python, storing a float in a list takes 16 bytes for the float object and 4 bytes for a pointer in the list; total 20. Storing a float in an array.array('d') takes only 8 bytes. Increasingly spectacular savings are available if all your data are int (any negatives?) that will fit in 8, 4, 2 or 1 byte(s) -- especially on a recent Python where all ints are longs.

The following pseudocode assumes floats stored in array.array('d'). In case you don't really have a memory problem, you can still use this method; I've put in comments to indicate the changes needed if you want to use a list.

# Preliminary:
import array # list: delete
hlist = []
dlist = []
for each row: 
    hlist.append(some_heading_string)
    dlist.append(array.array('d')) # list: dlist.append([])
# generate data
col_index = -1
for each column:
    col_index += 1
    for row_index in xrange(len(hlist)):
        v = calculated_data_value(row_index, colindex)
        dlist[row_index].append(v)
# write to csv file
for row_index in xrange(len(hlist)):
    row = [hlist[row_index]]
    row.extend(dlist[row_index])
    csv_writer.writerow(row)

Where does System.Diagnostics.Debug.Write output appear?

While you are debugging in Visual Studio, display the "Output" window (View->Output). It will show there.

How can I create directories recursively?

Here is my implementation for your reference:

def _mkdir_recursive(self, path):
    sub_path = os.path.dirname(path)
    if not os.path.exists(sub_path):
        self._mkdir_recursive(sub_path)
    if not os.path.exists(path):
        os.mkdir(path)

Hope this help!

How to list imported modules?

Stealing from @Lila (couldn't make a comment because of no formatting), this shows the module's /path/, as well:

#!/usr/bin/env python
import sys
from modulefinder import ModuleFinder
finder = ModuleFinder()
# Pass the name of the python file of interest
finder.run_script(sys.argv[1])
# This is what's different from @Lila's script
finder.report()

which produces:

Name                      File
----                      ----

...
m token                     /opt/rh/rh-python35/root/usr/lib64/python3.5/token.py
m tokenize                  /opt/rh/rh-python35/root/usr/lib64/python3.5/tokenize.py
m traceback                 /opt/rh/rh-python35/root/usr/lib64/python3.5/traceback.py
...

.. suitable for grepping or what have you. Be warned, it's long!

CKEditor automatically strips classes from div

Edit: this answer is for those who use ckeditor module in drupal.

I found a solution which doesn't require modifying ckeditor js file.

this answer is copied from here. all credits should goes to original author.

Go to "Admin >> Configuration >> CKEditor"; under Profiles, choose your profile (e.g. Full).

Edit that profile, and on "Advanced Options >> Custom JavaScript configuration" add config.allowedContent = true;.

enter image description here

Don't forget to flush the cache under "Performance tab."

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

Following the unobtrusive principle, it's not quite required for "_myPartial" to inject content directly into scripts section. You could add those partial view scripts into separate .js file and reference them into @scripts section from parent view.

Error when trying to access XAMPP from a network

This answer is for XAMPP on Ubuntu.

The manual for installation and download is on (site official)

http://www.apachefriends.org/it/xampp-linux.html

After to start XAMPP simply call this command:

sudo /opt/lampp/lampp start

You should now see something like this on your screen:

Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.

If you have this

Starting XAMPP for Linux 1.8.1...                                                             
XAMPP: Another web server daemon is already running.                                          
XAMPP: Another MySQL daemon is already running.                                               
XAMPP: Starting ProFTPD...                                                                    
XAMPP for Linux started

. The solution is

sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop

And the restast with sudo //opt/lampp/lampp restart

You to fix most of the security weaknesses simply call the following command:

/opt/lampp/lampp security

After the change this file

sudo kate //opt/lampp/etc/extra/httpd-xampp.conf

Find and replace on

    #
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    Allow from all
    #\
    #   fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
    #   fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Where does MySQL store database files on Windows and what are the names of the files?

in MySQL are
".myd" a database self and
".tmd" a temporal file.
But sometimes I see also ".sql".

It depends on your settings and/or export method.

How do implement a breadth first traversal?

This code which you have written, is not producing correct BFS traversal: (This is the code you claimed is BFS, but in fact this is DFS!)

//  search traversal
  public void breadth(TreeNode root){
      if (root == null)
          return;

      System.out.print(root.element + " ");
      breadth(root.left);
      breadth(root.right);
 }

Rails Root directory path?

You can use:

Rails.root

But to to join the assets you can use:

Rails.root.join(*%w( app assets))

Hopefully this helps you.

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Deleting/commenting

- (void)viewWillAppear:(BOOL)animated {[super viewWillAppear:YES];}

function solved the problem for me.

XCode (11.3.1)

Which are more performant, CTE or temporary tables?

I'd say they are different concepts but not too different to say "chalk and cheese".

  • A temp table is good for re-use or to perform multiple processing passes on a set of data.

  • A CTE can be used either to recurse or to simply improved readability.
    And, like a view or inline table valued function can also be treated like a macro to be expanded in the main query

  • A temp table is another table with some rules around scope

I have stored procs where I use both (and table variables too)

What exactly is the function of Application.CutCopyMode property in Excel

Normally, When you copy a cell you will find the below statement written down in the status bar (in the bottom of your sheet)

"Select destination and Press Enter or Choose Paste"

Then you press whether Enter or choose paste to paste the value of the cell.

If you didn't press Esc afterwards you will be able to paste the value of the cell several times

Application.CutCopyMode = False does the same like the Esc button, if you removed it from your code you will find that you are able to paste the cell value several times again.

And if you closed the Excel without pressing Esc you will get the warning 'There is a large amount of information on the Clipboard....'

Recommended Fonts for Programming?

I use Inconsolata in both Linux and Mac OS X.

Jasmine.js comparing arrays

Just did the test and it works with toEqual

please find my test:

http://jsfiddle.net/7q9N7/3/

describe('toEqual', function() {
    it('passes if arrays are equal', function() {
        var arr = [1, 2, 3];
        expect(arr).toEqual([1, 2, 3]);
    });
});

Just for information:

toBe() versus toEqual(): toEqual() checks equivalence. toBe(), on the other hand, makes sure that they're the exact same object.

How to hide underbar in EditText

if your edit text already has a background then you can use following.

android:textCursorDrawable="@null"

What's the difference between VARCHAR and CHAR?

Varchar cuts off trailing spaces if the entered characters is shorter than the declared length, while char will not. Char will pad spaces and will always be the length of the declared length. In terms of efficiency, varchar is more adept as it trims characters to allow more adjustment. However, if you know the exact length of char, char will execute with a bit more speed.

node.js: cannot find module 'request'

ReferenceError: Can't find variable: require.

You have installed "npm", you can run as normal the script to a "localhost" "127.0.0.1".

When you use the http.clientRequest() with "options" in a "npm" you need to install "RequireJS" inside of the module.

A module is any file or directory in the node_modules directory that can be loaded by the Node. Install "RequiereJS" for to make work the http.clientRequest(options).

Failed to open/create the internal network Vagrant on Windows10

Reboot your PC


Sadly, https://stackoverflow.com/a/33733454/2191572 did not work for me in Windows 10 x64 with VirtualBox 5.2.6

The box was already checked and a simple reboot fixed it.

After years of telling people to just reboot, I failed to follow my own golden advice; face, meet palm.

Delaying AngularJS route change until model loaded to prevent flicker

I have had a complex multi-level sliding panel interface, with disabled screen layer. Creating directive on disable screen layer that would create click event to execute the state like

$state.go('account.stream.social.view');

were producing a flicking effect. history.back() instead of it worked ok, however its not always back in history in my case. SO what I find out is that if I simply create attribute href on my disable screen instead of state.go , worked like a charm.

<a class="disable-screen" back></a>

Directive 'back'

app.directive('back', [ '$rootScope', function($rootScope) {

    return {
        restrict : 'A',
        link : function(scope, element, attrs) {
            element.attr('href', $rootScope.previousState.replace(/\./gi, '/'));
        }
    };

} ]);

app.js I just save previous state

app.run(function($rootScope, $state) {      

    $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {         

        $rootScope.previousState = fromState.name;
        $rootScope.currentState = toState.name;


    });
});

Calling other function in the same controller?

Yes. Problem is in wrong notation. Use:

$this->sendRequest($uri)

Instead. Or

self::staticMethod()

for static methods. Also read this for getting idea of OOP - http://www.php.net/manual/en/language.oop5.basic.php

Which language uses .pde extension?

Software application written with Arduino, an IDE used for prototyping electronics; contains source code written in the Arduino programming language; enables developers to control the electronics on an Arduino circuit board.

To avoid file association conflicts with the Processing software, Arduino changed the Sketch file extension to .INO with the version 1.0 release. Therefore, while Arduino can still open ".pde" files, the ".ino" file extension should be used instead.

Each PDE file is stored in its own folder when saved from the Processing IDE. It is saved with any other program assets, such as images. The project folder and PDE filename prefix have the same name. When the PDE file is run, it is opened in a Java display window, which renders and runs the resulting program.

Processing is commonly used in educational settings for teaching basic programming skills in a visual environment.

jQuery Ajax error handling, show custom exception messages

Throw a new exception on server using:

Response.StatusCode = 500

Response.StatusDescription = ex.Message()

I believe that the StatusDescription is returned to the Ajax call...

Example:

        Try

            Dim file As String = Request.QueryString("file")

            If String.IsNullOrEmpty(file) Then Throw New Exception("File does not exist")

            Dim sTmpFolder As String = "Temp\" & Session.SessionID.ToString()

            sTmpFolder = IO.Path.Combine(Request.PhysicalApplicationPath(), sTmpFolder)

            file = IO.Path.Combine(sTmpFolder, file)

            If IO.File.Exists(file) Then

                IO.File.Delete(file)

            End If

        Catch ex As Exception

            Response.StatusCode = 500

            Response.StatusDescription = ex.Message()

        End Try

TokenMismatchException in VerifyCsrfToken.php Line 67

I was about to start pulling out my hair!

Please check your session cookie domain in session.php config. There is a domain option that has to match your environment and it's good practice to have this configurable with you .env file for development.

'domain' => env('COOKIE_DOMAIN', 'some-sensible-default.com'),

AngularJS not detecting Access-Control-Allow-Origin header?

CROS needs to be resolved from server side.

Create Filters as per requirement to allow access and add filters in web.xml

Example using spring:

Filter Class:

@Component
public class SimpleFilter implements Filter {

@Override
public void init(FilterConfig arg0) throws ServletException {}

@Override
public void doFilter(ServletRequest req, ServletResponse resp,
                     FilterChain chain) throws IOException, ServletException {

    HttpServletResponse response=(HttpServletResponse) resp;

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

    chain.doFilter(req, resp);
}

@Override
public void destroy() {}

}

Web.xml:

<filter>
    <filter-name>simpleCORSFilter</filter-name>
    <filter-class>
        com.abc.web.controller.general.SimpleFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>simpleCORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

When should I really use noexcept?

  1. There are many examples of functions that I know will never throw, but for which the compiler cannot determine so on its own. Should I append noexcept to the function declaration in all such cases?

noexcept is tricky, as it is part of the functions interface. Especially, if you are writing a library, your client code can depend on the noexcept property. It can be difficult to change it later, as you might break existing code. That might be less of a concern when you are implementing code that is only used by your application.

If you have a function that cannot throw, ask yourself whether it will like stay noexcept or would that restrict future implementations? For example, you might want to introduce error checking of illegal arguments by throwing exceptions (e.g., for unit tests), or you might depend on other library code that could change its exception specification. In that case, it is safer to be conservative and omit noexcept.

On the other hand, if you are confident that the function should never throw and it is correct that it is part of the specification, you should declare it noexcept. However, keep in mind that the compiler will not be able to detect violations of noexcept if your implementation changes.

  1. For which situations should I be more careful about the use of noexcept, and for which situations can I get away with the implied noexcept(false)?

There are four classes of functions that should you should concentrate on because they will likely have the biggest impact:

  1. move operations (move assignment operator and move constructors)
  2. swap operations
  3. memory deallocators (operator delete, operator delete[])
  4. destructors (though these are implicitly noexcept(true) unless you make them noexcept(false))

These functions should generally be noexcept, and it is most likely that library implementations can make use of the noexcept property. For example, std::vector can use non-throwing move operations without sacrificing strong exception guarantees. Otherwise, it will have to fall back to copying elements (as it did in C++98).

This kind of optimization is on the algorithmic level and does not rely on compiler optimizations. It can have a significant impact, especially if the elements are expensive to copy.

  1. When can I realistically expect to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.

The advantage of noexcept against no exception specification or throw() is that the standard allows the compilers more freedom when it comes to stack unwinding. Even in the throw() case, the compiler has to completely unwind the stack (and it has to do it in the exact reverse order of the object constructions).

In the noexcept case, on the other hand, it is not required to do that. There is no requirement that the stack has to be unwound (but the compiler is still allowed to do it). That freedom allows further code optimization as it lowers the overhead of always being able to unwind the stack.

The related question about noexcept, stack unwinding and performance goes into more details about the overhead when stack unwinding is required.

I also recommend Scott Meyers book "Effective Modern C++", "Item 14: Declare functions noexcept if they won't emit exceptions" for further reading.

How to fix the session_register() deprecated issue?

Don't use it. The description says:

Register one or more global variables with the current session.

Two things that came to my mind:

  1. Using global variables is not good anyway, find a way to avoid them.
  2. You can still set variables with $_SESSION['var'] = "value".

See also the warnings from the manual:

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

This is pretty important, because the register_globals directive is set to False by default!

Further:

This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.

and

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered(), and session_unregister().

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

This problem can be easily solved by installing the following Individual components:

enter image description here

jquery: get id from class selector

$(".class").click(function(){
    alert($(this).attr('id'));
});

only on jquery button click we can do this class should be written there

Setting state on componentDidMount()

The only reason that the linter complains about using setState({..}) in componentDidMount and componentDidUpdate is that when the component render the setState immediately causes the component to re-render. But the most important thing to note: using it inside these component's lifecycles is not an anti-pattern in React.

Please take a look at this issue. you will understand more about this topic. Thanks for reading my answer.

add scroll bar to table body

If you don't want to wrap a table under any div:

table{
  table-layout: fixed;
}
tbody{
      display: block;
    overflow: auto;
}

How should I pass multiple parameters to an ASP.Net Web API GET?

 [Route("api/controller/{one}/{two}")]
    public string Get(int One, int Two)
    {
        return "both params of the root link({one},{two}) and Get function parameters (one, two)  should be same ";
    }

Both params of the root link({one},{two}) and Get function parameters (one, two) should be same

Angular @ViewChild() error: Expected 2 arguments, but got 1

you should use second argument with ViewChild like this:

@ViewChild("eleDiv", { static: false }) someElement: ElementRef;

How do I find the time difference between two datetime objects in python?

I have used time differences for continuous integration tests to check and improve my functions. Here is simple code if somebody need it

from datetime import datetime

class TimeLogger:
    time_cursor = None

    def pin_time(self):
        global time_cursor
        time_cursor = datetime.now()

    def log(self, text=None) -> float:
        global time_cursor

        if not time_cursor:
            time_cursor = datetime.now()

        now = datetime.now()
        t_delta = now - time_cursor

        seconds = t_delta.total_seconds()

        result = str(now) + ' tl -----------> %.5f' % seconds
        if text:
            result += "   " + text
        print(result)

        self.pin_time()

        return seconds


time_logger = TimeLogger()

Using:

from .tests_time_logger import time_logger
class Tests(TestCase):
    def test_workflow(self):
    time_logger.pin_time()

    ... my functions here ...

    time_logger.log()

    ... other function(s) ...

    time_logger.log(text='Tests finished')

and i have something like that in log output

2019-12-20 17:19:23.635297 tl -----------> 0.00007
2019-12-20 17:19:28.147656 tl -----------> 4.51234   Tests finished

Import text file as single character string

It seems your solution is not much ugly. You can use functions and make it proffesional like these ways

  • first way
new.function <- function(filename){
  readChar(filename, file.info(filename)$size)
}

new.function('foo.txt')
  • second way
new.function <- function(){
  filename <- 'foo.txt'
  return (readChar(filename, file.info(filename)$size))
}

new.function()

An implementation of the fast Fourier transform (FFT) in C#

The Numerical Recipes website (http://www.nr.com/) has an FFT if you don't mind typing it in. I am working on a project converting a Labview program to C# 2008, .NET 3.5 to acquire data and then look at the frequency spectrum. Unfortunately the Math.Net uses the latest .NET framework, so I couldn't use that FFT. I tried the Exocortex one - it worked but the results to match the Labview results and I don't know enough FFT theory to know what is causing the problem. So I tried the FFT on the numerical recipes website and it worked! I was also able to program the Labview low sidelobe window (and had to introduce a scaling factor).

You can read the chapter of the Numerical Recipes book as a guest on thier site, but the book is so useful that I highly recomend purchasing it. Even if you do end up using the Math.NET FFT.

Get url without querystring

Solution for Silverlight:

string path = HtmlPage.Document.DocumentUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);

Kill a Process by Looking up the Port being used by it from a .BAT

Just for completion:

I wanted to kill all processes connected to a specific port but not the process listening

the command (in cmd shell) for the port 9001 is:

FOR /F "tokens=5 delims= " %P IN ('netstat -ano ^| findstr -rc:":9001[ ]*ESTA"') DO TaskKill /F /PID %P

findstr:

  • r is for expressions and c for exact chain to match.
  • [ ]* is for matching spaces

netstat:

  • a -> all
  • n -> don't resolve (faster)
  • o -> pid

It works because netstat prints out the source port then destination port and then ESTABLISHED

How to query a CLOB column in Oracle

To add to the answer.

declare
v_result clob;
begin
---- some operation on v_result
dbms_lob.substr( v_result, 4000 ,length(v_result) - 3999 );

end;
/

In dbms_lob.substr

first parameter is clob which you want to extract .

Second parameter is how much length of clob you want to extract.

Third parameter is from which word you want to extract .

In above example i know my clob size is more than 50000 , so i want last 4000 character .

How to disable/enable select field using jQuery?

To be able to disable/enable selects first of all your selects need an ID or class. Then you could do something like this:

Disable:

$('#id').attr('disabled', 'disabled');

Enable:

$('#id').removeAttr('disabled');

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

If this happened to you after renaming your application package name, then you need to update the following:

1)google-services.json file in your application by looking up in the file for "package_name" attribute and update it with the new package name.

2)Update your application client Credentials in Google Developers Console by going to the Credentials and selecting your android client key then update the package name as well with the new one.

Hope this will help.

How to read from stdin line by line in Node

In my case the program (elinks) returned lines that looked empty, but in fact had special terminal characters, color control codes and backspace, so grep options presented in other answers did not work for me. So I wrote this small script in Node.js. I called the file tight, but that's just a random name.

#!/usr/bin/env node

function visible(a) {
    var R  =  ''
    for (var i = 0; i < a.length; i++) {
        if (a[i] == '\b') {  R -= 1; continue; }  
        if (a[i] == '\u001b') {
            while (a[i] != 'm' && i < a.length) i++
            if (a[i] == undefined) break
        }
        else R += a[i]
    }
    return  R
}

function empty(a) {
    a = visible(a)
    for (var i = 0; i < a.length; i++) {
        if (a[i] != ' ') return false
    }
    return  true
}

var readline = require('readline')
var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false })

rl.on('line', function(line) {
    if (!empty(line)) console.log(line) 
})

How can I select records ONLY from yesterday?

trunc(tran_date) = trunc(sysdate -1)

How to remove carriage return and newline from a variable in shell script

use this command on your script file after copying it to Linux/Unix

perl -pi -e 's/\r//' scriptfilename

A quick and easy way to join array elements with a separator (the opposite of split) in Java

A fast and simple solution without any 3rd party includes.

public static String strJoin(String[] aArr, String sSep) {
    StringBuilder sbStr = new StringBuilder();
    for (int i = 0, il = aArr.length; i < il; i++) {
        if (i > 0)
            sbStr.append(sSep);
        sbStr.append(aArr[i]);
    }
    return sbStr.toString();
}

Need to combine lots of files in a directory

copy *.txt all.txt

This will concatenate all text files of the folder to one text file all.txt

If you have any other type of files, like sql files

copy *.sql all.sql

How do I ignore a directory with SVN?

Set the svn:ignore property. Most UI svn tools have a way to do this as well as the command line discussion in the link.

Command /usr/bin/codesign failed with exit code 1

In my case, I had an extra expired distribution certificate in my keychain - I deleted the certificate from KeyChain Access and the compilation started working again.

CSS media queries for screen sizes

For all smartphones and large screens use this format of media query

/* Smartphones (portrait and landscape) ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */

@media only screen and (min-width : 321px) {
/* Styles */
}



/* Smartphones (portrait) ----------- */

@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}

/**********
iPad 3
**********/

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* Desktops and laptops ----------- */

@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* iPhone 5 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6 ----------- */

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6+ ----------- */

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S3 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

/* Samsung Galaxy S5 ----------- */

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

Removing duplicates from a list of lists

This should work.

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]

k_cleaned = []
for ele in k:
    if set(ele) not in [set(x) for x in k_cleaned]:
        k_cleaned.append(ele)
print(k_cleaned)

# output: [[1, 2], [4], [5, 6, 2], [3]]

How to replace a substring of a string

2 things you should note:

  1. Strings in Java are immutable to so you need to store return value of thereplace method call in another String.
  2. You don't really need a regex here, just a simple call to String#replace(String) will do the job.

So just use this code:

String replaced = string.replace("abcd", "dddd");

Is there StartsWith or Contains in t sql with variables?

I would use

like 'Express Edition%'

Example:

DECLARE @edition varchar(50); 
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)

DECLARE @isExpress bit
if @edition like 'Express Edition%'
    set @isExpress = 1;
else
    set @isExpress = 0;

print @isExpress

What is the purpose of a plus symbol before a variable?

Operator + is a unary operator which converts value to number. Below I prepared a table with corresponding results of using this operator for different values.

+-----------------------------+-----------+
| Value                       | + (Value) |
+-----------------------------+-----------+
| 1                           | 1         |
| '-1'                        | -1        |
| '3.14'                      | 3.14      |
| '3'                         | 3         |
| '0xAA'                      | 170       |
| true                        | 1         |
| false                       | 0         |
| null                        | 0         |
| 'Infinity'                  | Infinity  |
| 'infinity'                  | NaN       |
| '10a'                       | NaN       |
| undefined                   | Nan       |
| ['Apple']                   | Nan       |
| function(val){ return val } | NaN       |
+-----------------------------+-----------+

Operator + returns value for objects which have implemented method valueOf.

let something = {
    valueOf: function () {
        return 25;
    }
};

console.log(+something);

How to obtain image size using standard Python class (without using external library)?

If you happen to have ImageMagick installed, then you can use 'identify'. For example, you can call it like this:

path = "//folder/image.jpg"
dim = subprocess.Popen(["identify","-format","\"%w,%h\"",path], stdout=subprocess.PIPE).communicate()[0]
(width, height) = [ int(x) for x in re.sub('[\t\r\n"]', '', dim).split(',') ]

When does a cookie with expiration time 'At end of session' expire?

When you use setcookie, you can either set the expiration time to 0 or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).

What is the $$hashKey added to my JSON.stringify result

Angular adds this to keep track of your changes, so it knows when it needs to update the DOM.

If you use angular.toJson(obj) instead of JSON.stringify(obj) then Angular will strip out these internal-use values for you.

Also, if you change your repeat expression to use the track by {uniqueProperty} suffix, Angular won't have to add $$hashKey at all. For example

<ul>
    <li ng-repeat="link in navLinks track by link.href">
        <a ng-href="link.href">{{link.title}}</a>
    </li>
</ul>

Just always remember you need the "link." part of the expression - I always tend to forget that. Just track by href will surely not work.

Are multiple `.gitignore`s frowned on?

Pro single

  • Easy to find.

  • Hunting down exclusion rules can be quite difficult if I have multiple gitignore, at several levels in the repo.

  • With multiple files, you also typically wind up with a fair bit of duplication.

Pro multiple

  • Scopes "knowledge" to the part of the file tree where it is needed.

  • Since Git only tracks files, an empty .gitignore is the only way to commit an "empty" directory.

    (And before Git 1.8, the only way to exclude a pattern like my/**.example was to create my/.gitignore in with the pattern **.foo. This reason doesn't apply now, as you can do /my/**/*.example.)


I much prefer a single file, where I can find all the exclusions. I've never missed per-directory .svn, and I won't miss per-directory .gitignore either.

That said, multiple gitignores are quite common. If you do use them, at least be consistent in their use to make them reasonable to work with. For example, you may put them in directories only one level from the root.

Difference between object and class in Scala

The formal difference -

  1. you can not provide constructor parameters for Objects
  2. Object is not a type - you may not create an instance with new operator. But it can have fields, methods, extend a superclass and mix in traits.

The difference in usage:

  • Scala doesn't have static methods or fields. Instead you should use object. You can use it with or without related class. In 1st case it's called a companion object. You have to:
    1. use the same name for both class and object
    2. put them in the same source file.
  • To create a program you should use main method in object, not in class.

    object Hello {
      def main(args: Array[String]) {
        println("Hello, World!")
      }
    }
    
  • You also may use it as you use singleton object in java.

      
        
      

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

To use an identity column in v10,

ALTER TABLE test 
ADD COLUMN id { int | bigint | smallint}
GENERATED { BY DEFAULT | ALWAYS } AS IDENTITY PRIMARY KEY;

For an explanation of identity columns, see https://blog.2ndquadrant.com/postgresql-10-identity-columns/.

For the difference between GENERATED BY DEFAULT and GENERATED ALWAYS, see https://www.cybertec-postgresql.com/en/sequences-gains-and-pitfalls/.

For altering the sequence, see https://popsql.io/learn-sql/postgresql/how-to-alter-sequence-in-postgresql/.

How make background image on newsletter in outlook?

You can use the code below :

<!--[if gte mso 9]>
<v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" 
style="width: 700px; height: 460px;">
<v:fill type="tile" src="images/feature-background-01.png" color="#333333" />   
<v:textbox inset="0,0,0,0">                                 
<![endif]-->

Note: Include this code above the table for which the background image is needed. Also, add the closing tag mentioned below, after the closing tag of the table.

<!--[if gte mso 9]>
      </v:textbox>
      </v:rect>
<![endif]-->

Show loading gif after clicking form submit using jQuery

Better and clean example using JS only

Reference: TheDeveloperBlog.com

Step 1 - Create your java script and place it in your HTML page.

<script type="text/javascript">
    function ShowLoading(e) {
        var div = document.createElement('div');
        var img = document.createElement('img');
        img.src = 'loading_bar.GIF';
        div.innerHTML = "Loading...<br />";
        div.style.cssText = 'position: fixed; top: 5%; left: 40%; z-index: 5000; width: 422px; text-align: center; background: #EDDBB0; border: 1px solid #000';
        div.appendChild(img);
        document.body.appendChild(div);
        return true;
        // These 2 lines cancel form submission, so only use if needed.
        //window.event.cancelBubble = true;
        //e.stopPropagation();
    }
</script>

in your form call the java script function on submit event.

<form runat="server"  onsubmit="ShowLoading()">
</form>

Soon after you submit the form, it will show you the loading image.

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

git: patch does not apply

WARNING: This command can remove old lost commits PERMANENTLY. Make a copy of your entire repository before attempting this.

I have found this link

I have no idea why this works but I tried many work arounds and this is the only one that worked for me. In short, run the three commands below:

git fsck --full
git reflog expire --expire=now --all
git gc --prune=now

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

How to convert between bytes and strings in Python 3?

The 'mangler' in the above code sample was doing the equivalent of this:

bytesThing = stringThing.encode(encoding='UTF-8')

There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8'), but the above syntax makes it obvious what is going on, and also what to do to recover the string:

newStringThing = bytesThing.decode(encoding='UTF-8')

When we do this, the original string is recovered.

Note, using str(bytesThing) just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8'). No error is reported if the encoding is not specified.

@AspectJ pointcut for all methods of a class with specific annotation

I share with you a code that can be useful, it is to create an annotation that can be used either in a class or a method.

@Target({TYPE, METHOD})
@Retention(RUNTIME)
@Documented
public @interface AnnotationLogger {
    /**
     * It is the parameter is to show arguments in the method or the class.
     */
    boolean showArguments() default false;
}


@Aspect
@Component
public class AnnotationLoggerAspect {
    
    @Autowired 
    private Logger logger;  
    
    private static final String METHOD_NAME   = "METHOD NAME: {} ";
    private static final String ARGUMENTS     = "ARGS: {} ";
    
    @Before(value = "@within(com.org.example.annotations.AnnotationLogger) || @annotation(com.org.example.annotations.AnnotationLogger)")
    public void logAdviceExecutionBefore(JoinPoint joinPoint){  
        CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
        AnnotationLogger annotationLogger = getAnnotationLogger(joinPoint);
        if(annotationLogger!= null) {
            StringBuilder annotationLoggerFormat = new StringBuilder();
            List<Object> annotationLoggerArguments = new ArrayList<>();
            annotationLoggerFormat.append(METHOD_NAME);
            annotationLoggerArguments.add(codeSignature.getName());
            
            if (annotationLogger.showArguments()) {
                annotationLoggerFormat.append(ARGUMENTS);
                List<?> argumentList = Arrays.asList(joinPoint.getArgs());
                annotationLoggerArguments.add(argumentList.toString());
            }
            logger.error(annotationLoggerFormat.toString(), annotationLoggerArguments.toArray());
        }
    }
    
    private AnnotationLogger getAnnotationLogger(JoinPoint joinPoint) {
        AnnotationLogger annotationLogger = null;
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = joinPoint.getTarget().getClass().
                    getMethod(signature.getMethod().getName(), signature.getMethod().getParameterTypes());
            
            if (method.isAnnotationPresent(AnnotationLogger.class)){
                annotationLogger = method.getAnnotation(AnnotationLoggerAspect.class);
            }else if (joinPoint.getTarget().getClass().isAnnotationPresent(AnnotationLoggerAspect.class)){
                annotationLogger = joinPoint.getTarget().getClass().getAnnotation(AnnotationLoggerAspect.class);
            }
            return annotationLogger;
        }catch(Exception e) {
            return annotationLogger;
        }
    }
}

How to get memory usage at runtime using C++?

On your system there is a file named /proc/self/statm. The proc filesystem is a pseudo-filesystem which provides an interface to kernel data structures. This file contains the information you need in columns with only integers that are space separated.

Column no.:

  1. = total program size (VmSize in /proc/[pid]/status)

  2. = resident set size (VmRSS in /proc/[pid]/status)

For more info see the LINK.

Copy data from one column to other column (which is in a different table)

Now it's more easy with management studio 2016.

Using SQL Server Management Studio

To copy data from one table to another

1.Open the table with columns you want to copy and the one you want to copy into by right-clicking the tables, and then clicking Design.

2.Click the tab for the table with the columns you want to copy and select those columns.

3.From the Edit menu, click Copy.

4.Open a new Query Editor window.

5.Right-click the Query Editor, and then click Design Query in Editor.

6.In the Add Table dialog box, select the source and destination table, click Add, and then close the Add Table dialog box.

7.Right-click an open area of the the Query Editor, point to Change Type, and then click Insert Results.

8.In the Choose Target Table for Insert Results dialog box, select the destination table.

9.In the upper portion of the Query Designer, click the source column in the source table.

10.The Query Designer has now created an INSERT query. Click OK to place the query into the original Query Editor window.

11.Execute the query to insert the data from the source table to the destination table.

For More Information https://docs.microsoft.com/en-us/sql/relational-databases/tables/copy-columns-from-one-table-to-another-database-engine

How to run test cases in a specified file?

Visual Studio Code shows a link at the top of a Go test file which lets you run all the tests in just that file.

enter image description here

In the "Output" window, you can see that it automatically generates a regex which contains all of the test names in the current file:

Running tool: C:\Go\bin\go.exe test -timeout 30s -run ^(TestFoo|TestBar|TestBaz)$ rootpackage\mypackage

Note: the very first time you open a Go file in VS Code it automatically offers to install some Go extensions for you. I assume the above requires that you have previously accepted the offer to install.

C linked list inserting node at the end

This works fine:

struct node *addNode(node *head, int value) {
    node *newNode = (node *) malloc(sizeof(node));
    newNode->value = value;
    newNode->next = NULL;

    if (head == NULL) {
        // Add at the beginning
        head = newNode;
    } else {
        node *current = head;

        while (current->next != NULL) {
            current = current->next;
        };

        // Add at the end
        current->next = newNode;
    }

    return head;
}

Example usage:

struct node *head = NULL;

for (int currentIndex = 1; currentIndex < 10; currentIndex++) {
    head = addNode(head, currentIndex);
}

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

Thanks, Ogapo! Exporting that alias worked for me, and then I followed the link, and in my case the mysql2.bundle was up in /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle so I adjusted the install_name_tool to modify that bundle rather than one in ~/.rvm and got that working the way it should be done.

So now:

   $ otool -L /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle 
    /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle:
        /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/libruby.1.dylib (compatibility version 1.8.0, current version 1.8.7)
        /usr/local/mysql/lib/libmysqlclient.16.dylib (compatibility version 16.0.0, current version 16.0.0)
        /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.1)

What is the volatile keyword useful for?

Important point about volatile:

  1. Synchronization in Java is possible by using Java keywords synchronized and volatile and locks.
  2. In Java, we can not have synchronized variable. Using synchronized keyword with a variable is illegal and will result in compilation error. Instead of using the synchronized variable in Java, you can use the java volatile variable, which will instruct JVM threads to read the value of volatile variable from main memory and don’t cache it locally.
  3. If a variable is not shared between multiple threads then there is no need to use the volatile keyword.

source

Example usage of volatile:

public class Singleton {
    private static volatile Singleton _instance; // volatile variable
    public static Singleton getInstance() {
        if (_instance == null) {
            synchronized (Singleton.class) {
                if (_instance == null)
                    _instance = new Singleton();
            }
        }
        return _instance;
    }
}

We are creating instance lazily at the time the first request comes.

If we do not make the _instance variable volatile then the Thread which is creating the instance of Singleton is not able to communicate to the other thread. So if Thread A is creating Singleton instance and just after creation, the CPU corrupts etc, all other threads will not be able to see the value of _instance as not null and they will believe it is still assigned null.

Why does this happen? Because reader threads are not doing any locking and until the writer thread comes out of a synchronized block, the memory will not be synchronized and value of _instance will not be updated in main memory. With the Volatile keyword in Java, this is handled by Java itself and such updates will be visible by all reader threads.

Conclusion: volatile keyword is also used to communicate the content of memory between threads.

Example usage of without volatile:

public class Singleton{    
    private static Singleton _instance;   //without volatile variable
    public static Singleton getInstance(){   
          if(_instance == null){  
              synchronized(Singleton.class){  
               if(_instance == null) _instance = new Singleton(); 
      } 
     }   
    return _instance;  
    }

The code above is not thread-safe. Although it checks the value of instance once again within the synchronized block (for performance reasons), the JIT compiler can rearrange the bytecode in a way that the reference to the instance is set before the constructor has finished its execution. This means the method getInstance() returns an object that may not have been initialized completely. To make the code thread-safe, the keyword volatile can be used since Java 5 for the instance variable. Variables that are marked as volatile get only visible to other threads once the constructor of the object has finished its execution completely.
Source

enter image description here

volatile usage in Java:

The fail-fast iterators are typically implemented using a volatile counter on the list object.

  • When the list is updated, the counter is incremented.
  • When an Iterator is created, the current value of the counter is embedded in the Iterator object.
  • When an Iterator operation is performed, the method compares the two counter values and throws a ConcurrentModificationException if they are different.

The implementation of fail-safe iterators is typically light-weight. They typically rely on properties of the specific list implementation's data structures. There is no general pattern.

CSS/Javascript to force html table row on a single line

Try:

td, th {
  white-space: nowrap;
  overflow: hidden;
}

How to calculate a logistic sigmoid function in Python?

Here's how you would implement the logistic sigmoid in a numerically stable way (as described here):

def sigmoid(x):
    "Numerically-stable sigmoid function."
    if x >= 0:
        z = exp(-x)
        return 1 / (1 + z)
    else:
        z = exp(x)
        return z / (1 + z)

Or perhaps this is more accurate:

import numpy as np

def sigmoid(x):  
    return np.exp(-np.logaddexp(0, -x))

Internally, it implements the same condition as above, but then uses log1p.

In general, the multinomial logistic sigmoid is:

def nat_to_exp(q):
    max_q = max(0.0, np.max(q))
    rebased_q = q - max_q
    return np.exp(rebased_q - np.logaddexp(-max_q, np.logaddexp.reduce(rebased_q)))

(However, logaddexp.reduce could be more accurate.)

Why is the time complexity of both DFS and BFS O( V + E )

Time complexity is O(E+V) instead of O(2E+V) because if the time complexity is n^2+2n+7 then it is written as O(n^2).

Hence, O(2E+V) is written as O(E+V)

because difference between n^2 and n matters but not between n and 2n.

Scrolling an iframe with JavaScript?

Based on Chris's comment

CSS
.amazon-rating {
  width: 55px;
  height: 12px;
  overflow: hidden;
}

.rating-stars {
  left: -18px;
  top: -102px;
  position: relative;
}
HAML
.amazon-rating
  %iframe.rating-stars{src: $item->ratingURL, seamless: 'seamless', frameborder: 0, scrolling: 'no'}

How do I convert from a string to an integer in Visual Basic?

You can use the following to convert string to int:

  • CInt(String) for ints
  • CDec(String) for decimals

For details refer to Type Conversion Functions (Visual Basic).

NSCameraUsageDescription in iOS 10.0 runtime crash?

Another instance that I faced while trying to use the camera, was that it was still busy crashing giving same _CRASHING_DUE_TO_PRIVACY even after adding the "Camera Usage Description". After failing to get anything tangible from the call stack, switched to the "Organizer" and looked into the crash reports on the device. I found that it was in fact complaining about the privacy due to the missing "Microphone Usage Description". I added that and got rid of such a cryptic break down.

Why do I keep getting Delete 'cr' [prettier/prettier]?

What worked for me was:

  1. Update prettier to version 2.2.1 (latest version at the moment) as Roberto LL suggested. To do it execute

npm update prettier

  1. Execute lint fix as Hakan suggested (This will modify all files in the project to convert line ending to LF).

npm run lint -- --fix

It was not necessary to change .eslintrc and .prettierrc files!

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

Unable to generate an explicit migration in entity framework

This isn't going to be the answer for many people, but EF will chuck this error when it can't connect to the DB. If you're working from home like I am, make sure you're still connected to your VPN!

Python: Figure out local timezone

Here's a slightly more concise version of @vbem's solution:

from datetime import datetime as dt

dt.utcnow().astimezone().tzinfo

The only substantive difference is that I replaced datetime.datetime.now(datetime.timezone.utc) with datetime.datetime.utcnow(). For brevity, I also aliased datetime.datetime as dt.

For my purposes, I want the UTC offset in seconds. Here's what that looks like:

dt.utcnow().astimezone().utcoffset().total_seconds()

Ignore invalid self-signed ssl certificate in node.js with https.request?

Add the following environment variable:

NODE_TLS_REJECT_UNAUTHORIZED=0

e.g. with export:

export NODE_TLS_REJECT_UNAUTHORIZED=0

(with great thanks to Juanra)

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

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

Powershell send-mailmessage - email to multiple recipients

Just creating a Powershell array will do the trick

$recipients = @("Marcel <[email protected]>", "Marcelt <[email protected]>")

The same approach can be used for attachments

$attachments = @("$PSScriptRoot\image003.png", "$PSScriptRoot\image004.jpg")

Adding multiple class using ng-class

Found another way thanks to Scotch.io

<div ng-repeat="step in steps" class="step-container step" ng-class="[step.status, step.type]" ng-click="onClick(step.type)">

This was my reference.PATH

Disable mouse scroll wheel zoom on embedded Google Maps

I tried the first answer in this discussion and it wasn't working for me no matter what I did so I came up with my own solution:

Wrap the iframe with a class (.maps in this example) and ideally embedresponsively code: http://embedresponsively.com/ — Change the CSS of the iframe to pointer-events: none and then using jQuery's click function to the parent element you can change the iframes css to pointer-events:auto

HTML

<div class='embed-container maps'>
    <iframe width='600' height='450' frameborder='0' src='http://foo.com'></iframe>
</div>

CSS

.maps iframe{
    pointer-events: none;
}

jQuery

$('.maps').click(function () {
    $('.maps iframe').css("pointer-events", "auto");
});

$( ".maps" ).mouseleave(function() {
  $('.maps iframe').css("pointer-events", "none"); 
});

I'm sure there's a JavaScript only way of doing this, if someone wants to add to this feel free.

The JavaScript way to reactivate the pointer-events is pretty simple. Just give an Id to the iFrame (i.e. "iframe"), then apply an onclick event to the cointainer div:

onclick="document.getElementById('iframe').style.pointerEvents= 'auto'"

<div class="maps" onclick="document.getElementById('iframe').style.pointerEvents= 'auto'">
   <iframe id="iframe" src="" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>

How to check if function exists in JavaScript?

And then there is this...

( document.exitPointerLock || Function )();

Why do multiple-table joins produce duplicate rows?

This might sound like a really basic "DUH" answer, but make sure that the column you're using to Lookup from on the merging file is actually full of unique values!

I noticed earlier today that PowerQuery won't throw you an error (like in PowerPivot) and will happily allow you to run a Many-Many merge. This will result in multiple rows being produced for each record that matches with a non-unique value.

symfony2 twig path with parameter url creation

Set the default value for the active argument in the route.

How can I force users to access my page over HTTPS instead of HTTP?

Use $_SERVER['HTTPS'] to tell if it is SSL, and redirect to the right place if not.

And remember, the page that displays the form does not need to be fed via HTTPS, it's the post back URL that needs it most.

Edit: yes, as is pointed out below, it's best to have the entire process in HTTPS. It's much more reassuring - I was pointing out that the post is the most critical part. Also, you need to take care that any cookies are set to be secure, so they will only be sent via SSL. The mod_rewrite solution is also very nifty, I've used it to secure a lot of applications on my own website.

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Expanded(
  child: Align(
    alignment: FractionalOffset.bottomCenter,
      child: Padding(
        padding: EdgeInsets.only(bottom: 10.0),
          child: //Your widget here,
    ),
  ),
),

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

On my machine I tried check it. My result:

Calendar.getInstance().getTime() (*1000000 times) = 402ms
new Date().getTime(); (*1000000 times) = 18ms
System.currentTimeMillis() (*1000000 times) = 16ms

Don't forget about GC (if you use Calendar.getInstance() or new Date())

What is the JavaScript version of sleep()?

For browsers, I agree that setTimeout and setInterval are the way to go.

But for server-side code, it may require a blocking function (for example, so you can effectively have thread synchronization).

If you're using node.js and meteor, you may have run into the limitations of using setTimeout in a fiber. Here is the code for server-side sleep.

var Fiber = require('fibers');

function sleep(ms) {
    var fiber = Fiber.current;
    setTimeout(function() {
        fiber.run();
    }, ms);
    Fiber.yield();
}

Fiber(function() {
    console.log('wait... ' + new Date);
    sleep(1000);
    console.log('ok... ' + new Date);
}).run();
console.log('back in main');

See: https://github.com/laverdet/node-fibers#sleep

Insert data into table with result from another select query

INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`) 
SELECT sum(p1), sum(p2), sum(p3) 
FROM `test`.`product`;

Is there a “not in” operator in JavaScript for checking object properties?

It seems wrong to me to set up an if/else statement just to use the else portion...

Just negate your condition, and you'll get the else logic inside the if:

if (!(id in tutorTimes)) { ... }

Creating an R dataframe row-by-row

If you have vectors destined to become rows, concatenate them using c(), pass them to a matrix row-by-row, and convert that matrix to a dataframe.

For example, rows

dummydata1=c(2002,10,1,12.00,101,426340.0,4411238.0,3598.0,0.92,57.77,4.80,238.29,-9.9)
dummydata2=c(2002,10,2,12.00,101,426340.0,4411238.0,3598.0,-3.02,78.77,-9999.00,-99.0,-9.9)
dummydata3=c(2002,10,8,12.00,101,426340.0,4411238.0,3598.0,-5.02,88.77,-9999.00,-99.0,-9.9)

can be converted to a data frame thus:

dummyset=c(dummydata1,dummydata2,dummydata3)
col.len=length(dummydata1)
dummytable=data.frame(matrix(data=dummyset,ncol=col.len,byrow=TRUE))

Admittedly, I see 2 major limitations: (1) this only works with single-mode data, and (2) you must know your final # columns for this to work (i.e., I'm assuming that you're not working with a ragged array whose greatest row length is unknown a priori).

This solution seems simple, but from my experience with type conversions in R, I'm sure it creates new challenges down-the-line. Can anyone comment on this?

Math functions in AngularJS bindings

Angular Typescript example using a pipe.

math.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'math',
})

export class MathPipe implements PipeTransform {

  transform(value: number, args: any = null):any {
      if(value) {
        return Math[args](value);
      }
      return 0;
  }
}

Add to @NgModule declarations

@NgModule({
  declarations: [
    MathPipe,

then use in your template like so:

{{(100*count/total) | math:'round'}}

Chrome extension: accessing localStorage in content script

Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.

One downside is that it is asynchronous.

https://developer.chrome.com/extensions/storage.html

How to download a file with Node.js (without using third-party libraries)?

function download(url, dest, cb) {

  var request = http.get(url, function (response) {

    const settings = {
      flags: 'w',
      encoding: 'utf8',
      fd: null,
      mode: 0o666,
      autoClose: true
    };

    // response.pipe(fs.createWriteStream(dest, settings));
    var file = fs.createWriteStream(dest, settings);
    response.pipe(file);

    file.on('finish', function () {
      let okMsg = {
        text: `File downloaded successfully`
      }
      cb(okMsg);
      file.end(); 
    });
  }).on('error', function (err) { // Handle errors
    fs.unlink(dest); // Delete the file async. (But we don't check the result)
    let errorMsg = {
      text: `Error in file downloadin: ${err.message}`
    }
    if (cb) cb(errorMsg);
  });
};

How can I call a function using a function pointer?

The best way to read that is the clockwise/spiral rule by David Anderson.

How do I use PHP to get the current year?

This one gives you the local time:

$year = date('Y'); // 2008

And this one UTC:

$year = gmdate('Y'); // 2008

Python check if website exists

from urllib2 import Request, urlopen, HTTPError, URLError

user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com/"
req = Request(link, headers = headers)
try:
        page_open = urlopen(req)
except HTTPError, e:
        print e.code
except URLError, e:
        print e.reason
else:
        print 'ok'

To answer the comment of unutbu:

Because the default handlers handle redirects (codes in the 300 range), and codes in the 100-299 range indicate success, you will usually only see error codes in the 400-599 range. Source

How to return a result (startActivityForResult) from a TabHost Activity?

http://tylenoly.wordpress.com/2010/10/27/how-to-finish-activity-with-results/

With a slight modification for "param_result"

/* Start Activity */
public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setClassName("com.thinoo.ActivityTest", "com.thinoo.ActivityTest.NewActivity");
    startActivityForResult(intent,90);
}
/* Called when the second activity's finished */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
    case 90:
        if (resultCode == RESULT_OK) {
            Bundle res = data.getExtras();
            String result = res.getString("param_result");
            Log.d("FIRST", "result:"+result);
        }
        break;
    }
}

private void finishWithResult()
{
    Bundle conData = new Bundle();
    conData.putString("param_result", "Thanks Thanks");
    Intent intent = new Intent();
    intent.putExtras(conData);
    setResult(RESULT_OK, intent);
    finish();
}

How do I update the element at a certain position in an ArrayList?

 arrList.set(5,newValue);

and if u want to update it then add this line also

 youradapater.NotifyDataSetChanged();

get data from mysql database to use in javascript

You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.

Simple way to sort strings in the (case sensitive) alphabetical order

If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:

private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
        int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
        if (res == 0) {
            res = str1.compareTo(str2);
        }
        return res;
    }
};

Collections.sort(list, ALPHABETICAL_ORDER);

And I think it is just as easy to understand and code ...

The last 4 lines of the method can written more concisely as follows:

        return (res != 0) ? res : str1.compareTo(str2);

Rotating a view in Android

@Ichorus's answer is correct for views, but if you want to draw rotated rectangles or text, you can do the following in your onDraw (or onDispatchDraw) callback for your view:

(note that theta is the angle from the x axis of the desired rotation, pivot is the Point that represents the point around which we want the rectangle to rotate, and horizontalRect is the rect's position "before" it was rotated)

canvas.save();
canvas.rotate(theta, pivot.x, pivot.y);
canvas.drawRect(horizontalRect, paint);
canvas.restore();

Initializing entire 2D array with one value

You get this behavior, because int array [ROW][COLUMN] = {1}; does not mean "set all items to one". Let me try to explain how this works step by step.

The explicit, overly clear way of initializing your array would be like this:

#define ROW 2
#define COLUMN 2

int array [ROW][COLUMN] =
{
  {0, 0},
  {0, 0}
};

However, C allows you to leave out some of the items in an array (or struct/union). You could for example write:

int array [ROW][COLUMN] =
{
  {1, 2}
};

This means, initialize the first elements to 1 and 2, and the rest of the elements "as if they had static storage duration". There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero.

So in the above example, the first row gets set to 1,2 and the next to 0,0 since we didn't give them any explicit values.

Next, there is a rule in C allowing lax brace style. The first example could as well be written as

int array [ROW][COLUMN] = {0, 0, 0, 0};

although of course this is poor style, it is harder to read and understand. But this rule is convenient, because it allows us to write

int array [ROW][COLUMN] = {0};

which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."

therefore, if you attempt

int array [ROW][COLUMN] = {1};

it means "initialize the very first column in the first row to 1 and set all other items to zero".

How can I mix LaTeX in with Markdown?

you should look at multimarkdown http://fletcherpenney.net/multimarkdown/

it has support for metadata (headers, keywords, date, author, etc), tables, asciimath, mathml, hell i'm sure you could stick latex math code right in there. it's basically an extension to markdown to add all these other very useful features. It uses XSLT, so you can easily whip up your own LaTeX styles, and have it directly convert. I use it all the time, and I like it a lot.

I wish the markdown would just incorporate multimarkdown. it would be rather nice.

Edit: Multimarkdown will produce html, latex, and a few other formats. html can come with a style sheet of your choice. it will convert into MathML as well, which displays in Firefox and Safari/Chrome, if I remember correctly.

Assign an initial value to radio button as checked

The other way to set default checked on radio buttons, especially if you're using angularjs is setting the 'ng-checked' flag to "true" eg: <input id="d_man" value="M" ng-disabled="some Value" type="radio" ng-checked="true">Man

the checked="checked" did not work for me..

Difference between 'cls' and 'self' in Python classes?

This is very good question but not as wanting as question. There is difference between 'self' and 'cls' used method though analogically they are at same place

def moon(self, moon_name):
    self.MName = moon_name

#but here cls method its use is different 

@classmethod
def moon(cls, moon_name):
    instance = cls()
    instance.MName = moon_name

Now you can see both are moon function but one can be used inside class while other function name moon can be used for any class.

For practical programming approach :

While designing circle class we use area method as cls instead of self because we don't want area to be limited to particular class of circle only .

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

sql how to cast a select query

And when you use a case :

CASE
WHEN TB1.COD IS NULL THEN
    TB1.COD || ' - ' || TB1.NAME
ELSE
    TB1.COD || ' - ' || TB1.NAME || ' - ' || TB.NM_TABELAFRETE
END AS NR_FRETE,

How to reverse a singly linked list using only two pointers?

Here is my version:

void reverse(ListElem *&head)
{
    ListElem* temp;
    ListElem* elem = head->next();
    ListElem* prev = head;
    head->next(0);

    while(temp = elem->next())
    {
        elem->next(prev);
        prev = elem;
        elem = temp;
    }
    elem->next(prev);
    head = elem;
}

where

class ListElem{
public:
    ListElem(int val): _val(val){}
    ListElem *next() const { return _next; }
    void next(ListElem *elem) { _next = elem; }
    void val(int val){ _val = val; }
    int val() const { return _val;}
private:
    ListElem *_next;
    int _val;
};

How to make a .NET Windows Service start right after the installation?

You need to add a Custom Action to the end of the 'ExecuteImmediate' sequence in the MSI, using the component name of the EXE or a batch (sc start) as the source. I don't think this can be done with Visual Studio, you may have to use a real MSI authoring tool for that.

How to force a component's re-rendering in Angular 2?

ChangeDetectorRef approach

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

export class MyComponent {

    constructor(private cdr: ChangeDetectorRef) { }

    selected(item: any) {
        if (item == 'Department')
            this.isDepartment = true;
        else
            this.isDepartment = false;
        this.cdr.detectChanges();
    }

}

Get bottom and right position of an element

I think

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div>Testing</div>
<div id="result" style="margin:1em 4em; background:rgb(200,200,255); height:500px"></div>
<div style="background:rgb(200,255,200); height:3000px; width:5000px;"></div>

<script>
(function(){
    var link=$("#result");

    var top = link.offset().top; // position from $(document).offset().top
    var bottom = top + link.height(); // position from $(document).offset().top

    var left = link.offset().left; // position from $(document).offset().left
    var right = left + link.width(); // position from $(document).offset().left

    var bottomFromBottom = $(document).height() - bottom;
    // distance from document's bottom
    var rightFromRight = $(document).width() - right;
    // distance from document's right

    var str="";
    str+="top: "+top+"<br>";
    str+="bottom: "+bottom+"<br>";
    str+="left: "+left+"<br>";
    str+="right: "+right+"<br>";
    str+="bottomFromBottom: "+bottomFromBottom+"<br>";
    str+="rightFromRight: "+rightFromRight+"<br>";
    link.html(str);
})();
</script>

The result are

top: 44
bottom: 544
left: 72
right: 1277
bottomFromBottom: 3068
rightFromRight: 3731

in chrome browser of mine.

When the document is scrollable, $(window).height() returns height of browser viewport, not the width of document of which some parts are hiden in scroll. See http://api.jquery.com/height/ .

Saving response from Requests to file

You can use the response.text to write to a file:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()

What is a word boundary in regex, does \b match hyphen '-'?

I believe that your problem is due to the fact that - is not a word character. Thus, the word boundary will match after the -, and so will not capture it. Word boundaries match before the first and after the last word characters in a string, as well as any place where before it is a word character or non-word character, and after it is the opposite. Also note that word boundary is a zero-width match.

One possible alternative is

(?:(?:^|\s)-?)\d+\b

This will match any numbers starting with a space character and an optional dash, and ending at a word boundary. It will also match a number starting at the beginning of the string.

How to convert any date format to yyyy-MM-dd

Try this code:

 lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");

What does "subject" mean in certificate?

The subject of the certificate is the entity its public key is associated with (i.e. the "owner" of the certificate).

As RFC 5280 says:

The subject field identifies the entity associated with the public key stored in the subject public key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.

X.509 certificates have a Subject (Distinguished Name) field and can also have multiple names in the Subject Alternative Name extension.

The Subject DN is made of multiple relative distinguished names (RDNs) (themselves made of attribute assertion values) such as "CN=yourname" or "O=yourorganization".

In the context of the article you're linking to, the subject would be the user/owner of the cert.

How to get whole and decimal part of a number?

PHP 5.4+

$n = 12.343;
intval($n); // 12
explode('.', number_format($n, 1))[1]; // 3
explode('.', number_format($n, 2))[1]; // 34
explode('.', number_format($n, 3))[1]; // 343
explode('.', number_format($n, 4))[1]; // 3430

Unzip files programmatically in .net

This will do it System.IO.Compression.ZipFile.ExtractToDirectory(ZipName, ExtractToPath)

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

Instead of setting a fixed path try this in your post-build command-line first:

SET VCTargetsPath=$(VCTargetsPath)

The variable '$(VCTargetsPath)' seems to be a c++-related visual-studio-macro which is not shown in c#-sdk-projects as a macro but is still available there.

adb devices command not working

You need to restart the adb server as root. See here.

$(form).ajaxSubmit is not a function

Drupal 8

Drupal 8 does not include JS-libraries to pages automaticly. So most probably if you meet this error you need to attach 'core/jquery.form' library to your page (or form). Add something like this to your render array:

$form['#attached']['library'][] = 'core/jquery.form';

Is String.Contains() faster than String.IndexOf()?

If you really want to micro optimise your code your best approach is always benchmarking.

The .net framework has an excellent stopwatch implementation - System.Diagnostics.Stopwatch