Programs & Examples On #Smss

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

Resolving a service is done even before the class code is reached, so we need to check our dependency injections.

In my case I added

        services.AddScoped<IMeasurementService, MeasurementService>();

in StartupExtensions.cs

Why is HttpContext.Current null?

In IIS7 with integrated mode, Current is not available in Application_Start. There is a similar thread here.

PKIX path building failed in Java application

I ran into similar issues whose cause and solution turned out both to be rather simple:

Main Cause: Did not import the proper cert using keytool

NOTE: Only import root CA (or your own self-signed) certificates

NOTE: don't import an intermediate, non certificate chain root cert

Solution Example for imap.gmail.com

  1. Determine the root CA cert:

    openssl s_client -showcerts -connect imap.gmail.com:993
    

    in this case we find the root CA is Equifax Secure Certificate Authority

  2. Download root CA cert.
  3. Verify downloaded cert has proper SHA-1 and/or MD5 fingerprints by comparing with info found here
  4. Import cert for javax.net.ssl.trustStore:

    keytool -import -alias gmail_imap -file Equifax_Secure_Certificate_Authority.pem
    
  5. Run your java code

How to parse JSON and access results

Try:

$result = curl_exec($cURL);
$result = json_decode($result,true);

Now you can access MessageID from $result['MessageID'].

As for the database, it's simply using a query like so:

INSERT INTO `tableName`(`Cancelled`,`Queued`,`SMSError`,`SMSIncommingMessage`,`Sent`,`SentDateTime`) VALUES('?','?','?','?','?');

Prepared.

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

Why does Google prepend while(1); to their JSON responses?

Note: as of 2019, many of the old vulnerabilities that lead to the preventative measures discussed in this question are no longer an issue in modern browsers. I'll leave the answer below as a historical curiosity, but really the whole topic has changed radically since 2010 (!!) when this was asked.


It prevents it from being used as the target of a simple <script> tag. (Well, it doesn't prevent it, but it makes it unpleasant.) That way bad guys can't just put that script tag in their own site and rely on an active session to make it possible to fetch your content.

edit — note the comment (and other answers). The issue has to do with subverted built-in facilities, specifically the Object and Array constructors. Those can be altered such that otherwise innocuous JSON, when parsed, could trigger attacker code.

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Ctrl+3 in SQL Server 2012. Might work in 2008 too

Large WCF web service request failing with (400) HTTP Bad Request

It might be useful to debug the client, turn off Tools\Options\Debugging\General\'Enable Just My Code', click Debug\Exceptions\'catch all first-chance exceptions' for managed CLR exceptions, and see if there is an exception under-the-hood on the client before the protocol exception and before the message hits the wire. (My guess would be some kind of serialization failure.)

Uninstalling an MSI file from the command line without using msiexec

I'm assuming that when you type int file.msi into the command line, Windows is automatically calling msiexec file.msi for you. I'm assuming this because when you type in picture.png it brings up the default picture viewer.

inline if statement java, why is not working

This should be (condition)? True statement : False statement

Leave out the "if"

How to transition to a new view controller with code only using Swift

SWIFT

Usually for normal transition we use,

let next:SecondViewController = SecondViewController()
self.presentViewController(next, animated: true, completion: nil)

But sometimes when using navigation controller, you might face a black screen. In that case, you need to use like,

let next:ThirdViewController = storyboard?.instantiateViewControllerWithIdentifier("ThirdViewController") as! ThirdViewController
self.navigationController?.pushViewController(next, animated: true)

Moreover none of the above solution preserves navigationbar when you call from storyboard or single xib to another xib. If you use nav bar and want to preserve it just like normal push, you have to use,

Let's say, "MyViewController" is identifier for MyViewController

let viewController = MyViewController(nibName: "MyViewController", bundle: nil)
self.navigationController?.pushViewController(viewController, animated: true)

jQuery to remove an option from drop down list, given option's text/value

$("option[value='foo']").remove();

or better (if you have few selects in the page):

$("#select_id option[value='foo']").remove();

Accessing an array out of bounds gives no error, why?

g++ does not check for array bounds, and you may be overwriting something with 3,4 but nothing really important, if you try with higher numbers you'll get a crash.

You are just overwriting parts of the stack that are not used, you could continue till you reach the end of the allocated space for the stack and it'd crash eventually

EDIT: You have no way of dealing with that, maybe a static code analyzer could reveal those failures, but that's too simple, you may have similar(but more complex) failures undetected even for static analyzers

"Untrusted App Developer" message when installing enterprise iOS Application

Today, I was testing this with iOS 9 Beta and found the solution.

To solve it, go to:

  1. Settings -> General -> Profiles [Device Management on iOS 10]
  2. Under ENTERPRISE APP, choose your current developer account name.
  3. Tap Trust "Your developer account name"
  4. Tap "Trust" in pop up.
  5. Done

python dict to numpy structured array

Let me propose an improved method when the values of the dictionnary are lists with the same lenght :

import numpy

def dctToNdarray (dd, szFormat = 'f8'):
    '''
    Convert a 'rectangular' dictionnary to numpy NdArray
    entry 
        dd : dictionnary (same len of list 
    retrun
        data : numpy NdArray 
    '''
    names = dd.keys()
    firstKey = dd.keys()[0]
    formats = [szFormat]*len(names)
    dtype = dict(names = names, formats=formats)
    values = [tuple(dd[k][0] for k in dd.keys())]
    data = numpy.array(values, dtype=dtype)
    for i in range(1,len(dd[firstKey])) :
        values = [tuple(dd[k][i] for k in dd.keys())]
        data_tmp = numpy.array(values, dtype=dtype)
        data = numpy.concatenate((data,data_tmp))
    return data

dd = {'a':[1,2.05,25.48],'b':[2,1.07,9],'c':[3,3.01,6.14]}
data = dctToNdarray(dd)
print data.dtype.names
print data

HTML5 Video tag not working in Safari , iPhone and iPad

Just add a muted attribute and everything will work fine.

The source of this answer is here: https://webkit.org/blog/6784/new-video-policies-for-ios/

By default, WebKit will have the following policies:

<video autoplay> elements will now honor the autoplay attribute, for elements which meet the following conditions:

  • <video> elements will be allowed to autoplay without a user gesture if their source media contains no audio tracks.
  • <video muted> elements will also be allowed to autoplay without a user gesture.
  • If a <video> element gains an audio track or becomes un-muted without a user gesture, playback will pause.
  • <video autoplay> elements will only begin playing when visible on-screen such as when they are scrolled into the viewport, made visible through CSS, and inserted into the DOM.
  • <video autoplay> elements will pause if they become non-visible, such as by being scrolled out of the viewport.

<video> elements will now honor the play() method, for elements which meet the following conditions:

  • <video> elements will be allowed to play() without a user gesture if their source media contains no audio tracks, or if their muted property is set to true.
  • If a <video> element gains an audio track or becomes un-muted without a user gesture, playback will pause.
  • <video> elements will be allowed to play() when not visible on-screen or when out of the viewport.
  • video.play() will return a Promise, which will be rejected if any of these conditions are not met.

On iPhone, <video playsinline> elements will now be allowed to play inline, and will not automatically enter fullscreen mode when playback begins. <video> elements without playsinline attributes will continue to require fullscreen mode for playback on iPhone. When exiting fullscreen with a pinch gesture, <video> elements without playsinline will continue to play inline.

Java random number with given length

Would that work for you?

public class Main {

public static void main(String[] args) {
    Random r = new Random(System.currentTimeMillis());
    System.out.println(r.nextInt(100000) * 0.000001);
}

}

result e.g. 0.019007

What is simplest way to read a file into String?

Yes, you can do this in one line (though for robust IOException handling you wouldn't want to).

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);

This uses a java.util.Scanner, telling it to delimit the input with \Z, which is the end of the string anchor. This ultimately makes the input have one actual token, which is the entire file, so it can be read with one call to next().

There is a constructor that takes a File and a String charSetName (among many other overloads). These two constructor may throw FileNotFoundException, but like all Scanner methods, no IOException can be thrown beyond these constructors.

You can query the Scanner itself through the ioException() method if an IOException occurred or not. You may also want to explicitly close() the Scanner after you read the content, so perhaps storing the Scanner reference in a local variable is best.

See also

Related questions


Third-party library options

For completeness, these are some really good options if you have these very reputable and highly useful third party libraries:

Guava

com.google.common.io.Files contains many useful methods. The pertinent ones here are:

Apache Commons/IO

org.apache.commons.io.IOUtils also offer similar functionality:

  • String toString(InputStream, String encoding)
    • Using the specified character encoding, gets the contents of an InputStream as a String
  • List readLines(InputStream, String encoding)
    • ... as a (raw) List of String, one entry per line

Related questions

If else in stored procedure sql server

if not exists (select dist_id from tbl_stock where dist_id= @cust_id and item_id=@item_id)
    insert into tbl_stock(dist_id,item_id,qty)values(@cust_id, @item_id, @qty); 
else
    update tbl_stock set qty=(qty + @qty) where dist_id= @cust_id and item_id= @item_id;

How to break line in JavaScript?

alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");

or %0D%0A in a url

Global Events in Angular

You can use EventEmitter or observables to create an eventbus service that you register with DI. Every component that wants to participate just requests the service as constructor parameter and emits and/or subscribes to events.

See also

Converting file size in bytes to human-readable string

My answer might be late, but I guess it will help someone.

Metric prefix:

/**
 * Format file size in metric prefix
 * @param fileSize
 * @returns {string}
 */
const formatFileSizeMetric = (fileSize) => {
  let size = Math.abs(fileSize);

  if (Number.isNaN(size)) {
    return 'Invalid file size';
  }

  if (size === 0) {
    return '0 bytes';
  }

  const units = ['bytes', 'kB', 'MB', 'GB', 'TB'];
  let quotient = Math.floor(Math.log10(size) / 3);
  quotient = quotient < units.length ? quotient : units.length - 1;
  size /= (1000 ** quotient);

  return `${+size.toFixed(2)} ${units[quotient]}`;
};

Binary prefix:

/**
 * Format file size in binary prefix
 * @param fileSize
 * @returns {string}
 */
const formatFileSizeBinary = (fileSize) => {
  let size = Math.abs(fileSize);

  if (Number.isNaN(size)) {
    return 'Invalid file size';
  }

  if (size === 0) {
    return '0 bytes';
  }

  const units = ['bytes', 'kiB', 'MiB', 'GiB', 'TiB'];
  let quotient = Math.floor(Math.log2(size) / 10);
  quotient = quotient < units.length ? quotient : units.length - 1;
  size /= (1024 ** quotient);

  return `${+size.toFixed(2)} ${units[quotient]}`;
};

Examples:

// Metrics prefix
formatFileSizeMetric(0)      // 0 bytes
formatFileSizeMetric(-1)     // 1 bytes
formatFileSizeMetric(100)    // 100 bytes
formatFileSizeMetric(1000)   // 1 kB
formatFileSizeMetric(10**5)  // 10 kB
formatFileSizeMetric(10**6)  // 1 MB
formatFileSizeMetric(10**9)  // 1GB
formatFileSizeMetric(10**12) // 1 TB
formatFileSizeMetric(10**15) // 1000 TB

// Binary prefix
formatFileSizeBinary(0)     // 0 bytes
formatFileSizeBinary(-1)    // 1 bytes
formatFileSizeBinary(1024)  // 1 kiB
formatFileSizeBinary(2048)  // 2 kiB
formatFileSizeBinary(2**20) // 1 MiB
formatFileSizeBinary(2**30) // 1 GiB
formatFileSizeBinary(2**40) // 1 TiB
formatFileSizeBinary(2**50) // 1024 TiB

How to dynamically create a class?

Wow! Thank you for that answer! I added some features to it to create a "datatable to json" converter that I share with you.

    Public Shared Sub dt2json(ByVal _dt As DataTable, ByVal _sb As StringBuilder)
    Dim t As System.Type

    Dim oList(_dt.Rows.Count - 1) As Object
    Dim jss As New JavaScriptSerializer()
    Dim i As Integer = 0

    t = CompileResultType(_dt)

    For Each dr As DataRow In _dt.Rows
        Dim o As Object = Activator.CreateInstance(t)

        For Each col As DataColumn In _dt.Columns
            setvalue(o, col.ColumnName, dr.Item(col.ColumnName))
        Next

        oList(i) = o
        i += 1
    Next

    jss = New JavaScriptSerializer()
    jss.Serialize(oList, _sb)


End Sub

And in "compileresulttype" sub, I changed that:

    For Each column As DataColumn In _dt.Columns
        CreateProperty(tb, column.ColumnName, column.DataType)
    Next


Private Shared Sub setvalue(ByVal _obj As Object, ByVal _propName As String, ByVal _propValue As Object)
    Dim pi As PropertyInfo
    pi = _obj.GetType.GetProperty(_propName)
    If pi IsNot Nothing AndAlso pi.CanWrite Then
        If _propValue IsNot DBNull.Value Then
            pi.SetValue(_obj, _propValue, Nothing)

        Else
            Select Case pi.PropertyType.ToString
                Case "System.String"
                    pi.SetValue(_obj, String.Empty, Nothing)
                Case Else
                    'let the serialiser use javascript "null" value.
            End Select

        End If
    End If

End Sub

How to check version of a CocoaPods framework

pod --version used this to check the version of the last installed pod

Java reverse an int value without using array

public static void main(String args[]) {
    int n = 0, res = 0, n1 = 0, rev = 0;
    int sum = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please Enter No.: ");
    n1 = scan.nextInt(); // String s1=String.valueOf(n1);
    int len = (n1 == 0) ? 1 : (int) Math.log10(n1) + 1;
    while (n1 > 0) {
        rev = res * ((int) Math.pow(10, len));
        res = n1 % 10;
        n1 = n1 / 10;
        // sum+=res; //sum=sum+res;
        sum += rev;
        len--;
    }
    // System.out.println("sum No: " + sum);
    System.out.println("sum No: " + (sum + res));
}

This will return reverse of integer

Reset par to the default values at startup

An alternative solution for preventing functions to change the user par. You can set the default parameters early on the function, so that the graphical parameters and layout will not be changed during the function execution. See ?on.exit for further details.

on.exit(layout(1))
opar<-par(no.readonly=TRUE)
on.exit(par(opar),add=TRUE,after=FALSE)

How to Clone Objects

a and b are just two references to the same Person object. They both essentially hold the address of the Person.

There is a ICloneable interface, though relatively few classes support it. With this, you would write:

Person b = a.Clone();

Then, b would be an entirely separate Person.

You could also implement a copy constructor:

public Person(Person src)
{
  // ... 
}

There is no built-in way to copy all the fields. You can do it through reflection, but there would be a performance penalty.

Creating Accordion Table with Bootstrap

In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:

.collapse-row.collapsed + tr {
     display: none;
}

'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.

Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/

Excel VBA - Range.Copy transpose paste

WorksheetFunction Transpose()

Instead of copying, pasting via PasteSpecial, and using the Transpose option you can simply type a formula

    =TRANSPOSE(Sheet1!A1:A5)

or if you prefer VBA:

    Dim v
    v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
    Sheet2.Range("A1").Resize(1, UBound(v)) = v

Note: alternatively you could use late-bound Application.Transpose instead.

MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.

Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365

Android ListView with different layouts for each row

Take a look in the code below.

First, we create custom layouts. In this case, four types.

even.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ff500000"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/white"
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:textSize="24sp"
        android:layout_height="wrap_content" />

 </LinearLayout>

odd.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ff001f50"
    android:gravity="right"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:textSize="28sp"
        android:layout_height="wrap_content"  />

 </LinearLayout>

white.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ffffffff"
    android:gravity="right"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/black"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:textSize="28sp"
        android:layout_height="wrap_content"   />

 </LinearLayout>

black.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ff000000"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:textSize="33sp"
        android:layout_height="wrap_content"   />

 </LinearLayout>

Then, we create the listview item. In our case, with a string and a type.

public class ListViewItem {
        private String text;
        private int type;

        public ListViewItem(String text, int type) {
            this.text = text;
            this.type = type;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

    }

After that, we create a view holder. It's strongly recommended because Android OS keeps the layout reference to reuse your item when it disappears and appears back on the screen. If you don't use this approach, every single time that your item appears on the screen Android OS will create a new one and causing your app to leak memory.

public class ViewHolder {
        TextView text;

        public ViewHolder(TextView text) {
            this.text = text;
        }

        public TextView getText() {
            return text;
        }

        public void setText(TextView text) {
            this.text = text;
        }

    }

Finally, we create our custom adapter overriding getViewTypeCount() and getItemViewType(int position).

public class CustomAdapter extends ArrayAdapter {

        public static final int TYPE_ODD = 0;
        public static final int TYPE_EVEN = 1;
        public static final int TYPE_WHITE = 2;
        public static final int TYPE_BLACK = 3;

        private ListViewItem[] objects;

        @Override
        public int getViewTypeCount() {
            return 4;
        }

        @Override
        public int getItemViewType(int position) {
            return objects[position].getType();
        }

        public CustomAdapter(Context context, int resource, ListViewItem[] objects) {
            super(context, resource, objects);
            this.objects = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;
            ListViewItem listViewItem = objects[position];
            int listViewItemType = getItemViewType(position);


            if (convertView == null) {

                if (listViewItemType == TYPE_EVEN) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_even, null);
                } else if (listViewItemType == TYPE_ODD) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_odd, null);
                } else if (listViewItemType == TYPE_WHITE) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_white, null);
                } else {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_black, null);
                }

                TextView textView = (TextView) convertView.findViewById(R.id.text);
                viewHolder = new ViewHolder(textView);

                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.getText().setText(listViewItem.getText());

            return convertView;
        }

    }

