Programs & Examples On #Drush

drush is a command line shell and scripting interface for Drupal, a veritable Swiss Army knife designed to make life easier for those of us who spend some of our working hours hacking away at the command prompt.

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

What is the purpose of "&&" in a shell command?

A quite common usage for '&&' is compiling software with autotools. For example:

./configure --prefix=/usr && make && sudo make install

Basically if the configure succeeds, make is run to compile, and if that succeeds, make is run as root to install the program. I use this when I am mostly sure that things will work, and it allows me to do other important things like look at stackoverflow an not 'monitor' the progress.

Sometimes I get really carried away...

tar xf package.tar.gz && ( cd package; ./configure && make && sudo make install ) && rm package -rf

I do this when for example making a linux from scratch box.

Angular 2 declaring an array of objects

Another approach that is especially useful if you want to store data coming from an external API or a DB would be this:

  1. Create a class that represent your data model

    export class Data{
        private id:number;
        private text: string;
    
        constructor(id,text) {
            this.id = id;
            this.text = text;
        }
    
  2. In your component class you create an empty array of type Data and populate this array whenever you get a response from API or whatever data source you are using

    export class AppComponent {
        private search_key: string;
        private dataList: Data[] = [];
    
        getWikiData() {
           this.httpService.getDataFromAPI()
            .subscribe(data => {
              this.parseData(data);
            });
         }
    
        parseData(jsonData: string) {
        //considering you get your data in json arrays
        for (let i = 0; i < jsonData[1].length; i++) {
             const data = new WikiData(jsonData[1][i], jsonData[2][i]);
             this.wikiData.push(data);
        }
      }
    }
    

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

How to "Open" and "Save" using java

You can find an introduction to file dialogs in the Java Tutorials. Java2s also has some example code.

How to get the id of the element clicked using jQuery

You can get the id of clicked one by this code

$("span").on("click",function(e){
    console.log(e.target.Id);
});

Use .on() event for future compatibility

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You have to set the http header at the http response of your resource. So it needs to be set serverside, you can remove the "HTTP_OPTIONS"-header from your angular HTTP-Post request.

How to get df linux command output always in GB

If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:

alias df-gb='df -BG'

So if you type:

df-gb

into a terminal, you'll get your intended output of the disk usage in GB.

EDIT: or even use just df -h to get it in a standard, human readable format.

http://www.thegeekstuff.com/2012/05/df-examples/

SQL Server - boolean literal?

select * from SomeTable where null is null

or

select * from SomeTable where null is not null

maybe this is the best performance?

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

How to list records with date from the last 10 days?

Yes this does work in PostgreSQL (assuming the column "date" is of datatype date) Why don't you just try it?

The standard ANSI SQL format would be:

SELECT Table.date 
FROM Table 
WHERE date > current_date - interval '10' day;

I prefer that format as it makes things easier to read (but it is the same as current_date - 10).

Run a Command Prompt command from Desktop Shortcut

This is an old post but I have issues with coming across posts that have some incorrect information/syntax...

If you wanted to do this with a shorcut icon you could just create a shortcut on your desktop for the cmd.exe application. Then append a /K {your command} to the shorcut path.

So a default shorcut target path may look like "%windir%\system32\cmd.exe", just change it to %windir%\system32\cmd.exe /k {commands}

example: %windir%\system32\cmd.exe /k powercfg -lastwake

In this case i would use /k (keep open) to display results.

Arlen was right about the /k (keep open) and /c (close)

You can open a command prompt and type "cmd /?" to see your options.

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true

A batch file is kind of overkill for a single command prompt command...

Hope this helps someone else

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

It is defenetly not a appropriate answer, but it is a small hint.

If you want to make use of static files in your App. You should put them as resources or as assets. But, if U have memory concerns like to keep your APK small, then you need to change your App design in such a way that,

instead of putting them as resources, while running your App(after installation) you can take the files(defenately different files as user may not keep files what you need) from SD Card. For this U can use ContentResolver to take audio, Image files on user selection.

With this you can give the user another feature like he can load audio/image files to the app on his own choice.

General guidelines to avoid memory leaks in C++

If you can't/don't use a smart pointer for something (although that should be a huge red flag), type in your code with:

allocate
if allocation succeeded:
{ //scope)
     deallocate()
}

That's obvious, but make sure you type it before you type any code in the scope

New lines inside paragraph in README.md

You can use a backslash at the end of a line.
So this:

a\
b\
c

will then look like:

a
b
c

Notice that there is no backslash at the end of the last line (after the 'c' character).

What is the Linux equivalent to DOS pause?

read without any parameters will only continue if you press enter. The DOS pause command will continue if you press any key. Use read –n1 if you want this behaviour.

How do I set the icon for my application in visual studio 2008?

The important thing is that the icon you want to be displayed as the application icon ( in the title bar and in the task bar ) must be the FIRST icon in the resource script file

The file is in the res folder and is named (applicationName).rc

/////////////////////////////////////////////////////////////////////////////
//
// Icon
//

// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
(icon ID )          ICON                    "res\\filename.ico"

Should CSS always preceed Javascript?

Steve Souders has already given a definitive answer but...

I wonder whether there's an issue with both Sam's original test and Josh's repeat of it.

Both tests appear to have been performed on low latency connections where setting up the TCP connection will have a trivial cost.

How this affects the result of the test I'm not sure and I'd want to look at the waterfalls for the tests over a 'normal' latency connection but...

The first file downloaded should get the connection used for the html page, and the second file downloaded will get the new connection. (Flushing the early alters that dynamic, but it's not being done here)

In newer browsers the second TCP connection is opened speculatively so the connection overhead is reduced / goes away, in older browsers this isn't true and the second connection will have the overhead of being opened.

Quite how/if this affects the outcome of the tests I'm not sure.

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

As accepted answer has provided required info, and for more info about using and disabling App Transport Security one can find more on this.

For Per-Domain Exceptions add these to the Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

But What If I Don’t Know All the Insecure Domains I Need to Use? Use following key in your Info.plist

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>

For more detail you can get from this link.

AngularJS app.run() documentation?

Here's the calling order:

  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

Here's a simple demo where you can watch each one executing (and experiment if you'd like).

From Angular's module docs:

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

One situation where run blocks are used is during authentications.

Make: how to continue after a command fails?

Return successfully by blocking rm's returncode behind a pipe with the true command, which always returns 0 (success)

rm file | true

Writing to CSV with Python adds blank lines

If you're using Python 2.x on Windows you need to change your line open('test.csv', 'w') to open('test.csv', 'wb'). That is you should open the file as a binary file.

However, as stated by others, the file interface has changed in Python 3.x.

What is the difference between --save and --save-dev?

--save-dev is used for modules used in development of the application,not require while running it in production envionment --save is used to add it in package.json and it is required for running of the application.

Example: express,body-parser,lodash,helmet,mysql all these are used while running the application use --save to put in dependencies while mocha,istanbul,chai,sonarqube-scanner all are used during development ,so put those in dev-dependencies .

npm link or npm install will also install the dev-dependency modules along with dependency modules in your project folder

How can I set a cookie in react?

It appears that the functionality previously present in the react-cookie npm package has been moved to universal-cookie. The relevant example from the universal-cookie repository now is:

import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman

foreach vs someList.ForEach(){}

Behind the scenes, the anonymous delegate gets turned into an actual method so you could have some overhead with the second choice if the compiler didn't choose to inline the function. Additionally, any local variables referenced by the body of the anonymous delegate example would change in nature because of compiler tricks to hide the fact that it gets compiled to a new method. More info here on how C# does this magic:

http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

How do I request and process JSON with python?

For anything with requests to URLs you might want to check out requests. For JSON in particular:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

do you try

[{"name":"myEnterprise", "departments":["HR"]}]

the square brace is the key point.

java.lang.UnsupportedClassVersionError

This class was compiled with a JDK more recent than the one used for execution.

The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.

Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).

JAVA How to remove trailing zeros from a double

You should use DecimalFormat("0.#")


For 4.3000

Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

output is:

4.3

In case of 5.000 we have

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

And the output is:

5

Is there a way to make text unselectable on an HTML page?

Absolutely position divs over the text area with a z-index higher and give these divs a transparent GIF background graphic.

Note after a bit more thought - You'd need to have these 'covers' be linked so clicking on them would take you to where the tab was supposed to, which means you could/should do this with the anchor element set to display:box, width and height set as well as the transparent background image.

What is the exact location of MySQL database tables in XAMPP folder?

The exact location is stored in "my.ini" which exists under main mysql installation directory. In my.ini file, look for 'datadir'. This parameter points the data folder.

Pass a PHP string to a JavaScript variable (and escape newlines)

I have had a similar issue and understand that the following is the best solution:

<script>
    var myvar = decodeURIComponent("<?php echo rawurlencode($myVarValue); ?>");
</script>

However, the link that micahwittman posted suggests that there are some minor encoding differences. PHP's rawurlencode() function is supposed to comply with RFC 1738, while there appear to have been no such effort with Javascript's decodeURIComponent().

How to get the difference between two arrays of objects in JavaScript

You could use Array.prototype.filter() in combination with Array.prototype.some().

Here is an example (assuming your arrays are stored in the variables result1 and result2):

//Find values that are in result1 but not in result2
var uniqueResultOne = result1.filter(function(obj) {
    return !result2.some(function(obj2) {
        return obj.value == obj2.value;
    });
});

//Find values that are in result2 but not in result1
var uniqueResultTwo = result2.filter(function(obj) {
    return !result1.some(function(obj2) {
        return obj.value == obj2.value;
    });
});

//Combine the two arrays of unique entries
var result = uniqueResultOne.concat(uniqueResultTwo);

How to Correctly Use Lists in R?

If it helps, I tend to conceive "lists" in R as "records" in other pre-OO languages:

  • they do not make any assumptions about an overarching type (or rather the type of all possible records of any arity and field names is available).
  • their fields can be anonymous (then you access them by strict definition order).

The name "record" would clash with the standard meaning of "records" (aka rows) in database parlance, and may be this is why their name suggested itself: as lists (of fields).

How to align center the text in html table row?

Try to put this in your CSS file.

td {
    text-align: center;
    vertical-align: middle;
}

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

