Programs & Examples On #Mashery

Mashery is a commercial API management service for deploying, documenting and monitoring API services in the cloud or on premise

python list by value not by reference

When you do b = a you simply create another pointer to the same memory of a, that's why when you append to b , a changes too.

You need to create copy of a and that's done like this:

b = a[:]

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

How to verify Facebook access token?

Simply request (HTTP GET):

https://graph.facebook.com/USER_ID/access_token=xxxxxxxxxxxxxxxxx

That's it.

Reset all changes after last commit in git

There are two commands which will work in this situation,

root>git reset --hard HEAD~1

root>git push -f

For more git commands refer this page

How to force Sequential Javascript Execution?

I tried the callback way and could not get this to work, what you have to understand is that values are still atomic even though execution is not. For example:

alert('1'); <--- these two functions will be executed at the same time

alert('2'); <--- these two functions will be executed at the same time

but doing like this will force us to know the order of execution:

loop=2;
total=0;
for(i=0;i<loop;i++) {
           total+=1;
           if(total == loop)
                      alert('2');
           else
                      alert('1');
}

Angular 5 Service to read local .json file

import data  from './data.json';
export class AppComponent  {
    json:any = data;
}

See this article for more details.

Parsing a CSV file using NodeJS

I used this way:-

var fs = require('fs'); 
var parse = require('csv-parse');

var csvData=[];
fs.createReadStream(req.file.path)
    .pipe(parse({delimiter: ':'}))
    .on('data', function(csvrow) {
        console.log(csvrow);
        //do something with csvrow
        csvData.push(csvrow);        
    })
    .on('end',function() {
      //do something with csvData
      console.log(csvData);
    });

using stored procedure in entity framework

Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...

[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
    [TestMethod]
    public void GetTenantForName_ReturnsOneRecord()
    {
        // ARRANGE
        const int expectedCount = 1;
        const string expectedName = "Me";

        // Build the paraemeters object
        var parameters = new GetTenantForTenantNameParameters
        {
            TenantName = expectedName
        };

        // get an instance of the stored procedure passing the parameters
        var procedure = new GetTenantForTenantNameProcedure(parameters);

        // Initialise the procedure name and schema from procedure attributes
        procedure.InitializeFromAttributes();

        // Add some tenants to context so we have something for the procedure to return!
        AddTenentsToContext(Context);

        // ACT
        // Get the results by calling the stored procedure from the context extention method 
        var results = Context.ExecuteStoredProcedure(procedure);

        // ASSERT
        Assert.AreEqual(expectedCount, results.Count);
    }
}

internal class GetTenantForTenantNameParameters
{
    [Name("TenantName")]
    [Size(100)]
    [ParameterDbType(SqlDbType.VarChar)]
    public string TenantName { get; set; }
}

[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
    : StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
    public GetTenantForTenantNameProcedure(
        GetTenantForTenantNameParameters parameters)
        : base(parameters)
    {
    }
}

If either of those two approaches are any good?

Joda DateTime to Timestamp conversion

I've solved this problem in this way.

String dateUTC = rs.getString("date"); //UTC
DateTime date;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC();
date = dateTimeFormatter.parseDateTime(dateUTC);

In this way you ignore the server TimeZone forcing your chosen TimeZone.

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also:

Convert a negative number to a positive one in JavaScript

I know this is a bit late, but for people struggling with this, you can use the following functions:

  • Turn any number positive

    let x =  54;
    let y = -54;
    let resultx =  Math.abs(x); //  54
    let resulty =  Math.abs(y); //  54
    
  • Turn any number negative

    let x =  54;
    let y = -54;
    let resultx = -Math.abs(x); // -54
    let resulty = -Math.abs(y); // -54
    
  • Invert any number

    let x =  54;
    let y = -54;
    let resultx = -(x);         // -54
    let resulty = -(y);         //  54
    

jquery find class and get the value

You can get value of id,name or value in this way. class name my_class

 var id_value = $('.my_class').$(this).attr('id'); //get id value
 var name_value = $('.my_class').$(this).attr('name'); //get name value
 var value = $('.my_class').$(this).attr('value'); //get value any input or tag

JavaScript Chart.js - Custom data formatting to display on tooltip

For chart.js 2.0+, this has changed (no more tooltipTemplate/multiTooltipTemplate). For those that just want to access the current, unformatted value and start tweaking it, the default tooltip is the same as:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return tooltipItem.yLabel;
            }
        }
    }
}

I.e., you can return modifications to tooltipItem.yLabel, which holds the y-axis value. In my case, I wanted to add a dollar sign, rounding, and thousands commas for a financial chart, so I used:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return "$" + Number(tooltipItem.yLabel).toFixed(0).replace(/./g, function(c, i, a) {
                    return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
                });
            }
        }
    }
}

Direct method from SQL command text to DataSet

public static string textDataSource = "Data Source=localhost;Initial Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";

public static DataSet LoaderDataSet(string StrSql)      
{
    SqlConnection cnn;            
    SqlDataAdapter dad;
    DataSet dts = new DataSet();
    cnn = new SqlConnection(textDataSource);
    dad = new SqlDataAdapter(StrSql, cnn);
    try
    {
        cnn.Open();
        dad.Fill(dts);
        cnn.Close();

        return dts;
    }
    catch (Exception)
    {

        return dts;
    }
    finally
    {
        dad.Dispose();
        dts = null;
        cnn = null;
    }
}

Removing trailing newline character from fgets() input

 for(int i = 0; i < strlen(Name); i++ )
{
    if(Name[i] == '\n') Name[i] = '\0';
}

You should give it a try. This code basically loop through the string until it finds the '\n'. When it's found the '\n' will be replaced by the null character terminator '\0'

Note that you are comparing characters and not strings in this line, then there's no need to use strcmp():

if(Name[i] == '\n') Name[i] = '\0';

since you will be using single quotes and not double quotes. Here's a link about single vs double quotes if you want to know more

Android - running a method periodically using postDelayed() call

Handler h = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what==0){
            // do stuff
            h.removeMessages(0);  // clear the handler for those messages with what = 0
            h.sendEmptyMessageDelayed(0, 2000); 
        }
    }
};


 h.sendEmptyMessage(0);  

How do I escape double quotes in attributes in an XML String in T-SQL?

Cannot comment anymore but voted it up and wanted to let folks know that &quot; works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src=&quot;(.*)&quot;.*" using the escaped version instead of double-quotes.

How can I prevent the backspace key from navigating back?

All of the answers given so far focus on scripting the fix into the web page, but what if I simply want the feature for myself, without affecting other users?

In this case a solution for the browser itself is to be preferred:
- Firefox on Linux "unmapped" the backspace behavior since 2006 so it's not affected; (at any rate, it was simply set to scroll up before then)
- Chrome has just announced that it will do the same from now on; (http://forums.theregister.co.uk/forum/1/2016/05/20/chrome_deletes_backspace/)
- Firefox on Windows can be set to ignore backspace by going into about:config and changing the backspace_action setting to 2; (http://kb.mozillazine.org/Browser.backspace_action)
- Safari ?!

How to make div background color transparent in CSS

From https://developer.mozilla.org/en-US/docs/Web/CSS/background-color

To set background color:

/* Hexadecimal value with color and 100% transparency*/
background-color: #11ffee00;  /* Fully transparent */

/* Special keyword values */
background-color: transparent;

/* HSL value with color and 100% transparency*/
background-color: hsla(50, 33%, 25%, 1.00);  /* 100% transparent */

/* RGB value with color and 100% transparency*/
background-color: rgba(117, 190, 218, 1.0);  /* 100% transparent */

Why does Firebug say toFixed() is not a function?

In a function, use as

render: function (args) {
    if (args.value != 0)
        return (parseFloat(args.value).toFixed(2));


},

Concatenate a NumPy array to another NumPy array

I had the same issue, and I couldn't comment on @Sven Marnach answer (not enough rep, gosh I remember when Stackoverflow first started...) anyway.

Adding a list of random numbers to a 10 X 10 matrix.

myNpArray = np.zeros([1, 10])
for x in range(1,11,1):
    randomList = [list(np.random.randint(99, size=10))]
    myNpArray = np.vstack((myNpArray, randomList))
myNpArray = myNpArray[1:]

Using np.zeros() an array is created with 1 x 10 zeros.

array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

Then a list of 10 random numbers is created using np.random and assigned to randomList. The loop stacks it 10 high. We just have to remember to remove the first empty entry.

myNpArray

array([[31., 10., 19., 78., 95., 58.,  3., 47., 30., 56.],
       [51., 97.,  5., 80., 28., 76., 92., 50., 22., 93.],
       [64., 79.,  7., 12., 68., 13., 59., 96., 32., 34.],
       [44., 22., 46., 56., 73., 42., 62.,  4., 62., 83.],
       [91., 28., 54., 69., 60., 95.,  5., 13., 60., 88.],
       [71., 90., 76., 53., 13., 53., 31.,  3., 96., 57.],
       [33., 87., 81.,  7., 53., 46.,  5.,  8., 20., 71.],
       [46., 71., 14., 66., 68., 65., 68., 32.,  9., 30.],
       [ 1., 35., 96., 92., 72., 52., 88., 86., 94., 88.],
       [13., 36., 43., 45., 90., 17., 38.,  1., 41., 33.]])

So in a function:

def array_matrix(random_range, array_size):
    myNpArray = np.zeros([1, array_size])
    for x in range(1, array_size + 1, 1):
        randomList = [list(np.random.randint(random_range, size=array_size))]
        myNpArray = np.vstack((myNpArray, randomList))
    return myNpArray[1:]

a 7 x 7 array using random numbers 0 - 1000

array_matrix(1000, 7)

array([[621., 377., 931., 180., 964., 885., 723.],
       [298., 382., 148., 952., 430., 333., 956.],
       [398., 596., 732., 422., 656., 348., 470.],
       [735., 251., 314., 182., 966., 261., 523.],
       [373., 616., 389.,  90., 884., 957., 826.],
       [587., 963.,  66., 154., 111., 529., 945.],
       [950., 413., 539., 860., 634., 195., 915.]])

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

  1. Spring is an IoC container (at least the core of Spring) and is used to wire things using dependency injection. Spring provides additional services like transaction management and seamless integration of various other technologies.
  2. Struts is an action-based presentation framework (but don't use it for a new development).
  3. Struts 2 is an action-based presentation framework, the version 2 of the above (created from a merge of WebWork with Struts).
  4. Hibernate is an object-relational mapping tool, a persistence framework.
  5. JavaServer Faces is component-based presentation framework.
  6. JavaServer Pages is a view technology used by all mentioned presentation framework for the view.
  7. Tapestry is another component-based presentation framework.

So, to summarize:

  • Struts 2, JSF, Tapestry (and Wicket, Spring MVC, Stripes) are presentation frameworks. If you use one of them, you don't use another.
  • Hibernate is a persistence framework and is used to persist Java objects in a relational database.
  • Spring can be used to wire all this together and to provide declarative transaction management.

I don't want to make things more confusing but note that Java EE 6 provides modern, standardized and very nice equivalent of the above frameworks: JSF 2.0 and Facelets for the presentation, JPA 2.0 for the persistence, Dependency Injection, etc. For a new development, this is IMO a serious option, Java EE 6 is a great stack.

See also

Margin-Top not working for span element?

span element is display:inline; by default you need to make it inline-block or block

Change your CSS to be like this

span.first_title {
    margin-top: 20px;
    margin-left: 12px;
    font-weight: bold;
    font-size:24px;
    color: #221461;
    /*The change*/
    display:inline-block; /*or display:block;*/
}

How to copy marked text in notepad++

I had the same problem. You can list the regex matches in a new tab, every match in new line in PSPad Editor, which is very similar as Notepad++.

Hit Ctrl + F to search, check the regexp opion, put the regexp and click on List.

How to use "Share image using" sharing Intent to share images in android?

The solution proposed from superM worked for me for a long time, but lately I tested it on 4.2 (HTC One) and it stopped working there. I am aware that this is a workaround, but it was the only one which worked for me with all devices and versions.

According to the documentation, developers are asked to "use the system MediaStore" to send binary content. This, however, has the (dis-)advantage, that the media content will be saved permanently on the device.

If this is an option for you, you might want to grant permission WRITE_EXTERNAL_STORAGE and use the system-wide MediaStore.

Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");

ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
        values);


OutputStream outstream;
try {
    outstream = getContentResolver().openOutputStream(uri);
    icon.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
    outstream.close();
} catch (Exception e) {
    System.err.println(e.toString());
}

share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));

