Programs & Examples On #Smart playlist

How do I update an entity using spring-data-jpa?

Using spring-data-jpa save(), I was having same problem as @DtechNet. I mean every save() was creating new object instead of update. To solve this I had to add version field to entity and related table.

How to get the last character of a string in a shell?

Every answer so far implies the word "shell" in the question equates to Bash.

This is how one could do that in a standard Bourne shell:

printf $str | tail -c 1

How do I get git to default to ssh and not https for new repositories

SSH File

~/.ssh/config file
Host *
    StrictHostKeyChecking no
    UserKnownHostsFile=/dev/null
    LogLevel QUIET
    ConnectTimeout=10
Host github.com
        User git
        AddKeystoAgent yes
        UseKeychain yes
        Identityfile ~/github_rsa

Edit reponame/.git/config

[remote "origin"]
        url = [email protected]:username/repo.git

Encoding Error in Panda read_csv

Try calling read_csv with encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' (these are some of the various encodings found on Windows).

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

How to update values using pymongo?

in python the operators should be in quotes: db.ProductData.update({'fromAddress':'http://localhost:7000/'}, {"$set": {'fromAddress': 'http://localhost:5000/'}},{"multi": True})

Using an IF Statement in a MySQL SELECT query

The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:

SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...
WHERE ...

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Code verified to work in Hibernate 4.3.0. Notice you can remove the XML filename parameter, or else provide your own path there. This is similar to (but typos corrected) other posts here, but this one is correct.

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;    


Configuration configuration = new Configuration();
configuration.configure("/com/rtw/test/hiber/hibernate.cfg.xml");
ServiceRegistry  serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();        
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

Angular HTML binding

Working in Angular v2.1.1

<div [innerHTML]="variable or htmlString">
</div>

SELECT CASE WHEN THEN (SELECT)

I ended up leaving the common properties from the SELECT queries and making a second SELECT query later on in the page. I used a php IF command to call for different scripts depending on the first SELECT query, the scripts contained the second SELECT query.

Evaluate if list is empty JSTL

There's also the function tags, a bit more flexible:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">

And here's the tag documentation.

Alternate background colors for list items

You can by hardcoding the sequence, like so:

li, li + li + li, li + li + li + li + li {
  background-color: black;
}

li + li, li + li + li + li {
  background-color: white;
}

How do I center text vertically and horizontally in Flutter?

Text element inside Center of SizedBox work much better way, below Sample code

Widget build(BuildContext context) {
    return RawMaterialButton(
      fillColor: Colors.green,
      splashColor: Colors.greenAccent,
      shape: new CircleBorder(),
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            SizedBox(
              width: 100.0,
              height: 100.0,
              child: Center(
                child: Text(
                widget.buttonText,
                maxLines: 1,
                style: TextStyle(color: Colors.white)
              ),
              )
          )]
        ),
    ),
  onPressed: widget.onPressed
);
}

Enjoy coding ?

jQuery add text to span within a div

Careful - append() will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>').

Use text() to replace element content with text, or append(document.createTextNode(x)) to append a text node.

How do I change a TCP socket to be non-blocking?

It is sometimes convenient to employ the "send/recv" family of system calls. If the flags parameter contains the MSG_DONTWAIT flag, each call will behave similar to a socket having the O_NONBLOCK flag set.

ssize_t send(int sockfd, const void *buf, size_t len, int flags);

ssize_t recv(int sockfd, void *buf, size_t len, int flags);

What do $? $0 $1 $2 mean in shell script?

These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

How to manually trigger validation with jQuery validate?

There is a good way if you use validate() with parameters on a form and want to validate one field of your form manually afterwards:

var validationManager = $('.myForm').validate(myParameters);
...
validationManager.element($(this));

Documentation: Validator.element()

Add/remove class with jquery based on vertical scroll?

Is this value intended? if (scroll <= 500) { ... This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"

REST URI convention - Singular or plural name of resource while creating it

With naming conventions, it's usually safe to say "just pick one and stick to it", which makes sense.

However, after having to explain REST to lots of people, representing endpoints as paths on a file system is the most expressive way of doing it.
It is stateless (files either exist or don't exist), hierarchical, simple, and familiar - you already knows how to access static files, whether locally or via http.

And within that context, linguistic rules can only get you as far as the following:

A directory can contain multiple files and/or sub-directories, and therefore its name should be in plural form.

And I like that.
Although, on the other hand - it's your directory, you can name it "a-resource-or-multiple-resources" if that's what you want. That's not really the important thing.

What's important is that if you put a file named "123" under a directory named "resourceS" (resulting in /resourceS/123), you cannot then expect it to be accessible via /resource/123.

Don't try to make it smarter than it has to be - changing from plural to singluar depending on the count of resources you're currently accessing may be aesthetically pleasing to some, but it's not effective and it doesn't make sense in a hierarchical system.

Note: Technically, you can make "symbolic links", so that /resources/123 can also be accessed via /resource/123, but the former still has to exist!

How to set image name in Dockerfile?

Tagging of the image isn't supported inside the Dockerfile. This needs to be done in your build command. As a workaround, you can do the build with a docker-compose.yml that identifies the target image name and then run a docker-compose build. A sample docker-compose.yml would look like

version: '2'

services:
  man:
    build: .
    image: dude/man:v2

That said, there's a push against doing the build with compose since that doesn't work with swarm mode deploys. So you're back to running the command as you've given in your question:

docker build -t dude/man:v2 .

Personally, I tend to build with a small shell script in my folder (build.sh) which passes any args and includes the name of the image there to save typing. And for production, the build is handled by a ci/cd server that has the image name inside the pipeline script.

Is there a way to programmatically scroll a scroll view to a specific edit text?

Examining Android source code, you can find that there already is a member function of ScrollViewscrollToChild(View) – that does exactly what is requested. Unfortunatelly, this function is for some obscure reason marked private. Based on that function I've written following function that finds the first ScrollView above the View specified as a parameter and scrolls it so that it becomes visible within the ScrollView:

 private void make_visible(View view)
 {
  int vt = view.getTop();
  int vb = view.getBottom();

  View v = view;

  for(;;)
     {
      ViewParent vp = v.getParent();

      if(vp == null || !(vp instanceof ViewGroup))
         break;

      ViewGroup parent = (ViewGroup)vp;

      if(parent instanceof ScrollView)
        {
         ScrollView sv = (ScrollView)parent;

         // Code based on ScrollView.computeScrollDeltaToGetChildRectOnScreen(Rect rect) (Android v5.1.1):

         int height = sv.getHeight();
         int screenTop = sv.getScrollY();
         int screenBottom = screenTop + height;

         int fadingEdge = sv.getVerticalFadingEdgeLength();

         // leave room for top fading edge as long as rect isn't at very top
         if(vt > 0)
            screenTop += fadingEdge;

         // leave room for bottom fading edge as long as rect isn't at very bottom
         if(vb < sv.getChildAt(0).getHeight())
            screenBottom -= fadingEdge;

         int scrollYDelta = 0;

         if(vb > screenBottom && vt > screenTop) 
           {
            // need to move down to get it in view: move down just enough so
            // that the entire rectangle is in view (or at least the first
            // screen size chunk).

            if(vb-vt > height) // just enough to get screen size chunk on
               scrollYDelta += (vt - screenTop);
            else              // get entire rect at bottom of screen
               scrollYDelta += (vb - screenBottom);

             // make sure we aren't scrolling beyond the end of our content
            int bottom = sv.getChildAt(0).getBottom();
            int distanceToBottom = bottom - screenBottom;
            scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
           }
         else if(vt < screenTop && vb < screenBottom) 
           {
            // need to move up to get it in view: move up just enough so that
            // entire rectangle is in view (or at least the first screen
            // size chunk of it).

            if(vb-vt > height)    // screen size chunk
               scrollYDelta -= (screenBottom - vb);
            else                  // entire rect at top
               scrollYDelta -= (screenTop - vt);

            // make sure we aren't scrolling any further than the top our content
            scrollYDelta = Math.max(scrollYDelta, -sv.getScrollY());
           }

         sv.smoothScrollBy(0, scrollYDelta);
         break;
        }

      // Transform coordinates to parent:
      int dy = parent.getTop()-parent.getScrollY();
      vt += dy;
      vb += dy;

      v = parent;
     }
 }

ASP.net page without a code behind

File: logdate.aspx

<%@ Page Language="c#" %>
<%@ Import namespace="System.IO"%>
<%

StreamWriter tsw = File.AppendText(@Server.MapPath("./test.txt"));
tsw.WriteLine("--------------------------------");
tsw.WriteLine(DateTime.Now.ToString());

tsw.Close();
%>

Done

How to assert greater than using JUnit Assert?

Alternatively if adding extra library such as hamcrest is not desirable, the logic can be implemented as utility method using junit dependency only:

public static void assertGreaterThan(int greater, int lesser) {
    assertGreaterThan(greater, lesser, null);
}

public static void assertGreaterThan(int greater, int lesser, String message) {
    if (greater <= lesser) {
        fail((StringUtils.isNotBlank(message) ? message + " ==> " : "") +
                "Expected: a value greater than <" + lesser + ">\n" +
                "But <" + greater + "> was " + (greater == lesser ? "equal to" : "less than") + " <" + lesser + ">");
    }
}

Python read next()

You don't need to read the next line, you are iterating through the lines. lines is a list (an array), and for line in lines is iterating over it. Every time you are finished with one you move onto the next line. If you want to skip to the next line just continue out of the current loop.

filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')

lines = f.readlines() # get all lines as a list (array)

# Iterate over each line, printing each line and then move to the next
for line in lines:
    print line

f.close()

How can the error 'Client found response content type of 'text/html'.. be interpreted

That means that your consumer is expecting XML from the webservice but the webservice, as your error shows, returns HTML because it's failing due to a timeout.

So you need to talk to the remote webservice provider to let them know it's failing and take corrective action. Unless you are the provider of the webservice in which case you should catch the exceptions and return XML telling the consumer which error occurred (the 'remote provider' should probably do that as well).

Remove Safari/Chrome textinput/textarea glow

some times it's happens buttons also then use below to remove the outerline

input:hover
input:active, 
input:focus, 
textarea:active,
textarea:hover,
textarea:focus, 
button:focus,
button:active,
button:hover
{
    outline:0px !important;
}

Laravel Request::all() Should Not Be Called Statically

use the request() helper instead. You don't have to worry about use statements and thus this sort of problem wont happen again.

$input = request()->all();

simple

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

For those who still stumble upon this like I did, it's worth checking to make sure the attempted GRANT does not already exist:

SHOW GRANTS FOR username;

In my case, the error was not actually because there was a permission error, but because the GRANT already existed.

How can I read the contents of an URL with Python?

None of these answers are very good for Python 3 (tested on latest version at the time of this post).

This is how you do it...

import urllib.request

try:
   with urllib.request.urlopen('http://www.python.org/') as f:
      print(f.read().decode('utf-8'))
except urllib.error.URLError as e:
   print(e.reason)

The above is for contents that return 'utf-8'. Remove .decode('utf-8') if you want python to "guess the appropriate encoding."

Documentation: https://docs.python.org/3/library/urllib.request.html#module-urllib.request

Difference between classification and clustering in data mining?

By clustering, you can group data with your desired properties such as the number, the shape, and other properties of extracted clusters. While, in classification, the number and the shape of groups are fixed. Most of the clustering algorithms give the number of clusters as a parameter. However, there are some approaches to find out the appropriate number of clusters.

android asynctask sending callbacks to ui

I felt the below approach is very easy.

I have declared an interface for callback

public interface AsyncResponse {
    void processFinish(Object output);
}

Then created asynchronous Task for responding all type of parallel requests

 public class MyAsyncTask extends AsyncTask<Object, Object, Object> {

    public AsyncResponse delegate = null;//Call back interface

    public MyAsyncTask(AsyncResponse asyncResponse) {
        delegate = asyncResponse;//Assigning call back interfacethrough constructor
    }

    @Override
    protected Object doInBackground(Object... params) {

    //My Background tasks are written here

      return {resutl Object}

    }

    @Override
    protected void onPostExecute(Object result) {
        delegate.processFinish(result);
    }

}

Then Called the asynchronous task when clicking a button in activity Class.

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        Button mbtnPress = (Button) findViewById(R.id.btnPress);

        mbtnPress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {

                    @Override
                    public void processFinish(Object output) {
                        Log.d("Response From Asynchronous task:", (String) output);          
                        mbtnPress.setText((String) output);
                    }
                });
                asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });

            }
        });
    }
}