After some search for a solution, it turns out the -dev package is needed, not just ruby1.8. So if you have ruby1.9.1 doing

sudo apt-get install ruby1.9.1-dev

or to install generic ruby version, use (as per @lamplightdev comment):

sudo apt-get install ruby-dev

should fix it.

Try to locate mkmf to see if the file is actually there.

How can I reset eclipse to default settings?

Yes, Eclipse can be a pain, as almost any IDE can. Please remain factual, however.

Switching to a new workspace should help you. Eclipse has almost no settings that are stored outside your workspace.

how to get the 30 days before date from Todays Date

SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE());

Example.

SELECT `name`, `phone`, `product` FROM `tbmMember` WHERE `dateofServicw` < (Day,-30,GETDATE()); 

Is there any way to change input type="date" format?

Try this if you need a quick solution To make yyyy-mm-dd go "dd- Sep -2016"

1) Create near your input one span class (act as label)

2) Update the label everytime your date is changed by user, or when need to load from data.

Works for webkit browser mobiles and pointer-events for IE11+ requires jQuery and Jquery Date

_x000D_
_x000D_
$("#date_input").on("change", function () {_x000D_
     $(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px", top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" : ($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));_x000D_
        });
_x000D_
#date_input{text-indent: -500px;height:25px; width:200px;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>_x000D_
<input id ="date_input" dateformat="d M y" type="date"/>_x000D_
<span class="datepicker_label" style="pointer-events: none;"></span>
_x000D_
_x000D_
_x000D_

MySQL Orderby a number, Nulls last

NULL LAST

SELECT * FROM table_name ORDER BY id IS NULL, id ASC

Ruby on Rails: Where to define global constants?

Some options:

Using a constant:

class Card
  COLOURS = ['white', 'blue', 'black', 'red', 'green', 'yellow'].freeze
end

Lazy loaded using class instance variable:

class Card
  def self.colours
    @colours ||= ['white', 'blue', 'black', 'red', 'green', 'yellow'].freeze
  end
end

If it is a truly global constant (avoid global constants of this nature, though), you could also consider putting a top-level constant in config/initializers/my_constants.rb for example.

CSS - make div's inherit a height

The Problem

When an element is floated, its parent no longer contains it because the float is removed from the flow. The floated element is out of the natural flow, so all block elements will render as if the floated element is not even there, so a parent container will not fully expand to hold the floated child element.

Take a look at the following article to get a better idea of how the CSS Float property works:

The Mystery Of The CSS Float Property


A Potential Solution

Now, I think the following article resembles what you're trying to do. Take a look at it and see if you can solve your problem.

Equal Height Columns with Cross-Browser CSS

I hope this helps.

How to convert POJO to JSON and vice versa?

Use GSON for converting POJO to JSONObject. Refer here.

For converting JSONObject to POJO, just call the setter method in the POJO and assign the values directly from the JSONObject.

With android studio no jvm found, JAVA_HOME has been set

Here is the tutorial :- http://javatechig.com/android/installing-android-studio and http://codearetoy.wordpress.com/2010/12/23/jdk-not-found-on-installing-android-sdk/

Adding a system variable JDK_HOME with value c:\Program Files\Java\jdk1.7.0_21\ worked for me. The latest Java release can be downloaded here. Additionally, make sure the variable JAVA_HOME is also set with the above location.

Please note that the above location is my java location. Please post your location in the path

Print PHP Call Stack

phptrace is a great tool to print PHP stack anytime when you want without installing any extensions.

There are two major function of phptrace: first, print call stack of PHP which need not install anything, second, trace php execution flows which needs to install the extension it supplies.

as follows:

$ ./phptrace -p 3130 -s             # phptrace -p <PID> -s
phptrace 0.2.0 release candidate, published by infra webcore team
process id = 3130
script_filename = /home/xxx/opt/nginx/webapp/block.php
[0x7f27b9a99dc8]  sleep /home/xxx/opt/nginx/webapp/block.php:6
[0x7f27b9a99d08]  say /home/xxx/opt/nginx/webapp/block.php:3
[0x7f27b9a99c50]  run /home/xxx/opt/nginx/webapp/block.php:10 

Remove Duplicate objects from JSON Array

The following works for me:

_.uniq(standardsList, JSON.stringify)

This would probably be slow for very long lists, however.

What is the usefulness of PUT and DELETE HTTP request methods?

DELETE is for deleting the request resource:

The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully …

PUT is for putting or updating a resource on the server:

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI …

For the full specification visit:

Since current browsers unfortunately do not support any other verbs than POST and GET in HTML forms, you usually cannot utilize HTTP to it's full extent with them (you can still hijack their submission via JavaScript though). The absence of support for these methods in HTML forms led to URIs containing verbs, like for instance

POST http://example.com/order/1/delete

or even worse

POST http://example.com/deleteOrder/id/1

effectively tunneling CRUD semantics over HTTP. But verbs were never meant to be part of the URI. Instead HTTP already provides the mechanism and semantics to CRUD a Resource (e.g. an order) through the HTTP methods. HTTP is a protocol and not just some data tunneling service.

So to delete a Resource on the webserver, you'd call

DELETE http://example.com/order/1

and to update it you'd call

PUT http://example.com/order/1

and provide the updated Resource Representation in the PUT body for the webserver to apply then.

So, if you are building some sort of client for a REST API, you will likely make it send PUT and DELETE requests. This could be a client built inside a browser, e.g. sending requests via JavaScript or it could be some tool running on a server, etc.

For some more details visit:

Using setImageDrawable dynamically to set image in an ImageView

You can also use something like:

imageView.setImageDrawable(ActivityCompat.getDrawable(getContext(), R.drawable.generatedID));

or using Picasso:

Picasso.with(getContext()).load(R.drawable.generatedId).into(imageView);

Maven: Non-resolvable parent POM

Just for reference.

The joys of Maven.

Putting the relative path of the modules to ../pom.xml solved it.

The parent element has a relativePath element that you need to point to the directory of the parent. It defaults to ..

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

I've been using this function in my project.

function changeViewPort(key, val) {
    var reg = new RegExp(key, "i"), oldval = document.querySelector('meta[name="viewport"]').content;
    var newval = reg.test(oldval) ? oldval.split(/,\s*/).map(function(v){ return reg.test(v) ? key+"="+val : v; }).join(", ") : oldval+= ", "+key+"="+val ;
    document.querySelector('meta[name="viewport"]').content = newval;
}

so just addEventListener:

if( /iPad|iPhone|iPod|Android/i.test(navigator.userAgent) ){
    window.addEventListener("orientationchange", function() { 
        changeViewPort("maximum-scale", 1);
        changeViewPort("maximum-scale", 10);
    }
}

Run jQuery function onclick

There's several things you can improve upon here. To start, there's no reason to use an <a> (anchor) tag since you don't have a link.

Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.

I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?

== EDIT ==

The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.

http://jsfiddle.net/THEtheChad/j9Ump/

Write bytes to file

Try this:

private byte[] Hex2Bin(string hex) 
{
 if ((hex == null) || (hex.Length < 1)) {
  return new byte[0];
 }
 int num = hex.Length / 2;
 byte[] buffer = new byte[num];
 num *= 2;
 for (int i = 0; i < num; i++) {
  int num3 = int.Parse(hex.Substring(i, 2), NumberStyles.HexNumber);
  buffer[i / 2] = (byte) num3;
  i++;
 }
 return buffer;
}

private string Bin2Hex(byte[] binary) 
{
 StringBuilder builder = new StringBuilder();
 foreach(byte num in binary) {
  if (num > 15) {
   builder.AppendFormat("{0:X}", num);
  } else {
   builder.AppendFormat("0{0:X}", num); /////// ?? 15 ???? 0
  }
 }
 return builder.ToString();
}

Algorithm to detect overlapping periods

I'm building a booking system and found this page. I'm interested in range intersection only, so I built this structure; it is enough to play with DateTime ranges.

You can check Intersection and check if a specific date is in range, and get the intersection type and the most important: you can get intersected Range.

public struct DateTimeRange
{

    #region Construction
    public DateTimeRange(DateTime start, DateTime end) {
        if (start>end) {
            throw new Exception("Invalid range edges.");
        }
        _Start = start;
        _End = end;
    }
    #endregion

    #region Properties
    private DateTime _Start;

    public DateTime Start {
        get { return _Start; }
        private set { _Start = value; }
    }
    private DateTime _End;

    public DateTime End {
        get { return _End; }
        private set { _End = value; }
    }
    #endregion

    #region Operators
    public static bool operator ==(DateTimeRange range1, DateTimeRange range2) {
        return range1.Equals(range2);
    }

    public static bool operator !=(DateTimeRange range1, DateTimeRange range2) {
        return !(range1 == range2);
    }
    public override bool Equals(object obj) {
        if (obj is DateTimeRange) {
            var range1 = this;
            var range2 = (DateTimeRange)obj;
            return range1.Start == range2.Start && range1.End == range2.End;
        }
        return base.Equals(obj);
    }
    public override int GetHashCode() {
        return base.GetHashCode();
    }
    #endregion

    #region Querying
    public bool Intersects(DateTimeRange range) {
        var type = GetIntersectionType(range);
        return type != IntersectionType.None;
    }
    public bool IsInRange(DateTime date) {
        return (date >= this.Start) && (date <= this.End);
    }
    public IntersectionType GetIntersectionType(DateTimeRange range) {
        if (this == range) {
            return IntersectionType.RangesEqauled;
        }
        else if (IsInRange(range.Start) && IsInRange(range.End)) {
            return IntersectionType.ContainedInRange;
        }
        else if (IsInRange(range.Start)) {
            return IntersectionType.StartsInRange;
        }
        else if (IsInRange(range.End)) {
            return IntersectionType.EndsInRange;
        }
        else if (range.IsInRange(this.Start) && range.IsInRange(this.End)) {
            return IntersectionType.ContainsRange;
        }
        return IntersectionType.None;
    }
    public DateTimeRange GetIntersection(DateTimeRange range) {
        var type = this.GetIntersectionType(range);
        if (type == IntersectionType.RangesEqauled || type==IntersectionType.ContainedInRange) {
            return range;
        }
        else if (type == IntersectionType.StartsInRange) {
            return new DateTimeRange(range.Start, this.End);
        }
        else if (type == IntersectionType.EndsInRange) {
            return new DateTimeRange(this.Start, range.End);
        }
        else if (type == IntersectionType.ContainsRange) {
            return this;
        }
        else {
            return default(DateTimeRange);
        }
    }
    #endregion


    public override string ToString() {
        return Start.ToString() + " - " + End.ToString();
    }
}
public enum IntersectionType
{
    /// <summary>
    /// No Intersection
    /// </summary>
    None = -1,
    /// <summary>
    /// Given range ends inside the range
    /// </summary>
    EndsInRange,
    /// <summary>
    /// Given range starts inside the range
    /// </summary>
    StartsInRange,
    /// <summary>
    /// Both ranges are equaled
    /// </summary>
    RangesEqauled,
    /// <summary>
    /// Given range contained in the range
    /// </summary>
    ContainedInRange,
    /// <summary>
    /// Given range contains the range
    /// </summary>
    ContainsRange,
}

How to enter command with password for git pull?

Note that the way the git credential helper "store" will store the unencrypted passwords changes with Git 2.5+ (Q2 2014).
See commit 17c7f4d by Junio C Hamano (gitster)

credential-xdg

Tweak the sample "store" backend of the credential helper to honor XDG configuration file locations when specified.

The doc now say:

If not specified:

  • credentials will be searched for from ~/.git-credentials and $XDG_CONFIG_HOME/git/credentials, and
  • credentials will be written to ~/.git-credentials if it exists, or $XDG_CONFIG_HOME/git/credentials if it exists and the former does not.

How to get all table names from a database?

You need to iterate over your ResultSet calling next().

This is an example from java2s.com:

DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
  System.out.println(rs.getString(3));
}