Leap year calculation

PHP:

// is number of days in the year 366?  (php days of year is 0 based)
return ((int)date('z', strtotime('Dec 31')) === 365);

How to Bulk Insert from XLSX file extension?

you can save the xlsx file as a tab-delimited text file and do

BULK INSERT TableName
        FROM 'C:\SomeDirectory\my table.txt'
            WITH
    (
                FIELDTERMINATOR = '\t',
                ROWTERMINATOR = '\n'
    )
GO

Select2 doesn't work when embedded in a bootstrap modal

Just remove tabindex="-1" and add style overflow:hidden

Here is an example:

<div id="myModal" class="modal fade" role="dialog" style="overflow:hidden;">
    <!---content modal here -->
</div>

Exit a while loop in VBS/VBA

I know this is old as dirt but it ranked pretty high in google.

The problem with the solution maddy implemented (in response to rahul) to maintain the use of a While...Wend loop has some drawbacks

In the example given

num = 0
While num < 10
  If status = "Fail" Then
    num = 10
  End If
  num = num + 1
Wend

After status = "Fail" num will actually equal 11. The loop didn't end on the fail condition, it ends on the next test. All of the code after the check still processed and your counter is not what you might have expected it to be.

Now depending on what you are all doing in your loop it may not matter, but then again if your code looked something more like:

num = 0
While num < 10
  If folder = "System32" Then
    num = 10
  End If
  RecursiveDeleteFunction folder
  num = num + 1
Wend

Using Do While or Do Until allows you to stop execution of the loop using Exit Do instead of using trickery with your loop condition to maintain the While ... Wend syntax. I would recommend using that instead.

Best way to format integer as string with leading zeros?

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'

TypeError: 'list' object is not callable in python

You have already assigned a value to list.
So, you cannot use the list() when it’s a variable.
Restart the shell or IDE, by pressing Ctrl+F6 on your computer.
Hope this works too.

What does [object Object] mean? (JavaScript)

Another option is to use JSON.stringify(obj)

For example:

exampleObj = {'a':1,'b':2,'c':3};
alert(JSON.stringify(exampleObj))

https://www.w3schools.com/js/js_json_stringify.asp

What is memoization and how can I use it in Python?

I've found this extremely useful

def memoize(function):
    from functools import wraps

    memo = {}

    @wraps(function)
    def wrapper(*args):
        if args in memo:
            return memo[args]
        else:
            rv = function(*args)
            memo[args] = rv
            return rv
    return wrapper


@memoize
def fibonacci(n):
    if n < 2: return n
    return fibonacci(n - 1) + fibonacci(n - 2)

fibonacci(25)

How is a non-breaking space represented in a JavaScript string?

The jQuery docs for text() says

Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.

I'd use $td.html() instead.

Generating (pseudo)random alpha-numeric strings

This is something I use:

$cryptoStrong = true; // can be false
$length = 16; // Any length you want
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
$randomString = bin2hex($bytes);

You can see the Docs for openssl_random_pseudo_bytes here, and the Docs for bin2hex here

Auto-expanding layout with Qt-Designer

Set the horizontalPolicy & VerticalPolicy for the controls/widgets to "Preferred".

What do the terms "CPU bound" and "I/O bound" mean?

IO bound processes: spend more time doing IO than computations, have many short CPU bursts. CPU bound processes: spend more time doing computations, few very long CPU bursts

How to comment and uncomment blocks of code in the Office VBA Editor

Or just click View, ToolBars, Edit. Then you can select a block of code and then click the Comment or Uncomment toolbar button to do everything in one click.

As an aside, you can Tab/Shift+Tab a block of selected text also. When I was a noobie, I didn't know that for a long time and would do them one line at a time.

Good Luck!

X-Frame-Options: ALLOW-FROM in firefox and chrome

ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options

You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?

How to uncheck checked radio button

try this

_x000D_
_x000D_
var radio_button=false;_x000D_
$('.radio-button').on("click", function(event){_x000D_
  var this_input=$(this);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.attr('checked1','11')_x000D_
  } else {_x000D_
    this_input.attr('checked1','22')_x000D_
  }_x000D_
  $('.radio-button').prop('checked', false);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.prop('checked', false);_x000D_
    this_input.attr('checked1','22')_x000D_
  } else {_x000D_
    this_input.prop('checked', true);_x000D_
    this_input.attr('checked1','11')_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
_x000D_
_x000D_

Copy map values to vector in STL

If you are using the boost libraries, you can use boost::bind to access the second value of the pair as follows:

#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>

int main()
{
   typedef std::map<std::string, int> MapT;
   typedef std::vector<int> VecT;
   MapT map;
   VecT vec;

   map["one"] = 1;
   map["two"] = 2;
   map["three"] = 3;
   map["four"] = 4;
   map["five"] = 5;

   std::transform( map.begin(), map.end(),
                   std::back_inserter(vec),
                   boost::bind(&MapT::value_type::second,_1) );
}

This solution is based on a post from Michael Goldshteyn on the boost mailing list.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I don't think that solution would work anyways because you will see some error message in your error log file.

The solution was a lot easier than what I thought.

simply, open the following path to your php5-fpm

sudo nano /etc/php5/fpm/pool.d/www.conf

or if you're the admin 'root'

nano /etc/php5/fpm/pool.d/www.conf

Then find this line and uncomment it:

listen.allowed_clients = 127.0.0.1

This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks

like this: fastcgi_pass 127.0.0.1:9000;

after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm

Php5-fpm

sudo service php5-fpm restart

or

sudo service php5-fpm reload

Nginx

sudo service nginx restart

or

sudo service nginx reload

From the comments:

Also comment

;listen = /var/run/php5-fpm.sock 

and add

listen = 9000

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

As an alternative to everyone else's answers I've always done something like this:

List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
    if (someCondition) {
        toRemove.add(str);
    }
}
myArrayList.removeAll(toRemove);

This will avoid you having to deal with the iterator directly, but requires another list. I've always preferred this route for whatever reason.

How do I pass multiple parameter in URL?

This

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"&param2="+lon);

must work. For whatever strange reason1, you need ? before the first parameter and & before the following ones.

Using a compound parameter like

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);

would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20 or + (but this is even worse style).


1 Stating that ? separates the path and the parameters and that & separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.

automatically execute an Excel macro on a cell change

Your code looks pretty good.

Be careful, however, for your call to Range("H5") is a shortcut command to Application.Range("H5"), which is equivalent to Application.ActiveSheet.Range("H5"). This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.

With this in mind, I would utilize Target.Worksheet.Range("H5"):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro
End Sub

Or you can use Me.Range("H5"), if the event handler is on the code page for the worksheet in question (it usually is):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro
End Sub

Hope this helps...

Convert datetime object to a String of date only in Python

date and datetime objects (and time as well) support a mini-language to specify output, and there are two ways to access it:

So your example could look like:

  • dt.strftime('The date is %b %d, %Y')
  • 'The date is {:%b %d, %Y}'.format(dt)
  • f'The date is {dt:%b %d, %Y}'

In all three cases the output is:

The date is Feb 23, 2012

For completeness' sake: you can also directly access the attributes of the object, but then you only get the numbers:

'The date is %s/%s/%s' % (dt.month, dt.day, dt.year)
# The date is 02/23/2012

The time taken to learn the mini-language is worth it.


For reference, here are the codes used in the mini-language:

  • %a Weekday as locale’s abbreviated name.
  • %A Weekday as locale’s full name.
  • %w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
  • %d Day of the month as a zero-padded decimal number.
  • %b Month as locale’s abbreviated name.
  • %B Month as locale’s full name.
  • %m Month as a zero-padded decimal number. 01, ..., 12
  • %y Year without century as a zero-padded decimal number. 00, ..., 99
  • %Y Year with century as a decimal number. 1970, 1988, 2001, 2013
  • %H Hour (24-hour clock) as a zero-padded decimal number. 00, ..., 23
  • %I Hour (12-hour clock) as a zero-padded decimal number. 01, ..., 12
  • %p Locale’s equivalent of either AM or PM.
  • %M Minute as a zero-padded decimal number. 00, ..., 59
  • %S Second as a zero-padded decimal number. 00, ..., 59
  • %f Microsecond as a decimal number, zero-padded on the left. 000000, ..., 999999
  • %z UTC offset in the form +HHMM or -HHMM (empty if naive), +0000, -0400, +1030
  • %Z Time zone name (empty if naive), UTC, EST, CST
  • %j Day of the year as a zero-padded decimal number. 001, ..., 366
  • %U Week number of the year (Sunday is the first) as a zero padded decimal number.
  • %W Week number of the year (Monday is first) as a decimal number.
  • %c Locale’s appropriate date and time representation.
  • %x Locale’s appropriate date representation.
  • %X Locale’s appropriate time representation.
  • %% A literal '%' character.

I want to declare an empty array in java and then I want do update it but the code is not working

You need to give the array a size:

public static void main(String args[])
{
    int array[] = new int[4];
    int number = 5, i = 0,j = 0;
    while (i<4){
        array[i]=number;
        i=i+1;
    }
    while (j<4){
        System.out.println(array[j]);
        j++;
    }
}

MySQL Error: : 'Access denied for user 'root'@'localhost'

It can happen if you don't have enough privileges. Type su, enter root password and try again.

How can I determine the URL that a local Git repository was originally cloned from?

For me, this is the easier way (less typing):

$ git remote -v
origin    https://github.com/torvalds/linux.git (fetch)
origin    https://github.com/torvalds/linux.git (push)

actually, I've that into an alias called s that does:

git remote -v
git status

You can add to your profile with: alias s='git remote -v && git status'

What is the difference between 'java', 'javaw', and 'javaws'?

See Java tools documentation for:

  1. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
  2. The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear.

The javaws command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network.

If a JNLP file is specified, javaws will launch the Java application/applet specified in the JNLP file.

The javaws launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.

See also JDK 9 Release Notes Deprecated APIs, Features, and Options:

Java Deployment Technologies are deprecated and will be removed in a future release
Java Applet and WebStart functionality, including the Applet API, the Java plug-in, the Java Applet Viewer, JNLP and Java Web Start, including the javaws tool, are all deprecated in JDK 9 and will be removed in a future release.

What is the reason for a red exclamation mark next to my project in Eclipse?

If it is maven project and your project view not having any issue. Then try the following steps

Right click the project ---> maven --> update maven

C# Collection was modified; enumeration operation may not execute

The error tells you EXACTLY what the problem is (and running in the debugger or reading the stack trace will tell you exactly where the problem is):

C# Collection was modified; enumeration operation may not execute.

Your problem is the loop

foreach (KeyValuePair<int, int> kvp in rankings) {
    //
}

wherein you modify the collection rankings. In particular, the offensive line is

rankings[kvp.Key] = rankings[kvp.Key] + 4;

Before you enter the loop, add the following line:

var listOfRankingsToModify = new List<int>();

Replace the offending line with

listOfRankingsToModify.Add(kvp.Key);

and after you exit the loop

foreach(var key in listOfRankingsToModify) {
    rankings[key] = rankings[key] + 4;
}

That is, record what changes you need to make, and make them without iterating over the collection that you need to modify.

Rails has_many with alias name

To complete @SamSaffron's answer :

You can use class_name with either foreign_key or inverse_of. I personally prefer the more abstract declarative, but it's really just a matter of taste :

class BlogPost
  has_many :images, class_name: "BlogPostImage", inverse_of: :blog_post  
end

and you need to make sure you have the belongs_to attribute on the child model:

class BlogPostImage
  belongs_to :blog_post
end

How to append a char to a std::string?

Try the += operator link text, append() method link text, or push_back() method link text

The links in this post also contain examples of how to use the respective APIs.

What does !important mean in CSS?