And our activity is something like this:

private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main); // here, you can create a single layout with a listview

        listView = (ListView) findViewById(R.id.listview);

        final ListViewItem[] items = new ListViewItem[40];

        for (int i = 0; i < items.length; i++) {
            if (i == 4) {
                items[i] = new ListViewItem("White " + i, CustomAdapter.TYPE_WHITE);
            } else if (i == 9) {
                items[i] = new ListViewItem("Black " + i, CustomAdapter.TYPE_BLACK);
            } else if (i % 2 == 0) {
                items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_EVEN);
            } else {
                items[i] = new ListViewItem("ODD " + i, CustomAdapter.TYPE_ODD);
            }
        }

        CustomAdapter customAdapter = new CustomAdapter(this, R.id.text, items);
        listView.setAdapter(customAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                Toast.makeText(getBaseContext(), items[i].getText(), Toast.LENGTH_SHORT).show();
            }
        });

    }
}

now create a listview inside mainactivity.xml like this

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.shivnandan.gygy.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <ListView
        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:id="@+id/listView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"


        android:layout_marginTop="100dp" />

</android.support.design.widget.CoordinatorLayout>

How can I send emails through SSL SMTP with the .NET Framework?

As stated in a comment at

http://blogs.msdn.com/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx

with System.Net.Mail, use port 25 instead of 465:

You must set SSL=true and Port=25. Server responds to your request from unprotected 25 and then throws connection to protected 465.

How can I force clients to refresh JavaScript files?

One simple way. Edit htaccess

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} \.(jpe?g|bmp|png|gif|css|js|mp3|ogg)$ [NC]
RewriteCond %{QUERY_STRING} !^(.+?&v33|)v=33[^&]*(?:&(.*)|)$ [NC]
RewriteRule ^ %{REQUEST_URI}?v=33 [R=301,L]

'setInterval' vs 'setTimeout'

setTimeout():

It is a function that execute a JavaScript statement AFTER x interval.

setTimeout(function () {
    something();
}, 1000); // Execute something() 1 second later.

setInterval():

It is a function that execute a JavaScript statement EVERY x interval.

setInterval(function () {
    somethingElse();
}, 2000); // Execute somethingElse() every 2 seconds.

The interval unit is in millisecond for both functions.

What is the difference between Nexus and Maven?

Sonatype Nexus and Apache Maven are two pieces of software that often work together but they do very different parts of the job. Nexus provides a repository while Maven uses a repository to build software.

Here's a quote from "What is Nexus?":

Nexus manages software "artifacts" required for development. If you develop software, your builds can download dependencies from Nexus and can publish artifacts to Nexus creating a new way to share artifacts within an organization. While Central repository has always served as a great convenience for developers you shouldn't be hitting it directly. You should be proxying Central with Nexus and maintaining your own repositories to ensure stability within your organization. With Nexus you can completely control access to, and deployment of, every artifact in your organization from a single location.

And here is a quote from "Maven and Nexus Pro, Made for Each Other" explaining how Maven uses repositories:

Maven leverages the concept of a repository by retrieving the artifacts necessary to build an application and deploying the result of the build process into a repository. Maven uses the concept of structured repositories so components can be retrieved to support the build. These components or dependencies include libraries, frameworks, containers, etc. Maven can identify components in repositories, understand their dependencies, retrieve all that are needed for a successful build, and deploy its output back to repositories when the build is complete.

So, when you want to use both you will have a repository managed by Nexus and Maven will access this repository.

Getting session value in javascript

<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>

This code you can write in Aspx. If you want this in some js.file, you have two ways:

  1. Make aspx file which writes complete JS code, and set source of this file as Script src
  2. Make handler, to process JS file as aspx.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

It looks like someone might have revoked the permissions on sys.configurations for the public role. Or denied access to this view to this particular user. Or the user has been created after the public role was removed from the sys.configurations tables.

Provide SELECT permission to public user sys.configurations object.

std::cin input with spaces?

You have to use cin.getline():

char input[100];
cin.getline(input,sizeof(input));

Are static class variables possible in Python?

To avoid any potential confusion, I would like to contrast static variables and immutable objects.

Some primitive object types like integers, floats, strings, and touples are immutable in Python. This means that the object that is referred to by a given name cannot change if it is of one of the aforementioned object types. The name can be reassigned to a different object, but the object itself may not be changed.

Making a variable static takes this a step further by disallowing the variable name to point to any object but that to which it currently points. (Note: this is a general software concept and not specific to Python; please see others' posts for information about implementing statics in Python).

What does "var" mean in C#?

"var" means the compiler will determine the explicit type of the variable, based on usage. For example,

var myVar = new Connection();

would give you a variable of type Connection.

Pipe output and capture exit status in Bash

There is an internal Bash variable called $PIPESTATUS; it’s an array that holds the exit status of each command in your last foreground pipeline of commands.

<command> | tee out.txt ; test ${PIPESTATUS[0]} -eq 0

Or another alternative which also works with other shells (like zsh) would be to enable pipefail:

set -o pipefail
...

The first option does not work with zsh due to a little bit different syntax.

Bad operand type for unary +: 'str'

The code works for me. (after adding missing except clause / import statements)

Did you put \ in the original code?

urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
              + stock + '/chartdata;type=quote;range=5d/csv'

If you omit it, it could be a cause of the exception:

>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

BTW, string(e) should be str(e).

How can I make a CSS glass/blur effect work for an overlay?

Here's a possible solution.

HTML

<img id="source" src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />

<div id="crop">
    <img id="overlay" src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
</div>

CSS

#crop {
    overflow: hidden;

    position: absolute;
    left: 100px;
    top: 100px;

    width: 450px;
    height: 150px;
}

#overlay {
    -webkit-filter:blur(4px);
    filter:blur(4px);

    width: 450px;
}

#source {
    height: 300px;
    width: auto;
    position: absolute;
    left: 100px;
    top: 100px;
}

I know the CSS can be simplified and you probably should get rid of the ids. The idea here is to use a div as a cropping container and then apply blur on duplicate of the image. Fiddle

To make this work in Firefox, you would have to use SVG hack.

How to properly overload the << operator for an ostream?

You have declared your function as friend. It's not a member of the class. You should remove Matrix:: from the implementation. friend means that the specified function (which is not a member of the class) can access private member variables. The way you implemented the function is like an instance method for Matrix class which is wrong.

How to send custom headers with requests in Swagger UI?

You can add a header parameter to your request, and Swagger-UI will show it as an editable text box:

swagger: "2.0"
info:
  version: 1.0.0
  title: TaxBlaster
host: taxblaster.com
basePath: /api
schemes:
- http

paths:

  /taxFilings/{id}:

    get:
      parameters:
      - name: id
        in: path
        description: ID of the requested TaxFiling
        required: true
        type: string
      - name: auth
        in: header
        description: an authorization header
        required: true
        type: string
      responses:
        200:
          description: Successful response, with a representation of the Tax Filing.
          schema:
            $ref: "#/definitions/TaxFilingObject"
        404:
          description: The requested tax filing was not found.

definitions:
  TaxFilingObject:
    type: object
    description: An individual Tax Filing record.
    properties:
      filingID:
        type: string
      year:
        type: string
      period:
        type: integer
      currency:
        type: string
      taxpayer:
        type: object

Swagger-UI with auth param text box

You can also add a security definition with type apiKey:

swagger: "2.0"
info:
  version: 1.0.0
  title: TaxBlaster
host: taxblaster.com
basePath: /api
schemes:
- http

securityDefinitions:
  api_key:
    type: apiKey
    name: api_key
    in: header
    description: Requests should pass an api_key header.

security: 
 - api_key: []

paths:

  /taxFilings/{id}:

    get:
      parameters:
      - name: id
        in: path
        description: ID of the requested TaxFiling
        required: true
        type: string

      responses:
        200:
          description: Successful response, with a representation of the Tax Filing.
          schema:
            $ref: "#/definitions/TaxFilingObject"
        404:
          description: The requested tax filing was not found.