Thanks

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

When i tried the solution with /XD i found, that the path to exclude should be the source path - not the destination.

e.g. this Works

robocopy c:\test\a c:\test\b /MIR /XD c:\test\a\leavethisdiralone\

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

After a long struggle, I found the solution.

Solution: Add a reference to System.Net.Http.Formatting.dll. This assembly is also available in the C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies folder.

The method ReadAsAsync is an extension method declared in the class HttpContentExtensions, which is in the namespace System.Net.Http in the library System.Net.Http.Formatting.

Reflector came to rescue!

Creating columns in listView and add items

I didn't see anyone answer this correctly. So I'm posting it here. In order to get columns to show up you need to specify the following line.

lvRegAnimals.View = View.Details;

And then add your columns after that.

lvRegAnimals.Columns.Add("Id", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);

Hope this helps anyone else looking for this answer in the future.

Angular ng-if not true

Use like this

<div ng-if="data.IsActive === 1">InActive</div>
<div ng-if="data.IsActive === 0">Active</div>

Python and JSON - TypeError list indices must be integers not str

First of all, you should be using json.loads, not json.dumps. loads converts JSON source text to a Python value, while dumps goes the other way.

After you fix that, based on the JSON snippet at the top of your question, readable_json will be a list, and so readable_json['firstName'] is meaningless. The correct way to get the 'firstName' field of every element of a list is to eliminate the playerstuff = readable_json['firstName'] line and change for i in playerstuff: to for i in readable_json:.

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

Perform curl request in javascript?

curl is a command in linux (and a library in php). Curl typically makes an HTTP request.

What you really want to do is make an HTTP (or XHR) request from javascript.

Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax

Essentially you will want to call $.ajax with a few options for the header, etc.

$.ajax({
        url: 'https://api.wit.ai/message?v=20140826&q=',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
        }, success: function(data){
            alert(data);
            //process the JSON data etc
        }
})

What does T&& (double ampersand) mean in C++11?

The term for T&& when used with type deduction (such as for perfect forwarding) is known colloquially as a forwarding reference. The term "universal reference" was coined by Scott Meyers in this article, but was later changed.

That is because it may be either r-value or l-value.

Examples are:

// template
template<class T> foo(T&& t) { ... }

// auto
auto&& t = ...;

// typedef
typedef ... T;
T&& t = ...;

// decltype
decltype(...)&& t = ...;

More discussion can be found in the answer for: Syntax for universal references

How to exit an if clause

use return in the if condition will returns you out from the function, so that you can use return to break the the if condition.

Splitting dataframe into multiple dataframes

  • First, the method in the OP works, but isn't efficient. It may have seemed to run forever, because the dataset was long.
  • Use .groupby on the 'method' column, and create a dict of DataFrames with unique 'method' values as the keys, with a dict-comprehension.
    • .groupby returns a groupby object, that contains information about the groups, where g is the unique value in 'method' for each group, and d is the DataFrame for that group.
  • The value of each key in df_dict, will be a DataFrame, which can be accessed in the standard way, df_dict['key'].
  • The original question wanted a list of DataFrames, which can be done with a list-comprehension
    • df_list = [d for _, d in df.groupby('method')]
import pandas as pd
import seaborn as sns  # for test dataset

# load data for example
df = sns.load_dataset('planets')

# display(df.head())
            method  number  orbital_period   mass  distance  year
0  Radial Velocity       1         269.300   7.10     77.40  2006
1  Radial Velocity       1         874.774   2.21     56.95  2008
2  Radial Velocity       1         763.000   2.60     19.84  2011
3  Radial Velocity       1         326.030  19.40    110.62  2007
4  Radial Velocity       1         516.220  10.50    119.47  2009


# Using a dict-comprehension, the unique 'method' value will be the key
df_dict = {g: d for g, d in df.groupby('method')}

print(df_dict.keys())
[out]:
dict_keys(['Astrometry', 'Eclipse Timing Variations', 'Imaging', 'Microlensing', 'Orbital Brightness Modulation', 'Pulsar Timing', 'Pulsation Timing Variations', 'Radial Velocity', 'Transit', 'Transit Timing Variations'])

# or a specific name for the key, using enumerate (e.g. df1, df2, etc.)
df_dict = {f'df{i}': d for i, (g, d) in enumerate(df.groupby('method'))}

print(df_dict.keys())
[out]:
dict_keys(['df0', 'df1', 'df2', 'df3', 'df4', 'df5', 'df6', 'df7', 'df8', 'df9'])
  • df_dict['df1].head(3) or df_dict['Astrometry'].head(3)
  • There are only 2 in this group
         method  number  orbital_period  mass  distance  year
113  Astrometry       1          246.36   NaN     20.77  2013
537  Astrometry       1         1016.00   NaN     14.98  2010
  • df_dict['df2].head(3) or df_dict['Eclipse Timing Variations'].head(3)
                       method  number  orbital_period  mass  distance  year
32  Eclipse Timing Variations       1         10220.0  6.05       NaN  2009
37  Eclipse Timing Variations       2          5767.0   NaN    130.72  2008
38  Eclipse Timing Variations       2          3321.0   NaN    130.72  2008
  • df_dict['df3].head(3) or df_dict['Imaging'].head(3)
     method  number  orbital_period  mass  distance  year
29  Imaging       1             NaN   NaN     45.52  2005
30  Imaging       1             NaN   NaN    165.00  2007
31  Imaging       1             NaN   NaN    140.00  2004

Alternatively

  • This is a manual method to create separate DataFrames using pandas: Boolean Indexing
  • This is similar to the accepted answer, but .loc is not required.
  • This is an acceptable method for creating a couple extra DataFrames.
  • The pythonic way to create multiple objects, is by placing them in a container (e.g. dict, list, generator, etc.), as shown above.
df1 = df[df.method == 'Astrometry']
df2 = df[df.method == 'Eclipse Timing Variations']

How can I add comments in MySQL?

Several ways:

# Comment
-- Comment
/* Comment */

Remember to put the space after --.

See the documentation.

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

How to set image for bar button with swift?

Only two Lines of code required for this

Swift 3.0

let closeButtonImage = UIImage(named: "ic_close_white")
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: closeButtonImage, style: .plain, target: self, action:  #selector(ResetPasswordViewController.barButtonDidTap(_:)))

func barButtonDidTap(_ sender: UIBarButtonItem) 
{

}

How do I mock a static method that returns void with PowerMock?

You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources will throw the exception :

// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception

Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.

doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.


By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.

Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.

Hope that helps.

Regards

Trying to get property of non-object - CodeIgniter

To access the elements in the array, use array notation: $product['prodname']

$product->prodname is object notation, which can only be used to access object attributes and methods.

When should we implement Serializable interface?

The answer to this question is, perhaps surprisingly, never, or more realistically, only when you are forced to for interoperability with legacy code. This is the recommendation in Effective Java, 3rd Edition by Joshua Bloch:

There is no reason to use Java serialization in any new system you write

Oracle's chief architect, Mark Reinhold, is on record as saying removing the current Java serialization mechanism is a long-term goal.


Why Java serialization is flawed

Java provides as part of the language a serialization scheme you can opt in to, by using the Serializable interface. This scheme however has several intractable flaws and should be treated as a failed experiment by the Java language designers.

  • It fundamentally pretends that one can talk about the serialized form of an object. But there are infinitely many serialization schemes, resulting in infinitely many serialized forms. By imposing one scheme, without any way of changing the scheme, applications can not use a scheme most appropriate for them.
  • It is implemented as an additional means of constructing objects, which bypasses any precondition checks your constructors or factory methods perform. Unless tricky, error prone, and difficult to test extra deserialization code is written, your code probably has a gaping security weakness.
  • Testing interoperability of different versions of the serialized form is very difficult.
  • Handling of immutable objects is troublesome.

What to do instead

Instead, use a serialization scheme that you can explicitly control. Such as Protocol Buffers, JSON, XML, or your own custom scheme.

Pandas groupby month and year

Why not keep it simple?!

GB=DF.groupby([(DF.index.year),(DF.index.month)]).sum()

giving you,

print(GB)
        abc  xyz
2013 6   80  250
     8   40   -5
2014 1   25   15
     2   60   80

and then you can plot like asked using,

GB.plot('abc','xyz',kind='scatter')

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

Why is there no ForEach extension method on IEnumerable?

One workaround is to write .ToList().ForEach(x => ...).

pros

Easy to understand - reader only needs to know what ships with C#, not any additional extension methods.

Syntactic noise is very mild (only adds a little extranious code).

Doesn't usually cost extra memory, since a native .ForEach() would have to realize the whole collection, anyway.

cons

Order of operations isn't ideal. I'd rather realize one element, then act on it, then repeat. This code realizes all elements first, then acts on them each in sequence.

If realizing the list throws an exception, you never get to act on a single element.

If the enumeration is infinite (like the natural numbers), you're out of luck.

Hide div element when screen size is smaller than a specific size

if you are using bootstrap u can just use the hidden-sm ( lg or md or xs) depending on what u want. u can then go into the css file and specify the percentages u want it to show on. in the sample below it will be hiding on large screens, medium ones and extra small ones but show on small screens by taking half of the screen.

<div class="col-sm-12 hidden-lg hidden-md hidden-xs">what ever you want</div>

Best practice multi language website

I am not going to attempt to refine the answers already given. Instead I will tell you about the way my own OOP PHP framework handles translations.

Internally, my framework use codes like en, fr, es, cn and so on. An array holds the languages supported by the website: array('en','fr','es','cn') The language code is passed via $_GET (lang=fr) and if not passed or not valid, it is set to the first language in the array. So at any time during program execution and from the very beginning, the current language is known.

It is useful to understand the kind of content that needs to be translated in a typical application:

1) error messages from classes (or procedural code) 2) non-error messages from classes (or procedural code) 3) page content (usually store in a database) 4) site-wide strings (like website name) 5) script-specific strings

The first type is simple to understand. Basically, we are talking about messages like "could not connect to the database ...". These messages only need to be loaded when an error occurs. My manager class receives a call from the other classes and using the information passed as parameters simply goes to relevant the class folder and retrieves the error file.

The second type of error message is more like the messages you get when the validation of a form went wrong. ("You cannot leave ... blank" or "please choose a password with more than 5 characters"). The strings need to be loaded before the class runs.I know what is

For the actual page content, I use one table per language, each table prefixed by the code for the language. So en_content is the table with English language content, es_content is for spain, cn_content for China and fr_content is the French stuff.

The fourth kind of string is relevant throughout your website. This is loaded via a configuration file named using the code for the language, that is en_lang.php, es_lang.php and so on. In the global language file you will need to load the translated languages such as array('English','Chinese', 'Spanish','French') in the English global file and array('Anglais','Chinois', 'Espagnol', 'Francais') in the French file. So when you populate a dropdown for language selection, it is in the correct language ;)

Finally you have the script-specific strings. So if you write a cooking application, it might be "Your oven was not hot enough".

In my application cycle, the global language file is loaded first. In there you will find not just global strings (like "Jack's Website") but also settings for some of the classes. Basically anything that is language or culture-dependent. Some of the strings in there include masks for dates (MMDDYYYY or DDMMYYYY), or ISO Language Codes. In the main language file, I include strings for individual classes becaue there are so few of them.