It means, essentially, what it says; that 'this is important, ignore subsequent rules, and any usual specificity issues, apply this rule!'

In normal use a rule defined in an external stylesheet is overruled by a style defined in the head of the document, which, in turn, is overruled by an in-line style within the element itself (assuming equal specificity of the selectors). Defining a rule with the !important 'attribute' (?) discards the normal concerns as regards the 'later' rule overriding the 'earlier' ones.

Also, ordinarily, a more specific rule will override a less-specific rule. So:

a {
    /* css */
}

Is normally overruled by:

body div #elementID ul li a {
    /* css */
}

As the latter selector is more specific (and it doesn't, normally, matter where the more-specific selector is found (in the head or the external stylesheet) it will still override the less-specific selector (in-line style attributes will always override the 'more-', or the 'less-', specific selector as it's always more specific.

If, however, you add !important to the less-specific selector's CSS declaration, it will have priority.

Using !important has its purposes (though I struggle to think of them), but it's much like using a nuclear explosion to stop the foxes killing your chickens; yes, the foxes will be killed, but so will the chickens. And the neighbourhood.

It also makes debugging your CSS a nightmare (from personal, empirical, experience).

jQuery - Add active class and remove active from other element on click

You alread removed the active class from all the tabs but then you add the active class, again, to all the tabs. You should only add the active class to the currently selected tab like so http://jsfiddle.net/QFnRa/

$(".tab").removeClass("active");
$(this).addClass("active");  

Yes/No message box using QMessageBox

If you want to make it in python you need check this code in your workbench. also write like this. we created a popup box with python.

msgBox = QMessageBox()
msgBox.setText("The document has been modified.")
msgBox.setInformativeText("Do you want to save your changes?")
msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
msgBox.setDefaultButton(QMessageBox.Save)
ret = msgBox.exec_()

Local and global temporary tables in SQL Server

  • Table variables (DECLARE @t TABLE) are visible only to the connection that creates it, and are deleted when the batch or stored procedure ends.

  • Local temporary tables (CREATE TABLE #t) are visible only to the connection that creates it, and are deleted when the connection is closed.

  • Global temporary tables (CREATE TABLE ##t) are visible to everyone, and are deleted when all connections that have referenced them have closed.

  • Tempdb permanent tables (USE tempdb CREATE TABLE t) are visible to everyone, and are deleted when the server is restarted.

Select objects based on value of variable in object using jq

Just try this one as a full copy paste in the shell and you will grasp it

# create the example file to  be working on .. 
cat << EOF > tmp.json
[  
 { "card_id": "id-00", "card_id_type": "card_id_type-00"},
 {"card_id": "id-01", "card_id_type": "card_id_type-01"},
 {  "card_id": "id-02", "card_id_type": "card_id_type-02"}
]
EOF


# pipe the content of the file to the  jq query, which gets the array of objects
# and select the attribute named "card_id" ONLY if it's neighbour attribute
# named "card_id_type" has the "card_id_type-01" value
# jq -r means give me ONLY the value of the jq query no quotes aka raw
cat tmp.json | jq -r '.[]| select (.card_id_type == "card_id_type-01")|.card_id'

id-01

or with an aws cli command

 # list my vpcs or
 # list the values of the tags which names are "Name" 
 aws ec2 describe-vpcs | jq -r '.| .Vpcs[].Tags[]|select (.Key == "Name") | .Value'|sort  -nr

How can I convert a Word document to PDF?

unoconv, it's a python tool worked in UNIX. While I use Java to invoke the shell in UNIX, it works perfect for me. My source code : UnoconvTool.java. Both JODConverter and unoconv are said to use open office/libre office.

docx4j/docxreport, POI, PDFBox are good but they are missing some formats in conversion.

Is there an easy way to strike through text in an app widget?

To do it programatically in a textview, untested in other views >>

TextView tv = (TextView) findViewById(R.id.mytext);
tv.setText("This is strike-thru");
tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

ESLint - "window" is not defined. How to allow global variables in package.json

If you are using Angular you can get it off with:

"env": {
    "browser": true,
    "node": true
},
"rules" : {
    "angular/window-service": 0
 }

NumPy array is not JSON serializable

I had a similar problem with a nested dictionary with some numpy.ndarrays in it.

def jsonify(data):
    json_data = dict()
    for key, value in data.iteritems():
        if isinstance(value, list): # for lists
            value = [ jsonify(item) if isinstance(item, dict) else item for item in value ]
        if isinstance(value, dict): # for nested lists
            value = jsonify(value)
        if isinstance(key, int): # if key is integer: > to string
            key = str(key)
        if type(value).__module__=='numpy': # if value is numpy.*: > to python list
            value = value.tolist()
        json_data[key] = value
    return json_data

How to enable CORS in AngularJs

I had a similar problem and for me it boiled down to adding the following HTTP headers at the response of the receiving end:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

You may prefer not to use the * at the end, but only the domainname of the host sending the data. Like *.example.com

But this is only feasible when you have access to the configuration of the server.

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

Adding one more answer for Windows users. If none of this solves the problems.

Do not add space before or after =

-DgroupId= com.company.module //Wrong , Watch the space after the equal to 
-DgroupId=com.company.module //Right 

Its better to put everything inside double quotes, like "-DgroupId=com.." This will give you exact error rather than some random error.

Weird that , maven does not even care to mention this in the documentation.

How can I get a list of all classes within current module in Python?

import pyclbr
print(pyclbr.readmodule(__name__).keys())

Note that the stdlib's Python class browser module uses static source analysis, so it only works for modules that are backed by a real .py file.

Spring MVC: how to create a default controller for index page?

The redirect is one option. One thing you can try is to create a very simple index page that you place at the root of the WAR which does nothing else but redirecting to your controller like

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:redirect url="/welcome.html"/>

Then you map your controller with that URL with something like

@Controller("loginController")
@RequestMapping(value = "/welcome.html")
public class LoginController{
...
}

Finally, in web.xml, to have your (new) index JSP accessible, declare

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

dropping rows from dataframe based on a "not in" condition

You can use Series.isin:

df = df[~df.datecolumn.isin(a)]

While the error message suggests that all() or any() can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).

You can read more about this in the Gotchas.

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

You can also try turning off the SSL option in settings, in case you are sending it through POSTMAN

How to obtain a Thread id in Python?

Similarly to @brucexin I needed to get OS-level thread identifier (which != thread.get_ident()) and use something like below not to depend on particular numbers and being amd64-only:

---- 8< ---- (xos.pyx)
"""module xos complements standard module os""" 

cdef extern from "<sys/syscall.h>":                                                             
    long syscall(long number, ...)                                                              
    const int SYS_gettid                                                                        

# gettid returns current OS thread identifier.                                                  
def gettid():                                                                                   
    return syscall(SYS_gettid)                                                                  

and

---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos

...

print 'my tid: %d' % xos.gettid()

this depends on Cython though.

sys.argv[1] meaning in script

sys.argv[1] contains the first command line argument passed to your script.

For example, if your script is named hello.py and you issue:

$ python3.1 hello.py foo

or:

$ chmod +x hello.py  # make script executable
$ ./hello.py foo

Your script will print:

Hello there foo

How to open CSV file in R when R says "no such file or directory"?

To throw out another option, why not set the working directory (preferably via a script) to the desktop using setwd('C:\John\Desktop') and then read the files just using file names

Return HTML content as a string, given URL. Javascript Function

Here's a version of the accepted answer that 1) returns a value from the function (bugfix), and 2) doesn't break when using "use strict";

I use this code to pre-load a .txt file into my <textarea> when the user loads the page.

function httpGet(theUrl)
{
    let xmlhttp;
    
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();
    
    return xmlhttp.response;
}

How do I strip all spaces out of a string in PHP?

If you know the white space is only due to spaces, you can use:

$string = str_replace(' ','',$string); 

But if it could be due to space, tab...you can use:

$string = preg_replace('/\s+/','',$string);

Cannot access wamp server on local network

If you are using wamp stack, it will be fixed by open port in Firewall (Control Pannel). It work for my case (detail how to open port 80: https://tips.alocentral.com/open-tcp-port-80-in-windows-firewall/)

Oracle SqlDeveloper JDK path

For those who use Mac, edit this file:

/Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh

Mine had:

export JAVA_HOME=`/usr/libexec/java_home -v 1.7`

and I changed it to 1.8 and it stopped complaining about java version.

How to validate phone numbers using regex

    pattern="^[\d|\+|\(]+[\)|\d|\s|-]*[\d]$" 
    validateat="onsubmit"

Must end with a digit, can begin with ( or + or a digit, and may contain + - ( or )

How to preSelect an html dropdown list with php?

I use inline if's

($_POST['category'] == $data['id'] ? 'selected="selected"' : false)

Editing the git commit message in GitHub

For intellij users: If you want to make changes in interactive way for past commits, which are not pushed follow below steps in Intellij:

  • Select Version Control
  • Select Log
  • Right click the commit for which you want to amend comment
  • Click reword
  • Done

Hope it helps

How do you share code between projects/solutions in Visual Studio?

There is a very good case for using "adding existing file links" when reusing code across projects, and that is when you need to reference and support different versions of dependent libraries.

Making multiple assemblies with references to different external assemblies isn't easy to do otherwise without duplicating your code, or utilizing tricks with source code control.

I believe that it's easiest to maintain one project for development and unit test, then to create 'build' projects using existing file links when you need to create the assemblies which reference different versions of those external assemblies.

How to urlencode a querystring in Python?

If the urllib.parse.urlencode( ) is giving you errors , then Try the urllib3 module .

The syntax is as follows :

import urllib3
urllib3.request.urlencode({"user" : "john" }) 

How to empty the message in a text area with jquery?

$('#message').val('');

Explanation (from @BalusC):
textarea is an input element with a value. You actually want to "empty" the value. So as for every other input element (input, select, textarea) you need to use element.val('');.

Also see docs

Change New Google Recaptcha (v2) Width

.g-recaptcha{
    -moz-transform:scale(1.1);
    -ms-transform:scale(1.1); 
    -o-transform:scale(1.1); 
    -moz-transform-origin:0; 
    -ms-transform-origin:0;
    -o-transform-origin:0;
    -webkit-transform:scale(1.1);
    transform:scale(1.1);
    -webkit-transform-origin:0 0;
    transform-origin:0;
    filter: progid:DXImageTransform.Microsoft.Matrix(M11=1.1,M12=0,M21=0,M22=1.1,SizingMethod='auto expand');
}

xml.LoadData - Data at the root level is invalid. Line 1, position 1

if we are using XDocument.Parse(@""). Use @ it resolves the issue.

Why use argparse rather than optparse?

As of python 2.7, optparse is deprecated, and will hopefully go away in the future.

argparse is better for all the reasons listed on its original page (https://code.google.com/archive/p/argparse/):

  • handling positional arguments
  • supporting sub-commands
  • allowing alternative option prefixes like + and /
  • handling zero-or-more and one-or-more style arguments
  • producing more informative usage messages
  • providing a much simpler interface for custom types and actions

More information is also in PEP 389, which is the vehicle by which argparse made it into the standard library.

SQL Server String or binary data would be truncated

I had a similar issue. I was copying data from one table to an identical table in everything but name.

Eventually I dumped the source table into a temp table using a SELECT INTO statement.

SELECT *
INTO TEMP_TABLE
FROM SOURCE_TABLE;

I compared the schema of the source table to temp table. I found one of the columns was a varchar(4000) when I was expecting a varchar(250).

UPDATE: The varchar(4000) issue can be explained here in case you are interested:

For Nvarchar(Max) I am only getting 4000 characters in TSQL?

Hope this helps.

Notepad++ Regular expression find and delete a line

Using the "Replace all" functionality, you can delete a line directly by ending your pattern with:

  • If your file have linux (LF) line ending : $\n?
  • If your file have windows (CRLF) line ending : $(\r\n)?

For instance, in your case :

.*#RedirectMatch Permanent.*$\n?

MVC [HttpPost/HttpGet] for Action

In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution

[AcceptVerbs(WebRequestMethods.Http.Get, WebRequestMethods.Http.Post)]
public IHttpActionResult Login()
{
   // Login logic
}

How to throw std::exceptions with variable messages?

Ran into a similar issue, in that creating custom error messages for my custom exceptions make ugly code. This was my solution:

class MyRunTimeException: public std::runtime_error
{
public:
      MyRunTimeException(const std::string &filename):std::runtime_error(GetMessage(filename)) {}
private:
      static std::string GetMessage(const std::string &filename)
     {
           // Do your message formatting here. 
           // The benefit of returning std::string, is that the compiler will make sure the buffer is good for the length of the constructor call
           // You can use a local std::ostringstream here, and return os.str()
           // Without worrying that the memory is out of scope. It'll get copied
           // You also can create multiple GetMessage functions that take all sorts of objects and add multiple constructors for your exception
     }
}

This separates the logic for creating the messages. I had originally thought about overriding what(), but then you have to capture your message somewhere. std::runtime_error already has an internal buffer.

How to make program go back to the top of the code instead of closing

Python, like most modern programming languages, does not support "goto". Instead, you must use control functions. There are essentially two ways to do this.

1. Loops

An example of how you could do exactly what your SmallBasic example does is as follows:

while True :
    print "Poo"

It's that simple.

2. Recursion

def the_func() :
   print "Poo"
   the_func()

the_func()

Note on Recursion: Only do this if you have a specific number of times you want to go back to the beginning (in which case add a case when the recursion should stop). It is a bad idea to do an infinite recursion like I define above, because you will eventually run out of memory!

Edited to Answer Question More Specifically

#Alan's Toolkit for conversions

invalid_input = True
def start() :
    print ("Welcome to the converter toolkit made by Alan.")
    op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
    if op == "1":
        #stuff
        invalid_input = False # Set to False because input was valid


    elif op == "2":
        #stuff
        invalid_input = False # Set to False because input was valid
    elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
        #stuff
        invalid_input = False # Set to False because input was valid
    else:
        print ("Sorry, that was an invalid command!")

while invalid_input : # this will loop until invalid_input is set to be True
    start()

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Just open the R(software) and copy and paste

system("defaults write org.R-project.R force.LANG en_US.UTF-8")

Hope this will work fine or use the other method

open(on mac): Utilities/Terminal copy and paste

defaults write org.R-project.R force.LANG en_US.UTF-8

and close both terminal and R and reopen R.

syntaxerror: unexpected character after line continuation character in python

You need to quote that filename:

f = open("D\\python\\HW\\2_1 - Copy.cp", "r")

Otherwise the bare backslash after the D is interpreted as a line-continuation character, and should be followed by a newline. This is used to extend long expressions over multiple lines, for readability:

print "This is a long",\
      "line of text",\
      "that I'm printing."

Also, you shouldn't have semicolons (;) at the end of your statements in Python.

Regular expression for excluding special characters

I strongly suspect it's going to be easier to come up with a list of the characters that ARE allowed vs. the ones that aren't -- and once you have that list, the regex syntax becomes quite straightforward. So put me down as another vote for "whitelist".

Passing 'this' to an onclick event

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

How does the "this" keyword work?

What is Java String interning?

There are some "catchy interview" questions, such as why you get equals! if you execute the below piece of code.

String s1 = "testString";
String s2 = "testString";
if(s1 == s2) System.out.println("equals!");

If you want to compare Strings you should use equals(). The above will print equals because the testString is already interned for you by the compiler. You can intern the strings yourself using intern method as is shown in previous answers....

How to use bitmask?

Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value.

An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this:

RRRR RGGG GGGB BBBB

You could then use bit masking to retrieve the colour components as follows:

  const unsigned short redMask   = 0xF800;
  const unsigned short greenMask = 0x07E0;
  const unsigned short blueMask  = 0x001F;

  unsigned short lightGray = 0x7BEF;

  unsigned short redComponent   = (lightGray & redMask) >> 11;
  unsigned short greenComponent = (lightGray & greenMask) >> 5;
  unsigned short blueComponent =  (lightGray & blueMask);

How to detect IE11?

I'm using a simpler method:

The navigator global object has a property touchpoints, in Internet Exlorer 11 is called msMaxTouchPoints tho.

So if you look for:

navigator.msMaxTouchPoints !== void 0 

You will find Internet Explorer 11.

How to remove a character at the end of each line in unix

You can use sed:

sed 's/,$//' file > file.nocomma

and to remove whatever last character:

sed 's/.$//' file > file.nolast

How to create a thread?

public class ThreadParameter
        {
            public int Port { get; set; }
            public string Path { get; set; }
        }


Thread t = new Thread(new ParameterizedThreadStart(Startup));
t.Start(new ThreadParameter() { Port = port, Path = path});

Create an object with the port and path objects and pass it to the Startup method.

ModuleNotFoundError: What does it mean __main__ is not a package?

If you have created directory and sub-directory, follow the steps below and please keep in mind all directory must have __init__.py to get it recognized as a directory.

  1. In your script, include import sys and sys.path, you will be able to see all the paths available to Python. You must be able to see your current working directory.

  2. Now import sub-directory and respective module that you want to use using: import subdir.subdir.modulename as abc and now you can use the methods in that module.

enter image description here

As an example, you can see in this screenshot I have one parent directory and two sub-directories and under second sub-directories I have the module CommonFunction. On the right my console shows that after execution of sys.path, I can see my working directory.

Create a dropdown component

Hope this will help to someone. Works fine in Angular 6 with reactive forms. Can operate by keyboard too.

dropdown.component.html

<div class="dropdown-wrapper {{className}} {{isFocused ? 'focus':''}}" [ngClass]="{'is-open':isOpen, 'disabled':isReadOnly}" *ngIf="options" (contextmenu)="$event.stopPropagation();">
  <div class="box" (click)="toggle($event)">
    <ng-container>
      <div class="dropdown-selected" *ngIf="isSelectedValue" l10nTranslate><span>{{options[selected]}}</span></div>
      <div class="dropdown-selected" *ngIf="!isSelectedValue" l10nTranslate><span>{{placeholder}}</span></div>
    </ng-container>
  </div>

  <ul class="dropdown-options" *ngIf="options">
    <li *ngIf="placeholder" (click)="$event.stopPropagation()">{{placeholder}}</li>
    <ng-container>
      <li id="li{{i}}"
        *ngFor="let option of options; let i = index"
        [class.active]="selected === i"
        (click)="optionSelect(option, i, $event)"
        l10nTranslate
      >
        {{option}}
      </li>
    </ng-container>

  </ul>
</div>

dropdown.component.scss

@import "../../../assets/scss/variables";

// DROPDOWN STYLES
.dropdown-wrapper {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    border: 1px solid #DDDDDD;
    border-radius: 3px;
    cursor: pointer;
    position: relative;
    &.focus{
        border: 1px solid #a8a8a8;
    }
    .box {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        width: 100%;
    } 

    // SELECTED
    .dropdown-selected {
        height: 30px;
        position: relative;
        padding: 10px 30px 10px 10px;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-align: center;
            -ms-flex-align: center;
                align-items: center;
        width: 100%;
        font-size: 12px;
        color: #666666;
        overflow: hidden;
        background-color: #fff;
        &::before {
            content: "";
            position: absolute;
            top: 50%;
            right: 5px;
            -webkit-transform: translateY(-50%);
                    transform: translateY(-50%);
            width: 22px;
            height: 22px;
            background: url('/assets/i/dropdown-open-selector.svg');
            background-size: 22px 22px;
        }
        span {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    } 

    // DROPDOWN OPTIONS
    .dropdown-options {
        display: none;
        position: absolute;
        padding: 8px 6px 9px 5px;
        max-height: 261px;
        overflow-y: auto;
        z-index: 999;
        li {
            padding: 10px 25px 10px 10px;
            font-size: $regular-font-size;
            color: $content-text-black;
            position: relative;
            line-height: 10px;
            &:last-child {
                border-bottom: none;
            }
            &:hover {
                background-color: #245A88;
                border-radius: 3px;
                color: #fff;
                border-bottom-color: transparent;
            }
            &:focus{
                background-color: #245A88;
                border-radius: 3px;
                color: #fff;
            }
            &.active {
                background-color: #245A88;
                border-radius: 3px;
                color: #fff;
                border-bottom-color: transparent;
            }
            &:hover {
                background-color: #7898B3
            }
            &.active {
                font-weight: 600;
            }
        }
    }
    &.is-open {
        .dropdown-selected {
            &::before {
                content: "";
                position: absolute;
                top: 50%;
                right: 5px;
                -webkit-transform: translateY(-50%);
                        transform: translateY(-50%);
                width: 22px;
                height: 22px;
                background: url('/assets/i/dropdown-close-selector.svg');
                background-size: 22px 22px;
            }
        }
        .dropdown-options {
            display: -webkit-box;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-orient: vertical;
            -webkit-box-direction: normal;
                -ms-flex-direction: column;
                    flex-direction: column;
            width: 100%;
            top: 32px;
            border-radius: 3px;
            background-color: #ffffff;
            border: 1px solid #DDDDDD;
            -webkit-box-shadow: 0px 3px 11px 0 rgba(1, 2, 2, 0.14);
                    box-shadow: 0px 3px 11px 0 rgba(1, 2, 2, 0.14);
        }
    }
    &.data-input-fields {
        .box {
            height: 35px;
        }
    }
    &.send-email-table-select {
        min-width: 140px;
        border: none;
    }
    &.persoanal-settings {
        width: 80px;
    }
}

div.dropdown-wrapper.disabled
{
  pointer-events: none;
  background-color: #F1F1F1;
  opacity: 0.7;
}

dropdown.component.ts

import { Component, OnInit, Input, Output, EventEmitter, HostListener, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

const noop = () => {
};

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => DropdownComponent),
  multi: true
};

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss'],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class DropdownComponent implements OnInit, ControlValueAccessor {

  @Input() options: Array<string>;
  @Input() selected: number;
  @Input() className: string;
  @Input() placeholder: string;
  @Input() isReadOnly = false;
  @Output() optSelect = new EventEmitter();
  isOpen = false;
  selectedOption;


  private onTouchedCallback: () => void = noop;
  private onChangeCallback: (_: any) => void = noop;
  isSelectedValue: boolean;
  key: string;
  isFocused: boolean;

  /**
   *Creates an instance of DropdownComponent.
   * @memberof DropdownComponent
   */

  ngOnInit() {
    // Place default value in dropdown
    if (this.selected) {
      this.placeholder = '';
      this.isOpen = false;
    }
  }

  @HostListener('focus')
  focusHandler() {
    this.selected = 0;
    this.isFocused = true;
  }

  @HostListener('focusout')
  focusOutHandler() {
    this.isFocused = false;
  }

  @HostListener('document:keydown', ['$event'])
  keyPressHandle(event: KeyboardEvent) {

    if (this.isFocused) {
      this.key = event.code;
      switch (this.key) {
        case 'Space':
          this.isOpen = true;
          break;
        case 'ArrowDown':
          if (this.options.length - 1 > this.selected) {
            this.selected = this.selected + 1;
          }
          break;
        case 'ArrowUp':
          if (this.selected > 0) {
            this.selected = this.selected - 1;
          }
          break;
        case 'Enter':
          if (this.selected > 0) {
            this.isSelectedValue = true;
            this.isOpen = false;
            this.onChangeCallback(this.selected);
            this.optSelect.emit(this.options[this.selected]);
          }
          break;
      }
    }

  }

  /**
  * option selection
  * @param {string} selectedOption - text
  * @param {number} idx - current index of item
  * @param {any} event - object
  */
  optionSelect(selectedOption: string, idx, e: any) {
    e.stopPropagation();
    this.selected = idx;
    this.isSelectedValue = true;
    // this.placeholder = '';
    this.isOpen = false;
    this.onChangeCallback(this.selected);
    this.optSelect.emit(selectedOption);
  }

  /**
  * toggle the dropdown
  * @param {any} event object
  */
  toggle(e: any) {
    e.stopPropagation();
    // close all previously opened dropdowns, before open
    const allElems = document.querySelectorAll('.dropdown-wrapper');
    for (let i = 0; i < allElems.length; i++) {
      allElems[i].classList.remove('is-open');
    }
    this.isOpen = !this.isOpen;
    if (this.selected >= 0) {
      document.querySelector('#li' + this.selected).scrollIntoView(true);
    }
  }

  /**
  * dropdown click on outside
  */
  @HostListener('document: click', ['$event'])
  onClick() {
    this.isOpen = false;
  }

  /**
   * Method implemented from ControlValueAccessor and set default selected value
   * @param {*} obj
   * @memberof DropdownComponent
   */
  writeValue(obj: any): void {
    if (obj && obj !== '') {
      this.isSelectedValue = true;
      this.selected = obj;
    } else {
      this.isSelectedValue = false;
    }
  }

  // From ControlValueAccessor interface
  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  // From ControlValueAccessor interface
  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }

  setDisabledState?(isDisabled: boolean): void {

  }

}

Usage

<app-dropdown formControlName="type" [options]="types" [placeholder]="captureData.type" [isReadOnly]="isReadOnly">
</app-dropdown>

Options must bind an array as follows. It can change based on the requirement.

types= [
        {
            "id": "1",
            "value": "Type 1"
        },
        {
             "id": "2",
             "value": "Type 2"
        },
        {
              "id": "3",
              "value": "Type 3"
        }] 

How do I get the name of the active user via the command line in OS X?

The question has not been completely answered, IMHO. I will try to explain: I have a crontab entry that schedules a bash shell command procedure, that in turn does some cleanup of my files; and, when done, sends a notification to me using the OS X notification center (with the command osascript -e 'display notification ...). If someone (e.g. my wife or my daughter) switches the current user of the computer to her, leaving me in the background, the cron script fails when sending the notification.

So, Who is the current user means Has some other people become the effective user leaving me in the background? Do stat -f "%Su" /dev/console returns the current active user name?

The answer is yes; so, now my crontab shell script has been modified in the following way:

...
if [ "$(/usr/bin/stat -f ""%Su"" /dev/console)" = "loreti" ]
then /usr/bin/osascript -e \
  'display notification "Cleanup done" sound name "sosumi" with title "myCleanup"'
fi

How can I git stash a specific file?

EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>. For example:

git stash push -m welcome_cart app/views/cart/welcome.thtml

OLD ANSWER:

You can do that using git stash --patch (or git stash -p) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n to skip the files that you don't want to stash, y when you encounter the one that you want to stash, and q to quit and leave the remaining hunks unstashed. a will stash the shown hunk and the rest of the hunks in that file.

Not the most user-friendly approach, but it gets the work done if you really need it.

Maven: add a folder or jar file into current classpath

This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?

In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.

See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html

Display two fields side by side in a Bootstrap Form

Bootstrap 3.3.7:

Use form-inline.

It only works on screen resolutions greater than 768px though. To test the snippet below make sure to click the "Expand snippet" link to get a wider viewing area.

_x000D_
_x000D_
        <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>_x000D_
        <form class="form-inline">_x000D_
            <input type="text" class="form-control"/>-<input type="text" class="form-control"/>_x000D_
        </form>
_x000D_
_x000D_
_x000D_

Reference: https://getbootstrap.com/docs/3.3/css/#forms-inline

How to place two divs next to each other?

Having two divs,

<div id="div1">The two divs are</div>
<div id="div2">next to each other.</div>

you could also use the display property:

#div1 {
    display: inline-block;
}

#div2 {
    display: inline-block;
}

jsFiddle example here.

If div1 exceeds a certain height, div2 will be placed next to div1 at the bottom. To solve this, use vertical-align:top; on div2.

jsFiddle example here.

Laravel Advanced Wheres how to pass variable into function?

If you are using Laravel eloquent you may try this as well.

$result = self::select('*')
                    ->with('user')
                    ->where('subscriptionPlan', function($query) use($activated){
                        $query->where('activated', '=', $roleId);
                    })
                    ->get();

MySQL Removing Some Foreign keys

You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

SHOW CREATE TABLE region; This should show you a row ,at left upper corner click the +option ,the click the full text raio button then click the go .there you will get the name of the index, something like this:

CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION Now simply issue an:

alter table region drop foreign key region_ibfk_1;

or

more simply just type:- alter table TableName drop foreign key TableName_ibfk_1;

remember the only thing is to add _ibfk_1 after your tablename to make like this:- TableName_ibfk_1

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

This solution will allow you to load a local script using jQuery.getScript(). This is a global setting but you can also set the crossDomain option on a per-request basis.

$.ajaxPrefilter( "json script", function( options ) {
  options.crossDomain = true;
});

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Gotcha!

You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here My Example.

MasterPage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
    Inherits="prueba.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">

        function confirmCallBack() {
            var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');

            alert(a.value);

        }

    </script>

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

WebForm1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace prueba
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);

        }
    }
}