Column 3 is the TABLE_NAME (see documentation of DatabaseMetaData::getTables).

Managing jQuery plugin dependency in webpack

I don't know if I understand very well what you are trying to do, but I had to use jQuery plugins that required jQuery to be in the global context (window) and I put the following in my entry.js:

var $ = require('jquery');
window.jQuery = $;
window.$ = $;

The I just have to require wherever i want the jqueryplugin.min.js and window.$ is extended with the plugin as expected.

run main class of Maven project

Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec

Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec, as I have ~/bin in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...

Launch it from the root of your project, where you can see src and target dirs.

The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)

$ mvnexec 
 1) org.jmeld.ui.JMeldComponent
 2) org.jmeld.ui.text.FileDocument
 3) org.jmeld.JMeld
 4) org.jmeld.util.UIDefaultsPrint
 5) org.jmeld.util.PrintProperties
 6) org.jmeld.util.file.DirectoryDiff
 7) org.jmeld.util.file.VersionControlDiff
 8) org.jmeld.vc.svn.InfoCmd
 9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#? 

If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P)

By default it compiles project every run. but you can avoid that using mvnexec -B

It allows to search only in test classes -M or --no-main, or only in main classes -T or --no-test. also has a filter by name option -f <whatever>

Hope this could save you some time, for me it does.

Automatic vertical scroll bar in WPF TextBlock?

Wrap it in a scroll viewer:

<ScrollViewer>
    <TextBlock />
</ScrollViewer>

NOTE this answer applies to a TextBlock (a read-only text element) as asked for in the original question.

If you want to show scroll bars in a TextBox (an editable text element) then use the ScrollViewer attached properties:

<TextBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         ScrollViewer.VerticalScrollBarVisibility="Auto" />

Valid values for these two properties are Disabled, Auto, Hidden and Visible.

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

In my case it is a different issue. The database turned into single user mode and a second connection to the database was showing this exception. To resolve this issue follow below steps.

  1. Make sure the object explorer is pointed to a system database like master.
  2. Execute a exec sp_who2 and find all the connections to database ‘my_db’. Kill all the connections by doing KILL { session id } where session id is the SPID listed by sp_who2.
USE MASTER;
EXEC sp_who2
  1. Alter the database
USE MASTER;
ALTER DATABASE [my_db] SET MULTI_USER
GO

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Need to make sure you have the numeric keypad and the tab key working too

 // Allow only backspace and delete
            if (event.keyCode == 46 || event.keyCode == 8  || event.keyCode == 9) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {

                }
                else {
                    event.preventDefault();
                }
            }

Should I use SVN or Git?

I have used SVN for a long time, but whenever I used Git, I felt that Git is much powerful, lightweight, and although a little bit of learning curve involved but is better than SVN.

What I have noted is that each SVN project, as it grows, becomes a very big size project unless it is exported. Where as, GIT project (along with Git data) is very light weight in size.

In SVN, I've dealt with developers from novice to experts, and the novices and intermediates seem to introduce File conflicts if they copy one folder from another SVN project in order to re-use it. Whereas, I think in Git, you just copy the folder and it works, because Git doesn't introduce .git folders in all its subfolders (as SVN does).

After dealing alot with SVN since long time, I'm finally thinking to move my developers and me to Git, since it is easy to collaborate and merge work, as well as one great advantage is that a local copy's changes can be committed as much desired, and then finally pushed to the branch on server in one go, unlike SVN (where we have to commit the changes from time to time in the repository on server).

Anyone who can help me decide if I should really go with Git?

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

Is null check needed before calling instanceof?

Very good question indeed. I just tried for myself.

public class IsInstanceOfTest {

    public static void main(final String[] args) {

        String s;

        s = "";

        System.out.println((s instanceof String));
        System.out.println(String.class.isInstance(s));

        s = null;

        System.out.println((s instanceof String));
        System.out.println(String.class.isInstance(s));
    }
}

Prints

true
true
false
false

JLS / 15.20.2. Type Comparison Operator instanceof

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

API / Class#isInstance(Object)

If this Class object represents an interface, this method returns true if the class or any superclass of the specified Object argument implements this interface; it returns false otherwise. If this Class object represents a primitive type, this method returns false.

RSA: Get exponent and modulus given a public key

I manage to find the answer for this solution, have to do javascript injection for this to install atob

const atob:any = require('atob');
asn1(pem: any){
      asn1parser.Enc.base64ToBuf = function (b64:any) {
    return asn1parser.Enc.binToBuf(atob(b64));
  };
  const dertest = asn1parser.PEM.parseBlock(pem).der;
   var hex = asn1parser.Enc.bufToHex(asn1parser.PEM.parseBlock(pem).der)
   var buf = asn1parser.ASN1.parse(dertest);
  var asn1 = JSON.stringify(asn1parser.ASN1.parse(dertest), asn1parser.ASN1._replacer, 2 );

Emulate Samsung Galaxy Tab

If you are developing on Netbeans, you will not get the Third-Party add-ons. You can download the Skins directly from Samsung here: http://developer.samsung.com/android/tools-sdks

After download, unzip to ...\Android\android-sdk\add-ons[name of device]

Restart the Android SDK Manager, and the new device should be there under Extras.

It would be better to add the download site directly to the SDK...if anyone knows it, please post it.

Scott

Why is C so fast, and why aren't other languages as fast or faster?

There is a trade off the C designers have made. That's to say, they made the decision to put speed above safety. C won't

  • Check array index bounds
  • Check for uninitialized variable values
  • Check for memory leaks
  • Check for null pointer dereference

When you index into an array, in Java it takes some method call in the virtual machine, bound checking and other sanity checks. That is valid and absolutely fine, because it adds safety where it's due. But in C, even pretty trivial things are not put in safety. For example, C doesn't require memcpy to check whether the regions to copy overlap. It's not designed as a language to program a big business application.

But these design decisions are not bugs in the C language. They are by design, as it allows compilers and library writers to get every bit of performance out of the computer. Here is the spirit of C how the C Rationale document explains it:

C code can be non-portable. Although it strove to give programmers the opportunity to write truly portable programs, the Committee did not want to force programmers into writing portably, to preclude the use of C as a ``high-level assembler'': the ability to write machine-specific code is one of the strengths of C.

Keep the spirit of C. The Committee kept as a major goal to preserve the traditional spirit of C. There are many facets of the spirit of C, but the essence is a community sentiment of the underlying principles upon which the C language is based. Some of the facets of the spirit of C can be summarized in phrases like

  • Trust the programmer.
  • Don't prevent the programmer from doing what needs to be done.
  • Keep the language small and simple.
  • Provide only one way to do an operation.
  • Make it fast, even if it is not guaranteed to be portable.

The last proverb needs a little explanation. The potential for efficient code generation is one of the most important strengths of C. To help ensure that no code explosion occurs for what appears to be a very simple operation, many operations are defined to be how the target machine's hardware does it rather than by a general abstract rule. An example of this willingness to live with what the machine does can be seen in the rules that govern the widening of char objects for use in expressions: whether the values of char objects widen to signed or unsigned quantities typically depends on which byte operation is more efficient on the target machine.

.Net System.Mail.Message adding multiple "To" addresses

I wasn't able to replicate your bug:

var message = new MailMessage();

message.To.Add("[email protected]");
message.To.Add("[email protected]");

message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.Body = "Test";

var client = new SmtpClient("localhost", 25);
client.Send(message);

Dumping the contents of the To: MailAddressCollection:

MailAddressCollection (2 items)
DisplayName User Host Address

user example.com [email protected]
user2 example.com [email protected]

And the resulting e-mail as caught by smtp4dev:

Received: from mycomputername (mycomputername [127.0.0.1])
     by localhost (Eric Daugherty's C# Email Server)
     3/8/2010 12:50:28 PM
MIME-Version: 1.0
From: [email protected]
To: [email protected], [email protected]
Date: 8 Mar 2010 12:50:28 -0800
Subject: Test
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable

Test

Are you sure there's not some other issue going on with your code or SMTP server?

Twitter Bootstrap carousel different height images cause bouncing arrows

Try this (I'm using SASS):

.carousel {
  max-height: 700px;
  overflow: hidden;

  .item img {
    width: 100%;
    height: auto;
  }
}

You can wrap the .carousel into a .container if you wish.

Populating Spring @Value during Unit Test

If you want, you can still run your tests within Spring Context and set the required properties inside Spring configuration class. If you use JUnit, use SpringJUnit4ClassRunner and define dedicated configuration class for your tests like that:

The class under test:

@Component
public SomeClass {

    @Autowired
    private SomeDependency someDependency;

    @Value("${someProperty}")
    private String someProperty;
}

The test class:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = SomeClassTestsConfig.class)
public class SomeClassTests {

    @Autowired
    private SomeClass someClass;

    @Autowired
    private SomeDependency someDependency;

    @Before
    public void setup() {
       Mockito.reset(someDependency);

    @Test
    public void someTest() { ... }
}

And the configuration class for this test:

@Configuration
public class SomeClassTestsConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() throws Exception {
        final PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
        Properties properties = new Properties();

        properties.setProperty("someProperty", "testValue");

        pspc.setProperties(properties);
        return pspc;
    }
    @Bean
    public SomeClass getSomeClass() {
        return new SomeClass();
    }

    @Bean
    public SomeDependency getSomeDependency() {
        // Mockito used here for mocking dependency
        return Mockito.mock(SomeDependency.class);
    }
}

Having that said, I wouldn't recommend this approach, I just added it here for reference. In my opinion much better way is to use Mockito runner. In that case you don't run tests inside Spring at all, which is much more clear and simpler.

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Share link on Google+

New Google share link: http://plus.google.com/share?url=YOUR_URL

For secure connection:

https://plus.google.com/share?url=YOUR_URL

For Wordpress:

https://plus.google.com/share?url=<?php the_permalink(); ?>

Make REST API call in Swift

let headers = [
                "cache-control": "no-cache",
                "postman-token": "6f8a-12c6-87a1-ac0f25d6385a"
            ]

            let request = NSMutableURLRequest(url: NSURL(string: "Your url string")! as URL,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
            request.httpMethod = "GET"
            request.allHTTPHeaderFields = headers

            let session = URLSession.shared
            let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
                if error == nil && data != nil {
                    do {
                        // Convert NSData to Dictionary where keys are of type String, and values are of any type
                        let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
                        print(json)

                        //do your stuff

                      //  completionHandler(true)

                    } catch {
                       // completionHandler(false)
                    }
                }
                else if error != nil
                {
                    //completionHandler(false)
                }
            }).resume()
            }