The second and last language file that is read from disk is the script language file. lang_en_home_welcome.php is the language file for the home/welcome script. A script is defined by a mode (home) and an action (welcome). Each script has its own folder with config and lang files.

The script pulls the content from the database naming the content table as explained above.

If something goes wrong, the manager knows where to get the language-dependent error file. That file is only loaded in case of an error.

So the conclusion is obvious. Think about the translation issues before you start developing an application or framework. You also need a development workflow that incorporates translations. With my framework, I develop the whole site in English and then translate all the relevant files.

Just a quick final word on the way the translation strings are implemented. My framework has a single global, the $manager, which runs services available to any other service. So for example the form service gets hold of the html service and uses it to write the html. One of the services on my system is the translator service. $translator->set($service,$code,$string) sets a string for the current language. The language file is a list of such statements. $translator->get($service,$code) retrieves a translation string. The $code can be numeric like 1 or a string like 'no_connection'. There can be no clash between services because each has its own namespace in the translator's data area.

I post this here in the hope it will save somebody the task of reinventing the wheel like I had to do a few long years ago.

How to set a default row for a query that returns no rows?

*SQL solution

Suppose you have a review table which has primary key "id".

SELECT * FROM review WHERE id = 1555
UNION ALL
SELECT * FROM review WHERE NOT EXISTS ( SELECT * FROM review where id = 1555 ) AND id = 1

if table doesn't have review with 1555 id then this query will provide a review of id 1.

Skipping error in for-loop

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

How do I find the location of Python module sources?

datetime is a builtin module, so there is no (Python) source file.

For modules coming from .py (or .pyc) files, you can use mymodule.__file__, e.g.

> import random
> random.__file__
'C:\\Python25\\lib\\random.pyc'

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

I tweaked your code a bit and made it more robust. In terms of progressive enhancement it's probaly better to have all the fade-in-out logic in JavaScript. In the example of myfunksyde any user without JavaScript sees nothing because of the opacity: 0;.

    $(window).on("load",function() {
    function fade() {
        var animation_height = $(window).innerHeight() * 0.25;
        var ratio = Math.round( (1 / animation_height) * 10000 ) / 10000;

        $('.fade').each(function() {

            var objectTop = $(this).offset().top;
            var windowBottom = $(window).scrollTop() + $(window).innerHeight();

            if ( objectTop < windowBottom ) {
                if ( objectTop < windowBottom - animation_height ) {
                    $(this).html( 'fully visible' );
                    $(this).css( {
                        transition: 'opacity 0.1s linear',
                        opacity: 1
                    } );

                } else {
                    $(this).html( 'fading in/out' );
                    $(this).css( {
                        transition: 'opacity 0.25s linear',
                        opacity: (windowBottom - objectTop) * ratio
                    } );
                }
            } else {
                $(this).html( 'not visible' );
                $(this).css( 'opacity', 0 );
            }
        });
    }
    $('.fade').css( 'opacity', 0 );
    fade();
    $(window).scroll(function() {fade();});
});

See it here: http://jsfiddle.net/78xjLnu1/16/

Cheers, Martin

Insert multiple rows with one query MySQL

Here are a few ways to do it

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip' 
from SOMETABLEWITHTONSOFROWS LIMIT 3;

or

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'

or

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
values ('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')

Read .mat files in Python

Neither scipy.io.savemat, nor scipy.io.loadmat work for MATLAB arrays version 7.3. But the good part is that MATLAB version 7.3 files are hdf5 datasets. So they can be read using a number of tools, including NumPy.

For Python, you will need the h5py extension, which requires HDF5 on your system.

import numpy as np
import h5py
f = h5py.File('somefile.mat','r')
data = f.get('data/variable1')
data = np.array(data) # For converting to a NumPy array

Batch script loop

Here is a template script I will use.

@echo off
goto Loop

:Loop
<EXTRA SCRIPTING HERE!!!!>
goto Loop

exit

What this does is when it starts it turns off echo then after that it runs the "Loop" but in that place it keeps going to "Loop" (I hope this helps.)

Is there a way to iterate over a range of integers?

iter is a very small package that just provides a syntantically different way to iterate over integers.

for i := range iter.N(4) {
    fmt.Println(i)
}

Rob Pike (an author of Go) has criticized it:

It seems that almost every time someone comes up with a way to avoid doing something like a for loop the idiomatic way, because it feels too long or cumbersome, the result is almost always more keystrokes than the thing that is supposedly shorter. [...] That's leaving aside all the crazy overhead these "improvements" bring.

how to use jQuery ajax calls with node.js

I suppose your html page is hosted on a different port. Same origin policy requires in most browsers that the loaded file be on the same port than the loading file.

set default schema for a sql query

What i sometimes do when i need a lot of tablenames ill just get them plus their schema from the INFORMATION_SCHEMA system table: value


select  TABLE_SCHEMA + '.' + TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME in
(*select your table names*)

How to get all enum values in Java?

Object[] possibleValues = enumValue.getDeclaringClass().getEnumConstants();

How to convert datatype:object to float64 in python?

You can convert most of the columns by just calling convert_objects:

In [36]:

df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[36]:
Date         object
WD            int64
Manpower    float64
2nd          object
CTR          object
2ndU        float64
T1            int64
T2          int64
T3           int64
T4        float64
dtype: object

For column '2nd' and 'CTR' we can call the vectorised str methods to replace the thousands separator and remove the '%' sign and then astype to convert:

In [39]:

df['2nd'] = df['2nd'].str.replace(',','').astype(int)
df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
df.dtypes
Out[39]:
Date         object
WD            int64
Manpower    float64
2nd           int32
CTR         float64
2ndU        float64
T1            int64
T2            int64
T3            int64
T4           object
dtype: object
In [40]:

df.head()
Out[40]:
        Date  WD  Manpower   2nd   CTR  2ndU   T1    T2   T3     T4
0   2013/4/6   6       NaN  2645  5.27  0.29  407   533  454    368
1   2013/4/7   7       NaN  2118  5.89  0.31  257   659  583    369
2  2013/4/13   6       NaN  2470  5.38  0.29  354   531  473    383
3  2013/4/14   7       NaN  2033  6.77  0.37  396   748  681    458
4  2013/4/20   6       NaN  2690  5.38  0.29  361   528  541    381

Or you can do the string handling operations above without the call to astype and then call convert_objects to convert everything in one go.

UPDATE

Since version 0.17.0 convert_objects is deprecated and there isn't a top-level function to do this so you need to do:

df.apply(lambda col:pd.to_numeric(col, errors='coerce'))

See the docs and this related question: pandas: to_numeric for multiple columns

How to remove files that are listed in the .gitignore but still on the repository?

In linux you can use this commande :

for exemple i want to delete "*.py~" so my command should be ==>

find . -name "*.py~" -exec rm -f {} \;

Finding the length of a Character Array in C

using sizeof()

char h[] = "hello";
printf("%d\n",sizeof(h)-1); //Output = 5

using string.h

#include <string.h>

char h[] = "hello";
printf("%d\n",strlen(h)); //Output = 5

using function (strlen implementation)

int strsize(const char* str);
int main(){
    char h[] = "hello";
    printf("%d\n",strsize(h)); //Output = 5
    return 0;
}
int strsize(const char* str){
    return (*str) ? strsize(++str) + 1 : 0;
}

What is the PostgreSQL equivalent for ISNULL()

Create the following function

CREATE OR REPLACE FUNCTION isnull(text, text) RETURNS text AS 'SELECT (CASE (SELECT $1 "
    "is null) WHEN true THEN $2 ELSE $1 END) AS RESULT' LANGUAGE 'sql'

And it'll work.

You may to create different versions with different parameter types.

Javascript/Jquery to change class onclick?

I think you mean that you want want an onclick event that changes a class.

Here is the answer if someone visits this question and is literally looking to assign a class and it's onclick with JQUERY.

It is somewhat counter-intuitive, but if you want to change the onclick event by changing the class you need to declare the onclick event to apply to elements of a parent object.

HTML

<div id="containerid">
     Text <a class="myClass" href="#" />info</a>
     Other Text <div class="myClass">other info</div>
</div>
<div id="showhide" class="meta-info">hide info</div>

Document Ready