Navigation Drawer (Google+ vs. YouTube)

Personally I like the navigationDrawer in Google Drive official app. It just works and works great. I agree that the navigation drawer shouldn't move the action bar because is the key point to open and close the navigation drawer.

If you are still trying to get that behavior I recently create a project Called SherlockNavigationDrawer and as you may expect is the implementation of the Navigation Drawer with ActionBarSherlock and works for pre Honeycomb devices. Check it:

SherlockNavigationDrawer github

Slick.js: Get current and total slides (ie. 3/5)

I had an issue with multiple slides. version 1.8.1

if slidesToShow and slidesToScroll more than 1

trick is in slick.slickGetOption('slidesToShow');

$(".your-selector").on('init reInit afterChange', function(event, slick, currentSlide, nextSlide){
    var i = (currentSlide ? currentSlide : 0) + 1;
    var slidesToShow = slick.slickGetOption('slidesToShow');
    var curPage = parseInt((i-1)/slidesToShow) + 1;
    var lastPage =  parseInt((slick.slideCount-1)/slidesToShow) + 1;
    $('.your-selector').text(curPage);
    $('.your-selector').text(lastPage);
});

Note curPage and lastPage is separate. I had to color them differently.

Based on top-voted answer

Twitter Bootstrap 3: How to center a block