How to create User/Database in script for Docker Postgres

You can now put .sql files inside the init directory:

From the docs

If you would like to do additional initialization in an image derived from this one, add one or more *.sql or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files and source any *.sh scripts found in that directory to do further initialization before starting the service.

So copying your .sql file in will work.

Is there a Subversion command to reset the working copy?

svn revert . -R

to reset everything.

svn revert path/to/file

for a single file

Get integer value from string in swift

You can bridge from String to NSString and convert from CInt to Int like this:

var myint: Int = Int(stringNumb.bridgeToObjectiveC().intValue)

How can I change the Bootstrap default font family using font from Google?

This is the best and easy way to import font from google and
this is also a standard method to import font

Paste this code on your index page or on header

<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>

other method is to import on css like this:

@import url(http://fonts.googleapis.com/css?family=Oswald:400,300,700);

on your Css file as this code

body {
  font-family: 'Oswald', sans-serif !important;
}

Note : The @import code line will be the first lines in your css file (style.css, etc.css). They can be used in any of the .css files and should always be the first line in these files. The following is an example:

Laravel 5.5 ajax call 419 (unknown status)

formData = new FormData();
formData.append('_token', "{{csrf_token()}}");
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

Convert UTC datetime string to local datetime

From the answer here, you can use the time module to convert from utc to the local time set in your computer:

utc_time = time.strptime("2018-12-13T10:32:00.000", "%Y-%m-%dT%H:%M:%S.%f")
utc_seconds = calendar.timegm(utc_time)
local_time = time.localtime(utc_seconds)

How to implement a binary search tree in Python?

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None


class BinaryTree:
    def __init__(self, root=None):
        self.root = root

    def add_node(self, node, value):
        """
        Node points to the left of value if node > value; right otherwise,
        BST cannot have duplicate values
        """
        if node is not None:
            if value < node.value:
                if node.left is None:
                    node.left = TreeNode(value)
                else:
                    self.add_node(node.left, value)
            else:
                if node.right is None:
                    node.right = TreeNode(value)
                else:
                    self.add_node(node.right, value)
        else:
            self.root = TreeNode(value)

    def search(self, value):
        """
        Value will be to the left of node if node > value; right otherwise.
        """
        node = self.root
        while node is not None:
            if node.value == value:
                return True     # node.value
            if node.value > value:
                node = node.left
            else:
                node = node.right
        return False

    def traverse_inorder(self, node):
        """
        Traverse the left subtree of a node as much as possible, then traverse
        the right subtree, followed by the parent/root node.
        """
        if node is not None:
            self.traverse_inorder(node.left)
            print(node.value)
            self.traverse_inorder(node.right)


def main():
    binary_tree = BinaryTree()
    binary_tree.add_node(binary_tree.root, 200)
    binary_tree.add_node(binary_tree.root, 300)
    binary_tree.add_node(binary_tree.root, 100)
    binary_tree.add_node(binary_tree.root, 30)
    binary_tree.traverse_inorder(binary_tree.root)
    print(binary_tree.search(200))


if __name__ == '__main__':
    main()

Create a list with initial capacity in Python

Concerns about preallocation in Python arise if you're working with NumPy, which has more C-like arrays. In this instance, preallocation concerns are about the shape of the data and the default value.

Consider NumPy if you're doing numerical computation on massive lists and want performance.

Is it possible to add dynamically named properties to JavaScript object?

Just an addition to abeing's answer above. You can define a function to encapsulate the complexity of defineProperty as mentioned below.

var defineProp = function ( obj, key, value ){
  var config = {
    value: value,
    writable: true,
    enumerable: true,
    configurable: true
  };
  Object.defineProperty( obj, key, config );
};

//Call the method to add properties to any object
defineProp( data, "PropertyA",  1 );
defineProp( data, "PropertyB",  2 );
defineProp( data, "PropertyC",  3 );

reference: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript

Converting bool to text in C++

As long as strings can be viewed directly as a char array it's going to be really hard to convince me that std::string represents strings as first class citizens in C++.

Besides, combining allocation and boundedness seems to be a bad idea to me anyways.

How to change the default message of the required field in the popover of form-control in bootstrap?

$("input[required]").attr("oninvalid", "this.setCustomValidity('Say Somthing!')");

this work if you move to previous or next field by mouse, but by enter key, this is not work !!!

Select from where field not equal to Mysql Php

Or can also insert the statement inside bracket.

SELECT * FROM tablename WHERE NOT (columnA = 'x')

SQL Server Group By Month

I prefer combining DATEADD and DATEDIFF functions like this:

GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Created),0)

Together, these two functions zero-out the date component smaller than the specified datepart (i.e. MONTH in this example).

You can change the datepart bit to YEAR, WEEK, DAY, etc... which is super handy.

Your original SQL query would then look something like this (I can't test it as I don't have your data set, but it should put you on the right track).

DECLARE @start [datetime] = '2010-04-01';

SELECT
    ItemID,
    UserID,
    DATEADD(MONTH, DATEDIFF(MONTH, 0, Created),0) [Month],
    IsPaid,
    SUM(Amount)
FROM LIVE L
INNER JOIN Payments I ON I.LiveID = L.RECORD_KEY
WHERE UserID = 16178
AND PaymentDate > @start

One more thing: the Month column is typed as a DateTime which is also a nice advantage if you need to further process that data or map it .NET object for example.

How do I execute a program from Python? os.system fails due to spaces in path

Here's a different way of doing it.

If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.

filepath = 'textfile.txt'
import os
os.startfile(filepath)

Example:

import os
os.startfile('textfile.txt')

This will open textfile.txt with Notepad if Notepad is associated with .txt files.

java.lang.OutOfMemoryError: Java heap space

You can get your heap memory size through below programe.

public class GetHeapSize {
    public static void main(String[] args) {
        long heapsize = Runtime.getRuntime().totalMemory();
        System.out.println("heapsize is :: " + heapsize);
    }
} 

then accordingly you can increase heap size also by using: java -Xmx2g http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html

Concat strings by & and + in VB.Net

As your question confirms, they are different: & is ONLY string concatenation, + is overloaded with both normal addition and concatenation.

In your example:

  • because one of the operands to + is an integer VB attempts to convert the string to a integer, and as your string is not numeric it throws; and

  • & only works with strings so the integer is converted to a string.

How to decorate a class?

Django has method_decorator which is a decorator that turns any decorator into a method decorator, you can see how it's implemented in django.utils.decorators:

https://github.com/django/django/blob/50cf183d219face91822c75fa0a15fe2fe3cb32d/django/utils/decorators.py#L53

https://docs.djangoproject.com/en/3.0/topics/class-based-views/intro/#decorating-the-class

HTML5 Email input pattern attribute

I had this exact problem with HTML5s email input, using Alwin Keslers answer above I added the regex to the HTML5 email input so the user must have .something at the end.

<input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" />

What can MATLAB do that R cannot do?

As a user of both MATLAB and R, I think they are very different applications. I myself have a background in computer science, etc. and I can't help thinking that R is by statisticians for statisticians whereas MATLAB is by programmers for programmers.

R makes it very easy to visualize and compute all sorts of statistical stuff but I wouldn't use it to implement anything signal processing related if it was up to me.

To sum up, if you want to do statistics, use R. If you want to program, use MATLAB or some programming language.

Omit rows containing specific column of NA

It is possible to use na.omit for data.table:

na.omit(data, cols = c("x", "z"))

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

How to find all occurrences of a substring?

Whatever the solutions provided by others are completely based on the available method find() or any available methods.

What is the core basic algorithm to find all the occurrences of a substring in a string?

def find_all(string,substring):
    """
    Function: Returning all the index of substring in a string
    Arguments: String and the search string
    Return:Returning a list
    """
    length = len(substring)
    c=0
    indexes = []
    while c < len(string):
        if string[c:c+length] == substring:
            indexes.append(c)
        c=c+1
    return indexes

You can also inherit str class to new class and can use this function below.

class newstr(str):
def find_all(string,substring):
    """
    Function: Returning all the index of substring in a string
    Arguments: String and the search string
    Return:Returning a list
    """
    length = len(substring)
    c=0
    indexes = []
    while c < len(string):
        if string[c:c+length] == substring:
            indexes.append(c)
        c=c+1
    return indexes