$(function() {
     $("#containerid").on("click",".myclass",function(e){ /*do stuff*/ }
     $("#containerid").on("click",".mynewclass",function(e){ /*do different stuff*/ }
     $("#showhide").click(function() {changeclass()}
});

Slight Tweak to Your Javascript

<script>
function changeclass() {
        $(".myClass,.myNewClass").toggleClass('myNewClass').toggleClass('myClass');
} 
</script>

If you can't reliably identify a parent object you can do something like this.

$(function() {
     $(document).on("click",".myclass",function(e){}
     $(document).on("click",".mynewclass",function(e){}
});

If you just want to hide the items you might find it simpler to use .hide() and .show().

How can I put CSS and HTML code in the same file?

Two options: 1, add css inline like style="background:black" Or 2. In the head include the css as a style tag block.

Installing a dependency with Bower from URL and specify version

Just specifying the uri endpoint worked for me, bower 1.3.9

  "dependencies": {
    "jquery.cookie": "latest",
    "everestjs": "http://www.everestjs.net/static/st.v2.js"
  }

Running bower install, I received following output:

bower new           version for http://www.everestjs.net/static/st.v2.js#*
bower resolve       http://www.everestjs.net/static/st.v2.js#*
bower download      http://www.everestjs.net/static/st.v2.js

You could also try updating bower

  • npm update -g bower

According to documentation: the following types of urls are supported:

http://example.com/script.js
http://example.com/style.css
http://example.com/package.zip (contents will be extracted)
http://example.com/package.tar (contents will be extracted)

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

The excellent JavaScript library KeyboardJS handles all types of key presses including the SHIFT key. It even allows specifying key combinations such as first pressing CTRL+x and then a.

KeyboardJS.on('shift', function() { ...handleDown... }, function() { ...handleUp... });

If you want a simple version, head to the answer by @tonycoupland):

var shiftHeld = false;
$('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

Lots of people are running into it, so I wanted to post here .

Found a crazy easy workaround thanks to this guy: Expertdebugger.

Simply downgrade your language version from C# 6 to C# 5, like so:

<system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701">
        <providerOption name="CompilerVersion" value="v4.0"/>
      </compiler>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+">
          <providerOption name="CompilerVersion" value="v4.0"/>
      </compiler>
    </compilers>
</system.codedom>

Change the langversion:6 towards the bottom from 6 to 5 - langversion:5

Fixed it for me. Thank him.

How to set default value to all keys of a dict object in python?

Is this what you want:

>>> d={'a':1,'b':2,'c':3}
>>> default_val=99
>>> for k in d:
...     d[k]=default_val
...     
>>> d
{'a': 99, 'b': 99, 'c': 99}
>>> 

>>> d={'a':1,'b':2,'c':3}
>>> from collections import defaultdict
>>> d=defaultdict(lambda:99,d)
>>> d
defaultdict(<function <lambda> at 0x03D21630>, {'a': 1, 'c': 3, 'b': 2})
>>> d[3]
99

ImportError: No module named 'bottle' - PyCharm

In the case where you are able to import the module when using the CLI interpreter but not in PyCharm, make sure your project interpreter in PyCharm is set to an actual interpreter (eg. /usr/bin/python2.7) and not venv (~/PycharmProject/venv/...)

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had similar problem. I r?n npm cache clear, closed android SDK manager(which was open before) and re-ran npm install -g cordova and that was enough to solve the problem.

Unity Scripts edited in Visual studio don't provide autocomplete

Try this,

  1. In Unity Editor Go to Menu, Click on Edit -> Preferences -> External Tools -> External Script Editor. Set it to Visual Studio (your installed version of VS).

  2. Now in Menubar go to Edit -> Project Settings -> Player Settings -> Other Settings -> Under Configuration -> Check API Compatibility Level -> Change it to your installed .Net version. In my case I set it to .Net 4.x

Now if Visual Studio is running already go to Visual Studio, it will ask to reload project. Reload the project. Check if it works, if not close Visual Studio. Now Open cs file from Unity Editor, and now it should work.

C# How do I click a button by hitting Enter whilst textbox has focus?

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.Enter)
     {
         button.PerformClick();
         // these last two lines will stop the beep sound
         e.SuppressKeyPress = true;
         e.Handled = true;
     }
}

Bind this KeyDown event to the textbox, then when ever you press a key, this event will be fired. Inside the event we check whether user has pressed "Enter key", if so, you can perform you action

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.

How to force ViewPager to re-instantiate its items

I have found a solution. It is just a workaround to my problem but currently the only solution.

ViewPager PagerAdapter not updating the View

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

Does anyone know whether this is a bug or not?

How to take a first character from the string

"ABCDEFG".First returns "A"

Dim s as string

s = "Rajan"
s.First
'R

s = "Sajan"
s.First
'S

How long to brute force a salted SHA-512 hash? (salt provided)

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack), you just need to find an output of the hash function that is equal to the hash of a valid password (thus "collision"). Finding a collision using a birthday attack takes O(2^(n/2)) time, where n is the output length of the hash function in bits.

SHA-2 has an output size of 512 bits, so finding a collision would take O(2^256) time. Given there are no clever attacks on the algorithm itself (currently none are known for the SHA-2 hash family) this is what it takes to break the algorithm.

To get a feeling for what 2^256 actually means: currently it is believed that the number of atoms in the (entire!!!) universe is roughly 10^80 which is roughly 2^266. Assuming 32 byte input (which is reasonable for your case - 20 bytes salt + 12 bytes password) my machine takes ~0,22s (~2^-2s) for 65536 (=2^16) computations. So 2^256 computations would be done in 2^240 * 2^16 computations which would take

2^240 * 2^-2 = 2^238 ~ 10^72s ~ 3,17 * 10^64 years

Even calling this millions of years is ridiculous. And it doesn't get much better with the fastest hardware on the planet computing thousands of hashes in parallel. No human technology will be able to crunch this number into something acceptable.

So forget brute-forcing SHA-256 here. Your next question was about dictionary words. To retrieve such weak passwords rainbow tables were used traditionally. A rainbow table is generally just a table of precomputed hash values, the idea is if you were able to precompute and store every possible hash along with its input, then it would take you O(1) to look up a given hash and retrieve a valid preimage for it. Of course this is not possible in practice since there's no storage device that could store such enormous amounts of data. This dilemma is known as memory-time tradeoff. As you are only able to store so many values typical rainbow tables include some form of hash chaining with intermediary reduction functions (this is explained in detail in the Wikipedia article) to save on space by giving up a bit of savings in time.

Salts were a countermeasure to make such rainbow tables infeasible. To discourage attackers from precomputing a table for a specific salt it is recommended to apply per-user salt values. However, since users do not use secure, completely random passwords, it is still surprising how successful you can get if the salt is known and you just iterate over a large dictionary of common passwords in a simple trial and error scheme. The relationship between natural language and randomness is expressed as entropy. Typical password choices are generally of low entropy, whereas completely random values would contain a maximum of entropy.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords. If you google for them, you will end up finding torrent links for such password databases, often in the gigabyte size category. Being successful with such a tool is usually in the range of minutes to days if the attacker is not restricted in any way.

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5 and you should enforce a waiting period for a given user before they may retry entering their password. A good scheme is to start with 0.5s and then doubling that time for each failed attempt. In most cases users don't notice this and don't fail much more often than three times on average. But it will significantly slow down any malicious outsider trying to attack your application.

PHP decoding and encoding json with unicode characters

try setting the utf-8 encoding in your page:

header('content-type:text/html;charset=utf-8');

this works for me:

$arr = array('tag' => 'Odómetro');
$encoded = json_encode($arr);
$decoded = json_decode($encoded);
echo $decoded->{'tag'};

How can I get a user's media from Instagram without authenticating as a user?

_x000D_
_x000D_
var name = "smena8m";_x000D_
$.get("https://images"+~~(Math.random()*3333)+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https://www.instagram.com/" + name + "/", function(html) {_x000D_
if (html) {_x000D_
    var regex = /_sharedData = ({.*);<\/script>/m,_x000D_
        json = JSON.parse(regex.exec(html)[1]),_x000D_
        edges = json.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges;_x000D_
_x000D_
      $.each(edges, function(n, edge) {_x000D_
          var node = edge.node;_x000D_
          $('body').append(_x000D_
              $('<a/>', {_x000D_
              href: 'https://instagr.am/p/'+node.shortcode,_x000D_
              target: '_blank'_x000D_
          }).css({_x000D_
              backgroundImage: 'url(' + node.thumbnail_src + ')'_x000D_
          }));_x000D_
      });_x000D_
    }_x000D_
});
_x000D_
html, body {_x000D_
  font-size: 0;_x000D_
  line-height: 0;_x000D_
}_x000D_
_x000D_
a {_x000D_
  display: inline-block;_x000D_
  width: 25%;_x000D_
  height: 0;_x000D_
  padding-bottom: 25%;_x000D_
  background: #eee 50% 50% no-repeat;_x000D_
  background-size: cover;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

You can download any Instagram user photo feed in JSON format using ?__a=1 next to landing page address like this. No need to get user id or register an app, no tokens, no oAuth.

min_id and max_id variables can be used for pagination, here is example

YQL may not work here inside snipped iframe, so you can always check it manually in YQL Console

APRIL 2018 UPDATE: After latest instagram updates you can't do this on client side (javascript) because custom headers for signed request can't be set with javascript due to CORS Access-Control-Allow-Headers restrictions. It still possible to do this via php or any other server side method with proper signature based on rhx_gis, csrf_token and request parameters. You can read more about it here.

JANUARY 2019 UPDATE: YQL retired, so, check my latest update with Google Image Proxy as CORS proxy for Instagram page! Then only negative moment - pagination not available with this method.

PHP solution:

    $html = file_get_contents('https://instagram.com/apple/');
    preg_match('/_sharedData = ({.*);<\/script>/', $html, $matches);
    $profile_data = json_decode($matches[1])->entry_data->ProfilePage[0]->graphql->user;

How to trim whitespace from a Bash variable?

I needed to trim whitespace from a script when the IFS variable was set to something else. Relying on Perl did the trick:

# trim() { echo $1; } # This doesn't seem to work, as it's affected by IFS

trim() { echo "$1" | perl -p -e 's/^\s+|\s+$//g'; }

strings="after --> , <-- before,  <-- both -->  "

OLD_IFS=$IFS
IFS=","
for str in ${strings}; do
  str=$(trim "${str}")
  echo "str= '${str}'"
done
IFS=$OLD_IFS

Delete all files of specific type (extension) recursively down a directory using a batch file

I wrote a batch script a while ago that allows you to pick a file extension to delete. The script will look in the folder it is in and all subfolders for any file with that extension and delete it.

@ECHO OFF
CLS

SET found=0
ECHO Enter the file extension you want to delete...
SET /p ext="> "

IF EXIST *.%ext% (           rem Check if there are any in the current folder :)
  DEL *.%ext%
  SET found=1
)
FOR /D /R %%G IN ("*") DO (  rem Iterate through all subfolders
  IF EXIST %%G CD %%G
  IF EXIST *.%ext% (
    DEL *.%ext%
    SET found=1
  )
)

IF %found%==1 (
  ECHO.
  ECHO Deleted all .%ext% files.
  ECHO.
) ELSE (
  ECHO.
  ECHO There were no .%ext% files.
  ECHO Nothing has been deleted.
  ECHO.
)

PAUSE
EXIT

Hope this comes in useful to anyone who wants it :)

PowerShell The term is not recognized as cmdlet function script file or operable program

For the benefit of searchers, there is another way you can produce this error message - by missing the $ off the script block name when calling it.

e.g. I had a script block like so:

$qa = {
    param($question, $answer)
    Write-Host "Question = $question, Answer = $answer"
}

I tried calling it using:

&qa -question "Do you like powershell?" -answer "Yes!"

But that errored. The correct way was:

&$qa -question "Do you like powershell?" -answer "Yes!"

Difference between string and StringBuilder in C#

A StringBuilder will help you when you need to build strings in multiple steps.

Instead of doing this:

String x = "";
x += "first ";
x += "second ";
x += "third ";

you do

StringBuilder sb = new StringBuilder("");
sb.Append("first ");
sb.Append("second ");
sb.Append("third");
String x = sb.ToString();

The final effect is the same, but the StringBuilder will use less memory and will run faster. Instead of creating a new string which is the concatenation of the two, it will create the chunks separately, and only at the end it will unite them.

Get DOS path instead of Windows path

similar to this answer but uses a sub-routine

@echo off
CLS

:: my code goes here
set "my_variable=C:\Program Files (x86)\Microsoft Office"

echo %my_variable%

call :_sub_Short_Path "%my_variable%"
set "my_variable=%_s_Short_Path%"

echo %my_variable%

:: rest of my code goes here
goto EOF

:_sub_Short_Path
set _s_Short_Path=%~s1
EXIT /b

:EOF

git remove merge commit from history

There are two ways to tackle this based on what you want:

Solution 1: Remove purple commits, preserving history (incase you want to roll back)

git revert -m 1 <SHA of merge>

-m 1 specifies which parent line to choose

Purple commits will still be there in history but since you have reverted, you will not see code from those commits.


Solution 2: Completely remove purple commits (disruptive change if repo is shared)

git rebase -i <SHA before branching out>

and delete (remove lines) corresponding to purple commits.

This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase.

Using OpenSSL what does "unable to write 'random state'" mean?

In practice, the most common reason for this happening seems to be that the .rnd file in your home directory is owned by root rather than your account. The quick fix:

sudo rm ~/.rnd

For more information, here's the entry from the OpenSSL FAQ:

Sometimes the openssl command line utility does not abort with a "PRNG not seeded" error message, but complains that it is "unable to write 'random state'". This message refers to the default seeding file (see previous answer). A possible reason is that no default filename is known because neither RANDFILE nor HOME is set. (Versions up to 0.9.6 used file ".rnd" in the current directory in this case, but this has changed with 0.9.6a.)

So I would check RANDFILE, HOME, and permissions to write to those places in the filesystem.

If everything seems to be in order, you could try running with strace and see what exactly is going on.

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

Update for 2016

A lot of great editors have come out since my original answer. I currently use the following text editors: Sublime Text 3 (Mac/Windows), Visual Studio Code (Mac/Windows) and Atom (Mac/Windows). I also use the following IDEs: Visual Studio 2015 (Windows/Paid & Free Versions) and Jetrbrains WebStorm (Windows/Paid, tried the demo and liked it).

My preference is using Sublime Text 3.

Original Answer

Microsoft Web Matrix and Dreamweaver are great.

Visual Studio and Expression Web are also great but may be overkill for you.

For just plain text editors, Sublime Text 2 is really cool

Change the background color of a pop-up dialog

You can create a custom alertDialog and use a xml layout. in the layout, you can set the background color and textcolor.

Something like this:

Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root));
dialog.setContentView(view);

Creating a singleton in Python

I also prefer decorator syntax to deriving from metaclass. My two cents:

from typing import Callable, Dict, Set


def singleton(cls_: Callable) -> type:
    """ Implements a simple singleton decorator
    """
    class Singleton(cls_):  # type: ignore
        __instances: Dict[type, object] = {}
        __initialized: Set[type] = set()

        def __new__(cls, *args, **kwargs):
            if Singleton.__instances.get(cls) is None:
                Singleton.__instances[cls] = super().__new__(cls, *args, **kwargs)
            return Singleton.__instances[cls]

        def __init__(self, *args, **kwargs):
            if self.__class__ not in Singleton.__initialized:
                Singleton.__initialized.add(self.__class__)
                super().__init__(*args, **kwargs)

    return Singleton