definitions:
  TaxFilingObject:
    type: object
    description: An individual Tax Filing record.
    properties:
      filingID:
        type: string
      year:
        type: string
      period:
        type: integer
      currency:
        type: string
      taxpayer:
        type: object

The securityDefinitions object defines security schemes.

The security object (called "security requirements" in Swagger–OpenAPI), applies a security scheme to a given context. In our case, we're applying it to the entire API by declaring the security requirement a top level. We can optionally override it within individual path items and/or methods.

This would be the preferred way to specify your security scheme; and it replaces the header parameter from the first example. Unfortunately, Swagger-UI doesn't offer a text box to control this parameter, at least in my testing so far.

What is C# analog of C++ std::pair?

Since .NET 4.0 you have System.Tuple<T1, T2> class:

// pair is implicitly typed local variable (method scope)
var pair = System.Tuple.Create("Current century", 21);

VirtualBox and vmdk vmx files

Actually, for the configuration of the machine, just open the .vmx file with a text editor (e.g. notepad, gedit, etc.). You will be able to see the OS type, memsize, ethernet.connectionType, and other settings. Then when you make your machine, just look in the text editor for the corresponding settings. When it asks for the disk, select the .vmdk disk as mentioned above.

Why can't non-default arguments follow default arguments?

Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:

fun1("who is who", 3, "jack")

What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".

C++ - Hold the console window open?

If your problem is retaining the Console Window within Visual Studio without modifying your application (c-code) and are running it with Ctrl+F5 (when running Ctrl+F5) but the window is still closing the principal hint is to set the /SUBSYSTEM:CONSOLE linker option in your Visual Studio project.

as explained by DJMooreTX in http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6

1) Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.

  1. Right click on the 'hello" (or whatever your project name is.)

  2. Choose "Properties" from the context menu.

  3. Choose Configuration Properties>Linker>System.

  4. For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.

  5. Choose "Console (/SUBSYSTEM:CONSOLE)"

  6. Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)

Now do Boris' CTRL-F5, wait for your program to compile and link, find the console window under all the other junk on your desktop, and read your program's output, followed by the beloved "Press any key to continue...." prompt.

Again, CTRL-F5 and the subsystem hints work together; they are not separate options.

Embed Youtube video inside an Android app

Embedding the YouTube player in Android is very simple & it hardly takes you 10 minutes,

1) Enable YouTube API from Google API console
2) Download YouTube player Jar file
3) Start using it in Your app

Here are the detailed steps http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html.

Just refer it & if you face any problem, let me know, ill help you

Blue and Purple Default links, how to remove?

REMOVE DEFAULT LINK SOLVED that :visited thing is css.... you just go to your HTML and add a simple

< a href="" style="text-decoration: none" > < /a>

... thats the way html pages used to be

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

How can I hide a checkbox in html?

This two classes are borrowed from the HTML Boilerplate main.css. Although the invisible checkbox will be focused and not the label.

/*
 * Hide only visually, but have it available for screenreaders: h5bp.com/v
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element to be focusable
 * when navigated to via the keyboard: h5bp.com/p
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

Cannot attach the file *.mdf as database

You already have an old copy of that database installed in Server Explorer. So its a simple naming collision in the Server Object Explorer / SQL server. You likely created the same database Catalog Name already before you decided to move it to the Apps_Data folder. So that Database name already exists and just needs to be deleted.

Just go into Visual Studio > View > SQL Server Object Explorer and delete the old database name and its connection. Retry your app again and it should install the .mdf file in App_Data and create the same exact database again in the Server Explorer.

UIScrollView not scrolling

Add the UIScrollViewDelegate and adding the following code to the viewDidAppear method fixed it for me.

@interface testScrollViewController () <UIScrollViewDelegate>

-(void)viewDidAppear:(BOOL)animated {
    self.scrollView.delegate = self;
    self.scrollView.scrollEnabled = YES;
    self.scrollView.contentSize = CGSizeMake(375, 800);
}

Convert string to int array using LINQ

Actually correct one to one implementation is:

int n;
int[] ia = s1.Split(';').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();

Java says FileNotFoundException but file exists

The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.

Use this line and see where the path is:

System.out.println(new File(".").getAbsoluteFile());

SQL Server replace, remove all after certain character

For the times when some fields have a ";" and some do not you can also add a semi-colon to the field and use the same method described.

SET MyText = LEFT(MyText+';', CHARINDEX(';',MyText+';')-1)

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

Within the package there is a class called JwtSecurityTokenHandler which derives from System.IdentityModel.Tokens.SecurityTokenHandler. In WIF this is the core class for deserialising and serialising security tokens.

The class has a ReadToken(String) method that will take your base64 encoded JWT string and returns a SecurityToken which represents the JWT.

The SecurityTokenHandler also has a ValidateToken(SecurityToken) method which takes your SecurityToken and creates a ReadOnlyCollection<ClaimsIdentity>. Usually for JWT, this will contain a single ClaimsIdentity object that has a set of claims representing the properties of the original JWT.

JwtSecurityTokenHandler defines some additional overloads for ValidateToken, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters) overload. The TokenValidationParameters argument allows you to specify the token signing certificate (as a list of X509SecurityTokens). It also has an overload that takes the JWT as a string rather than a SecurityToken.

The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at

http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc

Alternatively, the JwtSecurityToken class has additional methods that are not on the base SecurityToken class, such as a Claims property that gets the contained claims without going via the ClaimsIdentity collection. It also has a Payload property that returns a JwtPayload object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.

The general (i.e. non JWT specific) documentation for the SecurityTokenHandler class is at

http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx

Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.

There are 3 samples of it in use in different types of application at

http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=SearchText&f%5B0%5D.Value=aal&f%5B1%5D.Type=User&f%5B1%5D.Value=Azure%20AD%20Developer%20Experience%20Team&f%5B1%5D.Text=Azure%20AD%20Developer%20Experience%20Team

Probably, one will suite your needs or at least be adaptable to them.

How to unblock with mysqladmin flush hosts

mysqladmin is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).

You type that command from a shell prompt.

Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:

FLUSH HOSTS;

http://dev.mysql.com/doc/refman/5.6/en/flush.html

http://dev.mysql.com/doc/refman/5.6/en/mysqladmin.html

How do I create an .exe for a Java program?

Launch4j perhaps? Can't say I've used it myself, but it sounds like what you're after.

How Exactly Does @param Work - Java

@param will not affect testNumber.It is a Javadoc comment - i.e used for generating documentation . You can put a Javadoc comment immediately before a class, field, method, constructor, or interface such as @param, @return . Generally begins with '@' and must be the first thing on the line.

The Advantage of using @param is :- By creating simple Java classes that contain attributes and some custom Javadoc tags, you allow those classes to serve as a simple metadata description for code generation.

    /* 
       *@param testNumber
       *@return integer
    */
    public int main testNumberIsValid(int testNumber){

       if (testNumber < 6) {
          //Something
        }
     }

Whenever in your code if you reuse testNumberIsValid method, IDE will show you the parameters the method accepts and return type of the method.

Field 'browser' doesn't contain a valid alias configuration

In my case, to the very end of the webpack.config.js, where I should exports the config, there was a typo: export(should be exports), which led to failure with loading webpack.config.js at all.

const path = require('path');

const config = {
    mode: 'development',
    entry: "./lib/components/Index.js",
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: path.resolve(__dirname, "node_modules")
            }
        ]
    }
}

// pay attention to "export!s!" here
module.exports = config;

MySQL error 1241: Operand should contain 1 column(s)

Just remove the ( and the ) on your SELECT statement:

insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;

AngularJS- Login and Authentication in each route and controller

Here is another possible solution, using the resolve attribute of the $stateProvider or the $routeProvider. Example with $stateProvider:

.config(["$stateProvider", function ($stateProvider) {

  $stateProvider

  .state("forbidden", {
    /* ... */
  })

  .state("signIn", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.isAnonymous(); }],
    }
  })

  .state("home", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.isAuthenticated(); }],
    }
  })

  .state("admin", {
    /* ... */
    resolve: {
      access: ["Access", function (Access) { return Access.hasRole("ROLE_ADMIN"); }],
    }
  });

}])

Access resolves or rejects a promise depending on the current user rights:

.factory("Access", ["$q", "UserProfile", function ($q, UserProfile) {

  var Access = {

    OK: 200,

    // "we don't know who you are, so we can't say if you're authorized to access
    // this resource or not yet, please sign in first"
    UNAUTHORIZED: 401,

    // "we know who you are, and your profile does not allow you to access this resource"
    FORBIDDEN: 403,

    hasRole: function (role) {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$hasRole(role)) {
          return Access.OK;
        } else if (userProfile.$isAnonymous()) {
          return $q.reject(Access.UNAUTHORIZED);
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    hasAnyRole: function (roles) {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$hasAnyRole(roles)) {
          return Access.OK;
        } else if (userProfile.$isAnonymous()) {
          return $q.reject(Access.UNAUTHORIZED);
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    isAnonymous: function () {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$isAnonymous()) {
          return Access.OK;
        } else {
          return $q.reject(Access.FORBIDDEN);
        }
      });
    },

    isAuthenticated: function () {
      return UserProfile.then(function (userProfile) {
        if (userProfile.$isAuthenticated()) {
          return Access.OK;
        } else {
          return $q.reject(Access.UNAUTHORIZED);
        }
      });
    }

  };

  return Access;

}])

UserProfile copies the current user properties, and implement the $hasRole, $hasAnyRole, $isAnonymous and $isAuthenticated methods logic (plus a $refresh method, explained later):

.factory("UserProfile", ["Auth", function (Auth) {

  var userProfile = {};

  var clearUserProfile = function () {
    for (var prop in userProfile) {
      if (userProfile.hasOwnProperty(prop)) {
        delete userProfile[prop];
      }
    }
  };

  var fetchUserProfile = function () {
    return Auth.getProfile().then(function (response) {
      clearUserProfile();
      return angular.extend(userProfile, response.data, {

        $refresh: fetchUserProfile,

        $hasRole: function (role) {
          return userProfile.roles.indexOf(role) >= 0;
        },

        $hasAnyRole: function (roles) {
          return !!userProfile.roles.filter(function (role) {
            return roles.indexOf(role) >= 0;
          }).length;
        },

        $isAnonymous: function () {
          return userProfile.anonymous;
        },

        $isAuthenticated: function () {
          return !userProfile.anonymous;
        }

      });
    });
  };

  return fetchUserProfile();

}])

Auth is in charge of requesting the server, to know the user profile (linked to an access token attached to the request for example):

.service("Auth", ["$http", function ($http) {

  this.getProfile = function () {
    return $http.get("api/auth");
  };

}])

The server is expected to return such a JSON object when requesting GET api/auth:

{
  "name": "John Doe", // plus any other user information
  "roles": ["ROLE_ADMIN", "ROLE_USER"], // or any other role (or no role at all, i.e. an empty array)
  "anonymous": false // or true
}

Finally, when Access rejects a promise, if using ui.router, the $stateChangeError event will be fired:

.run(["$rootScope", "Access", "$state", "$log", function ($rootScope, Access, $state, $log) {

  $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
    switch (error) {

    case Access.UNAUTHORIZED:
      $state.go("signIn");
      break;

    case Access.FORBIDDEN:
      $state.go("forbidden");
      break;

    default:
      $log.warn("$stateChangeError event catched");
      break;

    }
  });

}])

If using ngRoute, the $routeChangeError event will be fired:

.run(["$rootScope", "Access", "$location", "$log", function ($rootScope, Access, $location, $log) {

  $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
    switch (rejection) {

    case Access.UNAUTHORIZED:
      $location.path("/signin");
      break;

    case Access.FORBIDDEN:
      $location.path("/forbidden");
      break;

    default:
      $log.warn("$stateChangeError event catched");
      break;

    }
  });

}])

The user profile can also be accessed in the controllers:

.state("home", {
  /* ... */
  controller: "HomeController",
  resolve: {
    userProfile: "UserProfile"
  }
})

UserProfile then contains the properties returned by the server when requesting GET api/auth:

.controller("HomeController", ["$scope", "userProfile", function ($scope, userProfile) {

  $scope.title = "Hello " + userProfile.name; // "Hello John Doe" in the example

}])

UserProfile needs to be refreshed when a user signs in or out, so that Access can handle the routes with the new user profile. You can either reload the whole page, or call UserProfile.$refresh(). Example when signing in:

.service("Auth", ["$http", function ($http) {

  /* ... */

  this.signIn = function (credentials) {
    return $http.post("api/auth", credentials).then(function (response) {
      // authentication succeeded, store the response access token somewhere (if any)
    });
  };

}])
.state("signIn", {
  /* ... */
  controller: "SignInController",
  resolve: {
    /* ... */
    userProfile: "UserProfile"
  }
})
.controller("SignInController", ["$scope", "$state", "Auth", "userProfile", function ($scope, $state, Auth, userProfile) {

  $scope.signIn = function () {
    Auth.signIn($scope.credentials).then(function () {
      // user successfully authenticated, refresh UserProfile
      return userProfile.$refresh();
    }).then(function () {
      // UserProfile is refreshed, redirect user somewhere
      $state.go("home");
    });
  };

}])

Node.js - Find home directory in platform agnostic way

Well, it would be more accurate to rely on the feature and not a variable value. Especially as there are 2 possible variables for Windows.

function getUserHome() {
  return process.env.HOME || process.env.USERPROFILE;
}

EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (require('os').homedir()).

Is there Unicode glyph Symbol to represent "Search"

I'd recommend using http://shapecatcher.com/ to help search for unicode characters. It allows you to draw the shape you're after, and then lists the closest matches to that shape.

Get File Path (ends with folder)

Use Application.GetSaveAsFilename() in the same way that you used Application.GetOpenFilename()

maxReceivedMessageSize and maxBufferSize in app.config

The currently accepted answer is incorrect. It is NOT required to set maxBufferSize and maxReceivedMessageSize on the client and the server binding. It depends!

If your request is too large (i.e., method parameters of the service operation are memory intensive) set the properties on the server-side, if the response is too large (i.e., the method return value of the service operation is memory intensive) set the values on the client-side.

For the difference between maxBufferSize and maxReceivedMessageSize see MaxBufferSize property?.

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

Fastest way of finding differences between two files in unix?

You could also try to include md5-hash-sums or similar do determine whether there are any differences at all. Then, only compare files which have different hashes...

How to focus on a form input text field on page load using jQuery?

Sorry for bumping an old question. I found this via google.

Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.

eg.

$('#myform input,#myform textarea').first().focus();

This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.

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

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

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

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

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

  • Save and connect

Source

AWS Ubuntu 18.04: enter image description here

Load arrayList data into JTable

You can do something like what i did with my List< Future< String > > or any other Arraylist, Type returned from other class called PingScan that returns List> because it implements service executor. Anyway the code down note that you can use foreach and retrieve data from the List.

 PingScan p = new PingScan();
 List<Future<String>> scanResult = p.checkThisIP(jFormattedTextField1.getText(), jFormattedTextField2.getText());
                for (final Future<String> f : scanResult) {
                    try {
                        if (f.get() instanceof String) {
                            String ip = f.get();
                            Object[] data = {ip};
                            tableModel.addRow(data);
                        }
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

Forcing to download a file using PHP

This cannot be done reliably, since it's up to the browser to decide what to do with an URL it's been asked to retrieve.

You can suggest to the browser that it should offer to "save to disk" right away by sending a Content-disposition header:

header("Content-disposition: attachment");

I'm not sure how well this is supported by various browsers. The alternative is to send a Content-type of application/octet-stream, but that is a hack (you're basically telling the browser "I'm not telling you what kind of file this is" and depending on the fact that most browsers will then offer a download dialog) and allegedly causes problems with Internet Explorer.

Read more about this in the Web Authoring FAQ.

Edit You've already switched to a PHP file to deliver the data - which is necessary to set the Content-disposition header (unless there are some arcane Apache settings that can also do this). Now all that's left to do is for that PHP file to read the contents of the CSV file and print them - the filename=example.csv in the header only suggests to the client browser what name to use for the file, it does not actually fetch the data from the file on the server.

Why are #ifndef and #define used in C++ header files?

This prevent from the multiple inclusion of same header file multiple time.

#ifndef __COMMON_H__
#define __COMMON_H__
//header file content
#endif

Suppose you have included this header file in multiple files. So first time __COMMON_H__ is not defined, it will get defined and header file included.

Next time __COMMON_H__ is defined, so it will not include again.

how to generate web service out of wsdl

There isn't a magic bullet solution for what you're looking for, unfortunately. Here's what you can do:

  • create an Interface class using this command in the Visual Studio Command Prompt window:

    wsdl.exe yourFile.wsdl /l:CS /serverInterface
    Use VB or CS for your language of choice. This will create a new .cs or .vb file.

  • Create a new .NET Web Service project. Import Existing File into your project - the file that was created in the step above.

  • In your .asmx.cs file in Code-View, modify your class as such:

 

 public class MyWebService : System.Web.Services.WebService, IMyWsdlInterface
 {    
     [WebMethod]
     public string GetSomeString()
     {
         //you'll have to write your own business logic 
         return "Hello SOAP World";
     }
 }

"Could not get any response" response when using postman with subdomain

In my case the (corporate) proxy was using a self-signed SSL certificate which Postman disliked. I discovered it by activating View->Show Postman console and retrying the request. The console then showed the certificate error. In Settings->General I disabled SSL certificate verification.

How get value from URL

Website URL:

http://www.example.com/?id=2

Code:

$id = intval($_GET['id']);
$results = mysql_query("SELECT * FROM next WHERE id=$id");    
while ($row = mysql_fetch_array($results))     
{       
    $url = $row['url'];
    echo $url; //Outputs: 2
}

SOAP request to WebService with java

A SOAP request is an XML file consisting of the parameters you are sending to the server.

The SOAP response is equally an XML file, but now with everything the service wants to give you.

Basically the WSDL is a XML file that explains the structure of those two XML.


To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             http://www.webservicex.net/uszip.asmx?op=GetInfoByCity


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:GetInfoByCity>
                        <myNamespace:USCity>New York</myNamespace:USCity>
                    </myNamespace:GetInfoByCity>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}

how to install python distutils

you can use sudo apt-get install python3-distutils by root permission.

i believe it worked here

xlrd.biffh.XLRDError: Excel xlsx file; not supported

As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:

xlrd has explicitly removed support for anything other than xls files.

In your case, the solution is to:

  • make sure you are on a recent version of Pandas, at least 1.0.1, and preferably the latest release. 1.2 will make his even clearer.
  • install openpyxl: https://openpyxl.readthedocs.io/en/stable/
  • change your Pandas code to be:
    df1 = pd.read_excel(
         os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
         engine='openpyxl',
    )
    

array_push() with key value pair

If you need to add multiple key=>value, then try this.

$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));

Run class in Jar file

This is the right way to execute a .jar, and whatever one class in that .jar should have main() and the following are the parameters to it :

java -DLB="uk" -DType="CLIENT_IND" -jar com.fbi.rrm.rrm-batchy-1.5.jar

What is the difference between typeof and instanceof and when should one be used vs. the other?

I've discovered some really interesting (read as "horrible") behavior in Safari 5 and Internet Explorer 9. I was using this with great success in Chrome and Firefox.

if (typeof this === 'string') {
    doStuffWith(this);
}

Then I test in IE9, and it doesn't work at all. Big surprise. But in Safari, it's intermittent! So I start debugging, and I find that Internet Explorer is always returning false. But the weirdest thing is that Safari seems to be doing some kind of optimization in its JavaScript VM where it is true the first time, but false every time you hit reload!

My brain almost exploded.

So now I've settled on this:

if (this instanceof String || typeof this === 'string')
    doStuffWith(this.toString());
}

And now everything works great. Note that you can call "a string".toString() and it just returns a copy of the string, i.e.

"a string".toString() === new String("a string").toString(); // true

So I'll be using both from now on.

How to hide columns in an ASP.NET GridView with auto-generated columns?

Try this to hide columns in an ASP.NET GridView with auto-generated columns, both RowDataBound/RowCreated work too.

Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound

    If e.Row.RowType = DataControlRowType.DataRow Or _
        e.Row.RowType = DataControlRowType.Header Then   // apply to datarow and header 

        e.Row.Cells(e.Row.Cells.Count - 1).Visible = False // last column
        e.Row.Cells(0).Visible = False  // first column

    End If
End Sub

Protected Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowCreated

    If e.Row.RowType = DataControlRowType.DataRow Or _
        e.Row.RowType = DataControlRowType.Header Then

        e.Row.Cells(e.Row.Cells.Count - 1).Visible = False
        e.Row.Cells(0).Visible = False

    End If
End Sub

What does an exclamation mark before a cell reference mean?

When entered as the reference of a Named range, it refers to range on the sheet the named range is used on.

For example, create a named range MyName refering to =SUM(!B1:!K1)

Place a formula on Sheet1 =MyName. This will sum Sheet1!B1:K1

Now place the same formula (=MyName) on Sheet2. That formula will sum Sheet2!B1:K1

Note: (as pnuts commented) this and the regular SheetName!B1:K1 format are relative, so reference different cells as the =MyName formula is entered into different cells.

JFrame Maximize window

Provided that you are extending JFrame:

public void run() {
    MyFrame myFrame = new MyFrame();
    myFrame.setVisible(true);
    myFrame.setExtendedState(myFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}

Create local maven repository

Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.

  1. Make sure nginx has http dav module enabled, it should, but nonetheless verify it.

  2. Configure nginx http dav module:

    In Windows: d:\servers\nginx\nginx.conf

    location / {
        # maven repository
        dav_methods  PUT DELETE MKCOL COPY MOVE;
        create_full_put_path  on;
        dav_access  user:rw group:rw all:r;
    }
    

    In Linux (Ubuntu): /etc/nginx/sites-available/default

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;  # IMPORTANT comment this
            dav_methods  PUT DELETE MKCOL COPY MOVE;
            create_full_put_path  on;
            dav_access  user:rw group:rw all:r;
    }
    

    Don't forget to give permissions to the directory where the repo will be located:

    sudo chmod +777 /var/www/html/repository

  3. In your project's pom.xml add the respective configuration:

    Retrieve artifacts:

    <repositories>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </repositories>
    

    Publish artifacts:

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.wagon</groupId>
                <artifactId>wagon-http</artifactId>
                <version>3.2.0</version>
            </extension>
        </extensions>
    </build>
    <distributionManagement>
        <repository>
            <id>repository</id>
            <url>http://<your.ip.or.hostname>/repository</url>
        </repository>
    </distributionManagement>
    
  4. To publish artifacts use mvn deploy. To retrieve artifacts, maven will do it automatically.

And there you have it a simple maven repo.

How to find out line-endings in a text file?

In vi...

:set list to see line-endings.

:set nolist to go back to normal.

While I don't think you can see \n or \r\n in vi, you can see which type of file it is (UNIX, DOS, etc.) to infer which line endings it has...

:set ff

Alternatively, from bash you can use od -t c <filename> or just od -c <filename> to display the returns.

ld: framework not found Pods

you should delete your project some file as this picture.

your should delete the pods.framework and pods mark red files

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

How can I run a program from a batch file without leaving the console open after the program starts?

If this batch file is something you want to run as scheduled or always; you can use windows schedule tool and it doesn't opens up in a window when it starts the batch file.

To open Task Scheduler:

  • Start -> Run/Search -> 'cmd'
  • Type taskschd.msc -> enter

From the right side, click Create Basic Task and follow the menus.

Hope this helps.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You can use it without casting such as:

select sum(`stuff`) as mySum from test;

Or cast it to decimal:

select sum(cast(`stuff` as decimal(4,2))) as mySum from test;

SQLFiddle

EDIT

For SQL Server, you can use:

select sum(cast(stuff as decimal(5,2))) as mySum from test;

SQLFiddle

How to change a package name in Eclipse?

HOW TO COPY AND PASTE ANDROID PROJECT

A. If you are using Eclipse and all you want to do is first open the project that you want to copy(DON"T FORGET TO OPEN THE PROJECT THAT YOU NEED TO COPY), then clone(copy/paste) your Android project within the explorer package window on the left side of Eclipse. Eclipse will ask you for a new project name when you paste. Give it a new project name. Since Eclipse project name and directory are independent of the application name and package, the following steps will help you on how to change package names. Note: there are two types of package names.

1.To change src package names of packages within Src folder follow the following steps: First you need to create new package: (src >>>> right click >>>> new >>>> package).

Example of creating package: com.new.name

Follow these steps to move the Java files from the old copied package in part A to your new package.

Select the Java files within that old package

Right click that java files

select "Refactor" option

select "Move" option

Select your preferred package from the list of packages in a dialogue window. Most probably you need to select the new one you just created and hit "OK"

2.To change Application package name(main package), follow the following steps:

First right click your project

Then go to "Android tools"

Then select "Rename Application package"

Enter a new name in a dialogue window , and hit OK.

Then It will show you in which part of your project the Application name will be changed.

It will show you that the Application name will be changed in manifest, and in most relevant Java files. Hit "OK"

YOU DONE in this part, but make sure you rebuild your project to take effect.

To rebuild your project, go to ""project" >>> "Clean" >>>> select a Project from a projects

list, and hit "OK". Finally, you can run your new project.

How to insert Records in Database using C# language?

You should change your code to make use of SqlParameters and adapt your insert statement to the following

string connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
// [ ] required as your fields contain spaces!!
string insStmt = "insert into Main ([First Name], [Last Name]) values (@firstName,@lastName)";

using (SqlConnection cnn = new SqlConnection(connetionString))
{
    cnn.Open();
    SqlCommand insCmd = new SqlCommand(insStmt, cnn);
    // use sqlParameters to prevent sql injection!
    insCmd.Parameters.AddWithValue("@firstName", textbox2.Text);
    insCmd.Parameters.AddWithValue("@lastName", textbox3.Text);
    int affectedRows = insCmd.ExecuteNonQuery();
    MessageBox.Show (affectedRows + " rows inserted!");
}

json_decode to array

Please try this

<?php
$json_string = 'http://www.domain.com/jsondata.json';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
echo "<pre>"; print_r($obj['Result']);
?>

Fetch: POST json data

From search engines, I ended up on this topic for non-json posting data with fetch, so thought I would add this.

For non-json you don't have to use form data. You can simply set the Content-Type header to application/x-www-form-urlencoded and use a string:

fetch('url here', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
    body: 'foo=bar&blah=1'
});