Calling the method

newstr.find_all('Do you find this answer helpful? then upvote this!','this')

Junit test case for database insert method with DAO and web service

The design of your classes will make it hard to test them. Using hardcoded connection strings or instantiating collaborators in your methods with new can be considered as test-antipatterns. Have a look at the DependencyInjection pattern. Frameworks like Spring might be of help here.

To have your DAO tested you need to have control over your database connection in your unit tests. So the first thing you would want to do is extract it out of your DAO into a class that you can either mock or point to a specific test database, which you can setup and inspect before and after your tests run.

A technical solution for testing db/DAO code might be dbunit. You can define your test data in a schema-less XML and let dbunit populate it in your test database. But you still have to wire everything up yourself. With Spring however you could use something like spring-test-dbunit which gives you lots of leverage and additional tooling.

As you call yourself a total beginner I suspect this is all very daunting. You should ask yourself if you really need to test your database code. If not you should at least refactor your code, so you can easily mock out all database access. For mocking in general, have a look at Mockito.

List all virtualenv

This works on Windows only:

If you are trying to find all envs created using virtualenv
search for "activate_this.py" or "pip-selfcheck.json"

How to install Visual C++ Build tools?

You can check Announcing the official release of the Visual C++ Build Tools 2015 and from this blog, we can know that the Build Tools are the same C++ tools that you get with Visual Studio 2015 but they come in a scriptable standalone installer that only lays down the tools you need to build C++ projects. The Build Tools give you a way to install the tools you need on your build machines without the IDE you don’t need.

Because these components are the same as the ones installed by the Visual Studio 2015 Update 2 setup, you cannot install the Visual C++ Build Tools on a machine that already has Visual Studio 2015 installed. Therefore, it asks you to uninstall your existing VS 2015 when you tried to install the Visual C++ build tools using the standalone installer. Since you already have the VS 2015, you can go to Control Panel—Programs and Features and right click the VS 2015 item and Change-Modify, then check the option of those components that relates to the Visual C++ Build Tools, like Visual C++, Windows SDK… then install them. After the installation is successful, you can build the C++ projects.

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

Generating locales

Missing locales are generated with locale-gen:

locale-gen en_US.UTF-8

Alternatively a locale file can be created manually with localedef:[1]

localedef -i en_US -f UTF-8 en_US.UTF-8

Setting Locale Settings

The locale settings can be set (to en_US.UTF-8 in the example) as follows:

export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
locale-gen en_US.UTF-8
dpkg-reconfigure locales

The dpkg-reconfigure locales command will open a dialog under Debian for selecting the desired locale. This dialog will not appear under Ubuntu. The Configure Locales in Ubuntu article shows how to find the information regarding Ubuntu.

Convert categorical data in pandas dataframe

This works for me:

pandas.factorize( ['B', 'C', 'D', 'B'] )[0]

Output:

[0, 1, 2, 0]

Session 'app': Error Launching activity

The only one best Answer is to run uninstall command from adb and install the app again

C:\Users\YourUser\AppData\Local\Android\sdk\platform-tools>adb uninstall applicationId

applicationId: from gradle module file

how to output every line in a file python

You could try this. It doesn't read all of f into memory at once (using the file object's iterator) and it closes the file when the code leaves the with block.

if data.find('!masters') != -1:
    with open('masters.txt', 'r') as f:
        for line in f:
            print line
            sck.send('PRIVMSG ' + chan + " " + line + '\r\n')

If you're using an older version of python (pre 2.6) you'll have to have

from __future__ import with_statement

How to find the length of an array in shell?

$ a=(1 2 3 4)
$ echo ${#a[@]}
4

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

If you're using a graphical tool. It shows you the schema right next to the table name. In case of DB Browser For Sqlite, click to open the database(top right corner), navigate and open your database, you'll see the information populated in the table as below.

enter image description here

right click on the record/table_name, click on copy create statement and there you have it.

Hope it helped some beginner who failed to work with the commandline.

How to create temp table using Create statement in SQL Server?

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Regarding this part:

When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.

The easiest solution is to avoid the problem entirely by properly configuring Notepad++.

Try Settings -> Preferences -> New document -> Encoding -> choose UTF-8 without BOM, and check Apply to opened ANSI files.

notepad++ UTF-8 apply to opened ANSI files

That way all the opened ANSI files will be treated as UTF-8 without BOM.

For explanation what's going on, read the comments below this answer.

To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.

How do I set a ViewModel on a window in XAML using DataContext property?

You need to instantiate the MainViewModel and set it as datacontext. In your statement it just consider it as string value.

     <Window x:Class="BuildAssistantUI.BuildAssistantWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:BuildAssistantUI.ViewModels">
      <Window.DataContext>
        <local:MainViewModel/>
      </Window.DataContext>

Pure CSS to make font-size responsive based on dynamic amount of characters

You might be interested in the calc approach:

font-size: calc(4vw + 4vh + 2vmin);

done. Tweak values till matches your taste.

Source: https://codepen.io/CrocoDillon/pen/fBJxu

How do I convert an interval into a number of hours with postgres?

select floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600)), count(*)
from od_a_week
group by floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600));

The ::int conversion follows the principle of rounding. If you want a different result such as rounding down, you can use the corresponding math function such as floor.

Is there any simple way to convert .xls file to .csv file? (Excel)

Install these 2 packages

<packages>
  <package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
  <package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
</packages>

Helper function

using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExcelToCsv
{
    public class ExcelFileHelper
    {
        public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath)
        {

            using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                IExcelDataReader reader = null;
                if (excelFilePath.EndsWith(".xls"))
                {
                    reader = ExcelReaderFactory.CreateBinaryReader(stream);
                }
                else if (excelFilePath.EndsWith(".xlsx"))
                {
                    reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }

                if (reader == null)
                    return false;

                var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
                {
                    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                    {
                        UseHeaderRow = false
                    }
                });

                var csvContent = string.Empty;
                int row_no = 0;
                while (row_no < ds.Tables[0].Rows.Count)
                {
                    var arr = new List<string>();
                    for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    {
                        arr.Add(ds.Tables[0].Rows[row_no][i].ToString());
                    }
                    row_no++;
                    csvContent += string.Join(",", arr) + "\n";
                }
                StreamWriter csv = new StreamWriter(destinationCsvFilePath, false);
                csv.Write(csvContent);
                csv.Close();
                return true;
            }
        }
    }
}

Usage :

var excelFilePath = Console.ReadLine();
string output = Path.ChangeExtension(excelFilePath, ".csv");
ExcelFileHelper.SaveAsCsv(excelFilePath, output);

How to dump only specific tables from MySQL?

Usage: mysqldump [OPTIONS] database [tables]

i.e.

mysqldump -u username -p db_name table1_name table2_name table3_name > dump.sql

Telnet is not recognized as internal or external command

  1. Open "Start" (Windows Button)
  2. Search for "Turn Windows features On or Off"
  3. Check "Telnet client" and check "Telnet server".

Replace whitespace with a comma in a text file in Linux

If you want to replace an arbitrary sequence of blank characters (tab, space) with one comma, use the following:

sed 's/[\t ]+/,/g' input_file > output_file

or

sed -r 's/[[:blank:]]+/,/g' input_file > output_file

If some of your input lines include leading space characters which are redundant and don't need to be converted to commas, then first you need to get rid of them, and then convert the remaining blank characters to commas. For such case, use the following:

sed 's/ +//' input_file | sed 's/[\t ]+/,/g' > output_file

Disable browser's back button

This question is very similar to this one...

You need to force the cache to expire for this to work. Place the following code on your page code behind.

Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)

Convert datetime object to a String of date only in Python

You can convert datetime to string.

published_at = "{}".format(self.published_at)

Http Post request with content type application/x-www-form-urlencoded not working in Spring

Remove @ResponseBody annotation from your use parameters in method. Like this;

   @Autowired
    ProjectService projectService;

    @RequestMapping(path = "/add", method = RequestMethod.POST)
    public ResponseEntity<Project> createNewProject(Project newProject){
        Project project = projectService.save(newProject);

        return new ResponseEntity<Project>(project,HttpStatus.CREATED);
    }

Custom Adapter for List View

BaseAdapter is best custom adapter for listview.

Class MyAdapter extends BaseAdapter{}

and it has many functions such as getCount(), getView() etc.

Edit and Continue: "Changes are not allowed when..."

"Edit and Continue", when enabled, will only allow you to edit code when it is in break-mode: e.g. by having the execution paused by an exception or by hitting a breakpoint.

This implies you can't edit the code when the execution isn't paused! When it comes to debugging (ASP.NET) web projects, this is very unintuitive, as you would often want to make changes between requests. At this time, the code your (probably) debugging isn't running, but it isn't paused either!
To solve this, you can click "Break all" (or press Ctrl+Alt+Break). Alternatively, set a breakpoint somewhere (e.g. in your Page_Load event), then reload the page so the execution pauses when it hits the breakpoint, and now you can edit code. Even code in .cs files.

How to change navbar/container width? Bootstrap 3

just simple:

.navbar{
    width:65% !important;
    margin:0px auto;
    left:0;
    right:0;
    padding:0;
}

or,

.navbar.navbar-fixed-top{
    width:65% !important;
    margin:0px auto;
    left:0;
    right:0;
    padding:0;
}

Hope it works (at least, for future searchers)

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

Spring Data JpaRepository

The Spring Data JpaRepository defines the following two methods:

  • getOne, which returns an entity proxy that is suitable for setting a @ManyToOne or @OneToOne parent association when persisting a child entity.
  • findById, which returns the entity POJO after running the SELECT statement that loads the entity from the associated table

However, in your case, you didn't call either getOne or findById:

Person person = personRepository.findOne(1L);

So, I assume the findOne method is a method you defined in the PersonRepository. However, the findOne method is not very useful in your case. Since you need to fetch the Person along with is roles collection, it's better to use a findOneWithRoles method instead.

Custom Spring Data methods

You can define a PersonRepositoryCustom interface, as follows:

public interface PersonRepository
    extends JpaRepository<Person, Long>, PersonRepositoryCustom { 

}

public interface PersonRepositoryCustom {
    Person findOneWithRoles(Long id);
}

And define its implementation like this:

public class PersonRepositoryImpl implements PersonRepositoryCustom {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Person findOneWithRoles(Long id)() {
        return entityManager.createQuery("""
            select p 
            from Person p
            left join fetch p.roles
            where p.id = :id 
            """, Person.class)
        .setParameter("id", id)
        .getSingleResult();
    }
}

That's it!

round() for float in C++

There's no round() in the C++98 standard library. You can write one yourself though. The following is an implementation of round-half-up:

double round(double d)
{
  return floor(d + 0.5);
}

The probable reason there is no round function in the C++98 standard library is that it can in fact be implemented in different ways. The above is one common way but there are others such as round-to-even, which is less biased and generally better if you're going to do a lot of rounding; it's a bit more complex to implement though.

How can I hide or encrypt JavaScript code?

One of the best compressors (not specifically an obfuscator) is the YUI Compressor.

Hex colors: Numeric representation for "transparent"?

You can use this conversion table: http://roselab.jhu.edu/~raj/MISC/hexdectxt.html

eg, if you want a transparency of 60%, you use 3C (hex equivalent).

This is usefull for IE background gradient transparency:

filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#3C545454, endColorstr=#3C545454);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#3C545454, endColorstr=#3C545454)";

where startColorstr and endColorstr: 2 first characters are a hex value for transparency, and the six remaining are the hex color.

JavaScript - document.getElementByID with onClick

In JavaScript functions are objects.

document.getElementById('foo').onclick = function(){
    prompt('Hello world');
}

PHP Warning: PHP Startup: ????????: Unable to initialize module

Looks like you haven't upgraded PHP modules, they are not compatible.

Check extension_dir directive in your php.ini. It should point to folder with 5.2 modules.

Create and open a phpinfo file and search for extension_dir to find the path.

Since you did upgrade, there is a chance that you are using old php.ini that is pointing to 5.1 modules

Tar error: Unexpected EOF in archive

Interesting. I have a few questions which may point out the problem.

1/ Are you untarring on the same platform as you're tarring on? They may be different versions of tar (e.g., GNU and old-unix)? If they're different, can you untar on the same box you tarred on?

2/ What happens when you simply gunzip myarchive.tar.gz? Does that work? Maybe your file is being corrupted/truncated. I'm assuming you would notice if the compression generated errors, yes?

Based on the GNU tar source, it will only print that message if find_next_block() returns 0 prematurely which is usually caused by truncated archive.

Xcode build failure "Undefined symbols for architecture x86_64"

Could also be an #include <windows.h> in the .c file that you're trying to compile.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Solutions:

Solution A:

  1. Download http://www.servlets.com/cos/index.html
  2. Invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:

  1. Download http://jakarta.Apache.org/commons/fileupload/
  2. Invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:

  1. Download http://users.boone.net/wbrameld/multipartformdata/
  2. Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:

Use Struts. Struts 1.1 handles this automatically.

Reference: http://www.jguru.com/faq/view.jsp?EID=1045507

Redirecting from HTTP to HTTPS with PHP

On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:

if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

Equivalent of LIMIT and OFFSET for SQL Server?

Adding a slight variation on Aaronaught's solution, I typically parametrize page number (@PageNum) and page size (@PageSize). This way each page click event just sends in the requested page number along with a configurable page size:

begin
    with My_CTE  as
    (
         SELECT col1,
              ROW_NUMBER() OVER(ORDER BY col1) AS row_number
     FROM
          My_Table
     WHERE
          <<<whatever>>>
    )
    select * from My_CTE
            WHERE RowNum BETWEEN (@PageNum - 1) * (@PageSize + 1) 
                              AND @PageNum * @PageSize

end

max(length(field)) in mysql

Select URColumnName From URTableName Where length(URColumnName ) IN 
(Select max(length(URColumnName)) From URTableName);

This will give you the records in that particular column which has the maximum length.

[Vue warn]: Cannot find element

I get the same error. the solution is to put your script code before the end of body, not in the head section.

Pointer to incomplete class type is not allowed

An "incomplete class" is one declared but not defined. E.g.

class Wielrenner;

as opposed to

class Wielrenner
{
    /* class members */
};

You need to #include "wielrenner.h" in dokter.ccp

Is there a way to make AngularJS load partials in the beginning and not at when needed?

Yes, there are at least 2 solutions for this:

  1. Use the script directive (http://docs.angularjs.org/api/ng.directive:script) to put your partials in the initially loaded HTML
  2. You could also fill in $templateCache (http://docs.angularjs.org/api/ng.$templateCache) from JavaScript if needed (possibly based on result of $http call)

If you would like to use method (2) to fill in $templateCache you can do it like this:

$templateCache.put('second.html', '<b>Second</b> template');

Of course the templates content could come from a $http call:

$http.get('third.html', {cache:$templateCache});

Here is the plunker those techniques: http://plnkr.co/edit/J6Y2dc?p=preview

MySQL limit from descending order

yes, you can swap these 2 queries

select * from table limit 5, 5

select * from table limit 0, 5

How to set a value for a selectize.js input?

First load select dropdown and then selectize it. It will work with normal $(select).val().

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Two arrays in foreach loop

Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

becomes:

$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');

How to save RecyclerView's scroll position using RecyclerView.State?

I had the same problem with a minor difference, I was using Databinding, and I was setting recyclerView adapter and the layoutManager in the binding methods.

The problem was that data-binding was happening after onResume so it was resetting my layoutManager after onResume and that means it was scrolling back to original place every time. So when I stopped setting layoutManager in Databinding adaptor methods, it works fine again.

Finding local maxima/minima with Numpy in a 1D numpy array

Why not use Scipy built-in function signal.find_peaks_cwt to do the job ?

from scipy import signal
import numpy as np

#generate junk data (numpy 1D arr)
xs = np.arange(0, np.pi, 0.05)
data = np.sin(xs)

# maxima : use builtin function to find (max) peaks
max_peakind = signal.find_peaks_cwt(data, np.arange(1,10))

# inverse  (in order to find minima)
inv_data = 1/data
# minima : use builtin function fo find (min) peaks (use inversed data)
min_peakind = signal.find_peaks_cwt(inv_data, np.arange(1,10))

#show results
print "maxima",  data[max_peakind]
print "minima",  data[min_peakind]

results:

maxima [ 0.9995736]
minima [ 0.09146464]

Regards

MySQL vs MongoDB 1000 reads

On Single Server, MongoDb would not be any faster than mysql MyISAM on both read and write, given table/doc sizes are small 1 GB to 20 GB.
MonoDB will be faster on Parallel Reduce on Multi-Node clusters, where Mysql can NOT scale horizontally.

How can I check MySQL engine type for a specific table?

SHOW TABLE STATUS WHERE Name = 'xxx'

This will give you (among other things) an Engine column, which is what you want.

Python math module

add:

import math

at beginning. and then use:

math.sqrt(num)  # or any other function you deem neccessary

How to use bluetooth to connect two iPhone?

If I remember correctly, Bluetooth defines certain roles that devices can take. Most cell phones only support a certain number of roles. For instance, I can have a Bluetooth stereo headset that connects to my phone to receive audio, but just because my cell phone has Bluetooth does mean that it supports BEING a speaker for a different device - it doesn't advertise its capabilities of having a speaker for use by other Bluetooth devices.

I assume you want to transfer files between two iPhones? Transferring files via Bluetooth does seem like functionality that I would put in the iPhone, but I'm not Apple so I don't know for sure. In fact, yes, it seems that file transfer is not supported except in jailbroken phones:

http://gizmodo.com/5138797/iphone-bluetooth-file-transfer-coming-soon-yes

You'll probably get similar answers for Bluetooth Dial-Up Networking. I'd imagine they kept the Bluetooth commands out of the SDK for various reasons and you'll have to jailbreak your phone to get the functionality back.

Unable to show a Git tree in terminal

Keeping your commands short will make them easier to remember:

git log --graph --oneline

Finding the max value of an attribute in an array of objects

clean and simple ES6 (Babel)

const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);

The second parameter should ensure a default value if arrayToSearchIn is empty.

AngularJs .$setPristine to reset form

I solved the same problem of having to reset a form at its pristine state in Angular version 1.0.7 (no $setPristine method)

In my use case, the form, after being filled and submitted must disappear until it is again necessary for filling another record. So I made the show/hide effect by using ng-switch instead of ng-show. As I suspected, with ng-switch, the form DOM sub-tree is completely removed and later recreated. So the pristine state is automatically restored.

I like it because it is simple and clean but it may not be a fit for anybody's use case.

it may also imply some performance issues for big forms (?) In my situation I did not face this problem yet.

How to throw an exception in C?

As mentioned in numerous threads, the "standard" way of doing this is using setjmp/longjmp. I posted yet another such solution to https://github.com/psevon/exceptions-and-raii-in-c This is to my knowledge the only solution that relies on automatic cleanup of allocated resources. It implements unique and shared smartpointers, and allows intermediate functions to let exceptions pass through without catching and still have their locally allocated resources cleaned up properly.

How do I get the dialer to open with phone number displayed?

<TextView
 android:id="@+id/phoneNumber"
 android:autoLink="phone"
 android:linksClickable="true"
 android:text="+91 22 2222 2222"
 />

This is how you can open EditText label assigned number on dialer directly.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

Well try ini_set('memory_limit', '256M');

134217728 bytes = 128 MB

Or rewrite the code to consume less memory.

Check whether an array is empty

You can also check it by doing.

if(count($array) > 0)
{
    echo 'Error';
}
else
{
    echo 'No Error';
}

Add custom message to thrown exception while maintaining stack trace in Java

you can use super while extending Exception

if (pass.length() < minPassLength)
    throw new InvalidPassException("The password provided is too short");
 } catch (NullPointerException e) {
    throw new InvalidPassException("No password provided", e);
 }


// A custom business exception
class InvalidPassException extends Exception {

InvalidPassException() {

}

InvalidPassException(String message) {
    super(message);
}
InvalidPassException(String message, Throwable cause) {
   super(message, cause);
}

}

}

source

Currently running queries in SQL Server