@singleton
class MyClass(...):
    ...

This has some benefits above other decorators provided:

  • isinstance(MyClass(), MyClass) will still work (returning a function from the clausure instead of a class will make isinstance to fail)
  • property, classmethod and staticmethod will still work as expected
  • __init__() constructor is executed only once
  • You can inherit from your decorated class (useless?) using @singleton again

Cons:

  • print(MyClass().__class__.__name__) will return Singleton instead od MyClass. If you still need this, I recommend using a metaclass as suggested above.

If you need a different instance based on constructor parameters this solution needs to be improved (solution provided by siddhesh-suhas-sathe provides this).

Finally, as other suggested, consider using a module in python. Modules are objects. You can even pass them in variables and inject them in other classes.

Change the color of a checked menu item in a navigation drawer

One need to set NavigateItem checked true whenever item in NavigateView is clicked

//listen for navigation events
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
// select the correct nav menu item
navigationView.getMenu().findItem(mNavItemId).setChecked(true);

Add NavigationItemSelectedListener on NavigationView

  @Override
  public boolean onNavigationItemSelected(final MenuItem menuItem) {
    // update highlighted item in the navigation menu
    menuItem.setChecked(true);
    mNavItemId = menuItem.getItemId();

    // allow some time after closing the drawer before performing real navigation
    // so the user can see what is happening
    mDrawerLayout.closeDrawer(GravityCompat.START);
    mDrawerActionHandler.postDelayed(new Runnable() {
      @Override
      public void run() {
        navigate(menuItem.getItemId());
      }
    }, DRAWER_CLOSE_DELAY_MS);
    return true;
  }

How can I check the syntax of Python script without executing it?

Thanks to the above answers @Rosh Oxymoron. I improved the script to scan all files in a dir that are python files. So for us lazy folks just give it the directory and it will scan all the files in that directory that are python.

import sys
import glob, os

os.chdir(sys.argv[1])
for file in glob.glob("*.py"):
    source = open(file, 'r').read() + '\n'
    compile(source, file, 'exec')

Save this as checker.py and run python checker.py ~/YOURDirectoryTOCHECK

Ignore <br> with CSS?

You can use span elements instead of the br if you want the white space method to work, as it depends on pseudo-elements which are "not defined" for replaced elements.

HTML

<p>
   To break lines<span class="line-break">in a paragraph,</span><span>don't use</span><span>the 'br' element.</span>
</p>

CSS

span {white-space: pre;}

span:after {content: ' ';}

span.line-break {display: block;}

span.line-break:after {content: none;}

DEMO

The line break is simply achieved by setting the appropriate span element to display:block.

By using IDs and/ or Classes in your HTML markup you can easily target every single or combination of span elements by CSS or use CSS selectors like nth-child().

So you can e.g. define different break points by using media queries for a responsive layout.

And you can also simply add/ remove/ toggle classes by Javascript (jQuery).

The "advantage" of this method is its robustness - works in every browser that supports pseudo-elements (see: Can I use - CSS Generated content).

As an alternative it is also possible to add a line break via pseudo-elements:

span.break:before {  
    content: "\A";
    white-space: pre;
}

DEMO

Expression must have class type

It's a pointer, so instead try:

a->f();

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

The a->b notation is usually just a shorthand for (*a).b.

A note on smart pointers

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();

Reading InputStream as UTF-8

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

Responsive Bootstrap Jumbotron Background Image

TLDR: Use background-size: 100% 100%;.

background-size: cover; may cut off some parts of the image producing poor results.

Using background-size: 100% 100%; you force the image to take up 100% of the parent element for both height and width.

See W3Schools for more information on this.

Here is a working, responsive jumbotron background image:

<div class="jumbotron"  style="background-image: url(http://yourImageUrl.jpg); background-size: 100% 100%;">
    <h1>Welcome</h1>
    <p class="lead">Your message here</p>
    <p><a href="http://www.YourLinkHere.com" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

How to set an HTTP proxy in Python 2.7?

cd C:\Python34\Scripts

set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#

set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#

pip.exe install PackageName

Define the selected option with the old input in Laravel / Blade

Instead of using Input class you can also use old() helper to make this even shorter.

<option {{ old('name') == $key ? "selected" : "" }} value="{{ $value }}">

foreach for JSON array , syntax

You can use the .forEach() method of JavaScript for looping through JSON.

_x000D_
_x000D_
var datesBooking = [_x000D_
    {"date": "04\/24\/2018"},_x000D_
      {"date": "04\/25\/2018"}_x000D_
    ];_x000D_
    _x000D_
    datesBooking.forEach(function(data, index) {_x000D_
      console.log(data);_x000D_
    });
_x000D_
_x000D_
_x000D_

Xcode Debugger: view value of variable

You can print values onto console window at run-time. Below are steps :

  1. Place a break-point for which you want to get values
  2. Now perform step-by-step debug.
  3. Place a cursor on variable/delegate whose value is to be checked at run-time.
  4. Now this will show description of variable/delegate
  5. Clicking on "i" will show detailed description
  6. This will also print details onto console window.

Screenshot for printing details on console window

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

I was looking to do the same thing, and I have a work around that seems to be less complicated using the Frequency and Index functions. I use this part of the function from averaging over multiple sheets while excluding the all the 0's.

=(FREQUENCY(Start:End!B1,-0.000001)+INDEX(FREQUENCY(Start:End!B1,0),2))

How do I add a newline to a TextView in Android?

My 2 cents, using Android TV.

Add \n in XML strings, while reading:

public void setSubtitle(String subtitle) {
    this.subtitle = subtitle.replace("\\n", System.getProperty("line.separator"));
}

Count work days between two dates