An alternative way to build that body string, rather then typing it out as I did above, is to use libraries. For instance the stringify function from query-string or qs packages. So using this it would look like:

import queryString from 'query-string'; // import the queryString class

fetch('url here', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
    body: queryString.stringify({for:'bar', blah:1}) //use the stringify object of the queryString class
});

What's the difference between display:inline-flex and display:flex?

OK, I know at first might be a bit confusing, but display is talking about the parent element, so means when we say: display: flex;, it's about the element and when we say display:inline-flex;, is also making the element itself inline...

It's like make a div inline or block, run the snippet below and you can see how display flex breaks down to next line:

_x000D_
_x000D_
.inline-flex {_x000D_
  display: inline-flex;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
p {_x000D_
  color: red;_x000D_
}
_x000D_
<body>_x000D_
  <p>Display Inline Flex</p>_x000D_
  <div class="inline-flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
_x000D_
  <div class="inline-flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
_x000D_
  <p>Display Flex</p>_x000D_
  <div class="flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
_x000D_
  <div class="flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Also quickly create the image below to show the difference at a glance:

display flex vs display inline-flex

html <input type="text" /> onchange event not working

onchange is only triggered when the control is blurred. Try onkeypress instead.

What is the difference between a generative and a discriminative algorithm?

My two cents: Discriminative approaches highlight differences Generative approaches do not focus on differences; they try to build a model that is representative of the class. There is an overlap between the two. Ideally both approaches should be used: one will be useful to find similarities and the other will be useful to find dis-similarities.

How to get the width and height of an android.widget.ImageView?

The reason the ImageView's dimentions are 0 is because when you are querying them, the view still haven't performed the layout and measure steps. You only told the view how it would "behave" in the layout, but it still didn't calculated where to put each view.

How do you decide the size to give to the image view? Can't you simply use one of the scaling options natively implemented?

How to convert a UTF-8 string into Unicode?

I have string that displays UTF-8 encoded characters

There is no such thing in .NET. The string class can only store strings in UTF-16 encoding. A UTF-8 encoded string can only exist as a byte[]. Trying to store bytes into a string will not come to a good end; UTF-8 uses byte values that don't have a valid Unicode codepoint. The content will be destroyed when the string is normalized. So it is already too late to recover the string by the time your DecodeFromUtf8() starts running.

Only handle UTF-8 encoded text with byte[]. And use UTF8Encoding.GetString() to convert it.

Change priorityQueue to max priorityqueue

You can use MinMaxPriorityQueue (it's a part of the Guava library): here's the documentation. Instead of poll(), you need to call the pollLast() method.

How to change the data type of a column without dropping the column with query?

With SQL server 2008 and more, using this query:

ALTER TABLE [RecipeInventorys] ALTER COLUMN [RecipeName] varchar(550)

How do I disable orientation change on Android?

In Visual Studio Xamarin:

  1. Add:

using Android.Content.PM; to you activity namespace list.

  1. Add:

[Activity(ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]

as an attribute to you class, like that:

[Activity(ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : Activity
{...}

matplotlib error - no module named tkinter

For windows users, re-run the installer. Select Modify. Check the box for tcl/tk and IDLE. The description for this says "Installs tkinter"

postgresql return 0 if returned value is null

(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).


There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.

For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).

$ create table foo (bar int);
CREATE TABLE

$ select avg(bar) from foo;
 avg 
-----

(1 row)

$ select coalesce(avg(bar), 0) from foo;
 coalesce 
----------
        0
(1 row)

$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
      coalesce      
--------------------
 6.0000000000000000
(1 row)

of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"

Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.

$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
      coalesce      
--------------------
 4.0000000000000000
(1 row)

How do I set proxy for chrome in python webdriver?

from selenium import webdriver

PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)

chrome = webdriver.Chrome(options=chrome_options)
chrome.get("http://whatismyipaddress.com")

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

Babel command not found

Installing babel globally solves this issue:

npm install -g @babel/core @babel/cli

However, it is not encourage to install dependencies globally because they won't have their versions managed on a per-project basis.

You should install your dependencies locally, as suggested on babel's documentation:

npm install --save-dev @babel/core @babel/cli

The downside is that this gives you no fast/convenient way to invoke local binaries interactively (in this case babel). npx gives you a great solution:

npx babel --version

This will run your local installation of babel. Additionally, if you want to avoid typing npx, you can configure the shell auto fallback, and then just run:

babel --version

Note: it is important to create a file .babelrc, at your project's root, in which you specify your babel configuration. As a starting point you can use env-preset to transpile to ES2015+:

npm install @babel/preset-env --save-dev

In order to enable the preset you have to define it in your .babelrc file, like this:

{
  "presets": ["@babel/preset-env"]
}

Including dependencies in a jar with Maven

To make it more simple, You can use the below plugin.

             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        <configuration>
                            <classifier>spring-boot</classifier>
                            <mainClass>
                                com.nirav.certificate.CertificateUtility
                            </mainClass>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

How do I create batch file to rename large number of files in a folder?

you can do this easily without manual editing or using fancy text editors. Here's a vbscript.

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="c:\test"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
    If objFS.GetExtensionName(strFile) = "jpg" Then    
        strFileName = strFile.Name
        If InStr(strFileName,"Vacation2010") > 0 Then           
            strNewFileName = Replace(strFileName,"Vacation2010","December")
            strFile.Name = strNewFileName
        End If 
    End If  
Next 

save as myscript.vbs and

C:\test> cscript //nologo myscript.vbs 

Set active tab style with AngularJS

Came here for solution .. though above solutions are working fine but found them little bit complex unnecessary. For people who still looking for a easy and neat solution, it will do the task perfectly.

<section ng-init="tab=1">
                <ul class="nav nav-tabs">
                    <li ng-class="{active: tab == 1}"><a ng-click="tab=1" href="#showitem">View Inventory</a></li>
                    <li ng-class="{active: tab == 2}"><a ng-click="tab=2" href="#additem">Add new item</a></li>
                    <li ng-class="{active: tab == 3}"><a ng-click="tab=3" href="#solditem">Sold item</a></li>
                </ul>
            </section>

jQuery set radio button

Your selector looks for the descendant of a input:radio[name=cols] element that has the id of newcol (well the value of that variable).

Try this instead (since you're selecting by ID anyway):

$('#' + newcol).prop('checked',true);

Here is a demo: http://jsfiddle.net/jasper/n8CdM/1/

Also, as of jQuery 1.6 the perferred method of altering a property is .prop(): http://api.jquery.com/prop

Calculate difference in keys contained in two Python dictionaries

The top answer by hughdbrown suggests using set difference, which is definitely the best approach:

diff = set(dictb.keys()) - set(dicta.keys())

The problem with this code is that it builds two lists just to create two sets, so it's wasting 4N time and 2N space. It's also a bit more complicated than it needs to be.

Usually, this is not a big deal, but if it is:

diff = dictb.keys() - dicta

Python 2

In Python 2, keys() returns a list of the keys, not a KeysView. So you have to ask for viewkeys() directly.

diff = dictb.viewkeys() - dicta

For dual-version 2.7/3.x code, you're hopefully using six or something similar, so you can use six.viewkeys(dictb):

diff = six.viewkeys(dictb) - dicta

In 2.4-2.6, there is no KeysView. But you can at least cut the cost from 4N to N by building your left set directly out of an iterator, instead of building a list first:

diff = set(dictb) - dicta

Items

I have a dictA which can be the same as dictB or may have some keys missing as compared to dictB or else the value of some keys might be different

So you really don't need to compare the keys, but the items. An ItemsView is only a Set if the values are hashable, like strings. If they are, it's easy:

diff = dictb.items() - dicta.items()

Recursive diff

Although the question isn't directly asking for a recursive diff, some of the example values are dicts, and it appears the expected output does recursively diff them. There are already multiple answers here showing how to do that.

C# Set collection?

If you're using .NET 3.5, you can use HashSet<T>. It's true that .NET doesn't cater for sets as well as Java does though.

The Wintellect PowerCollections may help too.

What is causing the error `string.split is not a function`?

run this

// you'll see that it prints Object
console.log(typeof document.location);

you want document.location.toString() or document.location.href

Check if a string contains a number

use

str.isalpha() 

Ref: https://docs.python.org/2/library/stdtypes.html#str.isalpha

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

SSIS how to set connection string dynamically from a config file

Here's some background on the mechanism you should use, called Package Configurations: Understanding Integration Services Package Configurations. The article describes 5 types of configurations:

  • XML configuration file
  • Environment variable
  • Registry entry
  • Parent package variable
  • SQL Server

Here's a walkthrough of setting up a configuration on a Connection Manager: SQL Server Integration Services SSIS Package Configuration - I do realize this is using an environment variable for the connection string (not a great idea), but the basics are identical to using an XML file. The only step(s) you have to change in that walkthrough are the configuration type, and then a path.

Highlight text similar to grep, but don't filter out text

If you are looking for a pattern in a directory recursively, you can either first save it to file.

ls -1R ./ | list-of-files.txt

And then grep that, or pipe it to the grep search

ls -1R | grep --color -rE '[A-Z]|'

This will look of listing all files, but colour the ones with uppercase letters. If you remove the last | you will only see the matches.

I use this to find images named badly with upper case for example, but normal grep does not show the path for each file just once per directory so this way I can see context.

How to escape a JSON string containing newline characters using JavaScript?

As per user667073 suggested, except reordering the backslash replacement first, and fixing the quote replacement

escape = function (str) {
  return str
    .replace(/[\\]/g, '\\\\')
    .replace(/[\"]/g, '\\\"')
    .replace(/[\/]/g, '\\/')
    .replace(/[\b]/g, '\\b')
    .replace(/[\f]/g, '\\f')
    .replace(/[\n]/g, '\\n')
    .replace(/[\r]/g, '\\r')
    .replace(/[\t]/g, '\\t');
};

How to execute a query in ms-access in VBA code?

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop

CSS - display: none; not working

Try add this to your css

#tfl {
display: none !important;
}

How many significant digits do floats and doubles have in java?

A normal math answer.

Understanding that a floating point number is implemented as some bits representing the exponent and the rest, most for the digits (in the binary system), one has the following situation:

With a high exponent, say 10²³ if the least significant bit is changed, a large difference between two adjacent distinghuishable numbers appear. Furthermore the base 2 decimal point makes that many base 10 numbers can only be approximated; 1/5, 1/10 being endless numbers.

So in general: floating point numbers should not be used if you care about significant digits. For monetary amounts with calculation, e,a, best use BigDecimal.

For physics floating point doubles are adequate, floats almost never. Furthermore the floating point part of processors, the FPU, can even use a bit more precission internally.

Placing an image to the top right corner - CSS

While looking at the same problem, I found an example

<style type="text/css">
#topright {
    position: absolute;
    right: 0;
    top: 0;
    display: block;
    height: 125px;
    width: 125px;
    background: url(TRbanner.gif) no-repeat;
    text-indent: -999em;
    text-decoration: none;
}
</style>

<a id="topright" href="#" title="TopRight">Top Right Link Text</a>

The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)

How do I compare two DateTime objects in PHP 5.2.8?

From the official documentation:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2); // false
var_dump($date1 < $date2); // true
var_dump($date1 > $date2); // false

For PHP versions before 5.2.2 (actually for any version), you can use diff.

$datetime1 = new DateTime('2009-10-11'); // 11 October 2013
$datetime2 = new DateTime('2009-10-13'); // 13 October 2013

$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); // +2 days

The first day of the current month in php using date_modify as DateTime object

Here is what I use.

First day of the month:

date('Y-m-01');

Last day of the month:

date('Y-m-t');

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

If you use Java and spring MVC you just need to add the following annotation to your method returning your page :

@CrossOrigin(origins = "*")

"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.

NPM: npm-cli.js not found when running npm

On Windows 10:

  1. Press windows key, type edit the system environment variables then enter.
  2. Click environment variables...
  3. On the lower half of the window that opened with title Environment Variables there you will see a table titled System Variables, with two columns, the first one titled variable.
  4. Find the row with variable Path and click it.
  5. Click edit which will open a window titled Edit evironment variable.
  6. Here if you find

C:\Program Files\nodejs\node_modules\npm\bin

select it, and click edit button to your right, then edit the field to the path where you have the nodejs folder, in my case it was just shortening it to :

C:\Program Files\nodejs

Then I closed all my cmd or powershell terminals, opened them again and npm was working.

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

The javascript library sugar.js (http://sugarjs.com/) has functions to format dates

Example:

Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')

java.lang.Exception: No runnable methods exception in running JUnits

the solution is simple if you importing

import org.junit.Test;

you have to run as junit 4

right click ->run as->Test config-> test runner-> as junit 4

Incrementing a variable inside a Bash loop

minimalist

counter=0
((counter++))
echo $counter

Test for existence of nested JavaScript object key

I automated the process

if(isset(object,["prop1","prop2"])){
// YES!

}

function isset(object, props){
    var dump;
    try {
        for(var x in props){
            if(x == 0) {
                dump = object[props[x]];
                return;
            }
            dump = dump[props[x]];
        }
    } catch(e) {
        return false;
    }

    return true;
}

git-diff to ignore ^M

Developing on Windows, I ran into this problem when using git tfs. I solved it this way:

git config --global core.whitespace cr-at-eol

This basically tells Git that an end-of-line CR is not an error. As a result, those annoying ^M characters no longer appear at the end of lines in git diff, git show, etc.

It appears to leave other settings as-is; for instance, extra spaces at the end of a line still show as errors (highlighted in red) in the diff.

(Other answers have alluded to this, but the above is exactly how to set the setting. To set the setting for only one project, omit the --global.)

EDIT:

After many line-ending travails, I've had the best luck, when working on a .NET team, with these settings:

  • NO core.eol setting
  • NO core.whitespace setting
  • NO core.autocrlf setting
  • When running the Git installer for Windows, you'll get these three options:
    • Checkout Windows-style, commit Unix-style line endings <-- choose this one
    • Checkout as-is, commit Unix-style line endings
    • Checkout as-is, commit as-is

If you need to use the whitespace setting, you should probably enable it only on a per-project basis if you need to interact with TFS. Just omit the --global:

git config core.whitespace cr-at-eol

If you need to remove some core.* settings, the easiest way is to run this command:

git config --global -e

This opens your global .gitconfig file in a text editor, and you can easily delete the lines you want to remove. (Or you can put '#' in front of them to comment them out.)

Java: random long number in 0 <= x < n range

Starting from Java 7 (or Android API Level 21 = 5.0+) you could directly use ThreadLocalRandom.current().nextLong(n) (for 0 = x < n) and ThreadLocalRandom.current().nextLong(m, n) (for m = x < n). See @Alex's answer for detail.


If you are stuck with Java 6 (or Android 4.x) you need to use an external library (e.g. org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1), see @mawaldne's answer), or implement your own nextLong(n).

According to https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Random.html nextInt is implemented as

 public int nextInt(int n) {
     if (n<=0)
                throw new IllegalArgumentException("n must be positive");

     if ((n & -n) == n)  // i.e., n is a power of 2
         return (int)((n * (long)next(31)) >> 31);

     int bits, val;
     do {
         bits = next(31);
         val = bits % n;
     } while(bits - val + (n-1) < 0);
     return val;
 }

So we may modify this to perform nextLong:

long nextLong(Random rng, long n) {
   // error checking and 2^x checking removed for simplicity.
   long bits, val;
   do {
      bits = (rng.nextLong() << 1) >>> 1;
      val = bits % n;
   } while (bits-val+(n-1) < 0L);
   return val;
}

What is the difference between a deep copy and a shallow copy?

Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed; for a reference type --> the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed. If a field is a reference type --> a new copy of the referred object is performed. The classes to be cloned must be flagged as [Serializable].

Creating a BAT file for python script

This is the syntax: "python.exe path""python script path"pause

"C:\Users\hp\AppData\Local\Programs\Python\Python37\python.exe" "D:\TS_V1\TS_V2.py"
pause

Basically what will be happening the screen will appear for seconds and then go off take care of these 2 things:

  1. While saving the file you give extension as bat file but save it as a txt file and not all files and Encoding ANSI
  2. If the program still doesn't run save the batch file and the python script in same folder and specify the path of this folder in Environment Variables.

Unicode character for "X" cancel / close?

? works really well. The HTML code is &#10006;.

An alternative is &#x2715: ?

How can I check if a string is null or empty in PowerShell?

You guys are making this too hard. PowerShell handles this quite elegantly e.g.:

> $str1 = $null
> if ($str1) { 'not empty' } else { 'empty' }
empty

> $str2 = ''
> if ($str2) { 'not empty' } else { 'empty' }
empty

> $str3 = ' '
> if ($str3) { 'not empty' } else { 'empty' }
not empty

> $str4 = 'asdf'
> if ($str4) { 'not empty' } else { 'empty' }
not empty

> if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' }
one or both empty

> if ($str3 -and $str4) { 'neither empty' } else { 'one or both empty' }
neither empty

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Just to confirm: You are sure you are running MySQL 5.7, and not MySQL 5.6 or earlier version. And the plugin column contains "mysql_native_password". (Before MySQL 5.7, the password hash was stored in a column named password. Starting in MySQL 5.7, the password column is removed, and the password has is stored in the authentication_string column.) And you've also verified the contents of authentication string matches the return from PASSWORD('mysecret'). Also, is there a reason we are using DML against the mysql.user table instead of using the SET PASSWORD FOR syntax? – spencer7593

So Basically Just make sure that the Plugin Column contains "mysql_native_password".

Not my work but I read comments and noticed that this was stated as the answer but was not posted as a possible answer yet.

Fastest way to count number of occurrences in a Python list

Combination of lambda and map function can also do the job:

list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2

How to get name of dataframe column in pyspark?

The only way is to go an underlying level to the JVM.

df.col._jc.toString().encode('utf8')

This is also how it is converted to a str in the pyspark code itself.

From pyspark/sql/column.py:

def __repr__(self):
    return 'Column<%s>' % self._jc.toString().encode('utf8')

Spring security CORS Filter

  1. You don't need:

    @Configuration
    @ComponentScan("com.company.praktikant")
    

    @EnableWebSecurity already has @Configuration in it, and I cannot imagine why you put @ComponentScan there.

  2. About CORS filter, I would just put this:

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0); 
        return bean;
    }
    

    Into SecurityConfiguration class and remove configure and configure global methods. You don't need to set allowde orgins, headers and methods twice. Especially if you put different properties in filter and spring security config :)

  3. According to above, your "MyFilter" class is redundant.

  4. You can also remove those:

    final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.register(CORSConfig.class);
    annotationConfigApplicationContext.refresh();
    

    From Application class.

  5. At the end small advice - not connected to the question. You don't want to put verbs in URI. Instead of http://localhost:8080/getKunden you should use HTTP GET method on http://localhost:8080/kunden resource. You can learn about best practices for design RESTful api here: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