center-block can be found in bootstrap 3.0 in utilities.less on line 12 and mixins.less on line 39

How to correct TypeError: Unicode-objects must be encoded before hashing?

If it's a single line string. wrapt it with b or B. e.g:

variable = b"This is a variable"

or

variable2 = B"This is also a variable"

Histogram using gnuplot?

Different number of bins on the same dataset can reveal different features of the data.

Unfortunately, there is no universal best method that can determine the number of bins.

One of the powerful methods is the Freedman–Diaconis rule, which automatically determines the number of bins based on statistics of a given dataset, among many other alternatives.

Accordingly, the following can be used to utilise the Freedman–Diaconis rule in a gnuplot script:

Say you have a file containing a single column of samples, samplesFile:

# samples
0.12345
1.23232
...

The following (which is based on ChrisW's answer) may be embed into an existing gnuplot script:

...
## preceeding gnuplot commands
...

#
samples="$samplesFile"
stats samples nooutput
N = floor(STATS_records)
samplesMin = STATS_min
samplesMax = STATS_max
# Freedman–Diaconis formula for bin-width size estimation
    lowQuartile = STATS_lo_quartile
    upQuartile = STATS_up_quartile
    IQR = upQuartile - lowQuartile
    width = 2*IQR/(N**(1.0/3.0))
    bin(x) = width*(floor((x-samplesMin)/width)+0.5) + samplesMin

plot \
    samples u (bin(\$1)):(1.0/(N*width)) t "Output" w l lw 1 smooth freq 

How do I commit only some files?

This is a simple approach if you don't have much code changes:

1. git stash
2. git stash apply
3. remove the files/code you don't want to commit
4. commit the remaining files/code you do want

Then if you want the code you removed (bits you didn't commit) in a separate commit or another branch, then while still on this branch do:

5. git stash apply
6. git stash

With step 5 as you already applied the stash and committed the code you did want in step 4, the diff and untracked in the newly applied stash is just the code you removed in step 3 before you committed in step 4.

As such step 6 is a stash of the code you didn't [want to] commit, as you probably don't really want to lose those changes right? So the new stash from step 6 can now be committed to this or any other branch by doing git stash apply on the correct branch and committing.

Obviously this presumes you do the steps in one flow, if you stash at any other point in these steps you'll need to note the stash ref for each step above (rather than just basic stash and apply the most recent stash).

Conditional Formatting (IF not empty)

This method works for Excel 2016, and calculates on cell value, so can be used on formula arrays (i.e. it will ignore blank cells that contain a formula).

  • Highlight the range.
  • Home > Conditional Formatting > New Rule > Use a Formula.
  • Enter "=LEN(#)>0" (where '#' is the upper-left-most cell in your range).
  • Alter the formatting to suit your preference.

Note: Len(#)>0 be altered to only select cell values above a certain length.

Note 2: '#' must not be an absolute reference (i.e. shouldn't contain '$').

Install mysql-python (Windows)

There are windows installers for MySQLdb avaialable for both 32 and 64 bit, supporting Python from 2.6 to 3.4. Check here.

How to count objects in PowerShell?

in my exchange the cmd-let you presented did not work, the answer was null, so I had to make a little correction and worked fine for me:

@(get-transportservice | get-messagetrackinglog -Resultsize unlimited -Start "MM/DD/AAAA HH:MM" -End "MM/DD/AAAA HH:MM" -recipients "[email protected]" | where {$_.Event
ID -eq "DELIVER"}).count

Sql query to insert datetime in SQL Server

A more language-independent choice for string literals is the international standard ISO 8601 format "YYYY-MM-DDThh:mm:ss". I used the SQL query below to test the format, and it does indeed work in all SQL languages in sys.syslanguages:

declare @sql nvarchar(4000)

declare @LangID smallint
declare @Alias sysname

declare @MaxLangID smallint
select @MaxLangID = max(langid) from sys.syslanguages

set @LangID = 0

while @LangID <= @MaxLangID
begin

    select @Alias = alias
    from sys.syslanguages
    where langid = @LangID

    if @Alias is not null
    begin

        begin try
            set @sql = N'declare @TestLang table (langdate datetime)
    set language ''' + @alias + N''';
    insert into @TestLang (langdate)
    values (''2012-06-18T10:34:09'')'
            print 'Testing ' + @Alias

            exec sp_executesql @sql
        end try
        begin catch
            print 'Error in language ' + @Alias
            print ERROR_MESSAGE()
        end catch
    end

    select @LangID = min(langid)
    from sys.syslanguages
    where langid > @LangID
end

According to the String Literal Date and Time Formats section in Microsoft TechNet, the standard ANSI Standard SQL date format "YYYY-MM-DD hh:mm:ss" is supposed to be "multi-language". However, using the same query, the ANSI format does not work in all SQL languages.

For example, in Danish, you will many errors like the following:

Error in language Danish The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

If you want to build a query in C# to run on SQL Server, and you need to pass a date in the ISO 8601 format, use the Sortable "s" format specifier:

string.Format("select convert(datetime2, '{0:s}'", DateTime.Now);

How do I get list of methods in a Python class?

Say you want to know all methods associated with list class Just Type The following

 print (dir(list))

Above will give you all methods of list class

What is Ad Hoc Query?

Ad hoc queries are those that are not already defined that are not needed on a regular basis, so they're not included in the typical set of reports or queries

Split string into array

You can try this:

var entryArray = Array.prototype.slice.call(entry)

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

Find max and second max salary for a employee table MySQL

select 
    e.salary
        from(
           SELECT * FROM 
           Employee 
             group by salary
             order by salary desc
             limit 2
          ) e
     order by salary asc
     limit 1;

Generating a PNG with matplotlib when DISPLAY is undefined

The clean answer is to take a little bit of time correctly prepare your execution environment.

The first technique you have to prepare your execution environment is to use a matplotlibrc file, as wisely recommended by Chris Q., setting

backend : Agg

in that file. You can even control — with no code changes — how and where matplotlib looks for and finds the matplotlibrc file.

The second technique you have to prepare your execution environment is to use the MPLBACKEND environment variable (and inform your users to make use of it):

export MPLBACKEND="agg"
python <program_using_matplotlib.py>

This is handy because you don't even have to provide another file on disk to make this work. I have employed this approach with, for example, testing in continuous integration, and running on remote machines that do not have displays.

Hard-coding your matplotlib backend to "Agg" in your Python code is like bashing a square peg into a round hole with a big hammer, when, instead, you could have just told matplotlib it needs to be a square hole.

Difference between Fact table and Dimension table?

This is to answer the part:

I was trying to understand whether dimension tables can be fact table as well or not?

The short answer (INMO) is No.That is because the 2 types of tables are created for different reasons. However, from a database design perspective, a dimension table could have a parent table as the case with the fact table which always has a dimension table (or more) as a parent. Also, fact tables may be aggregated, whereas Dimension tables are not aggregated. Another reason is that fact tables are not supposed to be updated in place whereas Dimension tables could be updated in place in some cases.

More details:

Fact and dimension tables appear in a what is commonly known as a Star Schema. A primary purpose of star schema is to simplify a complex normalized set of tables and consolidate data (possibly from different systems) into one database structure that can be queried in a very efficient way.

On its simplest form, it contains a fact table (Example: StoreSales) and a one or more dimension tables. Each Dimension entry has 0,1 or more fact tables associated with it (Example of dimension tables: Geography, Item, Supplier, Customer, Time, etc.). It would be valid also for the dimension to have a parent, in which case the model is of type "Snow Flake". However, designers attempt to avoid this kind of design since it causes more joins that slow performance. In the example of StoreSales, The Geography dimension could be composed of the columns (GeoID, ContenentName, CountryName, StateProvName, CityName, StartDate, EndDate)

In a Snow Flakes model, you could have 2 normalized tables for Geo information, namely: Content Table, Country Table.

You can find plenty of examples on Star Schema. Also, check this out to see an alternative view on the star schema model Inmon vs. Kimball. Kimbal has a good forum you may also want to check out here: Kimball Forum.

Edit: To answer comment about examples for 4NF:

  • Example for a fact table violating 4NF:

Sales Fact (ID, BranchID, SalesPersonID, ItemID, Amount, TimeID)

  • Example for a fact table not violating 4NF:

AggregatedSales (BranchID, TotalAmount)

Here the relation is in 4NF

The last example is rather uncommon.

Outline radius?

There is the solution if you need only outline without border. It's not mine. I got if from Bootstrap css file. If you specify outline: 1px auto certain_color, you'll get thin outer line around div of certain color. In this case the specified width has no matter, even if you specify 10 px width, anyway it will be thin line. The key word in mentioned rule is "auto".
If you need outline with rounded corners and certain width, you may add css rule on border with needed width and same color. It makes outline thicker.

AFNetworking Post Request

For AFNetworking 4

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
                         @"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params headers:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

Break when a value changes using the Visual Studio debugger

Imagine you have a class called A with the following declaration.

class A  
{  
    public:  
        A();

    private:
        int m_value;
};

You want the program to stop when someone modifies the value of "m_value".

Go to the class definition and put a breakpoint in the constructor of A.

A::A()
{
    ... // set breakpoint here
}

Once we stopped the program:

Debug -> New Breakpoint -> New Data Breakpoint ...

Address: &(this->m_value)
Byte Count: 4 (Because int has 4 bytes)

Now, we can resume the program. The debugger will stop when the value is changed.

You can do the same with inherited classes or compound classes.

class B
{
   private:
       A m_a;
};

Address: &(this->m_a.m_value)

If you don't know the number of bytes of the variable you want to inspect, you can use the sizeof operator.

For example:

// to know the size of the word processor,  
// if you want to inspect a pointer.
int wordTam = sizeof (void* ); 

If you look at the "Call stack" you can see the function that changed the value of the variable.

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

You can't create a new branch with this command

git checkout --track origin/branch

if you have changes that are not staged.

Here is example:

$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   src/App.js

no changes added to commit (use "git add" and/or "git commit -a")

// TRY TO CREATE:

$ git checkout --track origin/new-branch
fatal: 'origin/new-branch' is not a commit and a branch 'new-branch' cannot be created from it

However you can easily create a new branch with un-staged changes with git checkout -b command:

$ git checkout -b new-branch
Switched to a new branch 'new-branch'
M       src/App.js

Check whether a variable is a string in Ruby

A more duck-typing approach would be to say

foo.respond_to?(:to_str)

to_str indicates that an object's class may not be an actual descendant of the String, but the object itself is very much string-like (stringy?).

How do I use brew installed Python as the default Python?

No idea what you mean with default Python. I consider it bad practice to replace the system Python interpreter with a different version. System functionality may depend in some way on the system Python and specific modules or a specific Python version. Instead install your custom Python installations in a safe different place and adjust your $PATH as needed in order to call you Python through a path lookup instead of looking for the default Python.

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

Setup Bitbucket Repository (Command Line with Mac)

Create New APPLICATION from starting with local reposity :

  1. Terminal -> cd ~/Documents (Paste your APPLICATION base directory path)
  2. Terminal -> mkdir (create directory with )
  3. Terminal -> cd (change directory with directory)
  4. BitBucket A/C -> create repository on bitBucket account
  5. Xcode -> create new xcode project with same name
  6. Terminal -> git init (initilize empty repo)
  7. Terminal -> git remote add origin (Ex. https://[email protected]/app/app.git)
  8. Terminal -> git add .
  9. Terminal -> git status
    1. Terminal -> git commit -m "IntialCommet"
    2. Terminal -> git push origin master

Create APPLICATION clone repository :

  1. Terminal -> mkdir (create directory with )
  2. Terminal -> cd (change directory with directory)
  3. Terminal -> git clone (Ex. https://[email protected]/app/app.git)
  4. Terminal -> cd
  5. Terminal -> git status (Show edit/updated file status)
  6. Terminal -> git pull origin master
  7. Terminal -> git add .
  8. Terminal -> git push origin master

MySQL: How to copy rows, but change a few fields?

Hey how about to copy all fields, change one of them to the same value + something else.

INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, Event_ID+"155"
  FROM Table
 WHERE Event_ID = "120"

??????????

Display TIFF image in all web browser

I found this resource that details the various methods: How to embed TIFF files in HTML documents

As mentioned, it will very much depend on browser support for the format. Viewing that page in Chrome on Windows didn't display any of the images.

It would also be helpful if you posted the code you've tried already.

Type of expression is ambiguous without more context Swift

I got this error when I put a space before a comma in the parameters when calling a function.

eg, I used:

myfunction(parameter1: parameter1 , parameter2: parameter2)

Whereas it should have been:

myfunction(parameter1: parameter1, parameter2: parameter2)

Deleting the space got rid of the error message

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

When I read in various places that hibernate didn't like you to assign to a collection, I assumed that the safest thing to do would obviously be to make it final like this:

class User {
  private final Set<Role> roles = new HashSet<>();

public void setRoles(Set<Role> roles) {
  this.roles.retainAll(roles);
  this.roles.addAll(roles);
}
}

However, this doesn't work, and you get the dreaded "no longer referenced" error, which is actually quite misleading in this case.

It turns out that hibernate calls your setRoles method AND it wants its special collection class installed here, and won't accept your collection class. This had me stumped for a LONG time, despite reading all the warnings about not assigning to your collection in your set method.

So I changed to this:

public class User {
  private Set<Role> roles = null;

  public void setRoles(Set<Role> roles) {
  if (this.roles == null) {
    this.roles = roles;
  } else {
    this.roles.retainAll(roles);
   this.roles.addAll(roles);
  }
}
}

So that on the first call, hibernate installs its special class, and on subsequent calls you can use the method yourself without wrecking everything. If you want to use your class as a bean, you probably need a working setter, and this at least seems to work.

How can I make a Python script standalone executable to run without ANY dependency?

You may like py2exe. You'll also find information in there for doing it on Linux.

XCOPY switch to create specified directory if it doesn't exist?

You could use robocopy:

robocopy "$(TargetPath)" "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules" /E

How to make HTML open a hyperlink in another window or tab?

below example with target="_blank" works for Safari and Mozilla

<a href="http://www.starfall.com" `target="_blank"`>

Using target="new"worked for Chrome

<a href="http://www.starfall.com" `target="new"`>

How does the "final" keyword in Java work? (I can still modify an object.)

  1. Since the final variable is non-static, it can be initialized in constructor. But if you make it static it can not be initialized by constructor (because constructors are not static).
  2. Addition to list is not expected to stop by making list final. final just binds the reference to particular object. You are free to change the 'state' of that object, but not the object itself.

In PHP with PDO, how to check the final SQL parametrized query?

I think easiest way to see final query text when you use pdo is to make special error and look error message. I don't know how to do that, but when i make sql error in yii framework that use pdo i could see query text

How to get all files under a specific directory in MATLAB?

I used the code mentioned in this great answer and expanded it to support 2 additional parameters which I needed in my case. The parameters are file extensions to filter on and a flag indicating whether to concatenate the full path to the name of the file or not.

I hope it is clear enough and someone will finds it beneficial.

function fileList = getAllFiles(dirName, fileExtension, appendFullPath)

  dirData = dir([dirName '/' fileExtension]);      %# Get the data for the current directory
  dirWithSubFolders = dir(dirName);
  dirIndex = [dirWithSubFolders.isdir];  %# Find the index for directories
  fileList = {dirData.name}';  %'# Get a list of the files
  if ~isempty(fileList)
    if appendFullPath
      fileList = cellfun(@(x) fullfile(dirName,x),...  %# Prepend path to files
                       fileList,'UniformOutput',false);
    end
  end
  subDirs = {dirWithSubFolders(dirIndex).name};  %# Get a list of the subdirectories
  validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
                                               %#   that are not '.' or '..'
  for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dirName,subDirs{iDir});    %# Get the subdirectory path
    fileList = [fileList; getAllFiles(nextDir, fileExtension, appendFullPath)];  %# Recursively call getAllFiles
  end

end

Example for running the code:

fileList = getAllFiles(dirName, '*.xml', 0); %#0 is false obviously

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

What is the best way to implement constants in Java?

I prefer to use getters rather than constants. Those getters might return constant values, e.g. public int getMaxConnections() {return 10;}, but anything that needs the constant will go through a getter.

One benefit is that if your program outgrows the constant--you find that it needs to be configurable--you can just change how the getter returns the constant.

The other benefit is that in order to modify the constant you don't have to recompile everything that uses it. When you reference a static final field, the value of that constant is compiled into any bytecode that references it.

Vertical Text Direction

I was searching for an actual vertical text and not the rotated text in HTML as shown below. So I could achieve it by using the following method.

enter image description here HTML:-

<p class="vericaltext">
Hi This is Vertical Text!
</p>

CSS:-

.vericaltext{
    width:1px;
    word-wrap: break-word;
    font-family: monospace; /* this is just for good looks */
}

JSFiddle! Demo.

Update:- If you need the whitespaces to be displayed, then add the following property to your css.

white-space: pre;

So, the css class shall be

.vericaltext{
    width:1px;
    word-wrap: break-word;
    font-family: monospace; /* this is just for good looks */
    white-space: pre;/* this is for displaying whitespaces */
}

JSFiddle! Demo With Whitespace

Update 2 (28-JUN-2015)

Since white-space: pre; doesnt seem to work (for this specific use) on Firefox(as of now), just change that line to

white-space: pre-wrap;

So, the css class shall be

.vericaltext{
    width:1px;
    word-wrap: break-word;
    font-family: monospace; /* this is just for good looks */
    white-space:pre-wrap; /* this is for displaying whitespaces including Moz-FF.*/
}

JsFiddle Demo FF Compatible.

jQuery Validate Plugin - How to create a simple custom rule?

// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
        return jQuery.validator.methods['date'].call(
            this,value,element
        )||value==("0000/00/00");
    }, "Please enter a valid date."
);

// connect it to a css class
jQuery.validator.addClassRules({
    optdate : { optdate : true }    
});

What is the purpose of the "role" attribute in HTML?

Is this role attribute necessary?

Answer: Yes.

  • The role attribute is necessary to support Accessible Rich Internet Applications (WAI-ARIA) to define roles in XML-based languages, when the languages do not define their own role attribute.
  • Although this is the reason the role attribute is published by the Protocols and Formats Working Group, the attribute has more general use cases as well.

It provides you:

  • Accessibility
  • Device adaptation
  • Server-side processing
  • Complex data description,...etc.

Get current folder path

I created a simple console application with the following code:

Console.WriteLine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory);
Console.WriteLine(System.Environment.CurrentDirectory);
Console.WriteLine(System.IO.Directory.GetCurrentDirectory());
Console.WriteLine(Environment.CurrentDirectory);

I copied the resulting executable to C:\temp2. I then placed a shortcut to that executable in C:\temp3, and ran it (once from the exe itself, and once from the shortcut). It gave the following outputs both times:

C:\temp2
C:\temp2\
C:\temp2
C:\temp2
C:\temp2

While I'm sure there must be some cockamamie reason to explain why there are five different methods that do virtually the exact same thing, I certainly don't know what it is. Nevertheless, it would appear that under most circumstances, you are free to choose whichever one you fancy.

UPDATE: I modified the Shortcut properties, changing the "Start In:" field to C:\temp3. This resulted in the following output:

C:\temp2
C:\temp2\
C:\temp3
C:\temp3
C:\temp3

...which demonstrates at least some of the distinctions between the different methods.

How to backup Sql Database Programmatically in C#

This worked for me...

private void BackupButtonClick(object sender, RoutedEventArgs e)
{
    // FILE NAME WITH DATE DISTICNTION
    string fileName = string.Format("SchoolBackup_{0}.bak", DateTime.Now.ToString("yyyy_MM_dd_h_mm_tt"));
    try
    {
        // YOUR SEREVER OR MACHINE NAME
        Server dbServer = new Server (new ServerConnection("DESKTOP"));
        Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
        {
            Action = BackupActionType.Database, 
            Database = "School"
        };

        dbBackup.Devices.AddDevice(@backupDirectory() +"\\"+ fileName, DeviceType.File);
        dbBackup.Initialize = true;
        dbBackup.SqlBackupAsync(dbServer);


        MessageBox.Show("Backup", "Backup Completed!");
    }
    catch(Exception err)
    {
        System.Windows.MessageBox.Show(err.ToString());
    }
}


// THE DIRECTOTRY YOU WANT TO SAVE IN
public string backupDirectory()
{
    using (var dialog = new FolderBrowserDialog())
    {
        var result = dialog.ShowDialog();
        return dialog.SelectedPath;
    }
}

Jquery mouseenter() vs mouseover()

See the example code and demo at the bottom of the jquery documentation page:

http://api.jquery.com/mouseenter/

... mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.

What is the difference between Python's list methods append and extend?

extend(L) extends the list by appending all the items in the given list L.

>>> a
[1, 2, 3]
a.extend([4])  #is eqivalent of a[len(a):] = [4]
>>> a
[1, 2, 3, 4]
a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a[len(a):] = [4]
>>> a
[1, 2, 3, 4]

get url content PHP

original answer moved to this topic .

How to make System.out.println() shorter

Using System.out.println() is bad practice (better use logging framework) -> you should not have many occurences in your code base. Using another method to simply shorten it does not seem a good option.

In Java how does one turn a String into a char or a char into a String?

char firstLetter = someString.charAt(0);
String oneLetter = String.valueOf(someChar);

You find the documentation by identifying the classes likely to be involved. Here, candidates are java.lang.String and java.lang.Character.

You should start by familiarizing yourself with:

  • Primitive wrappers in java.lang
  • Java Collection framework in java.util

It also helps to get introduced to the API more slowly through tutorials.

Using R to list all files with a specified extension

I am not very good in using sophisticated regular expressions, so I'd do such task in the following way:

files <- list.files()
dbf.files <- files[-grep(".xml", files, fixed=T)]

First line just lists all files from working dir. Second one drops everything containing ".xml" (grep returns indices of such strings in 'files' vector; subsetting with negative indices removes corresponding entries from vector). "fixed" argument for grep function is just my whim, as I usually want it to peform crude pattern matching without Perl-style fancy regexprs, which may cause surprise for me.

I'm aware that such solution simply reflects drawbacks in my education, but for a novice it may be useful =) at least it's easy.

What is the difference between Google App Engine and Google Compute Engine?

To put it simply: compute engine gives you a server which you have full control/responsibility for. You have direct access to the operating system, and you install all the software that you want, which is usually a web server, database, etc...

In app engine you don't manage the operating system of any of the underlying software. You only upload code (Java, PHP, Python, or Go) and voila - it just runs...

App engine saves tons of headache, especially for inexperienced people but it has 2 significant drawbacks: 1. more expensive (but it does have a free quota which compute engine doesn't) 2. you have less control, thus certain things are just not possible, or only possible in one specific way (for example saving and writing files).

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

Oracle - How to create a readonly user

A user in an Oracle database only has the privileges you grant. So you can create a read-only user by simply not granting any other privileges.

When you create a user

CREATE USER ro_user
 IDENTIFIED BY ro_user
 DEFAULT TABLESPACE users
 TEMPORARY TABLESPACE temp;

the user doesn't even have permission to log in to the database. You can grant that

GRANT CREATE SESSION to ro_user

and then you can go about granting whatever read privileges you want. For example, if you want RO_USER to be able to query SCHEMA_NAME.TABLE_NAME, you would do something like

GRANT SELECT ON schema_name.table_name TO ro_user

Generally, you're better off creating a role, however, and granting the object privileges to the role so that you can then grant the role to different users. Something like

Create the role

CREATE ROLE ro_role;

Grant the role SELECT access on every table in a particular schema

BEGIN
  FOR x IN (SELECT * FROM dba_tables WHERE owner='SCHEMA_NAME')
  LOOP
    EXECUTE IMMEDIATE 'GRANT SELECT ON schema_name.' || x.table_name || 
                                  ' TO ro_role';
  END LOOP;
END;

And then grant the role to the user

GRANT ro_role TO ro_user;

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

You may need to clear the plugin column for your root account. On my fresh install, all of the root user accounts had unix_socket set in the plugin column. This was causing the root sql account to be locked only to the root unix account, since only system root could login via socket.

If you update user set plugin='' where User='root';flush privileges;, you should now be able to login to the root account from any localhost unix account (with a password).

See this AskUbuntu question and answer for more details.

How to provide password to a command that prompts for one in bash?

Programs that prompt for passwords usually set the tty into "raw" mode, and read input directly from the tty. If you spawn the subprocess in a pty you can make that work. That is what Expect does...

How do I get the day month and year from a Windows cmd.exe script?

This variant works for all localizations:

@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    if "%%B" NEQ "" (
        SET /A FDATE=%%F*10000+%%D*100+%%A
    )
)
@echo on
echo date=%FDATE%
echo year=%FDATE:~2,2%
echo month=%FDATE:~4,2%

bootstrap 4 file input doesn't show the file name

Johann-S solution works great. (And it looks like he created the awesome plugin)

The Bootstrap 4.3 documentation example page uses this plugin to modify the filename: https://github.com/Johann-S/bs-custom-file-input

Use the Bootstrap custom file input classes. Add the plugin to your project, and add this code in your script file on the page.

$(document).ready(function () {
  bsCustomFileInput.init()
})

The smallest difference between 2 Angles

A simple method, which I use in C++ is:

double deltaOrientation = angle1 - angle2;
double delta =  remainder(deltaOrientation, 2*M_PI);

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

How to have Java method return generic list of any type?

You can simply cast to List and then check if every element can be casted to T.

public <T> List<T> asList(final Class<T> clazz) {
    List<T> values = (List<T>) this.value;
    values.forEach(clazz::cast);
    return values;
}

How to insert a line break before an element using CSS

Following CSS worked for me:

/* newline before element */
#myelementId:before{
    content:"\a";
    white-space: pre;
}

Code for download video from Youtube on Java, Android

3 steps:

  1. Check the sorce code (HTML) of YouTube, you'll get the link like this (http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...);

  2. Decode the url (remove the codes %2B,%25 etc), create a decoder with the codes: http://www.w3schools.com/tags/ref_urlencode.asp and use the function Uri.decode(url) to replace invalid escaped octets;

  3. Use the code to download stream:

    URL u = null;
    InputStream is = null;  
    
    try {
        u = new URL(url);
        is = u.openStream(); 
        HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
        int size = huc.getContentLength();                 
    
        if(huc != null) {
            String fileName = "FILE.mp4";
            String storagePath = Environment.getExternalStorageDirectory().toString();
            File f = new File(storagePath,fileName);
    
            FileOutputStream fos = new FileOutputStream(f);
            byte[] buffer = new byte[1024];
            int len1 = 0;
            if(is != null) {
                while ((len1 = is.read(buffer)) > 0) {
                    fos.write(buffer,0, len1);  
                }
            }
            if(fos != null) {
                fos.close();
            }
        }                       
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {               
            if(is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            // just going to ignore this one
        }
    }
    

That's all, most of stuff you'll find on the web!!!

C# Create New T()

Take a look at new Constraint

public class MyClass<T> where T : new()
{
    protected T GetObject()
    {
        return new T();
    }
}

T could be a class that does not have a default constructor: in this case new T() would be an invalid statement. The new() constraint says that T must have a default constructor, which makes new T() legal.

You can apply the same constraint to a generic method:

public static T GetObject<T>() where T : new()
{
    return new T();
}

If you need to pass parameters:

protected T GetObject(params object[] args)
{
    return (T)Activator.CreateInstance(typeof(T), args);
}

How to add a class to body tag?

This should do it:

var newClass = window.location.href;
newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5);
$('body').addClass(newClass);

The whole "five characters" thing is a little worrisome; that kind of arbitrary cutoff is usually a red flag. I'd recommend catching everything until an _ or .:

newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);