(I'm a few points shy of commenting privileges)

If you decide to forgo the +1 day in CMS's elegant solution, note that if your start date and end date are in the same weekend, you get a negative answer. Ie., 2008/10/26 to 2008/10/26 returns -1.

my rather simplistic solution:

select @Result = (..CMS's answer..)
if  (@Result < 0)
        select @Result = 0
    RETURN @Result

.. which also sets all erroneous posts with start date after end date to zero. Something you may or may not be looking for.

How to create a .NET DateTime from ISO 8601 format

It seems important to exactly match the format of the ISO string for TryParseExact to work. I guess Exact is Exact and this answer is obvious to most but anyway...

In my case, Reb.Cabin's answer doesn't work as I have a slightly different input as per my "value" below.

Value: 2012-08-10T14:00:00.000Z

There are some extra 000's in there for milliseconds and there may be more.

However if I add some .fff to the format as shown below, all is fine.

Format String: @"yyyy-MM-dd\THH:mm:ss.fff\Z"

In VS2010 Immediate Window:

DateTime.TryParseExact(value,@"yyyy-MM-dd\THH:mm:ss.fff\Z", CultureInfo.InvariantCulture,DateTimeStyles.AssumeUniversal, out d);

true

You may have to use DateTimeStyles.AssumeLocal as well depending upon what zone your time is for...

How does Java resolve a relative path in new File()?

Only slightly related to the question, but try to wrap your head around this one. So un-intuitive:

import java.nio.file.*;
class Main {
  public static void main(String[] args) {
    Path p1 = Paths.get("/personal/./photos/./readme.txt");
    Path p2 = Paths.get("/personal/index.html");
    Path p3 = p1.relativize(p2);
    System.out.println(p3); //prints  ../../../../index.html  !!
  }
}

SQL: Return "true" if list of records exists?

This may be too simple, but I always use:

SELECT COUNT(*)>0 FROM `table` WHERE condition;

Can't get Python to import from a different folder

You have to create __init__.py on the Models subfolder. The file may be empty. It defines a package.

Then you can do:

from Models.user import User

Read all about it in python tutorial, here.

There is also a good article about file organization of python projects here.

SQL Server: Get table primary key using sql query

Found another one:

SELECT 
     KU.table_name as TABLENAME
    ,column_name as PRIMARYKEYCOLUMN
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC 

INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
    ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' 
    AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME 
    AND KU.table_name='YourTableName'

ORDER BY 
     KU.TABLE_NAME
    ,KU.ORDINAL_POSITION
; 

I have tested this on SQL Server 2003/2005

Hide keyboard in react-native

Updated usage of ScrollView for React Native 0.39

<ScrollView scrollEnabled={false} contentContainerStyle={{flex: 1}} />

Although, there is still a problem with two TextInput boxes. eg. A username and password form would now dismiss the keyboard when switching between inputs. Would love to get some suggestions to keep keyboard alive when switching between TextInputs while using a ScrollView.

Moving items around in an ArrayList

Kotlin solution to move an Element from "fromPos" to "toPos" and shift all other items accordingly (useful for moving an item in a staggered layout recyclerView in an Android application)

            if(fromPos < toPos){                    
                val movingElement = myList[fromPos]
                //shifts all elements between fromPos and toPos 1 down
                for(i in fromPos+1..toPos){
                    myList[i-1] = myList[i]
                }
                //re-add element that was saved in the beginning
                myList[toPos] = movingElement
            }

            if(fromPos > toPos){
                val movingElement = myList[fromPos]
                //shifts elements between toPos and fromPos 1 up
                for(i in fromPos downTo toPos+1){
                    myList[i] = myList[i-1]
                }                    
                //re-add element that was saved in the beginning
                myList[toPos] = movingElement
            }

How to vertically align an image inside a div

For a more modern solution, and if there is no need to support legacy browsers, you can do this:

_x000D_
_x000D_
.frame {_x000D_
    display: flex;_x000D_
    /**_x000D_
    Uncomment 'justify-content' below to center horizontally._x000D_
    ? Read below for a better way to center vertically and horizontally._x000D_
    **/_x000D_
_x000D_
    /* justify-content: center; */_x000D_
    align-items: center;_x000D_
}_x000D_
_x000D_
img {_x000D_
    height: auto;_x000D_
_x000D_
    /**_x000D_
    ? To center this image both vertically and horizontally,_x000D_
    in the .frame rule above comment the 'justify-content'_x000D_
    and 'align-items' declarations,_x000D_
    then  uncomment 'margin: auto;' below._x000D_
    **/_x000D_
_x000D_
    /* margin: auto; */_x000D_
}_x000D_
_x000D_
/* Styling stuff not needed for demo */_x000D_
.frame {_x000D_
    max-width: 900px;_x000D_
    height: 200px;_x000D_
    margin: auto;_x000D_
    background: #222;_x000D_
}_x000D_
p {_x000D_
    max-width: 900px;_x000D_
    margin: 20px auto 0;_x000D_
}_x000D_
img {_x000D_
    width: 150px;_x000D_
}
_x000D_
<div class="frame">_x000D_
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9988/hand-pointing.png">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's a Pen: http://codepen.io/ricardozea/pen/aa0ee8e6021087b6e2460664a0fa3f3e

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

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

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

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

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

axes[0, 1].clear()

Compile error: "g++: error trying to exec 'cc1plus': execvp: No such file or directory"

You may have this issue as well if you have environment variable GCC_ROOT pointing to a wrong location. Probably simplest fix could be (on *nix like system):

unset GCC_ROOT

in more complicated cases you may need to repoint it to proper location

How to wait for async method to complete?

Here is a workaround using a flag:

//outside your event or method, but inside your class
private bool IsExecuted = false;

private async Task MethodA()
{

//Do Stuff Here

IsExecuted = true;
}

.
.
.

//Inside your event or method

{
await MethodA();

while (!isExecuted) Thread.Sleep(200); // <-------

await MethodB();
}

Benefits of EBS vs. instance-store (and vice-versa)

For someone new to all this and if accidentally landed here

As of now all AMI's in quickstart section are EBS backed

enter image description here

Also there's a good explanation at official doc for difference between EBS and Instance store

& this image pretty much sums it up enter image description here

Virtual Memory Usage from Java under Linux, too much memory used

The amount of memory allocated for the Java process is pretty much on-par with what I would expect. I've had similar problems running Java on embedded/memory limited systems. Running any application with arbitrary VM limits or on systems that don't have adequate amounts of swap tend to break. It seems to be the nature of many modern apps that aren't design for use on resource-limited systems.

You have a few more options you can try and limit your JVM's memory footprint. This might reduce the virtual memory footprint:

-XX:ReservedCodeCacheSize=32m Reserved code cache size (in bytes) - maximum code cache size. [Solaris 64-bit, amd64, and -server x86: 48m; in 1.5.0_06 and earlier, Solaris 64-bit and and64: 1024m.]

-XX:MaxPermSize=64m Size of the Permanent Generation. [5.0 and newer: 64 bit VMs are scaled 30% larger; 1.4 amd64: 96m; 1.3.1 -client: 32m.]

Also, you also should set your -Xmx (max heap size) to a value as close as possible to the actual peak memory usage of your application. I believe the default behavior of the JVM is still to double the heap size each time it expands it up to the max. If you start with 32M heap and your app peaked to 65M, then the heap would end up growing 32M -> 64M -> 128M.

You might also try this to make the VM less aggressive about growing the heap:

-XX:MinHeapFreeRatio=40 Minimum percentage of heap free after GC to avoid expansion.

Also, from what I recall from experimenting with this a few years ago, the number of native libraries loaded had a huge impact on the minimum footprint. Loading java.net.Socket added more than 15M if I recall correctly (and I probably don't).

Excel VBA function to print an array to the workbook

As others have suggested, you can directly write a 2-dimensional array into a Range on sheet, however if your array is single-dimensional then you have two options:

  1. Convert your 1D array into a 2D array first, then print it on sheet (as a Range).
  2. Convert your 1D array into a string and print it in a single cell (as a String).

Here is an example depicting both options:

Sub PrintArrayIn1Cell(myArr As Variant, cell As Range)
    cell = Join(myArr, ",")
End Sub
Sub PrintArrayAsRange(myArr As Variant, cell As Range)
    cell.Resize(UBound(myArr, 1), UBound(myArr, 2)) = myArr
End Sub
Sub TestPrintArrayIntoSheet()  '2dArrayToSheet
    Dim arr As Variant
    arr = Split("a  b  c", "  ")

    'Printing in ONE-CELL: To print all array-elements as a single string separated by comma (a,b,c):
    PrintArrayIn1Cell arr, [A1]

    'Printing in SEPARATE-CELLS: To print array-elements in separate cells:
    Dim arr2D As Variant
    arr2D = Application.WorksheetFunction.Transpose(arr) 'convert a 1D array into 2D array
    PrintArrayAsRange arr2D, Range("B1:B3")
End Sub

Note: Transpose will render column-by-column output, to get row-by-row output transpose it again - hope that makes sense.

HTH

SQL Server Management Studio, how to get execution time down to milliseconds

I was struggling with that until i found this...

http://blog.sqlauthority.com/2009/10/01/sql-server-sql-server-management-studio-and-client-statistics/

Also, if you open the Properties window you may find some magical "Connection elapsed time" that may give you some execution time... Hope it helps...

Get the current date and time

Get Current DateTime

Now.ToShortDateString()
DateTime.Now
Today.Now

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

I had this problem I iOS 12.4 when calling evaluateJavascript. I solved it by wrapping the call in DispatchQueue.main.async { }

Border Radius of Table is not working

Just add overflow:hidden to the table with border-radius.

.tablewithradius {
  overflow:hidden ;
  border-radius: 15px;
}

Problems when trying to load a package in R due to rJava

The reason is probably linked to the fact you are using a 64-bit OS and R version but do not have Java installed with the same architecture. What you have to do is to download Java 64-bit from this page: https://www.java.com/en/download/manual.jsp

After that just try to reload the xlsx package. You shouldn't need to re-start R.

Need a query that returns every field that contains a specified letter

try this

Select * From Table
Where field like '%' + ltrValue1 + '%'
  And field like '%' + ltrValue2 + '%'
... etc.

and be prepared for a table scan as this functionality cannot use any existing indices

Changing directory in Google colab (breaking out of the python interpreter)

If you want to use the cd or ls functions , you need proper identifiers before the function names ( % and ! respectively) use %cd and !ls to navigate

.

!ls    # to find the directory you're in ,
%cd ./samplefolder  #if you wanna go into a folder (say samplefolder)

or if you wanna go out of the current folder

%cd ../      

and then navigate to the required folder/file accordingly

Converting URL to String and back again

Swift 3 version code:

let urlString = "file:///Users/Documents/Book/Note.txt"
let pathURL = URL(string: urlString)!
print("the url = " + pathURL.path)

Bootstrap 4 responsive tables won't take up 100% width

Create responsive tables by wrapping any .table with .table-responsive{-sm|-md|-lg|-xl}, making the table scroll horizontally at each max-width breakpoint of up to (but not including) 576px, 768px, 992px, and 1120px, respectively.

just wrap table with .table-responsive{-sm|-md|-lg|-xl}

for example

<div class="table-responsive-md">
    <table class="table">
    </table>
</div>

bootstrap 4 tables

How to prevent "The play() request was interrupted by a call to pause()" error?

Trying to get an autoplaying video to loop by calling play() when it ends, the timeout workaround did not work for me (however long the timeout is).

But I discovered that by cloning/replacing the video with jQuery when it ended, it would loop properly.

For example:

<div class="container">
  <video autoplay>
    <source src="video.mp4" type="video/mp4">
  </video>
</div>

and

$(document).ready(function(){
  function bindReplay($video) {
    $video.on('ended', function(e){
      $video.remove();
      $video = $video.clone();
      bindReplay($video);
      $('.container').append($video);
    });
  }
  var $video = $('.container video');
  bindReplay($video);
});

I'm using Chrome 54.0.2840.59 (64-bit) / OS X 10.11.6

How to use ng-repeat without an html element

Update: If you are using Angular 1.2+, use ng-repeat-start. See @jmagnusson's answer.

Otherwise, how about putting the ng-repeat on tbody? (AFAIK, it is okay to have multiple <tbody>s in a single table.)

<tbody ng-repeat="row in array">
  <tr ng-repeat="item in row">
     <td>{{item}}</td>
  </tr>
</tbody>

How to count check-boxes using jQuery?

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;

Angular 4 img src is not found

Copy your images into the assets folder. Angular can only access static files like images and config files from assets folder.

Try like this: <img src="assets/img/myimage.png">

Jquery : Refresh/Reload the page on clicking a button

Use this line simply inside your head with

       window.location.reload(true);

It will load your current page or view.

How to access global js variable in AngularJS directive

Copy the global variable to a variable in the scope in your controller.

function MyCtrl($scope) {
   $scope.variable1 = variable1;
}

Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).

But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.

How can I check for "undefined" in JavaScript?

On the contrary of @Thomas Eding answer:

If I forget to declare myVar in my code, then I'll get myVar is not defined.

Let's take a real example:

I've a variable name, but I am not sure if it is declared somewhere or not.

Then @Anurag's answer will help:

var myVariableToCheck = 'myVar';
if (window[myVariableToCheck] === undefined)
    console.log("Not declared or declared, but undefined.");

// Or you can check it directly 
if (window['myVar'] === undefined) 
    console.log("Not declared or declared, but undefined.");

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

Handling NULL values in Hive

Try to include length > 0 as well.

column1 is not NULL AND column1 <> '' AND length(column1) > 0 

How to hide a column (GridView) but still access its value?

Here is how to get the value of a hidden column in a GridView that is set to Visible=False: add the data field in this case SpecialInstructions to the DataKeyNames property of the bound GridView , and access it this way.

txtSpcInst.Text = GridView2.DataKeys(GridView2.SelectedIndex).Values("SpecialInstructions")

That's it, it works every time very simple.

"On Exit" for a Console Application

This code works to catch the user closing the console window:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        handler = new ConsoleEventDelegate(ConsoleEventCallback);
        SetConsoleCtrlHandler(handler, true);
        Console.ReadLine();
    }

    static bool ConsoleEventCallback(int eventType) {
        if (eventType == 2) {
            Console.WriteLine("Console window closing, death imminent");
        }
        return false;
    }
    static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
    // Pinvoke
    private delegate bool ConsoleEventDelegate(int eventType);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

}

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

How to Create a real one-to-one relationship in SQL Server

This can be done by creating a simple primary foreign key relationship and setting the foreign key column to unique in the following manner:

CREATE TABLE [Employee] (
    [ID]    INT PRIMARY KEY
,   [Name]  VARCHAR(50)
);

CREATE TABLE [Salary] (
    [EmployeeID]    INT UNIQUE NOT NULL
,   [SalaryAmount]  INT 
);

ALTER TABLE [Salary]
ADD CONSTRAINT FK_Salary_Employee FOREIGN KEY([EmployeeID]) 
    REFERENCES [Employee]([ID]);

Schema

INSERT INTO [Employee] (
    [ID]
,   [Name]
)
VALUES
    (1, 'Ram')
,   (2, 'Rahim')
,   (3, 'Pankaj')
,   (4, 'Mohan');

INSERT INTO [Salary] (
    [EmployeeID]
,   [SalaryAmount]
)
VALUES
    (1, 2000)
,   (2, 3000)
,   (3, 2500)
,   (4, 3000);

Check to see if everything is fine

SELECT * FROM [Employee];
SELECT * FROM [Salary];

Now Generally in Primary Foreign Relationship (One to many), you could enter multiple times EmployeeID, but here an error will be thrown

INSERT INTO [Salary] (
    [EmployeeID]
,   [SalaryAmount]
)
VALUES
    (1, 3000);

The above statement will show error as

Violation of UNIQUE KEY constraint 'UQ__Salary__7AD04FF0C044141D'. Cannot insert duplicate key in object 'dbo.Salary'. The duplicate key value is (1).

openssl s_client using a proxy

for anyone coming here as of post-May 2015: there's a new "-proxy" option that will be included in the next release of openssl: https://rt.openssl.org/Ticket/Display.html?id=2651&user=guest&pass=guest

In angular $http service, How can I catch the "status" of error?

Response status comes as second parameter in callback, (from docs):

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Codeigniter unset session

answering to your question:

How can I destroy or unset the value of the session?

I can help you by this:

$this->session->unset_userdata('some_name');

and for multiple data you can:

$array_items = array('username' => '', 'email' => '');

$this->session->unset_userdata($array_items);

and to destroy the session:

$this->session->sess_destroy();

Now for the on page change part (on the top of my mind):

you can set the config "anchor_class" of the paginator equal to the classname you want.

after that just check it with jquery onclick for that class which will send a head up to the controller function that will unset the user session.

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

sed s/^M//g file1.txt > file2.txt

where ^M is typed by simultaneously pressing the 3 keys, ctrl + v + m

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

bootstrap-4 add class float-left or right for floating

Save bitmap to file function

Two example works for me, for your reference.

Bitmap bitmap = Utils.decodeBase64(base64);
try {
    File file = new File(filePath);
    FileOutputStream fOut = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
}
catch (Exception e) {
    e.printStackTrace();
    LOG.i(null, "Save file error!");
    return false;
}

and this one

Bitmap savePic = Utils.decodeBase64(base64);
File file = new File(filePath);
File path = new File(file.getParent());