fast way to copy formatting in excel

Remember that when you write:

MyArray = Range("A1:A5000")

you are really writing

MyArray = Range("A1:A5000").Value

You can also use names:

MyArray = Names("MyWSTable").RefersToRange.Value

But Value is not the only property of Range. I have used:

MyArray = Range("A1:A5000").NumberFormat

I doubt

MyArray = Range("A1:A5000").Font

would work but I would expect

MyArray = Range("A1:A5000").Font.Bold

to work.

I do not know what formats you want to copy so you will have to try.

However, I must add that when you copy and paste a large range, it is not as much slower than doing it via an array as we all thought.

Post Edit information

Having posted the above I tried by own advice. My experiments with copying Font.Color and Font.Bold to an array have failed.

Of the following statements, the second would fail with a type mismatch:

  ValueArray = .Range("A1:T5000").Value
  ColourArray = .Range("A1:T5000").Font.Color

ValueArray must be of type variant. I tried both variant and long for ColourArray without success.

I filled ColourArray with values and tried the following statement:

  .Range("A1:T5000").Font.Color = ColourArray

The entire range would be coloured according to the first element of ColourArray and then Excel looped consuming about 45% of the processor time until I terminated it with the Task Manager.

There is a time penalty associated with switching between worksheets but recent questions about macro duration have caused everyone to review our belief that working via arrays was substantially quicker.

I constructed an experiment that broadly reflects your requirement. I filled worksheet Time1 with 5000 rows of 20 cells which were selectively formatted as: bold, italic, underline, subscript, bordered, red, green, blue, brown, yellow and gray-80%.

With version 1, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" using copy.

With version 2, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the value and the colour via an array.

With version 3, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the formula and the colour via an array.

Version 1 took an average of 12.43 seconds, version 2 took an average of 1.47 seconds while version 3 took an average of 1.83 seconds. Version 1 copied formulae and all formatting, version 2 copied values and colour while version 3 copied formulae and colour. With versions 1 and 2 you could add bold and italic, say, and still have some time in hand. However, I am not sure it would be worth the bother given that copying 21,300 values only takes 12 seconds.

** Code for Version 1**

I do not think this code includes anything that needs an explanation. Respond with a comment if I am wrong and I will fix.

Sub SelectionCopyAndPaste()

  Dim ColDestCrnt As Integer
  Dim ColSrcCrnt As Integer
  Dim NumSelect As Long
  Dim RowDestCrnt As Integer
  Dim RowSrcCrnt As Integer
  Dim StartTime As Single

  Application.ScreenUpdating = False
  Application.Calculation = xlCalculationManual
  NumSelect = 1
  ColDestCrnt = 1
  RowDestCrnt = 1
  With Sheets("Time2")
    .Range("A1:T715").EntireRow.Delete
  End With
  StartTime = Timer
  Do While True
    ColSrcCrnt = (NumSelect Mod 20) + 1
    RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
    If RowSrcCrnt > 5000 Then
      Exit Do
    End If
    Sheets("Time1").Cells(RowSrcCrnt, ColSrcCrnt).Copy _
                 Destination:=Sheets("Time2").Cells(RowDestCrnt, ColDestCrnt)
    If ColDestCrnt = 20 Then
      ColDestCrnt = 1
      RowDestCrnt = RowDestCrnt + 1
    Else
     ColDestCrnt = ColDestCrnt + 1
    End If
    NumSelect = NumSelect + 7
  Loop
  Debug.Print Timer - StartTime
  ' Average 12.43 secs
  Application.Calculation = xlCalculationAutomatic

End Sub

** Code for Versions 2 and 3**

The User type definition must be placed before any subroutine in the module. The code works through the source worksheet copying values or formulae and colours to the next element of the array. Once selection has been completed, it copies the collected information to the destination worksheet. This avoids switching between worksheets more than is essential.

Type ValueDtl
  Value As String
  Colour As Long
End Type

Sub SelectionViaArray()

  Dim ColDestCrnt As Integer
  Dim ColSrcCrnt As Integer
  Dim InxVLCrnt As Integer
  Dim InxVLCrntMax As Integer
  Dim NumSelect As Long
  Dim RowDestCrnt As Integer
  Dim RowSrcCrnt As Integer
  Dim StartTime As Single
  Dim ValueList() As ValueDtl

  Application.ScreenUpdating = False
  Application.Calculation = xlCalculationManual

  ' I have sized the array to more than I expect to require because ReDim
  ' Preserve is expensive.  However, I will resize if I fill the array.
  ' For my experiment I know exactly how many elements I need but that
  ' might not be true for you.
  ReDim ValueList(1 To 25000)

  NumSelect = 1
  ColDestCrnt = 1
  RowDestCrnt = 1
  InxVLCrntMax = 0      ' Last used element in ValueList.
  With Sheets("Time2")
    .Range("A1:T715").EntireRow.Delete
  End With
  StartTime = Timer
  With Sheets("Time1")
    Do While True
      ColSrcCrnt = (NumSelect Mod 20) + 1
      RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
      If RowSrcCrnt > 5000 Then
        Exit Do
      End If
      InxVLCrntMax = InxVLCrntMax + 1
      If InxVLCrntMax > UBound(ValueList) Then
        ' Resize array if it has been filled 
        ReDim Preserve ValueList(1 To UBound(ValueList) + 1000)
      End If
      With .Cells(RowSrcCrnt, ColSrcCrnt)
        ValueList(InxVLCrntMax).Value = .Value              ' Version 2
        ValueList(InxVLCrntMax).Value = .Formula            ' Version 3
        ValueList(InxVLCrntMax).Colour = .Font.Color
      End With
      NumSelect = NumSelect + 7
    Loop
  End With
  With Sheets("Time2")
    For InxVLCrnt = 1 To InxVLCrntMax
      With .Cells(RowDestCrnt, ColDestCrnt)
        .Value = ValueList(InxVLCrnt).Value                 ' Version 2
        .Formula = ValueList(InxVLCrnt).Value               ' Version 3
        .Font.Color = ValueList(InxVLCrnt).Colour
      End With
      If ColDestCrnt = 20 Then
        ColDestCrnt = 1
        RowDestCrnt = RowDestCrnt + 1
      Else
       ColDestCrnt = ColDestCrnt + 1
      End If
    Next
  End With
  Debug.Print Timer - StartTime
  ' Version 2 average 1.47 secs
  ' Version 3 average 1.83 secs
  Application.Calculation = xlCalculationAutomatic