here is what you need to install the SQL profiler http://msdn.microsoft.com/en-us/library/bb500441.aspx. However, i would suggest you to read through this one http://blog.sqlauthority.com/2009/08/03/sql-server-introduction-to-sql-server-2008-profiler-2/ if you are looking to do it on your Production Environment. There is another better way to look at the queries watch this one and see if it helps http://www.youtube.com/watch?v=vvziPI5OQyE

How do I use Wget to download all images into a single folder, from a URL?

wget utility retrieves files from World Wide Web (WWW) using widely used protocols like HTTP, HTTPS and FTP. Wget utility is freely available package and license is under GNU GPL License. This utility can be install any Unix-like Operating system including Windows and MAC OS. It’s a non-interactive command line tool. Main feature of Wget is it’s robustness. It’s designed in such way so that it works in slow or unstable network connections. Wget automatically start download where it was left off in case of network problem. Also downloads file recursively. It’ll keep trying until file has be retrieved completely.

Install wget in linux machine sudo apt-get install wget

Create a folder where you want to download files . sudo mkdir myimages cd myimages

Right click on the webpage and for example if you want image location right click on image and copy image location. If there are multiple images then follow the below:

If there are 20 images to download from web all at once, range starts from 0 to 19.

wget http://joindiaspora.com/img{0..19}.jpg

A table name as a variable

Declare  @tablename varchar(50) 
set @tablename = 'Your table Name' 
EXEC('select * from ' + @tablename)

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

@Autowired annotation is defined in the Spring framework.

@Inject annotation is a standard annotation, which is defined in the standard "Dependency Injection for Java" (JSR-330). Spring (since the version 3.0) supports the generalized model of dependency injection which is defined in the standard JSR-330. (Google Guice frameworks and Picocontainer framework also support this model).

With @Inject can be injected the reference to the implementation of the Provider interface, which allows injecting the deferred references.

Annotations @Inject and @Autowired- is almost complete analogies. As well as @Autowired annotation, @Inject annotation can be used for automatic binding properties, methods, and constructors.

In contrast to @Autowired annotation, @Inject annotation has no required attribute. Therefore, if the dependencies will not be found - will be thrown an exception.

There are also differences in the clarifications of the binding properties. If there is ambiguity in the choice of components for the injection the @Named qualifier should be added. In a similar situation for @Autowired annotation will be added @Qualifier qualifier (JSR-330 defines it's own @Qualifier annotation and via this qualifier annotation @Named is defined).

Attempted to read or write protected memory

Check to make sure you don't have threads within threads. That's what caused this error for me. See this link: Attempted to read or write protected memory. This is often an indication that other memory is corrupt

addID in jQuery?

Like this :

var id = $('div.foo').attr('id');
$('div.foo').attr('id', id + ' id_adding');
  1. get actual ID
  2. put actuel ID and add the new one

top nav bar blocking top content of the page

The bootstrap v4 starter template css uses:

body {
  padding-top: 5rem;
}

What is the difference between an IntentService and a Service?

Service

  • Task with no UI,but should not use for long Task. Use Thread within service for long Task
  • Invoke by onStartService()
  • Triggered from any Thread
  • Runs On Main Thread
  • May block main(UI) thread

IntentService

  • Long task usually no communication with main thread if communication is needed then it is done by Handler or broadcast
  • Invoke via Intent
  • triggered from Main Thread (Intent is received on main Thread and worker thread is spawned)
  • Runs on separate thread
  • We can't run task in parallel and multiple intents are Queued on the same worker thread.

How to compile and run C/C++ in a Unix console/Mac terminal?

Assuming the current directory is not in the path, the syntax is ./[name of the program].

For example ./a.out

Assignment makes pointer from integer without cast

You don't need these two assigments:

cString1 = strToLower(cString1); 
cString2 = strToLower(cString2);

you are modifying the strings in place.

Warnings are because you are returning a char, and assigning to a char[] (which is equivalent to char*)

Data at the root level is invalid

This:

doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));

should be:

doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));

LoadXml() is for loading an XML string, not a file name.

html script src="" triggering redirection with button

your folder name is scripts..

and you are Referencing it like ../script/login.js

Also make sure that script folder is in your project directory

Thanks

Is there a way to get version from package.json in nodejs code?

Using ES6 modules you can do the following:

import {version} from './package.json';

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

Let's say you have a tar file and you want to uncompress it after placing it in your container, remove it, you can use the COPY command to do this. Butt he various commands would be 1) Copy the tar file to the destination, 2). Uncompress it, 3) Remove the tar file. If you did this in 3 steps then there will be a new image created after each step. You can do this in one step using & but it becomes a hassle.

But you used ADD, then Docker will take care of everything for you and only one intermediate image will be created.

Angular 2 optional route parameter

You can define multiple routes with and without parameter:

@RouteConfig([
    { path: '/user/:id', component: User, name: 'User' },
    { path: '/user', component: User, name: 'Usernew' }
])

and handle the optional parameter in your component:

constructor(params: RouteParams) {
    var paramId = params.get("id");

    if (paramId) {
        ...
    }
}

See also the related github issue: https://github.com/angular/angular/issues/3525

Scala how can I count the number of occurrences in a list

using cats

import cats.implicits._

"Alphabet".toLowerCase().map(c => Map(c -> 1)).toList.combineAll
"Alphabet".toLowerCase().map(c => Map(c -> 1)).toList.foldMap(identity)

Java - Convert integer to string

Integer class has static method toString() - you can use it:

int i = 1234;
String str = Integer.toString(i);

Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.

How do I escape double and single quotes in sed?

May be the "\" char, try this one:

sed 's/\"http:\/\/www.fubar.com\"/URL_FUBAR/g'

'JSON' is undefined error in JavaScript in Internet Explorer

Please add json2.js in your project . i was faced the same issue i have fixed.

please use the link: https://raw.github.com/douglascrockford/JSON-js/master/json2.js and create new file json.js, copy the page and past into newly created file , and move that file into your web application.

I hope it will work.

Check div is hidden using jquery

You can check the CSS display property:

if ($('#car').css('display') == 'none') {
    alert('Car 2 is hidden');
}

Here is a demo: http://jsfiddle.net/YjP4K/

Call function with setInterval in jQuery?

To write the best code, you "should" use the latter approach, with a function reference:

var refreshId = setInterval(function() {}, 5000);

or

function test() {}
var refreshId = setInterval(test, 5000);

but your approach of

function test() {}
var refreshId = setInterval("test()", 5000);

is basically valid, too (as long as test() is global).

Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library.

How to prevent errno 32 broken pipe?

This might be because you are using two method for inserting data into database and this cause the site to slow down.

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email).save()  <==== 
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

In above function, the error is where arrow is pointing. The correct implementation is below:

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email)
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

How to Consume WCF Service with Android

To get started with WCF, it might be easiest to just use the default SOAP format and HTTP POST (rather than GET) for the web-service bindings. The easiest HTTP binding to get working is "basicHttpBinding". Here is an example of what the ServiceContract/OperationContract might look like for your login service:

[ServiceContract(Namespace="http://mycompany.com/LoginService")]
public interface ILoginService
{
    [OperationContract]
    string Login(string username, string password);
}

The implementation of the service could look like this:

public class LoginService : ILoginService
{
    public string Login(string username, string password)
    {
        // Do something with username, password to get/create sessionId
        // string sessionId = "12345678";
        string sessionId = OperationContext.Current.SessionId;

        return sessionId;
    }
}

You can host this as a windows service using a ServiceHost, or you can host it in IIS like a normal ASP.NET web (service) application. There are a lot of tutorials out there for both of these.

The WCF service config might look like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>


    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="LoginServiceBehavior">
                    <serviceMetadata />
                </behavior>
            </serviceBehaviors>
        </behaviors>

        <services>
            <service name="WcfTest.LoginService"
                     behaviorConfiguration="LoginServiceBehavior" >
                <host>
                    <baseAddresses>
                        <add baseAddress="http://somesite.com:55555/LoginService/" />
                    </baseAddresses>
                </host>
                <endpoint name="LoginService"
                          address=""
                          binding="basicHttpBinding"
                          contract="WcfTest.ILoginService" />

                <endpoint name="LoginServiceMex"
                          address="mex"
                          binding="mexHttpBinding"
                          contract="IMetadataExchange" />
            </service>
        </services>
    </system.serviceModel>
</configuration>

(The MEX stuff is optional for production, but is needed for testing with WcfTestClient.exe, and for exposing the service meta-data).

You'll have to modify your Java code to POST a SOAP message to the service. WCF can be a little picky when inter-operating with non-WCF clients, so you'll have to mess with the POST headers a little to get it to work. Once you get this running, you can then start to investigate security for the login (might need to use a different binding to get better security), or possibly using WCF REST to allow for logins with a GET rather than SOAP/POST.

Here is an example of what the HTTP POST should look like from the Java code. There is a tool called "Fiddler" that can be really useful for debugging web-services.

POST /LoginService HTTP/1.1
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://mycompany.com/LoginService/ILoginService/Login"
Host: somesite.com:55555
Content-Length: 216
Expect: 100-continue
Connection: Keep-Alive

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Login xmlns="http://mycompany.com/LoginService">
<username>Blah</username>
<password>Blah2</password>
</Login>
</s:Body>
</s:Envelope>

How to pass multiple parameters in thread in VB

Just create a class or structure that has two members, one List(Of OneItem) and the other Integer and send in an instance of that class.

Edit: Sorry, missed that you had problems with one parameter as well. Just look at Thread Constructor (ParameterizedThreadStart) and that page includes a simple sample.

iOS 6 apps - how to deal with iPhone 5 screen size?

@interface UIDevice (Screen)
typedef enum
{
    iPhone          = 1 << 1,
    iPhoneRetina    = 1 << 2,
    iPhone5         = 1 << 3,
    iPad            = 1 << 4,
    iPadRetina      = 1 << 5

} DeviceType;

+ (DeviceType)deviceType;
@end

.m

#import "UIDevice+Screen.h"
@implementation UIDevice (Screen)

+ (DeviceType)deviceType
{
    DeviceType thisDevice = 0;
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    {
        thisDevice |= iPhone;
        if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
        {
            thisDevice |= iPhoneRetina;
            if ([[UIScreen mainScreen] bounds].size.height == 568)
                thisDevice |= iPhone5;
        }
    }
    else
    {
        thisDevice |= iPad;
        if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
            thisDevice |= iPadRetina;
    }
    return thisDevice;
}