if (savePic != null) {
    try {
        // build directory
        if (file.getParent() != null && !path.isDirectory()) {
            path.mkdirs();
        }
        // output image to file
        FileOutputStream fos = new FileOutputStream(filePath);
        savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
        ret = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
} else {
    LOG.i(TAG, "savePicture image parsing error");
}

How to change int into int64?

This is called type conversion :

i := 23
var i64 int64
i64 = int64(i)

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

EDIT: Handlebars now has a built-in way of accomplishing this; see the selected answer above. When working with plain Mustache, the below still applies.

Mustache can iterate over items in an array. So I'd suggest creating a separate data object formatted in a way Mustache can work with:

var o = {
  bob : 'For sure',
  roger: 'Unknown',
  donkey: 'What an ass'
},
mustacheFormattedData = { 'people' : [] };

for (var prop in o){
  if (o.hasOwnProperty(prop)){
    mustacheFormattedData['people'].push({
      'key' : prop,
      'value' : o[prop]
     });
  }
}

Now, your Mustache template would be something like:

{{#people}}
  {{key}} : {{value}}
{{/people}}

Check out the "Non-Empty Lists" section here: https://github.com/janl/mustache.js

Any shortcut to initialize all array elements to zero?

You can save the loop, initialization is already made to 0. Even for a local variable.

But please correct the place where you place the brackets, for readability (recognized best-practice):

int[] arr = new int[10];

How to connect Android app to MySQL database?

Use android vollley, it is very fast and you can betterm manipulate requests. Send post request using Volley and receive in PHP

Basically, you will create a map with key-value params for the php request(POST/GET), the php will do the desired processing and you will return the data as JSON(json_encode()). Then you can either parse the JSON as needed or use GSON from Google to let it do the parsing.

RegEx for matching UK Postcodes

First half of postcode Valid formats

  • [A-Z][A-Z][0-9][A-Z]
  • [A-Z][A-Z][0-9][0-9]
  • [A-Z][0-9][0-9]
  • [A-Z][A-Z][0-9]
  • [A-Z][A-Z][A-Z]
  • [A-Z][0-9][A-Z]
  • [A-Z][0-9]

Exceptions
Position 1 - QVX not used
Position 2 - IJZ not used except in GIR 0AA
Position 3 - AEHMNPRTVXY only used
Position 4 - ABEHMNPRVWXY

Second half of postcode

  • [0-9][A-Z][A-Z]

Exceptions
Position 2+3 - CIKMOV not used

Remember not all possible codes are used, so this list is a necessary but not sufficent condition for a valid code. It might be easier to just match against a list of all valid codes?

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

This is such a useful thread, a checklist of things to try for this pernicious problem. For me the one that worked was swapping to IE. It took me a while to realise as I was already using IE, I had the project's web properties set so that the start action was to start extenal program

C:\Program Files (x86)\Internet Explorer\iexplore.exe

with the command line arguments

http://localhost/MyProject -private

I needed the -private flag to stop IE caching the swf I'm working on. Switching back to 'specific page' from 'start external program' fixed the 'no symbols have been loaded' problem for me.

XPath Query: get attribute href from a tag

The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.

If someone is using frameworks like scrapy the you will have to use /html/body//a[contains(@href,'com')][2]/@href along with get() like this:

response.xpath('//a[contains(@href,'com')][2]/@href').get()

SQL: sum 3 columns when one column has a null value?

looks like you want to SUM all the columns (I'm not sure where "sum 3 columns" comes from), not just TotalHoursM, so try this:

SELECT 
    SUM(    ISNULL(TotalHoursM  ,0)
          + ISNULL(TotalHoursT  ,0)
          + ISNULL(TotalHoursW  ,0)
          + ISNULL(TotalHoursTH ,0)
          + ISNULL(TotalHoursF  ,0) 
       ) AS TOTAL
    FROM LeaveRequest

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

How to redirect to Login page when Session is expired in Java web application?

Inside the filter inject this JavaScript which will bring the login page like this. If you don't do this then in your AJAX call you will get login page and the contents of login page will be appended.

Inside your filter or redirect insert this script in response:

String scr = "<script>window.location=\""+request.getContextPath()+"/login.do\"</script>";
response.getWriter().write(scr);

UIScrollView not scrolling

I found that with this AutoLayout issue... if I just make the ViewController use UIView instead of UIScrollView for the class... then just add a UIScrollView myself... that it works.

Get cart item name, quantity all details woocommerce

Since WooCommerce 2.1 (2014) you should use the WC function instead of the global. You can also call more appropriate functions:

foreach ( WC()->cart->get_cart() as $cart_item ) {
   $item_name = $cart_item['data']->get_title();
   $quantity = $cart_item['quantity'];
   $price = $cart_item['data']->get_price();
   ...

This will not only be clean code, but it will be better than accessing the post_meta directly because it will apply filters if necessary.

Filter an array using a formula (without VBA)

Today, in Office 365, Excel has so called 'array functions'. The filter function does exactly what you want. No need to use CTRL+SHIFT+ENTER anymore, a simple enter will suffice.

In Office 365, your problem would be simply solved by using:

=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)

SQL Server - How to lock a table until a stored procedure finishes

Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.

How can I know if Object is String type object?

Either use instanceof or method Class.isAssignableFrom(Class<?> cls).

what is an illegal reflective access

If you want to go with the add-open option, here's a command to find which module provides which package ->

java --list-modules | tr @ " " | awk '{ print $1 }' | xargs -n1 java -d

the name of the module will be shown with the @ while the name of the packages without it

NOTE: tested with JDK 11

IMPORTANT: obviously is better than the provider of the package does not do the illegal access

Python, how to check if a result set is empty?

You can do like this :

count = 0
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=serverName;"
                      "Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute(SQL query)
for row in cursor:
    count = 1
    if true condition:
        print("True")
    else:
        print("False")
if count == 0:
    print("No Result")

Thanks :)

How do I manually configure a DataSource in Java?

The javadoc for DataSource you refer to is of the wrong package. You should look at javax.sql.DataSource. As you can see this is an interface. The host and port name configuration depends on the implementation, i.e. the JDBC driver you are using.

I have not checked the Derby javadocs but I suppose the code should compile like this:

ClientDataSource ds = org.apache.derby.jdbc.ClientDataSource()
ds.setHost etc....

how to find host name from IP with out login to the host

  • For Windows, try:

    NBTSTAT -A 10.100.3.104
    

    or

    ping -a 10.100.3.104
    
  • For Linux, try:

    nmblookup -A 10.100.3.104
    

They are almost same.

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Is a LINQ statement faster than a 'foreach' loop?

LINQ is slower now, but it might get faster at some point. The good thing about LINQ is that you don't have to care about how it works. If a new method is thought up that's incredibly fast, the people at Microsoft can implement it without even telling you and your code would be a lot faster.

More importantly though, LINQ is just much easier to read. That should be enough reason.

Create SQLite database in android

A simple database example to insert Todo List of day today life in DB and get list of all todo list.

public class MyDatabaseHelper extends SQLiteOpenHelper {

// Logcat tag
private static final String LOG = "DatabaseHelper";

// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "SQLiteDemoDB";

// Table Names
private static final String TABLE_TODO = "todos";

// column names
private static final String KEY_ID = "id";
private static final String KEY_CREATED_AT = "created_at";
private static final String KEY_TODO = "todoDescr";

// *********************************************************************************************
public MyDatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(CREATE_TABLE_TODO);


}

// Upgrading database **************************************************************************
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);


    // Create tables again
    onCreate(db);
}

// Creating Table TABLE_TEAM
String CREATE_TABLE_TODO = "CREATE TABLE " + TABLE_TODO + "("
        + KEY_ID + " integer primary key autoincrement, "
        + KEY_TODO + " text, "
        + KEY_CREATED_AT + " text" + ")";


// insert values of todo
public boolean InsertTodoDetails(String todo, String createdAt) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_TODO, todo);
    contentValues.put(KEY_CREATED_AT, createdAt);


    long rowInserted = db.insert(TABLE_TODO, null, contentValues);
    db.close();
    return true;
}


// Select values of todo
public Cursor GetAllTodoDetails() {
    SQLiteDatabase db = this.getReadableDatabase();


    String query = "SELECT * FROM " + TABLE_TODO;
    Cursor mcursor = db.rawQuery(query, null);

    if (mcursor != null) {
        mcursor.moveToFirst();
    }

    return mcursor;

}



}

My activity To save and get the record.

public class MyDbActivity extends AppCompatActivity {

    @Bind(R.id.edt_todo)
    EditText edtTodo;
    @Bind(R.id.btn_save)
    Button btnSave;

    MyDatabaseHelper db;
    @Bind(R.id.btn_getTodo)
    Button btnGetTodo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_db);
        ButterKnife.bind(this);

// creating database object
        db = new MyDatabaseHelper(this);


    }

    @OnClick(R.id.btn_save)
    public void onViewClicked() {


        String datetime = "";
        try {
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            datetime = dateformat.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }

        db.InsertTodoDetails(edtTodo.getText().toString().trim(), datetime);

    }

    @OnClick(R.id.btn_getTodo)
    public void onGetTodoClicked() {
        String todos = "";
        Cursor TodoList = db.GetAllTodoDetails();
        if (TodoList.moveToFirst()) {
            do {
                if (todos.equals("")) {
                    todos = TodoList.getString(TodoList.getColumnIndex("todoDescr"));

                } else {
                    todos = todos + ", " + TodoList.getString(TodoList.getColumnIndex("todoDescr"));
                }
                // do what ever you want here
            } while (TodoList.moveToNext());
        }
        TodoList.close();
        Toast.makeText(this, "" + todos, Toast.LENGTH_SHORT).show();

    }
}

HttpURLConnection timeout settings

I could get solution for such a similar problem with addition of a simple line

HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");

My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.

Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.

What is setup.py?

setup.py is a python file, the presence of which is an indication that the module/package you are about to install has likely been packaged and distributed with Distutils, which is the standard for distributing Python Modules.

This allows you to easily install Python packages. Often it's enough to write:

$ pip install . 

pip will use setup.py to install your module. Avoid calling setup.py directly.

https://docs.python.org/3/installing/index.html#installing-index