That pattern should yield the following:

  • ../about_us.html : about
  • ../something.html : something
  • ../has_two_underscores.html : has

How can I loop through a C++ map of maps?

You can use an iterator.

typedef std::map<std::string, std::map<std::string, std::string>>::iterator it_type;
for(it_type iterator = m.begin(); iterator != m.end(); iterator++) {
    // iterator->first = key
    // iterator->second = value
    // Repeat if you also want to iterate through the second map.
}

Java getting the Enum name given the Enum Value

Try below code

public enum SalaryHeadMasterEnum {

    BASIC_PAY("basic pay"),
    MEDICAL_ALLOWANCE("Medical Allowance");

    private String name;

    private SalaryHeadMasterEnum(String stringVal) {
        name=stringVal;
    }
    public String toString(){
        return name;
    }

    public static String getEnumByString(String code){
        for(SalaryHeadMasterEnum e : SalaryHeadMasterEnum.values()){
            if(e.name.equals(code)) return e.name();
        }
        return null;
    }
}

Now you can use below code to retrieve the Enum by Value

SalaryHeadMasterEnum.getEnumByString("Basic Pay")

Use Below code to get ENUM as String

SalaryHeadMasterEnum.BASIC_PAY.name()

Use below code to get string Value for enum

SalaryHeadMasterEnum.BASIC_PAY.toString()