@end

This way, if you want to detect whether it is just an iPhone or iPad (regardless of screen-size), you just use:

if ([UIDevice deviceType] & iPhone) 

or

if ([UIDevice deviceType] & iPad)

If you want to detect just the iPhone 5, you can use

if ([UIDevice deviceType] & iPhone5)

As opposed to Malcoms answer where you would need to check just to figure out if it's an iPhone,

if ([UIDevice currentResolution] == UIDevice_iPhoneHiRes || 
    [UIDevice currentResolution] == UIDevice_iPhoneStandardRes || 
    [UIDevice currentResolution] == UIDevice_iPhoneTallerHiRes)`

Neither way has a major advantage over one another, it is just a personal preference.

How to use type: "POST" in jsonp ajax call

You can't POST using JSONP...it simply doesn't work that way, it creates a <script> element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.

Can't start Tomcat as Windows Service

I had the similar issue, But installing tomcat 32bit and jdk 32 bit worked, This happens mostly because of mismatch Bit.

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

Can I obtain method parameter name using Java reflection?

In Java 8 you can do the following:

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

public final class Methods {

    public static List<String> getParameterNames(Method method) {
        Parameter[] parameters = method.getParameters();
        List<String> parameterNames = new ArrayList<>();

        for (Parameter parameter : parameters) {
            if(!parameter.isNamePresent()) {
                throw new IllegalArgumentException("Parameter names are not present!");
            }

            String parameterName = parameter.getName();
            parameterNames.add(parameterName);
        }

        return parameterNames;
    }

    private Methods(){}
}

So for your class Whatever we can do a manual test:

import java.lang.reflect.Method;

public class ManualTest {
    public static void main(String[] args) {
        Method[] declaredMethods = Whatever.class.getDeclaredMethods();

        for (Method declaredMethod : declaredMethods) {
            if (declaredMethod.getName().equals("aMethod")) {
                System.out.println(Methods.getParameterNames(declaredMethod));
                break;
            }
        }
    }
}

which should print [aParam] if you have passed -parameters argument to your Java 8 compiler.

For Maven users:

<properties>
    <!-- PLUGIN VERSIONS -->
    <maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>

    <!-- OTHER PROPERTIES -->
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven-compiler-plugin.version}</version>
            <configuration>
                <!-- Original answer -->
                <compilerArgument>-parameters</compilerArgument>
                <!-- Or, if you use the plugin version >= 3.6.2 -->
                <parameters>true</parameters>
                <testCompilerArgument>-parameters</testCompilerArgument>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

For more information see following links:

  1. Official Java Tutorial: Obtaining Names of Method Parameters
  2. JEP 118: Access to Parameter Names at Runtime
  3. Javadoc for Parameter class

Getting String Value from Json Object Android

This might help you.

Java:

JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");

Kotlin:

val jsonArray = JSONArray(result)
val jsonObject: JSONObject = jsonArray.getJSONObject(0)
val date= jsonObject.get("NeededString")
  • getJSONObject(index). In above example 0 represents index.

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

Using XAMPP on ubuntu:

  1. Create a folder called mysqld inside /var/run directory. You can accomplish that using the command sudo mkdir /var/run/mysqld.

  2. Create a symbolic link to mysql.sock file that is created by the XAMPP server when it is started. You can use the command sudo ln -s /opt/lampp/var/mysql/mysql.sock /var/run/mysqld/mysqld.sock.

Note: The mysql.sock file is created when the server is started and removed when the server is stopped, so sometimes the link you created might appear to be broken but it should work as long as you have started the server using either sudo /opt/lampp/lampp start or any other means.

  1. Start the server if it's not already running and try executing your program again.

Good luck! I hope you'll get away with it this time.

TCPDF ERROR: Some data has already been output, can't send PDF file

Use ob_start(); at the beginning of your code.

git commit error: pathspec 'commit' did not match any file(s) known to git

I would just like to add--

In windows the commit message should be in double quotes (git commit -m "initial commit" instead of git commit -m 'initial commit'), as I spent about an hour, just to figure out that single quote is not working in windows.

Determining if an Object is of primitive type

The primitve wrapper types will not respond to this value. This is for class representation of primitives, though aside from reflection I can't think of too many uses for it offhand. So, for example

System.out.println(Integer.class.isPrimitive());

prints "false", but

public static void main (String args[]) throws Exception
{
    Method m = Junk.class.getMethod( "a",null);
    System.out.println( m.getReturnType().isPrimitive());
}

public static int a()
{
    return 1;
}

prints "true"

not:first-child selector

You can use any selector with not

p:not(:first-child){}
p:not(:first-of-type){}
p:not(:checked){}
p:not(:last-child){}
p:not(:last-of-type){}
p:not(:first-of-type){}
p:not(:nth-last-of-type(2)){}
p:not(nth-last-child(2)){}
p:not(:nth-child(2)){}

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I ran into this issue as well and found this post. Ultimately none of these answers solved my problem, instead I had to put in a rewrite rule to strip out the location /rt as the backend my developers made was not expecting any additional paths:

+-(william@wkstn18)--(Thu, 05 Nov 20)-+
+-(~)--(16:13)->wscat -c ws://WebsocketServerHostname/rt
error: Unexpected server response: 502

Testing with wscat repeatedly gave a 502 response. Nginx error logs provided the same upstream error as above, but notice the upstream string shows the GET Request is attempting to access localhost:12775/rt and not localhost:12775:

 2020/11/05 22:13:32 [error] 10175#10175: *7 upstream prematurely closed
 connection while reading response header from upstream, client: WANIP,
 server: WebsocketServerHostname, request: "GET /rt/socket.io/?transport=websocket
 HTTP/1.1", upstream: "http://127.0.0.1:12775/rt/socket.io/?transport=websocket",
 host: "WebsocketServerHostname"

Since the devs had not coded their websocket (listening on 12775) to expect /rt/socket.io but instead just /socket.io/ (NOTE: /socket.io/ appears to just be a way to specify websocket transport discussed here). Because of this, rather than ask them to rewrite their socket code I just put in a rewrite rule to translate WebsocketServerHostname/rt to WebsocketServerHostname:12775 as below:

upstream websocket-rt {
        ip_hash;

        server 127.0.0.1:12775;
}

server {
        listen 80;
        server_name     WebsocketServerHostname;

        location /rt {
                proxy_http_version 1.1;

                #rewrite /rt/ out of all requests and proxy_pass to 12775
                rewrite /rt/(.*) /$1  break;

                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;

                proxy_pass http://websocket-rt;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection $connection_upgrade;
        }

}

How to get the week day name from a date?

To do this for oracle sql, the syntax would be:

,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field

for this example, I look for the second '-' and take the substring to the end

Single statement across multiple lines in VB.NET without the underscore character

Not sure if you can do that with multi-line code, but multi-line variables can be done:

Multiline strings in VB.NET

Here is the relevant chunk:

I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

Dim script As String = <code><![CDATA[
  <script type="text/javascript">
    var URL = ']]><%= domain %><![CDATA[/mypage.html';
  </script>]]>
</code>.value

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

            using (var tbl = new DataTable())
            using (var rdr = cmd.ExecuteReader())
            {
                tbl.BeginLoadData();

                try
                {
                    tbl.Load(rdr);
                }
                catch (ConstraintException ex)
                {
                    rdr.Close();
                    tbl.Clear();

                    // clear constraints, source of exceptions
                    // note: column schema already loaded!
                    tbl.Constraints.Clear();
                    tbl.Load(cmd.ExecuteReader());
                }
                finally
                {
                    tbl.EndLoadData();
                }
            }

Convert a secure string to plain text

You are close, but the parameter you pass to SecureStringToBSTR must be a SecureString. You appear to be passing the result of ConvertFrom-SecureString, which is an encrypted standard string. So call ConvertTo-SecureString on this before passing to SecureStringToBSTR.

$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

Also realized this problem comes up when trying to combine reactive form and template form approaches. I had #name="ngModel" and [formControl]="name" on the same element. Removing either one fixed the issue. Also not that if you use #name=ngModel you should also have a property such as this [(ngModel)]="name" , otherwise, You will still get the errors. This applies to angular 6, 7 and 8 too.

List comprehension on a nested list?

Here is how you would do this with a nested list comprehension:

[[float(y) for y in x] for x in l]

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use [float(y) for x in l for y in x].

How to place div side by side

If you're not tagetting IE6, then float the second <div> and give it a margin equal to (or maybe a little bigger than) the first <div>'s fixed width.

HTML:

<div id="main-wrapper">
    <div id="fixed-width"> lorem ipsum </div>
    <div id="rest-of-space"> dolor sit amet </div>
</div>

CSS:

#main-wrapper {
    100%;
    background:red;
}
#fixed-width {
    width:100px;
    float:left
}
#rest-of-space {
    margin-left:101px;
        /* May have to increase depending on borders and margin of the fixd width div*/
    background:blue;
}

The margin accounts for the possibility that the 'rest-of-space' <div> may contain more content than the 'fixed-width' <div>.

Don't give the fixed width one a background; if you need to visibly see these as different 'columns' then use the Faux Columns trick.

READ_EXTERNAL_STORAGE permission for Android

http://developer.android.com/reference/android/provider/MediaStore.Audio.AudioColumns.html

Try changing the line contentResolver.query

//change it to the columns you need
String[] columns = new String[]{MediaStore.Audio.AudioColumns.DATA}; 
Cursor cursor = contentResolver.query(uri, columns, null, null, null);

public static final String MEDIA_CONTENT_CONTROL

Not for use by third-party applications due to privacy of media consumption

http://developer.android.com/reference/android/Manifest.permission.html#MEDIA_CONTENT_CONTROL

try to remove the <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/> first and try again?

How to force Laravel Project to use HTTPS for all routes?

I would prefer forceScheme instead of doing it on a web server. So Laravel app should be responsible for it.

So right way is to add if statement inside boot function in your app/Providers/AppServiceProvider.php

    if (env('APP_ENV') === 'production') {
        \Illuminate\Support\Facades\URL::forceScheme('https');
    }

Tip: to prove that you have APP_ENV configured correctly. Go to your Linux server, type env

This was tested on Laravel 5, specifically 5.6.