Overloading operators in typedef structs (c++)

  1. bool operator==(pos a) const{ - this method doesn't change object's elements.
  2. bool operator==(pos a) { - it may change object's elements.

Get the Id of current table row with Jquery

Your code would be more like so:

$('tr input[type=button]').click(function(){
    id = $(this).closest('tr').attr('id');
});

Getting values from query string in an url using AngularJS $location

Not sure if it has changed since the accepted answer was accepted, but it is possible.

$location.search() will return an object of key-value pairs, the same pairs as the query string. A key that has no value is just stored in the object as true. In this case, the object would be:

{"test_user_bLzgB": true}

You could access this value directly with $location.search().test_user_bLzgB

Example (with larger query string): http://fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse

Note: Due to hashes (as it will go to http://fiddle.jshell.net/#/url, which would create a new fiddle), this fiddle will not work in browsers that do not support js history (will not work in IE <10)

Edit:
As pointed out in the comments by @Naresh and @DavidTchepak, the $locationProvider also needs to be configured properly: https://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration

How can I find all of the distinct file extensions in a folder hierarchy?

Find everythin with a dot and show only the suffix.

find . -type f -name "*.*" | awk -F. '{print $NF}' | sort -u

if you know all suffix have 3 characters then

find . -type f -name "*.???" | awk -F. '{print $NF}' | sort -u

or with sed shows all suffixes with one to four characters. Change {1,4} to the range of characters you are expecting in the suffix.

find . -type f | sed -n 's/.*\.\(.\{1,4\}\)$/\1/p'| sort -u

MYSQL Truncated incorrect DOUBLE value

I experienced this error when using bindParam, and specifying PDO::PARAM_INT where I was actually passing a string. Changing to PDO::PARAM_STR fixed the error.

Codeigniter - multiple database connections

You should provide the second database information in `application/config/database.php´

Normally, you would set the default database group, like so:

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Notice that the login information and settings are provided in the array named $db['default'].

You can then add another database in a new array - let's call it 'otherdb'.

$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_database_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = TRUE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;

Now, to actually use the second database, you have to send the connection to another variabel that you can use in your model:

function my_model_method()
{
  $otherdb = $this->load->database('otherdb', TRUE); // the TRUE paramater tells CI that you'd like to return the database object.

  $query = $otherdb->select('first_name, last_name')->get('person');
  var_dump($query);
}

That should do it. The documentation for connecting to multiple databases can be found here: http://codeigniter.com/user_guide/database/connecting.html

How can I get href links from HTML using Python?

This answer is similar to others with requests and BeautifulSoup, but using list comprehension.

Because find_all() is the most popular method in the Beautiful Soup search API, you can use soup("a") as a shortcut of soup.findAll("a") and using list comprehension:

import requests
from bs4 import BeautifulSoup

URL = "http://www.yourwebsite.com"
page = requests.get(URL)
soup = BeautifulSoup(page.content, features='lxml')
# Find links
all_links = [link.get("href") for link in soup("a")]
# Only external links
ext_links = [link.get("href") for link in soup("a") if "http" in link.get("href")]

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#calling-a-tag-is-like-calling-find-all

Using .text() to retrieve only text not nested in child tags

Simple answer:

$("#listItem").contents().filter(function(){ 
  return this.nodeType == 3; 
})[0].nodeValue = "The text you want to replace with" 

What is thread safe or non-thread safe in PHP?

Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).

So basically, from bottom to top

Linux

Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx

PHP-FPM + APC

ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.

Remove table row after clicking table row delete button

Following solution is working fine.

HTML:

<table>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
</table>

JQuery:

function SomeDeleteRowFunction(btndel) {
    if (typeof(btndel) == "object") {
        $(btndel).closest("tr").remove();
    } else {
        return false;
    }
}

I have done bins on http://codebins.com/bin/4ldqpa9

How to write a confusion matrix in Python?

If you don't want scikit-learn to do the work for you...

    import numpy
    actual = numpy.array(actual)
    predicted = numpy.array(predicted)

    # calculate the confusion matrix; labels is numpy array of classification labels
    cm = numpy.zeros((len(labels), len(labels)))
    for a, p in zip(actual, predicted):
        cm[a][p] += 1

    # also get the accuracy easily with numpy
    accuracy = (actual == predicted).sum() / float(len(actual))

Or take a look at a more complete implementation here in NLTK.

Most recent previous business day in Python

 def getNthBusinessDay(startDate, businessDaysInBetween):
    currentDate = startDate
    daysToAdd = businessDaysInBetween
    while daysToAdd > 0:
        currentDate += relativedelta(days=1)
        day = currentDate.weekday()
        if day < 5:
            daysToAdd -= 1

    return currentDate 

How to handle checkboxes in ASP.NET MVC forms?

Here's what I've been doing.

View:


<input type="checkbox" name="applyChanges" />

Controller:


var checkBox = Request.Form["applyChanges"];

if (checkBox == "on")
{
...
}

I found the Html.* helper methods not so useful in some cases, and that I was better off doing it in plain old HTML. This being one of them, the other one that comes to mind is radio buttons.

Edit: this is on Preview 5, obviously YMMV between versions.

Change border-bottom color using jquery?

If you have this in your CSS file:

.myApp
{
    border-bottom-color:#FF0000;
}

and a div for instance of:

<div id="myDiv">test text</div>

you can use:

$("#myDiv").addClass('myApp');// to add the style

$("#myDiv").removeClass('myApp');// to remove the style

or you can just use

$("#myDiv").css( 'border-bottom-color','#FF0000');

I prefer the first example, keeping all the CSS related items in the CSS files.

how to add new <li> to <ul> onclick with javascript

There is nothing much to add to your code except appending the li tag to the ul

ul.appendChild(li)

and there you go just add this to your function and then it should work.

"A lambda expression with a statement body cannot be converted to an expression tree"

The LINQ to SQL return object were implementing IQueryable interface. So for Select method predicate parameter you should only supply single lambda expression without body.

This is because LINQ for SQL code is not execute inside program rather than on remote side like SQL server or others. This lazy loading execution type were achieve by implementing IQueryable where its expect delegate is being wrapped in Expression type class like below.

Expression<Func<TParam,TResult>>

Expression tree do not support lambda expression with body and its only support single line lambda expression like var id = cols.Select( col => col.id );

So if you try the following code won't works.

Expression<Func<int,int>> function = x => {
    return x * 2;
}

The following will works as per expected.

Expression<Func<int,int>> function = x => x * 2;

How to install older version of node.js on Windows?

run:

npm install -g [email protected]

- or whatever version you want after the @ symbol (This works as of 2019)

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

I've solved this problem by deleting the google-services.json file and downloading it again from Firebase console.

Convert array into csv

A slight adaptation to the solution above by kingjeffrey for when you want to create and echo the CSV within a template (Ie - most frameworks will have output buffering enabled and you are required to set headers etc in controllers.)

// Create Some data
<?php
    $data = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),
    );


// Create a stream opening it with read / write mode
$stream = fopen('data://text/plain,' . "", 'w+');

// Iterate over the data, writting each line to the text stream
foreach ($data as $val) {
    fputcsv($stream, $val);
}

// Rewind the stream
rewind($stream);

// You can now echo it's content
echo stream_get_contents($stream);

// Close the stream 
fclose($stream);

Credit to Kingjeffrey above and also to this blog post where I found the information about creating text streams.

How to make Java honor the DNS Caching Timeout?

According to the official oracle java properties, sun.net.inetaddr.ttl is Sun implementation-specific property, which "may not be supported in future releases". "the preferred way is to use the security property" networkaddress.cache.ttl.

jQuery check if it is clicked or not

Alright, before I go into the solution, lets be on the same line about this one fact: Javascript is Event Based. So you'll usually have to setup callbacks to be able to do procedures.

Based on your comment I assumed you have a trigger that will do the logic that launched the function depending if the element is clicked; for sake of demonstration I made it a "submit button"; but this can be a timer or something else.

var the_action = function(type) {
    switch(type) {
        case 'a':
            console.log('Case A');
            break;
         case 'b':
            console.log('Case B');
            break;
    }
};

$('.clickme').click(function() { 
    console.log('Clicked');
    $(this).data('clicked', true);
});

$('.submit').click(function() {
    // All your logic can go here if you want.
    if($('.clickme').data('clicked') == true) {
        the_action('a');
    } else {
        the_action('b');
    }
});

Live Example: http://jsfiddle.net/kuroir/6MCVJ/

How do you refresh the MySQL configuration file without restarting?

Try:

sudo /etc/init.d/mysql reload

or

sudo /etc/init.d/mysql force-reload

That should initiate a reload of the configuration. Make sureyour init.d script supports it though, I don't know what version of MySQL/OS you are using?

My MySQL script contains the following:

'reload'|'force-reload')
        log_daemon_msg "Reloading MySQL database server" "mysqld"
        $MYADMIN reload
        log_end_msg 0
        ;;

Get user's non-truncated Active Directory groups from command line

GPRESULT is the right command, but it cannot be run without parameters. /v or verbose option is difficult to manage without also outputting to a text file. E.G. I recommend using

gpresult /user myAccount /v > C:\dev\me.txt--Ensure C:\Dev\me.txt exists

Another option is to display summary information only which may be entirely visible in the command window:

gpresult /user myAccount /r

The accounts are listed under the heading:

The user is a part of the following security groups
---------------------------------------------------

JQuery: Change value of hidden input field

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

Does C# have extension properties?

For the moment it is still not supported out of the box by Roslyn compiler ...

Until now, the extension properties were not seen as valuable enough to be included in the previous versions of C# standard. C# 7 and C# 8.0 have seen this as proposal champion but it wasn't released yet, most of all because even if there is already an implementation, they want to make it right from the start.

But it will ...

There is an extension members item in the C# 7 work list so it may be supported in the near future. The current status of extension property can be found on Github under the related item.

However, there is an even more promising topic which is the "extend everything" with a focus on especially properties and static classes or even fields.

Moreover you can use a workaround

As specified in this article, you can use the TypeDescriptor capability to attach an attribute to an object instance at runtime. However, it is not using the syntax of the standard properties.
It's a little bit different from just syntactic sugar adding a possibility to define an extended property like
string Data(this MyClass instance) as an alias for extension method
string GetData(this MyClass instance) as it stores data into the class.

I hope that C#7 will provide a full featured extension everything (properties and fields), however on that point, only time will tell.

And feel free to contribute as the software of tomorrow will come from the community.

Update: August 2016

As dotnet team published what's new in C# 7.0 and from a comment of Mads Torgensen:

Extension properties: we had a (brilliant!) intern implement them over the summer as an experiment, along with other kinds of extension members. We remain interested in this, but it’s a big change and we need to feel confident that it’s worth it.

It seems that extension properties and other members, are still good candidates to be included in a future release of Roslyn, but maybe not the 7.0 one.

Update: May 2017

The extension members has been closed as duplicate of extension everything issue which is closed too. The main discussion was in fact about Type extensibility in a broad sense. The feature is now tracked here as a proposal and has been removed from 7.0 milestone.

Update: August, 2017 - C# 8.0 proposed feature

While it still remains only a proposed feature, we have now a clearer view of what would be its syntax. Keep in mind that this will be the new syntax for extension methods as well:

public interface IEmployee 
{
    public decimal Salary { get; set; }
}

public class Employee
{
    public decimal Salary { get; set; }
}

public extension MyPersonExtension extends Person : IEmployee
{
    private static readonly ConditionalWeakTable<Person, Employee> _employees = 
        new ConditionalWeakTable<Person, Employee>();


    public decimal Salary
    {
        get 
        {
            // `this` is the instance of Person
            return _employees.GetOrCreate(this).Salary; 
        }
        set 
        {
            Employee employee = null;
            if (!_employees.TryGetValue(this, out employee)
            {
                employee = _employees.GetOrCreate(this);
            }
            employee.Salary = value;
        }
    }
}

IEmployee person = new Person();
var salary = person.Salary;

Similar to partial classes, but compiled as a separate class/type in a different assembly. Note you will also be able to add static members and operators this way. As mentioned in Mads Torgensen podcast, the extension won't have any state (so it cannot add private instance members to the class) which means you won't be able to add private instance data linked to the instance. The reason invoked for that is it would imply to manage internally dictionaries and it could be difficult (memory management, etc...). For this, you can still use the TypeDescriptor/ConditionalWeakTable technique described earlier and with the property extension, hides it under a nice property.

Syntax is still subject to change as implies this issue. For example, extends could be replaced by for which some may feel more natural and less java related.

Update December 2018 - Roles, Extensions and static interface members

Extension everything didn't make it to C# 8.0, because of some of drawbacks explained as the end of this GitHub ticket. So, there was an exploration to improve the design. Here, Mads Torgensen explains what are roles and extensions and how they differs:

Roles allow interfaces to be implemented on specific values of a given type. Extensions allow interfaces to be implemented on all values of a given type, within a specific region of code.

It can be seen at a split of previous proposal in two use cases. The new syntax for extension would be like this:

public extension ULongEnumerable of ulong
{
    public IEnumerator<byte> GetEnumerator()
    {
        for (int i = sizeof(ulong); i > 0; i--)
        {
            yield return unchecked((byte)(this >> (i-1)*8));
        }
    }
}

then you would be able to do this:

foreach (byte b in 0x_3A_9E_F1_C5_DA_F7_30_16ul)
{
    WriteLine($"{e.Current:X}");
}

And for a static interface:

public interface IMonoid<T> where T : IMonoid<T>
{
    static T operator +(T t1, T t2);
    static T Zero { get; }
}

Add an extension property on int and treat the int as IMonoid<int>:

public extension IntMonoid of int : IMonoid<int>
{
    public static int Zero => 0;
}

How can I use jQuery to make an input readonly?

simply add the following attribute

// for disabled i.e. cannot highlight value or change
disabled="disabled"

// for readonly i.e. can highlight value but not change
readonly="readonly"

jQuery to make the change to the element (substitute disabled for readonly in the following for setting readonly attribute).

$('#fieldName').attr("disabled","disabled") 

or

$('#fieldName').attr("disabled", true) 

NOTE: As of jQuery 1.6, it is recommended to use .prop() instead of .attr(). The above code will work exactly the same except substitute .attr() for .prop().