Can a variable number of arguments be passed to a function?

Yes. You can use *args as a non-keyword argument. You will then be able to pass any number of arguments.

def manyArgs(*arg):
  print "I was called with", len(arg), "arguments:", arg

>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2, 3)
I was called with 3 arguments: (1, 2, 3)

As you can see, Python will unpack the arguments as a single tuple with all the arguments.

For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.

MySQL: selecting rows where a column is null

As all are given answers I want to add little more. I had also faced the same issue.

Why did your query fail? You have,

SELECT pid FROM planets WHERE userid = NULL;

This will not give you the expected result, because from mysql doc

In SQL, the NULL value is never true in comparison to any other value, even NULL. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression.

Emphasis mine.

To search for column values that are NULL, you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression

Solution

SELECT pid FROM planets WHERE userid IS NULL; 

To test for NULL, use the IS NULL and IS NOT NULL operators.

Emulator: ERROR: x86 emulation currently requires hardware acceleration

If you recently installed Docker on Windows OS, you need to turn off the Hyper-V feature. See the top answer of VT Not Supported when Installing HAXM

jQuery datepicker to prevent past date

This should work <input type="text" id="datepicker">

var dateToday = new Date();
$("#datepicker").datepicker({
    minDate: dateToday,
    onSelect: function(selectedDate) {
    var option = this.id == "datepicker" ? "minDate" : "maxDate",
    instance = $(this).data("datepicker"),
    date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
    dates.not(this).datepicker("option", option, date);
    }
});