End Sub

Linux find file names with given string recursively

This is a very simple solution using the tree command in the directory you want to search for. -f shows the full file path and | is used to pipe the output of tree to grep to find the file containing the string filename in the name.

tree -f | grep filename

ActiveRecord find and only return selected columns

In Rails 2

l = Location.find(:id => id, :select => "name, website, city", :limit => 1)

...or...

l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])

This reference doc gives you the entire list of options you can use with .find, including how to limit by number, id, or any other arbitrary column/constraint.

In Rails 3 w/ActiveRecord Query Interface

l = Location.where(["id = ?", id]).select("name, website, city").first

Ref: Active Record Query Interface

You can also swap the order of these chained calls, doing .select(...).where(...).first - all these calls do is construct the SQL query and then send it off.

how to get curl to output only http response body (json) and no other headers etc

#!/bin/bash

req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"

How to add an image in Tkinter?

Python 3.3.1 [MSC v.1600 32 bit (Intel)] on win32 14.May.2013

This worked for me, by following the code above

from tkinter import *
from PIL import ImageTk, Image
import os

root = Tk()
img = ImageTk.PhotoImage(Image.open("True1.gif"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

segmentation fault : 11

Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.

Writing that much data to a file is going to take a while.

You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).

You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?

You should also write a function to do the calculation; you could use an inline function in C99 or later (or C++). The repetition in the code is excruciating to behold.

You should also use C99 notation for main(), with the explicit return type (and preferably void for the argument list when you are not using argc or argv):

int main(void)

Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 }; (thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static in front of the functions, and the main array; file becomes a local to main; error check the fopen(), etc.).

I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.

#include <stdio.h>

#define   lambda   2.0
#define   g        1.0
#define   F0       1.0
#define   h        0.1
#define   e        0.00001

enum { ROWS = 1000, COLS = 10000 };

static double F[ROWS][COLS];

static void Inicio(double D[ROWS][COLS])
{
    for (int i = 399; i < 600; i++) // Magic numbers!!
        D[i][0] = F0;
}

enum { R = ROWS - 1 };

static inline int ko(int k, int n)
{
    int rv = k + n;
    if (rv >= R)
        rv -= R;
    else if (rv < 0)
        rv += R;
    return(rv);
}

static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
    int ks2 = ko(k, -2);
    int ks1 = ko(k, -1);
    int kp1 = ko(k, +1);
    int kp2 = ko(k, +2);

    A[k][i] = A[k][i-1]
            + e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
            + 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
            + e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}

static void Iteration(double A[ROWS][COLS])
{
    for (int i = 1; i < COLS; i++)
    {
        for (int k = 0; k < R; k++)
            calculate_value(i, k, A);
        A[999][i] = A[0][i];
    }
}

int main(void)
{
    FILE *file = fopen("P2.txt","wt");
    if (file == 0)
        return(1);
    Inicio(F);
    Iteration(F);
    for (int i = 0; i < COLS; i++)
    {
        for (int j = 0; j < ROWS; j++)
        {
            fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
        }
    }
    fclose(file);
    return(0);
}

This program writes to P2.txt instead of P1.txt. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:

Original   Modified
6.334s      6.367s
6.241s      6.231s
6.315s     10.778s
6.378s      6.320s
6.388s      6.293s
6.285s      6.268s
6.387s     10.954s
6.377s      6.227s
8.888s      6.347s
6.304s      6.286s
6.258s     10.302s
6.975s      6.260s
6.663s      6.847s
6.359s      6.313s
6.344s      6.335s
7.762s      6.533s
6.310s      9.418s
8.972s      6.370s
6.383s      6.357s

However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for loop became:

for (int i = COLS - 1; i < COLS; i++)

the timings were vastly reduced and very much more consistent:

Original    Modified
0.168s      0.165s
0.145s      0.165s
0.165s      0.166s
0.164s      0.163s
0.151s      0.151s
0.148s      0.153s
0.152s      0.171s
0.165s      0.165s
0.173s      0.176s
0.171s      0.165s
0.151s      0.169s

The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.

Intel's HAXM equivalent for AMD on Windows OS

Buying a new processor is one solution, but for some of us that means buying other components as well. Alternatively you could just buy an Android phone that supports your lowest target API level and run your apps off the phone. You can find some of those phones on Amazon, Ebay, craigslist for pennies (sometimes). Plus this grants you the benefit of actually running on the minimum hardware you intend to support. While this may be a bit slower than installing your app on an emulated system, it will probably save you money.

Android, device testing/debugging link: http://developer.android.com/tools/device.html

How to copy sheets to another workbook using vba?

    Workbooks.Open Filename:="Path(Ex: C:\Reports\ClientWiseReport.xls)"ReadOnly:=True


    For Each Sheet In ActiveWorkbook.Sheets

        Sheet.Copy After:=ThisWorkbook.Sheets(1)

    Next Sheet

How to compare two tables column by column in oracle

As an alternative which saves from full scanning each table twice and also gives you an easy way to tell which table had more rows with a combination of values than the other:

SELECT col1
     , col2
     -- (include all columns that you want to compare)
     , COUNT(src1) CNT1
     , COUNT(src2) CNT2
  FROM (SELECT a.col1
             , a.col2
             -- (include all columns that you want to compare)
             , 1 src1
             , TO_NUMBER(NULL) src2
          FROM tab_a a
         UNION ALL
        SELECT b.col1
             , b.col2
             -- (include all columns that you want to compare)
             , TO_NUMBER(NULL) src1
             , 2 src2
          FROM tab_b b
       )
 GROUP BY col1
        , col2
HAVING COUNT(src1) <> COUNT(src2) -- only show the combinations that don't match

Credit goes here: http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:1417403971710

Android: No Activity found to handle Intent error? How it will resolve

Add the below to your manifest:

  <activity   android:name=".AppPreferenceActivity" android:label="@string/app_name">  
     <intent-filter> 
       <action android:name="com.scytec.datamobile.vd.gui.android.AppPreferenceActivity" />  
       <category android:name="android.intent.category.DEFAULT" />  
     </intent-filter>   
  </activity>

ArrayList filter

In , they introduced the method removeIf which takes a Predicate as parameter.

So it will be easy as:

List<String> list = new ArrayList<>(Arrays.asList("How are you",
                                                  "How you doing",
                                                  "Joe",
                                                  "Mike"));
list.removeIf(s -> !s.contains("How"));

Return first N key:value pairs from dict

def GetNFirstItems(self):
    self.dict = {f'Item{i + 1}': round(uniform(20.40, 50.50), 2) for i in range(10)}#Example Dict
    self.get_items = int(input())
    for self.index,self.item in zip(range(len(self.dict)),self.dict.items()):
        if self.index==self.get_items:
          break
        else:
            print(self.item,",",end="")

Unusual approach, as it gives out intense O(N) time complexity.

Push items into mongo array via mongoose

An easy way to do that is to use the following:

var John = people.findOne({name: "John"});
John.friends.push({firstName: "Harry", lastName: "Potter"});
John.save();

Showing Difference between two datetime values in hours

Is there a reason you're using Nullable?

If you want to use Nullable then you can write variable.Value.TotalHours.

Or you can just write: (datevalue1 - datevalue2).TotalHours.

Get difference between 2 dates in JavaScript?

A more correct solution

... since dates naturally have time-zone information, which can span regions with different day light savings adjustments

Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24, so the typical calculation will fail.

You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.

Now, the solution can be written as,

const _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// test it
const a = new Date("2017-01-01"),
    b = new Date("2017-07-25"),
    difference = dateDiffInDays(a, b);

This works because UTC time never observes DST. See Does UTC observe daylight saving time?

p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.

Npm install failed with "cannot run in wd"

OP here, I have learned a lot more about node since I first asked this question. Though Dmitry's answer was very helpful, what ultimately did it for me is to install node with the correct permissions.

I highly recommend not installing node using any package managers, but rather to compile it yourself so that it resides in a local directory with normal permissions.

This article provides a very clear step-by-step instruction of how to do so:

https://www.digitalocean.com/community/tutorials/how-to-install-an-upstream-version-of-node-js-on-ubuntu-12-04

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

How can I change the Java Runtime Version on Windows (7)?

All you need to do is set the PATH environment variable in Windows to point to where your java6 bin directory is instead of the java7 directory.

Right click My Computer > Advanced System Settings > Advanced > Environmental Variables

If there is a JAVA_HOME environment variable set this to point to the correct directory as well.

How to do an INNER JOIN on multiple columns

Why can't it just use AND in the ON clause? For example:

SELECT *
FROM flights
INNER JOIN airports
   ON ((airports.code = flights.fairport)
       AND (airports.code = flights.tairport))

round() doesn't seem to be rounding properly

Here's where I see round failing. What if you wanted to round these 2 numbers to one decimal place? 23.45 23.55 My education was that from rounding these you should get: 23.4 23.6 the "rule" being that you should round up if the preceding number was odd, not round up if the preceding number were even. The round function in python simply truncates the 5.

Way to create multiline comments in Bash?

what's your opinion on this one?

function giveitauniquename()
{
  so this is a comment
  echo "there's no need to further escape apostrophes/etc if you are commenting your code this way"
  the drawback is it will be stored in memory as a function as long as your script runs unless you explicitly unset it
  only valid-ish bash allowed inside for instance these would not work without the "pound" signs:
  1, for #((
  2, this #wouldn't work either
  function giveitadifferentuniquename()
  {
    echo nestable
  }
}

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

In my case, I need to set the path of openssl.cnf file manually on the command using config option. So the command

openssl req -x509 -config "C:\Users\sk\Downloads\openssl-0.9.8k_X64\openssl.cnf" -newkey rsa:4096 -keyout key.pem -out cert.pem -nodes -days 900

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

In testing IE7/8/9 I was getting an ActiveX warning trying to use this code snippet:

filter:progid:DXImageTransform.Microsoft.gradient

After removing this the warning went away. I know this isn't an answer, but I thought it was worthwhile to note.

How to ignore a property in class if null, using json.net

As per James Newton King: If you create the serializer yourself rather than using JavaScriptConvert there is a NullValueHandling property which you can set to ignore.

Here's a sample:

JsonSerializer _jsonWriter = new JsonSerializer {
                                 NullValueHandling = NullValueHandling.Ignore
                             };

Alternatively, as suggested by @amit

JsonConvert.SerializeObject(myObject, 
                            Newtonsoft.Json.Formatting.None, 
                            new JsonSerializerSettings { 
                                NullValueHandling = NullValueHandling.Ignore
                            });

Center align "span" text inside a div

You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.

You could give the span a set width, then add the margin:0 auto again. This would center-align it.

.left 
{
   background-color: #999999;
   height: 50px;
   width: 24.5%;
}
span.panelTitleTxt 
{
   display:block;
   width:100px;
   height: 100%;
   margin: 0 auto;
}

Splitting a string at every n-th character

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        for (String part : getParts("foobarspam", 3)) {
            System.out.println(part);
        }
    }
    private static List<String> getParts(String string, int partitionSize) {
        List<String> parts = new ArrayList<String>();
        int len = string.length();
        for (int i=0; i<len; i+=partitionSize)
        {
            parts.add(string.substring(i, Math.min(len, i + partitionSize)));
        }
        return parts;
    }
}

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Go to config.inc.php file using terminal by typing the following:

sudo gedit /opt/lampp/phpmyadmin/config.inc.php

The file will open in gedit.

Now open the file and edit

$cfg['Servers'][$i]['auth_type'] = 'localhost';

to

$cfg['Servers'][$i]['auth_type'] = 'cookie';

and keep the username as: root password:

Also make sure that the lines with username and password are not commented:

//$cfg['Servers'][$i]['user'] = 'root'; //$cfg['Servers'][$i]['password'] = '';

Make sure that // is removed from the above lines.