How to add an image to the "drawable" folder in Android Studio?

Just copy your images and select drawable then on the option of Paste or press shortcut ctrl v. images are added

Returning from a void function

Neither is more correct, so take your pick. The empty return; statement is provided to allow a return in a void function from somewhere other than the end. No other reason I believe.

Random String Generator Returning Same String

A LINQ one-liner for good measure (assuming a private static Random Random)...

public static string RandomString(int length)
{
    return new string(Enumerable.Range(0, length).Select(_ => (char)Random.Next('a', 'z')).ToArray());
}

How to catch curl errors in PHP

you can generate curl error after its execution

$url = 'http://example.com';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
}

and here are curl error code

if someone need more information about curl errors

<?php

    $error_codes=array(
    [1] => 'CURLE_UNSUPPORTED_PROTOCOL',
    [2] => 'CURLE_FAILED_INIT',
    [3] => 'CURLE_URL_MALFORMAT',
    [4] => 'CURLE_URL_MALFORMAT_USER',
    [5] => 'CURLE_COULDNT_RESOLVE_PROXY',
    [6] => 'CURLE_COULDNT_RESOLVE_HOST',
    [7] => 'CURLE_COULDNT_CONNECT',
    [8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
    [9] => 'CURLE_REMOTE_ACCESS_DENIED',
    [11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
    [13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
    [14]=>'CURLE_FTP_WEIRD_227_FORMAT',
    [15] => 'CURLE_FTP_CANT_GET_HOST',
    [17] => 'CURLE_FTP_COULDNT_SET_TYPE',
    [18] => 'CURLE_PARTIAL_FILE',
    [19] => 'CURLE_FTP_COULDNT_RETR_FILE',
    [21] => 'CURLE_QUOTE_ERROR',
    [22] => 'CURLE_HTTP_RETURNED_ERROR',
    [23] => 'CURLE_WRITE_ERROR',
    [25] => 'CURLE_UPLOAD_FAILED',
    [26] => 'CURLE_READ_ERROR',
    [27] => 'CURLE_OUT_OF_MEMORY',
    [28] => 'CURLE_OPERATION_TIMEDOUT',
    [30] => 'CURLE_FTP_PORT_FAILED',
    [31] => 'CURLE_FTP_COULDNT_USE_REST',
    [33] => 'CURLE_RANGE_ERROR',
    [34] => 'CURLE_HTTP_POST_ERROR',
    [35] => 'CURLE_SSL_CONNECT_ERROR',
    [36] => 'CURLE_BAD_DOWNLOAD_RESUME',
    [37] => 'CURLE_FILE_COULDNT_READ_FILE',
    [38] => 'CURLE_LDAP_CANNOT_BIND',
    [39] => 'CURLE_LDAP_SEARCH_FAILED',
    [41] => 'CURLE_FUNCTION_NOT_FOUND',
    [42] => 'CURLE_ABORTED_BY_CALLBACK',
    [43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
    [45] => 'CURLE_INTERFACE_FAILED',
    [47] => 'CURLE_TOO_MANY_REDIRECTS',
    [48] => 'CURLE_UNKNOWN_TELNET_OPTION',
    [49] => 'CURLE_TELNET_OPTION_SYNTAX',
    [51] => 'CURLE_PEER_FAILED_VERIFICATION',
    [52] => 'CURLE_GOT_NOTHING',
    [53] => 'CURLE_SSL_ENGINE_NOTFOUND',
    [54] => 'CURLE_SSL_ENGINE_SETFAILED',
    [55] => 'CURLE_SEND_ERROR',
    [56] => 'CURLE_RECV_ERROR',
    [58] => 'CURLE_SSL_CERTPROBLEM',
    [59] => 'CURLE_SSL_CIPHER',
    [60] => 'CURLE_SSL_CACERT',
    [61] => 'CURLE_BAD_CONTENT_ENCODING',
    [62] => 'CURLE_LDAP_INVALID_URL',
    [63] => 'CURLE_FILESIZE_EXCEEDED',
    [64] => 'CURLE_USE_SSL_FAILED',
    [65] => 'CURLE_SEND_FAIL_REWIND',
    [66] => 'CURLE_SSL_ENGINE_INITFAILED',
    [67] => 'CURLE_LOGIN_DENIED',
    [68] => 'CURLE_TFTP_NOTFOUND',
    [69] => 'CURLE_TFTP_PERM',
    [70] => 'CURLE_REMOTE_DISK_FULL',
    [71] => 'CURLE_TFTP_ILLEGAL',
    [72] => 'CURLE_TFTP_UNKNOWNID',
    [73] => 'CURLE_REMOTE_FILE_EXISTS',
    [74] => 'CURLE_TFTP_NOSUCHUSER',
    [75] => 'CURLE_CONV_FAILED',
    [76] => 'CURLE_CONV_REQD',
    [77] => 'CURLE_SSL_CACERT_BADFILE',
    [78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
    [79] => 'CURLE_SSH',
    [80] => 'CURLE_SSL_SHUTDOWN_FAILED',
    [81] => 'CURLE_AGAIN',
    [82] => 'CURLE_SSL_CRL_BADFILE',
    [83] => 'CURLE_SSL_ISSUER_ERROR',
    [84] => 'CURLE_FTP_PRET_FAILED',
    [84] => 'CURLE_FTP_PRET_FAILED',
    [85] => 'CURLE_RTSP_CSEQ_ERROR',
    [86] => 'CURLE_RTSP_SESSION_ERROR',
    [87] => 'CURLE_FTP_BAD_FILE_LIST',
    [88] => 'CURLE_CHUNK_FAILED');

    ?>

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.

sudo apt-get install openjfx

How to avoid a System.Runtime.InteropServices.COMException?

Probably you are trying to access the excel with the index 0, please note that Excel rows/columns start from 1.

JavaScript click event listener on class

With modern JavaScript it can be done like this:

_x000D_
_x000D_
const divs = document.querySelectorAll('.a');

divs.forEach(el => el.addEventListener('click', event => {
  console.log(event.target.getAttribute("data-el"));
}));
_x000D_
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Example</title>
  <style>
    .a {
      background-color:red;
      height: 33px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      cursor: pointer;
    }
    
    .b {
      background-color:#00AA00;
      height: 50px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div class="a" data-el="1">1</div>
  <div class="b" data-el="no-click-handler">2</div>
  <div class="a" data-el="3">11</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

  1. Gets all elements by class name
  2. Loops over all elements with using forEach
  3. Attach an event listener on each element
  4. Uses event.target to retrieve more information for specific element

How do I find all of the symlinks in a directory tree?

Kindly find below one liner bash script command to find all broken symbolic links recursively in any linux based OS

a=$(find / -type l); for i in $(echo $a); do file $i ; done |grep -i broken 2> /dev/null

Checking if a textbox is empty in Javascript

your validation should be occur before your event suppose you are going to submit your form.

anyway if you want this on onchange, so here is code.

function valid(id)
{
    var textVal=document.getElementById(id).value;
    if (!textVal.match(/\S/)) 
    {
        alert("Field is blank");
        return false;
    } 
    else 
    {
        return true;
    }
 }

How to raise a ValueError?

>>> response='bababa'
...  if "K" in response.text:
...     raise ValueError("Not found")

Call a method of a controller from another controller using 'scope' in AngularJS

Each controller has it's own scope(s) so that's causing your issue.

Having two controllers that want access to the same data is a classic sign that you want a service. The angular team recommends thin controllers that are just glue between views and services. And specifically- "services should hold shared state across controllers".

Happily, there's a nice 15-minute video describing exactly this (controller communication via services): video

One of the original author's of Angular, Misko Hevery, discusses this recommendation (of using services in this situation) in his talk entitled Angular Best Practices (skip to 28:08 for this topic, although I very highly recommended watching the whole talk).

You can use events, but they are designed just for communication between two parties that want to be decoupled. In the above video, Misko notes how they can make your app more fragile. "Most of the time injecting services and doing direct communication is preferred and more robust". (Check out the above link starting at 53:37 to hear him talk about this)

Multiple SQL joins

It will be something like this:

SELECT b.Title, b.Edition, b.Year, b.Pages, b.Rating, c.Category, p.Publisher, w.LastName
FROM
    Books b
    JOIN Categories_Book cb ON cb._ISBN = b._Books_ISBN
    JOIN Category c ON c._CategoryID = cb._Categories_Category_ID
    JOIN Publishers p ON p._PublisherID = b.PublisherID
    JOIN Writers_Books wb ON wb._Books_ISBN = b._ISBN
    JOIN Writer w ON w._WritersID = wb._Writers_WriterID

You use the join statement to indicate which fields from table A map to table B. I'm using aliases here thats why you see Books b the Books table will be referred to as b in the rest of the query. This makes for less typing.

FYI your naming convention is very strange, I would expect it to be more like this:

Book: ID, ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Category: ID, [Name]
BookCategory: ID, CategoryID, BookID
Publisher: ID, [Name]
Writer: ID, LastName
BookWriter: ID, WriterID, BookID

Why are only final variables accessible in anonymous class?

When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the final variable cannot change. For object values, the reference cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its stack frame has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.

(http://en.wikipedia.org/wiki/Final_%28Java%29)

C++ - Assigning null to a std::string

Many C APIs use a null pointer to indicate "use the default", e.g. mosquittopp. Here is the pattern I am using, based on David Cormack's answer:

    mosqpp::tls_set(
        MqttOptions->CAFile.length() > 0 ? MqttOptions->CAFile.c_str() : NULL,
        MqttOptions->CAPath.length() > 0 ? MqttOptions->CAPath.c_str() : NULL,
        MqttOptions->CertFile.length() > 0 ? MqttOptions->CertFile.c_str() : NULL,
        MqttOptions->KeyFile.length() > 0 ? MqttOptions->KeyFile.c_str() : NULL
    );

It is a little cumbersome, but allows one to keep everything as a std::string up until the API call itself.

Singleton in Android

It is simple, as a java, Android also supporting singleton. -

Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns.

-> Static member : This contains the instance of the singleton class.

-> Private constructor : This will prevent anybody else to instantiate the Singleton class.

-> Static public method : This provides the global point of access to the Singleton object and returns the instance to the client calling class.

  1. create private instance
  2. create private constructor
  3. use getInstance() of Singleton class

    public class Logger{
    private static Logger   objLogger;
    private Logger(){
    
            //ToDo here
    
    }
    public static Logger getInstance()
    {
        if (objLogger == null)
       {
          objLogger = new Logger();
       }
       return objLogger;
       }
    
    }
    

while use singleton -

Logger.getInstance();

Query based on multiple where clauses in Firebase

Firebase doesn't allow querying with multiple conditions. However, I did find a way around for this:

We need to download the initial filtered data from the database and store it in an array list.

                Query query = databaseReference.orderByChild("genre").equalTo("comedy");
                databaseReference.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                        ArrayList<Movie> movies = new ArrayList<>();
                        for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                            String lead = dataSnapshot1.child("lead").getValue(String.class);
                            String genre = dataSnapshot1.child("genre").getValue(String.class);

                            movie = new Movie(lead, genre);

                            movies.add(movie);

                        }

                        filterResults(movies, "Jack Nicholson");

                        }

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });

Once we obtain the initial filtered data from the database, we need to do further filter in our backend.

public void filterResults(final List<Movie> list,  final String genre) {
        List<Movie> movies = new ArrayList<>();
        movies = list.stream().filter(o -> o.getLead().equals(genre)).collect(Collectors.toList());
        System.out.println(movies);

        employees.forEach(movie -> System.out.println(movie.getFirstName()));
    }

Create a rounded button / button with border-radius in Flutter

RaisedButton(
          child: Text("Button"),
          onPressed: (){},
          shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0),
          side: BorderSide(color: Colors.red))
        )