Traverse a list in reverse order in Python

The other answers are good, but if you want to do as List comprehension style

collection = ['a','b','c']
[item for item in reversed( collection ) ]

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Limit characters displayed in span

You can do this with jQuery :

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  _x000D_
  $('.claimedRight').each(function (f) {_x000D_
_x000D_
      var newstr = $(this).text().substring(0,20);_x000D_
      $(this).text(newstr);_x000D_
_x000D_
    });_x000D_
})
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <title></title>_x000D_
    <script         src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
    <span class="claimedRight" maxlength="20">Hello this is the first test string. _x000D_
    </span><br>_x000D_
    <span class="claimedRight" maxlength="20">Hello this is the second test string. _x000D_
    </span>_x000D_
    _x000D_
    _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

jQuery ajax request with json response, how to?

Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener

see https://github.com/ArtNazarov/LazyJs

Sorry for my bad English

commands not found on zsh

Uninstall and reinstall zsh worked for me:

sudo yum remove zsh
sudo yum install -y zsh

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Why should we include ttf, eot, woff, svg,... in a font-face

Answer in 2019:

Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format

(svg and eot are dead formats, ttf and otf are full system fonts, and should not be used for web purposes)

Original answer from 2012:

In short, font-face is very old, but only recently has been supported by more than IE.

  • eot is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.

  • ttf and otf are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.

  • Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.

  • Then, woff gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.

  • 2019 edit A few years later, woff2 gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.

If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)

@font-face {
  font-family: 'MyWebFont';
  src:  url('myfont.woff2') format('woff2'),
        url('myfont.woff') format('woff');
}

Support for woff can be checked at http://caniuse.com/woff
Support for woff2 can be checked at http://caniuse.com/woff2

What causes a TCP/IP reset (RST) flag to be sent?

Some firewalls do that if a connection is idle for x number of minutes. Some ISPs set their routers to do that for various reasons as well.

In this day and age, you'll need to gracefully handle (re-establish as needed) that condition.

Creating hard and soft links using PowerShell

I combined two answers (@bviktor and @jocassid). It was tested on Windows 10 and Windows Server 2012.

function New-SymLink ($link, $target)
{
    if ($PSVersionTable.PSVersion.Major -ge 5)
    {
        New-Item -Path $link -ItemType SymbolicLink -Value $target
    }
    else
    {
        $command = "cmd /c mklink /d"
        invoke-expression "$command ""$link"" ""$target"""
    }
}

multiple conditions for filter in spark data frames

For future references : we can use isInCollection to filter ,here is a example : Note : It will look for exact match

  def getSelectedTablesRows(allTablesInfoDF: DataFrame, tableNames: Seq[String]): DataFrame = {

    allTablesInfoDF.where(col("table_name").isInCollection(tableNames))

  }

Eclipse reports rendering library more recent than ADT plug-in

The Reason for Warning is your using Old ADT (Android development tools), so Update your ADT by following the procedures below

Procedure 1:

  1. Inside Eclipse Click Help menu
  2. Choose Check for Updates
  3. It will show Required Updates in that window choose All options using Check box or else choose ADT Updated.

enter image description here

Procedure 2:

Click Help > Install New Software. In the Work with field, enter: https://dl-ssl.google.com/android/eclipse/ Select Developer Tools / Android Development Tools. Click Next and complete the wizard.

Making a drop down list using swift?

(Swift 3) Add text box and uipickerview to the storyboard then add delegate and data source to uipickerview and add delegate to textbox. Follow video for assistance https://youtu.be/SfjZwgxlwcc

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var textBox: UITextField!
    @IBOutlet weak var dropDown: UIPickerView!

    var list = ["1", "2", "3"]

    public func numberOfComponents(in pickerView: UIPickerView) -> Int{
        return 1
    }

    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{

        return list.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        self.view.endEditing(true)
        return list[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        self.textBox.text = self.list[row]
        self.dropDown.isHidden = true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {

        if textField == self.textBox {
            self.dropDown.isHidden = false
            //if you don't want the users to se the keyboard type:

            textField.endEditing(true)
        }
    }
}

Space between two divs

You can try something like the following:

h1{
   margin-bottom:<x>px;
}
div{
   margin-bottom:<y>px;
}
div:last-of-type{
   margin-bottom:0;
}

or instead of the first h1 rule:

div:first-of-type{
   margin-top:<x>px;
}

or even better use the adjacent sibling selector. With the following selector, you could cover your case in one rule:

div + div{
   margin-bottom:<y>px;
}

Respectively, h1 + div would control the first div after your header, giving you additional styling options.

Google.com and clients1.google.com/generate_204

The generate 204 might be dynamically loading the suggestions of search criteria. AS i can see from my load test script, this is seemingly responsible for every server call each time the user types into the text box

What throws an IOException in Java?

In general, I/O means Input or Output. Those methods throw the IOException whenever an input or output operation is failed or interpreted. Note that this won't be thrown for reading or writing to memory as Java will be handling it automatically.

Here are some cases which result in IOException.

  • Reading from a closed inputstream
  • Try to access a file on the Internet without a network connection

g++ undefined reference to typeinfo

in my case, i used a third-party library with header files and so file. i subclassed one class, and link error like this occurred when i try to instantiate my subclass.

as mentioned by @sergiy, knowning it could be the problem of 'rtti', i managed to workaround it by put the constructor implementation into separate .cpp file and apply '-fno-rtti' compile flags to the file. it works well.

as i am still not quite clear about the internal of this link error, i am not sure whether my solution is general. however, i think it worth a shot before trying the adaptor way as mentioned by @francois . and of course, if all source codes are available(not in my case), better do recompile with '-frtti' if possible.

one more thing, if you choose to try my solution, try make the separate file as simple as possible, and do not use some fancy features of C++. take special attention on boost related things, cause much of it depends on rtti.

Assigning multiple styles on an HTML element

You needed to do it like this:

_x000D_
_x000D_
<h2 style="text-align: center;font-family: Tahoma">TITLE</h2>
_x000D_
_x000D_
_x000D_

Hope it helped.

Maven: add a dependency to a jar by relative path

Using the system scope. ${basedir} is the directory of your pom.

<dependency>
    <artifactId>..</artifactId>
    <groupId>..</groupId>
    <scope>system</scope>
    <systemPath>${basedir}/lib/dependency.jar</systemPath>
</dependency>

However it is advisable that you install your jar in the repository, and not commit it to the SCM - after all that's what maven tries to eliminate.

Alternate table row color using CSS?

We can use odd and even CSS rules and jQuery method for alternate row colors

Using CSS

table tr:nth-child(odd) td{
           background:#ccc;
}
table tr:nth-child(even) td{
            background:#fff;
}

Using jQuery

$(document).ready(function()
{
  $("table tr:odd").css("background", "#ccc");
  $("table tr:even").css("background", "#fff");
});

_x000D_
_x000D_
table tr:nth-child(odd) td{_x000D_
           background:#ccc;_x000D_
}_x000D_
table tr:nth-child(even) td{_x000D_
            background:#fff;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>One</td>_x000D_
    <td>one</td>_x000D_
   </tr>_x000D_
  <tr>_x000D_
    <td>Two</td>_x000D_
    <td>two</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

os.walk without digging into directories below

Use the walklevel function.

import os

def walklevel(some_dir, level=1):
    some_dir = some_dir.rstrip(os.path.sep)
    assert os.path.isdir(some_dir)
    num_sep = some_dir.count(os.path.sep)
    for root, dirs, files in os.walk(some_dir):
        yield root, dirs, files
        num_sep_this = root.count(os.path.sep)
        if num_sep + level <= num_sep_this:
            del dirs[:]

It works just like os.walk, but you can pass it a level parameter that indicates how deep the recursion will go.

calculating execution time in c++

If you have cygwin installed, from it's bash shell, run your executable, say MyProgram, using the time utility, like so:

/usr/bin/time ./MyProgram

This will report how long the execution of your program took -- the output would look something like the following:

real    0m0.792s
user    0m0.046s
sys     0m0.218s

You could also manually modify your C program to instrument it using the clock() library function, like so:

#include <time.h>
int main(void) {
    clock_t tStart = clock();
    /* Do your stuff here */
    printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
    return 0;
}

Display a tooltip over a button using Windows Forms

The ToolTip is a single WinForms control that handles displaying tool tips for multiple elements on a single form.

Say your button is called MyButton.

  1. Add a ToolTip control (under Common Controls in the Windows Forms toolbox) to your form.
  2. Give it a name - say MyToolTip
  3. Set the "Tooltip on MyToolTip" property of MyButton (under Misc in the button property grid) to the text that should appear when you hover over it.

The tooltip will automatically appear when the cursor hovers over the button, but if you need to display it programmatically, call

MyToolTip.Show("Tooltip text goes here", MyButton);

in your code to show the tooltip, and

MyToolTip.Hide(MyButton);

to make it disappear again.

How to fix Python indentation

I have a simple solution for this problem. You can first type ":retab" and then ":retab!", then everything would be fine

Undefined index with $_POST

Prior to PHP 5.2.0 and above you should use filter_input() which is especially created for that to get a specific external user inputs such as get, post or cookie variables by name and optionally filters it to avoid any XSS/Injection attacks on your site. For example:

$user = filter_input(INPUT_POST, 'username');

You may use one of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

By using optional 3rd argument, you can extend it by variety of filters (for validating, sanitizing, filtering or other), e.g. FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_ENCODED, etc.

For example:

<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>

The syntax is:

mixed filter_input ( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] )

(PHP 5 >= 5.2.0, PHP 7)

See also: Why is better to use filter_input()?

Removing Spaces from a String in C?

Here is the simplest thing i could think of. Note that this program uses second command line argument (argv[1]) as a line to delete whitespaces from.

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

/*The function itself with debug printing to help you trace through it.*/

char* trim(const char* str)
{
    char* res = malloc(sizeof(str) + 1);
    char* copy = malloc(sizeof(str) + 1);
    copy = strncpy(copy, str, strlen(str) + 1);
    int index = 0;

    for (int i = 0; i < strlen(copy) + 1; i++) {
        if (copy[i] != ' ')
        {
            res[index] = copy[i];
            index++;
        }
        printf("End of iteration %d\n", i);
        printf("Here is the initial line: %s\n", copy);
        printf("Here is the resulting line: %s\n", res);
        printf("\n");
    }
    return res;
}

int main(int argc, char* argv[])
{
    //trim function test

    const char* line = argv[1];
    printf("Here is the line: %s\n", line);

    char* res = malloc(sizeof(line) + 1);
    res = trim(line);

    printf("\nAnd here is the formatted line: %s\n", res);

    return 0;
}

Xcode 4: How do you view the console?

Here' an alternative

In Xcode 4 short cut to display and hide console is (command-shift-Y) , this will show the console and debugger below ur text edior in the same window.

Check if value is in select list with JQuery

I know this is kind of an old question by this one works better.

if(!$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"] option[value="'+data['item'][i]['id']+'"]')[0]){
  //Doesn't exist, so it isn't a repeat value being added. Go ahead and append.
  $('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"]').append(option);
}

As you can see in this example, I am searching by unique tags data-dropdown name and the value of the selected option. Of course you don't need these for these to work but I included them so that others could see you can search multi values, etc.

On design patterns: When should I use the singleton?

It can be very pragmatic to configure specific infrastructure concerns as singletons or global variables. My favourite example of this is Dependency Injection frameworks that make use of singletons to act as a connection point to the framework.

In this case you are taking a dependency on the infrastructure to simplify using the library and avoid unneeded complexity.

C# DataTable.Select() - How do I format the filter criteria to include null?

Try this

myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )

Edit: Relevant sources:

Angular 2 ngfor first, last, index loop

Check out this plunkr.

When you're binding to variables, you need to use the brackets. Also, you use the hashtag when you want to get references to elements in your html, not for declaring variables inside of templates like that.

<md-button-toggle *ngFor="let indicador of indicadores; let first = first;" [value]="indicador.id" [checked]="first"> 
...

Edit: Thanks to Christopher Moore: Angular exposes the following local variables:

  • index
  • first
  • last
  • even
  • odd

Combining a class selector and an attribute selector with jQuery

This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

How to remove a character at the end of each line in unix

Try doing this :

awk '{print substr($0, 1, length($0)-1)}' file.txt

This is more generic than just removing the final comma but any last character

If you'd want to only remove the last comma with awk :

awk '{gsub(/,$/,""); print}' file.txt

Build fat static library (device + simulator) using Xcode and SDK 4+

I've made this into an Xcode 4 template, in the same vein as Karl's static framework template.

I found that building static frameworks (instead of plain static libraries) was causing random crashes with LLVM, due to an apparent linker bug - so, I guess static libraries are still useful!

Convert string to date in bash

This worked for me :

date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'

then you can format output adding parameter '+%Y%m%d'