Appending an element to the end of a list in Scala
List(1,2,3) :+ 4
Results in List[Int] = List(1, 2, 3, 4)
Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).
How to convert DateTime? to DateTime
How about the following:
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue ? _objHotelPackageOrder.UpdatedDate.value : DateTime.Now;
Importing Excel files into R, xlsx or xls
If you are running into the same problem and R is giving you an error -- could not find function ".jnew" -- Just install the library rJava. Or if you have it already just run the line library(rJava). That should be the problem.
Also, it should be clear to everybody that csv and txt files are easier to work with, but life is not easy and sometimes you just have to open an xlsx.
How to check object is nil or not in swift?
if (MyUnknownClassOrType is nil) {
println("No class or object to see here")
}
Apple also recommends that you use this to check for depreciated and removed classes from previous frameworks.
Here's an exact quote from a developer at Apple:
Yes. If the currently running OS doesn’t implement the class then the class method will return nil.
Hope this helps :)
Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0
Since I don't have a 50 reputation Stackoverflow wont let me comment on the second best answer. Found another trick for finding the culprit label in the Storyboard.
So once you know the id of the label, open your storyboard in a seperate tab with view controllers displayed and just do command F and command V and will take you straight to that label :)
Checking if a folder exists using a .bat file
For a file:
if exist yourfilename (
echo Yes
) else (
echo No
)
Replace yourfilename with the name of your file.
For a directory:
if exist yourfoldername\ (
echo Yes
) else (
echo No
)
Replace yourfoldername with the name of your folder.
A trailing backslash (\
) seems to be enough to distinguish between directories and ordinary files.
Function to Calculate Median in SQL Server
Building on Jeff Atwood's answer above here it is with GROUP BY and a correlated subquery to get the median for each group.
SELECT TestID,
(
(SELECT MAX(Score) FROM
(SELECT TOP 50 PERCENT Score FROM Posts WHERE TestID = Posts_parent.TestID ORDER BY Score) AS BottomHalf)
+
(SELECT MIN(Score) FROM
(SELECT TOP 50 PERCENT Score FROM Posts WHERE TestID = Posts_parent.TestID ORDER BY Score DESC) AS TopHalf)
) / 2 AS MedianScore,
AVG(Score) AS AvgScore, MIN(Score) AS MinScore, MAX(Score) AS MaxScore
FROM Posts_parent
GROUP BY Posts_parent.TestID
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Delete all items from a c++ std::vector
If you keep pointers in container and don't want to bother with manually destroying of them, then use boost shared_ptr. Here is sample for std::vector, but you can use it for any other STL container (set, map, queue, ...)
#include <iostream>
#include <vector>
#include <boost/shared_ptr.hpp>
struct foo
{
foo( const int i_x ) : d_x( i_x )
{
std::cout << "foo::foo " << d_x << std::endl;
}
~foo()
{
std::cout << "foo::~foo " << d_x << std::endl;
}
int d_x;
};
typedef boost::shared_ptr< foo > smart_foo_t;
int main()
{
std::vector< smart_foo_t > foos;
for ( int i = 0; i < 10; ++i )
{
smart_foo_t f( new foo( i ) );
foos.push_back( f );
}
foos.clear();
return 0;
}
Is it possible to read from a InputStream with a timeout?
Assuming your stream is not backed by a socket (so you can't use Socket.setSoTimeout()
), I think the standard way of solving this type of problem is to use a Future.
Suppose I have the following executor and streams:
ExecutorService executor = Executors.newFixedThreadPool(2);
final PipedOutputStream outputStream = new PipedOutputStream();
final PipedInputStream inputStream = new PipedInputStream(outputStream);
I have writer that writes some data then waits for 5 seconds before writing the last piece of data and closing the stream:
Runnable writeTask = new Runnable() {
@Override
public void run() {
try {
outputStream.write(1);
outputStream.write(2);
Thread.sleep(5000);
outputStream.write(3);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
executor.submit(writeTask);
The normal way of reading this is as follows. The read will block indefinitely for data and so this completes in 5s:
long start = currentTimeMillis();
int readByte = 1;
// Read data without timeout
while (readByte >= 0) {
readByte = inputStream.read();
if (readByte >= 0)
System.out.println("Read: " + readByte);
}
System.out.println("Complete in " + (currentTimeMillis() - start) + "ms");
which outputs:
Read: 1
Read: 2
Read: 3
Complete in 5001ms
If there was a more fundamental problem, like the writer not responding, the reader would block for ever.
If I wrap the read in a future, I can then control the timeout as follows:
int readByte = 1;
// Read data with timeout
Callable<Integer> readTask = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return inputStream.read();
}
};
while (readByte >= 0) {
Future<Integer> future = executor.submit(readTask);
readByte = future.get(1000, TimeUnit.MILLISECONDS);
if (readByte >= 0)
System.out.println("Read: " + readByte);
}
which outputs:
Read: 1
Read: 2
Exception in thread "main" java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:228)
at java.util.concurrent.FutureTask.get(FutureTask.java:91)
at test.InputStreamWithTimeoutTest.main(InputStreamWithTimeoutTest.java:74)
I can catch the TimeoutException and do whatever cleanup I want.
css3 text-shadow in IE9
I tried out the filters referenced above and strongly disliked the effect it created. I also didn't want to use any plugins since they'd slow down loading time for what seems like such a basic effect.
In my case I was looking for a text shadow with a 0px blur, which means the shadow is an exact replica of the text but just offset and behind. This effect can be easily recreated with jquery.
<script>
var shadowText = $(".ie9 .normalText").html();
$(".ie9 .normalText").before('<div class="shadow">' + shadowText + '</div>');
</script>
<style>
.ie9 .shadow { position: relative; top: 2px; left: -3px; }
</style>
This will create an identical effect to the css3 text-shadow below.
text-shadow: -3px 2px 0px rgba(0, 0, 0, 1.0);
here's a working example (see the large white text over the main banner image) http://www.cb.restaurantconnectinc.com/
Fatal error: Call to undefined function sqlsrv_connect()
This helped me get to my answer. There are two php.ini
files located, in my case, for wamp. One is under the php folder and the other one is in the C:\wamp\bin\apache\Apachex.x.x\bin
folder. When connecting to SQL through sqlsrv_connect
function, we are referring to the php.ini
file in the apache
folder. Add the following (as per your version) to this file:
extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll
Android Studio - Emulator - eglSurfaceAttrib not implemented
I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)
In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!
Passing parameters from jsp to Spring Controller method
Use the @RequestParam to pass a parameter to the controller handler method.
In the jsp your form should have an input field with name = "id"
like the following:
<input type="text" name="id" />
<input type="submit" />
Then in your controller, your handler method should be like the following:
@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
Person person = personService.getCurrentlyAuthenticatedUser();
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
return "note";
}
Please also refer to these answers and tutorial:
Getting visitors country from their IP
I have written a class based on "Chandra Nakka" answer. Hopefully it can help people out it saves the information from geoplugin to a session so the load is much faster when recalling the information. It also saves the values to a private array so recalling in the same code is the fastest as it could be.
class Geo {
private $_ip = null;
private $_useSession = true;
private $_sessionNameData = 'GEO_SESSION_DATA';
private $_hasError = false;
private $_geoData = [];
const PURPOSE_SUPPORT = [
"all", "*", "location",
"request",
"latitude",
"longitude",
"accuracy",
"timezonde",
"currencycode",
"currencysymbol",
"currencysymbolutf8",
"country",
"countrycode",
"state", "region",
"city",
"address",
"continent",
"continentcode"
];
const CONTINENTS = [
"AF" => "Africa",
"AN" => "Antarctica",
"AS" => "Asia",
"EU" => "Europe",
"OC" => "Australia (Oceania)",
"NA" => "North America",
"SA" => "South America"
];
function __construct($ip = null, $deepDetect = true, $useSession = true)
{
// define the session useage within this class
$this->_useSession = $useSession;
$this->_startSession();
// define a ip as far as possible
$this->_ip = $this->_defineIP($ip, $deepDetect);
// check if the ip was set
if (!$this->_ip) {
$this->_hasError = true;
return $this;
}
// define the geoData
$this->_geoData = $this->_fetchGeoData();
return $this;
}
function get($purpose)
{
// making sure its lowercase
$purpose = strtolower($purpose);
// makeing sure there are no error and the geodata is not empty
if ($this->_hasError || !count($this->_geoData) && !in_array($purpose, self::PURPOSE_SUPPORT)) {
return 'error';
}
if (in_array($purpose, ['*', 'all', 'location'])) {
return $this->_geoData;
}
if ($purpose === 'state') $purpose = 'region';
return (isset($this->_geoData[$purpose]) ? $this->_geoData[$purpose] : 'missing: '.$purpose);
}
private function _fetchGeoData()
{
// check if geo data was set before
if (count($this->_geoData)) {
return $this->_geoData;
}
// check possible session
if ($this->_useSession && ($sessionData = $this->_getSession($this->_sessionNameData))) {
return $sessionData;
}
// making sure we have a valid ip
if (!$this->_ip || $this->_ip === '127.0.0.1') {
return [];
}
// fetch the information from geoplusing
$ipdata = @json_decode($this->curl("http://www.geoplugin.net/json.gp?ip=" . $this->_ip));
// check if the data was fetched
if (!@strlen(trim($ipdata->geoplugin_countryCode)) === 2) {
return [];
}
// make a address array
$address = [$ipdata->geoplugin_countryName];
if (@strlen($ipdata->geoplugin_regionName) >= 1)
$address[] = $ipdata->geoplugin_regionName;
if (@strlen($ipdata->geoplugin_city) >= 1)
$address[] = $ipdata->geoplugin_city;
// makeing sure the continentCode is upper case
$continentCode = strtoupper(@$ipdata->geoplugin_continentCode);
$geoData = [
'request' => @$ipdata->geoplugin_request,
'latitude' => @$ipdata->geoplugin_latitude,
'longitude' => @$ipdata->geoplugin_longitude,
'accuracy' => @$ipdata->geoplugin_locationAccuracyRadius,
'timezonde' => @$ipdata->geoplugin_timezone,
'currencycode' => @$ipdata->geoplugin_currencyCode,
'currencysymbol' => @$ipdata->geoplugin_currencySymbol,
'currencysymbolutf8' => @$ipdata->geoplugin_currencySymbol_UTF8,
'city' => @$ipdata->geoplugin_city,
'region' => @$ipdata->geoplugin_regionName,
'country' => @$ipdata->geoplugin_countryName,
'countrycode' => @$ipdata->geoplugin_countryCode,
'continent' => self::CONTINENTS[$continentCode],
'continentcode' => $continentCode,
'address' => implode(", ", array_reverse($address))
];
if ($this->_useSession) {
$this->_setSession($this->_sessionNameData, $geoData);
}
return $geoData;
}
private function _startSession()
{
// only start a new session when the status is 'none' and the class
// requires a session
if ($this->_useSession && session_status() === PHP_SESSION_NONE) {
session_start();
}
}
private function _defineIP($ip, $deepDetect)
{
// check if the ip was set before
if ($this->_ip) {
return $this->_ip;
}
// check if the ip given is valid
if (filter_var($ip, FILTER_VALIDATE_IP)) {
return $ip;
}
// try to get the ip from the REMOTE_ADDR
$ip = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP);
// check if we need to end the search for a IP if the REMOTE_ADDR did not
// return a valid and the deepDetect is false
if (!$deepDetect) {
return $ip;
}
// try to get the ip from HTTP_X_FORWARDED_FOR
if (($ip = filter_input(INPUT_SERVER, 'HTTP_X_FORWARDED_FOR', FILTER_VALIDATE_IP))) {
return $ip;
}
// try to get the ip from the HTTP_CLIENT_IP
if (($ip = filter_input(INPUT_SERVER, 'HTTP_CLIENT_IP', FILTER_VALIDATE_IP))) {
return $ip;
}
return $ip;
}
private function _hasSession($key, $filter = FILTER_DEFAULT)
{
return (isset($_SESSION[$key]) ? (bool)filter_var($_SESSION[$key], $filter) : false);
}
private function _getSession($key, $filter = FILTER_DEFAULT)
{
if ($this->_hasSession($key, $filter)) {
$value = filter_var($_SESSION[$key], $filter);
if (@json_decode($value)) {
return json_decode($value, true);
}
return filter_var($_SESSION[$key], $filter);
} else {
return false;
}
}
private function _setSession($key, $value)
{
if (is_array($value)) {
$value = json_encode($value);
}
$_SESSION[$key] = $value;
}
function emptySession($key) {
if (!$this->_hasSession($key)) {
return;
}
$_SESSION[$key] = null;
unset($_SESSION[$key]);
}
function curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
Answering the 'op' question with this class you can call
$country = (new \Geo())->get('country'); // United Kingdom
And the other properties available are:
$geo = new \Geo('185.35.50.4');
var_dump($geo->get('*')); // allias all / location
var_dump($geo->get('country'));
var_dump($geo->get('countrycode'));
var_dump($geo->get('state')); // allias region
var_dump($geo->get('city'));
var_dump($geo->get('address'));
var_dump($geo->get('continent'));
var_dump($geo->get('continentcode'));
var_dump($geo->get('request'));
var_dump($geo->get('latitude'));
var_dump($geo->get('longitude'));
var_dump($geo->get('accuracy'));
var_dump($geo->get('timezonde'));
var_dump($geo->get('currencyCode'));
var_dump($geo->get('currencySymbol'));
var_dump($geo->get('currencySymbolUTF8'));
Returning
array(15) {
["request"]=>
string(11) "185.35.50.4"
["latitude"]=>
string(7) "51.4439"
["longitude"]=>
string(7) "-0.1854"
["accuracy"]=>
string(2) "50"
["timezonde"]=>
string(13) "Europe/London"
["currencycode"]=>
string(3) "GBP"
["currencysymbol"]=>
string(2) "£"
["currencysymbolutf8"]=>
string(2) "£"
["city"]=>
string(10) "Wandsworth"
["region"]=>
string(10) "Wandsworth"
["country"]=>
string(14) "United Kingdom"
["countrycode"]=>
string(2) "GB"
["continent"]=>
string(6) "Europe"
["continentcode"]=>
string(2) "EU"
["address"]=>
string(38) "Wandsworth, Wandsworth, United Kingdom"
}
string(14) "United Kingdom"
string(2) "GB"
string(10) "Wandsworth"
string(10) "Wandsworth"
string(38) "Wandsworth, Wandsworth, United Kingdom"
string(6) "Europe"
string(2) "EU"
string(11) "185.35.50.4"
string(7) "51.4439"
string(7) "-0.1854"
string(2) "50"
string(13) "Europe/London"
string(3) "GBP"
string(2) "£"
string(2) "£"
Rails Model find where not equal
You should always include the table name in the SQL query when dealing with associations.
Indeed if another table has the user_id
column and you join both tables, you will have an ambiguous column name in the SQL query (i.e. troubles).
So, in your example:
GroupUser.where("groups_users.user_id != ?", me)
Or a bit more verbose:
GroupUser.where("#{table_name}.user_id IS NOT ?", me)
Note that if you are using a hash, you don't need to worry about that because Rails takes care of it for you:
GroupUser.where(user: me)
In Rails 4, as said by @dr4k3, the query method not
has been added:
GroupUser.where.not(user: me)
Map enum in JPA with fixed values?
The problem is, I think, that JPA was never incepted with the idea in mind that we could have a complex preexisting Schema already in place.
I think there are two main shortcomings resulting from this, specific to Enum:
- The limitation of using name() and ordinal(). Why not just mark a getter with @Id, the way we do with @Entity?
- Enum's have usually representation in the database to allow association with all sorts of metadata, including a proper name, a descriptive name, maybe something with localization etc. We need the easy of use of an Enum combined with the flexibility of an Entity.
Help my cause and vote on JPA_SPEC-47
Would this not be more elegant than using a @Converter to solve the problem?
// Note: this code won't work!!
// it is just a sample of how I *would* want it to work!
@Enumerated
public enum Language {
ENGLISH_US("en-US"),
ENGLISH_BRITISH("en-BR"),
FRENCH("fr"),
FRENCH_CANADIAN("fr-CA");
@ID
private String code;
@Column(name="DESCRIPTION")
private String description;
Language(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
}
Difference between SurfaceView and View?
Views are all drawn on the same GUI thread which is also used for all user interaction.
So if you need to update GUI rapidly or if the rendering takes too much time and affects user experience then use SurfaceView
.
How can I push a specific commit to a remote, and not previous commits?
The simplest way to accomplish this is to use two commands.
First, get the local directory into the state that you want. Then,
$ git push origin +HEAD^:someBranch
removes the last commit from someBranch
in the remote only, not local. You can do this a few times in a row, or change +HEAD^
to reflect the number of commits that you want to batch remove from remote. Now you're back on your feet, and use
$ git push origin someBranch
as normal to update the remote.
On postback, how can I check which control cause postback in Page_Init event
If you need to check which control caused the postback, then you could just directly compare ["__EVENTTARGET"]
to the control you are interested in:
if (specialControl.UniqueID == Page.Request.Params["__EVENTTARGET"])
{
/*do special stuff*/
}
This assumes you're just going to be comparing the result from any GetPostBackControl(...)
extension method anyway. It may not handle EVERY situation, but if it works it is simpler. Plus, you won't scour the page looking for a control you didn't care about to begin with.
Line Break in HTML Select Option?
An idea could be to use the optgroup. In my case found it better than the disabled approach. It's less confusing for the user than seeing the disabled option I think.
<select id="q1" v-model="selected" v-on:change="setCPost1(selected)">
<option value="0"></option>
<template
v-for="(child, idx) in getLevel1"
v-bind:value="child.id"
>
<optgroup v-bind:value="child.id" :key="idx"
:label="child.label"
v-if="child.label_line_two"
>
</optgroup>
<option v-bind:value="child.id" :key="idx" v-if="!child.label_line_two"
>
{{ child.label }}
</option>
<option v-bind:value="child.id" :key="idx" v-if="child.label_line_two"
style="font-style:italic">
{{ child.label_line_two }}
</option>
</template>
</select>
An external component sounds cool like Vue Select, but I wanted to stick with the native html select at the moment.
.NET Core vs Mono
This is one of my favorite topics and the content here was just amazing. I was thinking if it would be worth while or effective to compare the methods available in Runtime vs. Mono. I hope I got my terms right, but I think you know what I mean. In order to have a somewhat better understanding of what each Runtime supports currently, would it make sense to compare the methods they provide? I realize implementations may vary, and I have not considered the Framework Class libraries or the slew of other libraries available in one environment vs. the other. I also realize someone might have already done this work even more efficiently. I would be most grateful if you would let me know so I can review it. I feel doing a diff between the outcome of such activity would be of value, and wanted to see how more experienced developers feel about it, and would they provide useful guidance. While back I was playing with reflection, and wrote some lines that traverse the .net directory, and list the assemblies.
What is LDAP used for?
Well,
LDAP is a protocol(way) to access structured info. LDAP uses client-server model so, LDAP client makes request to access required info. LDAP server stores info not in relational way but in attribute and value pair. You can use LDAP to assign same privilege to group of user or same credential to access multiple services. For more details refer following link : http://www.zytrax.com/books/ldap/ch2/
numpy: most efficient frequency counts for unique values in an array
numpy.bincount
is the probably the best choice. If your array contains anything besides small dense integers it might be useful to wrap it something like this:
def count_unique(keys):
uniq_keys = np.unique(keys)
bins = uniq_keys.searchsorted(keys)
return uniq_keys, np.bincount(bins)
For example:
>>> x = array([1,1,1,2,2,2,5,25,1,1])
>>> count_unique(x)
(array([ 1, 2, 5, 25]), array([5, 3, 1, 1]))
sass :first-child not working
I think that it is better (for my expirience) to use: :first-of-type
, :nth-of-type()
, :last-of-type
. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type
, than *-child
selectors.
How to initialize an array's length in JavaScript?
Array(5)
gives you an array with length 5 but no values, hence you can't iterate over it.
Array.apply(null, Array(5)).map(function () {})
gives you an array with length 5 and undefined as values, now it can be iterated over.
Array.apply(null, Array(5)).map(function (x, i) { return i; })
gives you an array with length 5 and values 0,1,2,3,4.
Array(5).forEach(alert)
does nothing, Array.apply(null, Array(5)).forEach(alert)
gives you 5 alerts
ES6
gives us Array.from
so now you can also use Array.from(Array(5)).forEach(alert)
If you want to initialize with a certain value, these are good to knows...
Array.from('abcde')
, Array.from('x'.repeat(5))
or Array.from({length: 5}, (v, i) => i) // gives [0, 1, 2, 3, 4]
Abort Ajax requests using jQuery
Just use ajax.abort() for example you could abort any pending ajax request before sending another one like this
//check for existing ajax request
if(ajax){
ajax.abort();
}
//then you make another ajax request
$.ajax(
//your code here
);
File to byte[] in Java
Simplest Way for reading bytes from file
import java.io.*;
class ReadBytesFromFile {
public static void main(String args[]) throws Exception {
// getBytes from anyWhere
// I'm getting byte array from File
File file = null;
FileInputStream fileStream = new FileInputStream(file = new File("ByteArrayInputStreamClass.java"));
// Instantiate array
byte[] arr = new byte[(int) file.length()];
// read All bytes of File stream
fileStream.read(arr, 0, arr.length);
for (int X : arr) {
System.out.print((char) X);
}
}
}
Difference between variable declaration syntaxes in Javascript (including global variables)?
<title>Index.html</title>
<script>
var varDeclaration = true;
noVarDeclaration = true;
window.hungOnWindow = true;
document.hungOnDocument = true;
</script>
<script src="external.js"></script>
/* external.js */
console.info(varDeclaration == true); // could be .log, alert etc
// returns false in IE8
console.info(noVarDeclaration == true); // could be .log, alert etc
// returns false in IE8
console.info(window.hungOnWindow == true); // could be .log, alert etc
// returns true in IE8
console.info(document.hungOnDocument == true); // could be .log, alert etc
// returns ??? in IE8 (untested!) *I personally find this more clugy than hanging off window obj
Is there a global object that all vars are hung off of by default? eg: 'globals.noVar declaration'
Use of "instanceof" in Java
instanceof
can be used to determine the actual type of an object:
class A { }
class C extends A { }
class D extends A { }
public static void testInstance(){
A c = new C();
A d = new D();
Assert.assertTrue(c instanceof A && d instanceof A);
Assert.assertTrue(c instanceof C && d instanceof D);
Assert.assertFalse(c instanceof D);
Assert.assertFalse(d instanceof C);
}
Jquery $.ajax fails in IE on cross domain calls
I had a similar problem in IE9 where some CORS calls were aborting, while others weren't. My app is also dependent on a promise interface, so the XDomainRequest suggestions above weren't EXACTLY what I needed, so I added a deferred into my service.get workaround for IE9. Hopefully it can be useful to someone else running across this problem. :
get: function (url) {
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var deferred = $.Deferred();
var xdr = new XDomainRequest();
xdr.open("get", url);
xdr.onload = function() {
json = xdr.responseText;
parsed_json = $.parseJSON(json);
deferred.resolve(parsed_json);
}
xdr.send();
return deferred;
} else {
return $.ajax({
url: url,
type: 'GET',
dataType: 'json',
crossDomain: true
});
}
}
Downloading images with node.js
I'd suggest using the request module. Downloading a file is as simple as the following code:
var fs = require('fs'),
request = require('request');
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
console.log('done');
});
How do I check if a Socket is currently connected in Java?
Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.
TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.
See Do I need to heartbeat to keep a TCP connection open? for more discussion.
Electron: jQuery is not defined
I face the same issue and this worked for me!
Install jQuery using npm
$ npm install jquery
Then include jQuery in one of the following ways.
Using script tag
<script>window.$ = window.jQuery = require('jquery');</script>
Using Babel
import $ from 'jquery';
Using Webpack
const $ = require('jquery');
Understanding the Gemfile.lock file
It seems no clear document talking on the Gemfile.lock
format. Maybe it's because Gemfile.lock
is just used by bundle internally.
However, since Gemfile.lock
is a snapshot of Gemfile
, which means all its information should come from Gemfile
(or from default value if not specified in Gemfile
).
For GEM
, it lists all the dependencies you introduce directly or indirectly in the Gemfile
. remote
under GEM
tells where to get the gems, which is specified by source in Gemfile
.
If a gem is not fetch from remote
, PATH
tells the location to find it. PATH
's info comes from path in Gemfile
when you declare a dependency.
And PLATFORM
is from here.
For DEPENDENCIES
, it's the snapshot of dependencies resolved by bundle.
Android - Start service on boot
I've had success without the full package, do you know where the call chain is getting interrupted? If you debug with Log()
's, at what point does it no longer work?
I think it may be in your IntentService, this all looks fine.
List passed by ref - help me explain this behaviour
While I agree with what everyone has said above. I have a different take on this code.
Basically you're assigning the new list to the local variable myList not the global.
if you change the signature of ChangeList(List myList) to private void ChangeList() you'll see the output of 3, 4.
Here's my reasoning...
Even though list is passed by reference, think of it as passing a pointer variable by value
When you call ChangeList(myList) you're passing the pointer to (Global)myList. Now this is stored in the (local)myList variable. So now your (local)myList and (global)myList are pointing to the same list.
Now you do a sort => it works because (local)myList is referencing the original (global)myList
Next you create a new list and assign the pointer to that your (local)myList. But as soon as the function exits the (local)myList variable is destroyed.
HTH
class Test
{
List<int> myList = new List<int>();
public void TestMethod()
{
myList.Add(100);
myList.Add(50);
myList.Add(10);
ChangeList();
foreach (int i in myList)
{
Console.WriteLine(i);
}
}
private void ChangeList()
{
myList.Sort();
List<int> myList2 = new List<int>();
myList2.Add(3);
myList2.Add(4);
myList = myList2;
}
}
Convert DataTable to List<T>
Create a list with type<DataRow>
by extend the datatable
with AsEnumerable
call.
var mylist = dt.AsEnumerable().ToList();
Cheers!! Happy Coding
New lines inside paragraph in README.md
Interpreting newlines as <br />
used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.
Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change
a
b
c
into
a__
b__
c
(where _
is a blank space).
Or, you can add explicit <br />
tags.
a <br />
b <br />
c
Parsing a JSON array using Json.Net
You can get at the data values like this:
string json = @"
[
{ ""General"" : ""At this time we do not have any frequent support requests."" },
{ ""Support"" : ""For support inquires, please see our support page."" }
]";
JArray a = JArray.Parse(json);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + " -- " + value);
}
}
Fiddle: https://dotnetfiddle.net/uox4Vt
How to see local history changes in Visual Studio Code?
Basic Functionality
- Automatically saved local edit history is available with the Local History extension.
- Manually saved local edit history is available with the Checkpoints extension (this is the IntelliJ equivalent to adding tags to the local history).
Advanced Functionality
- None of the extensions mentioned above support edit history when a file is moved or renamed.
- The extensions above only support edit history. They do not support move/delete history, for example, like IntelliJ does.
Open Request
If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.
Java - ignore exception and continue
It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.
However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.
How do I convert a dictionary to a JSON String in C#?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Dictionary<int, List<int>> foo = new Dictionary<int, List<int>>();
foo.Add(1, new List<int>( new int[] { 1, 2, 3, 4 }));
foo.Add(2, new List<int>(new int[] { 2, 3, 4, 1 }));
foo.Add(3, new List<int>(new int[] { 3, 4, 1, 2 }));
foo.Add(4, new List<int>(new int[] { 4, 1, 2, 3 }));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<int, List<int>>));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, foo);
Console.WriteLine(Encoding.Default.GetString(ms.ToArray()));
}
}
}
}
This will write to the console:
[{\"Key\":1,\"Value\":[1,2,3,4]},{\"Key\":2,\"Value\":[2,3,4,1]},{\"Key\":3,\"Value\":[3,4,1,2]},{\"Key\":4,\"Value\":[4,1,2,3]}]
What is the difference between Double.parseDouble(String) and Double.valueOf(String)?
parseDouble
returns a primitive double containing the value of the string:
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
valueOf
returns a Double instance, if already cached, you'll get the same cached instance.
Returns a Double instance representing the specified double value. If
a new Double instance is not required, this method should generally be
used in preference to the constructor Double(double), as this method
is likely to yield significantly better space and time performance by
caching frequently requested values.
To avoid the overhead of creating a new Double object instance, you should normally use valueOf
Detect if user is scrolling
If you want detect when user scroll over certain div, you can do something like this:
window.onscroll = function() {
var distanceScrolled = document.documentElement.scrollTop;
console.log('Scrolled: ' + distanceScrolled);
}
For example, if your div appear after scroll until the position 112:
window.onscroll = function() {
var distanceScrolled = document.documentElement.scrollTop;
if (distanceScrolled > 112) {
do something...
}
}
But as you can see you don't need a div, just the offset distance you want something to happen.
Android: remove left margin from actionbar's custom layout
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:paddingLeft="0dp">
This should be good enough.
Why do I need to override the equals and hashCode methods in Java?
It is useful when using Value Objects. The following is an excerpt from the Portland Pattern Repository:
Examples of value objects are things
like numbers, dates, monies and
strings. Usually, they are small
objects which are used quite widely.
Their identity is based on their state
rather than on their object identity.
This way, you can have multiple copies
of the same conceptual value object.
So I can have multiple copies of an
object that represents the date 16 Jan
1998. Any of these copies will be equal to each other. For a small
object such as this, it is often
easier to create new ones and move
them around rather than rely on a
single object to represent the date.
A value object should always override
.equals() in Java (or = in Smalltalk).
(Remember to override .hashCode() as
well.)
Getting list of Facebook friends with latest API
Just a heads up for anyone stumbling across this question using v2.0 of the Graph API: This will not work anymore. In v2.0, calling /me/friends only returns a list the person's friends who also use the app:
- A user access token with user_friends permission is required to view the current person's friends.
- This will only return any friends who have used (via Facebook Login) the app making the request.
- If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.
Remove all files in a directory
os.remove()
does not work on a directory, and os.rmdir()
will only work on an empty directory. And Python won't automatically expand "/home/me/test/*" like some shells do.
You can use shutil.rmtree()
on the directory to do this, however.
import shutil
shutil.rmtree('/home/me/test')
be careful as it removes the files and the sub-directories as well.
How to open a WPF Popup when another control is clicked, using XAML markup only?
The following uses EventTrigger
to show the Popup
. This means we don't need a ToggleButton
for state binding.
In this example the Click
event of a Button
is used. You can adapt it to use another element/event combination.
<Button x:Name="OpenPopup">Popup
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetName="ContextPopup"
Storyboard.TargetProperty="IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
</Button>
<Popup x:Name="ContextPopup"
PlacementTarget="{Binding ElementName=OpenPopup}"
StaysOpen="False">
<Label>Popupcontent...</Label>
</Popup>
Please note that the Popup
is referencing the Button
by name and vice versa. So x:Name="..."
is required on both, the Popup
and the Button
.
It can actually be further simplified by replacing the Storyboard
stuff with a custom SetProperty
EventTrigger Action described in this SO Answer
Should I make HTML Anchors with 'name' or 'id'?
You shouldn’t use <h1><a name="foo"/>Foo Title</h1>
in any flavor of HTML served as text/html
, because the XML empty element syntax isn’t supported in text/html
. However, <h1><a name="foo">Foo Title</a></h1>
is OK in HTML4. It is not valid in HTML5 as currently drafted.
<h1 id="foo">Foo Title</h1>
is OK in both HTML4 and HTML5. This won’t work in Netscape 4, but you’ll probably use a dozen other features that don’t work in Netscape 4.
Windows command to convert Unix line endings?
try this:
(for /f "delims=" %i in (file.unix) do @echo %i)>file.dos
Session protocol:
C:\TEST>xxd -g1 file.unix
0000000: 36 31 36 38 39 36 32 39 33 30 38 31 30 38 36 35 6168962930810865
0000010: 0a 34 38 36 38 39 37 34 36 33 32 36 31 38 31 39 .486897463261819
0000020: 37 0a 37 32 30 30 31 33 37 33 39 31 39 32 38 35 7.72001373919285
0000030: 34 37 0a 35 30 32 32 38 31 35 37 33 32 30 32 30 47.5022815732020
0000040: 35 32 34 0a 524.
C:\TEST>(for /f "delims=" %i in (file.unix) do @echo %i)>file.dos
C:\TEST>xxd -g1 file.dos
0000000: 36 31 36 38 39 36 32 39 33 30 38 31 30 38 36 35 6168962930810865
0000010: 0d 0a 34 38 36 38 39 37 34 36 33 32 36 31 38 31 ..48689746326181
0000020: 39 37 0d 0a 37 32 30 30 31 33 37 33 39 31 39 32 97..720013739192
0000030: 38 35 34 37 0d 0a 35 30 32 32 38 31 35 37 33 32 8547..5022815732
0000040: 30 32 30 35 32 34 0d 0a 020524..
Difference between EXISTS and IN in SQL?
As per my knowledge when a subquery returns a NULL
value then the whole statement becomes NULL
. In that cases we are using the EXITS
keyword. If we want to compare particular values in subqueries then we are using the IN
keyword.
Performing SQL queries on an Excel Table within a Workbook with VBA Macro
Hi recently looked into this and had issues referencing the named table (list object) within excel
if you place a suffix '$' on the table name all is well in the world
Sub testSQL()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
' Declare variables
strFile = ThisWorkbook.FullName
' construct connection string
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
' create connection and recordset objects
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
' open connection
cn.Open strCon
' construct SQL query
strSQL = "SELECT * FROM [TableName$] where [ColumnHeader] = 'wibble';"
' execute SQL query
rs.Open strSQL, cn
Debug.Print rs.GetString
' close connection
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
Find specific string in a text file with VBS script
Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job.
Here's the code:
Option Explicit
Dim StdIn: Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
Main()
Sub Main()
Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false
Do until objInputFile.AtEndOfStream
tmpStr = objInputFile.ReadLine
If foundStrMatch(tmpStr)=true Then
If foundFirstMatch = false Then
index = getIndex(tmpStr)
foundFirstMatch = true
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
If index = getIndex(tmpStr) Then
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
ElseIf index < getIndex(tmpStr) Then
index = getIndex(tmpStr)
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
Else
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub
Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function
Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
getIndex = CInt(char1 & char2)
Else
getIndex = CInt(char1)
End If
End Function
Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
foundStrMatch = true
Else
foundStrMatch = false
End If
End Function
This is the original txt file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
And this is the result I'm expecting
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
What are the differences between virtual memory and physical memory?
Softwares run on the OS on a very simple premise - they require memory. The device OS provides it in the form of RAM. The amount of memory required may vary - some softwares need huge memory, some require paltry memory. Most (if not all) users run multiple applications on the OS simultaneously, and given that memory is expensive (and device size is finite), the amount of memory available is always limited. So given that all softwares require a certain amount of RAM, and all of them can be made to run at the same time, OS has to take care of two things:
- That the software always runs until user aborts it, i.e. it should not auto-abort because OS has run out of memory.
- The above activity, while maintaining a respectable performance for the softwares running.
Now the main question boils down to how the memory is being managed. What exactly governs where in the memory will the data belonging to a given software reside?
Possible solution 1: Let individual softwares specify explicitly the memory address they will use in the device. Suppose Photoshop declares that it will always use memory addresses ranging from 0
to 1023
(imagine the memory as a linear array of bytes, so first byte is at location 0
, 1024
th byte is at location 1023
) - i.e. occupying 1 GB
memory. Similarly, VLC declares that it will occupy memory range 1244
to 1876
, etc.
Advantages:
- Every application is pre-assigned a memory slot, so when it is installed and executed, it just stores its data in that memory area, and everything works fine.
Disadvantages:
This does not scale. Theoretically, an app may require a huge amount of memory when it is doing something really heavy-duty. So to ensure that it never runs out of memory, the memory area allocated to it must always be more than or equal to that amount of memory. What if a software, whose maximal theoretical memory usage is 2 GB
(hence requiring 2 GB
memory allocation from RAM), is installed in a machine with only 1 GB
memory? Should the software just abort on startup, saying that the available RAM is less than 2 GB
? Or should it continue, and the moment the memory required exceeds 2 GB
, just abort and bail out with the message that not enough memory is available?
It is not possible to prevent memory mangling. There are millions of softwares out there, even if each of them was allotted just 1 kB
memory, the total memory required would exceed 16 GB
, which is more than most devices offer. How can, then, different softwares be allotted memory slots that do not encroach upon each other's areas? Firstly, there is no centralized software market which can regulate that when a new software is being released, it must assign itself this much memory from this yet unoccupied area, and secondly, even if there were, it is not possible to do it because the no. of softwares is practically infinite (thus requiring infinite memory to accommodate all of them), and the total RAM available on any device is not sufficient to accommodate even a fraction of what is required, thus making inevitable the encroaching of the memory bounds of one software upon that of another. So what happens when Photoshop is assigned memory locations 1
to 1023
and VLC is assigned 1000
to 1676
? What if Photoshop stores some data at location 1008
, then VLC overwrites that with its own data, and later Photoshop accesses it thinking that it is the same data is had stored there previously? As you can imagine, bad things will happen.
So clearly, as you can see, this idea is rather naive.
Possible solution 2: Let's try another scheme - where OS will do majority of the memory management. Softwares, whenever they require any memory, will just request the OS, and the OS will accommodate accordingly. Say OS ensures that whenever a new process is requesting for memory, it will allocate the memory from the lowest byte address possible (as said earlier, RAM can be imagined as a linear array of bytes, so for a 4 GB
RAM, the addresses range for a byte from 0
to 2^32-1
) if the process is starting, else if it is a running process requesting the memory, it will allocate from the last memory location where that process still resides. Since the softwares will be emitting addresses without considering what the actual memory address is going to be where that data is stored, OS will have to maintain a mapping, per software, of the address emitted by the software to the actual physical address (Note: that is one of the two reasons we call this concept Virtual Memory
. Softwares are not caring about the real memory address where their data are getting stored, they just spit out addresses on the fly, and the OS finds the right place to fit it and find it later if required).
Say the device has just been turned on, OS has just launched, right now there is no other process running (ignoring the OS, which is also a process!), and you decide to launch VLC. So VLC is allocated a part of the RAM from the lowest byte addresses. Good. Now while the video is running, you need to start your browser to view some webpage. Then you need to launch Notepad to scribble some text. And then Eclipse to do some coding.. Pretty soon your memory of 4 GB
is all used up, and the RAM looks like this:
Problem 1: Now you cannot start any other process, for all RAM is used up. Thus programs have to be written keeping the maximum memory available in mind (practically even less will be available, as other softwares will be running parallelly as well!). In other words, you cannot run a high-memory consuming app in your ramshackle 1 GB
PC.
Okay, so now you decide that you no longer need to keep Eclipse and Chrome open, you close them to free up some memory. The space occupied in RAM by those processes is reclaimed by OS, and it looks like this now:
Suppose that closing these two frees up 700 MB
space - (400
+ 300
) MB. Now you need to launch Opera, which will take up 450 MB
space. Well, you do have more than 450 MB
space available in total, but...it is not contiguous, it is divided into individual chunks, none of which is big enough to fit 450 MB
. So you hit upon a brilliant idea, let's move all the processes below to as much above as possible, which will leave the 700 MB
empty space in one chunk at the bottom. This is called compaction
. Great, except that...all the processes which are there are running. Moving them will mean moving the address of all their contents (remember, OS maintains a mapping of the memory spat out by the software to the actual memory address. Imagine software had spat out an address of 45
with data 123
, and OS had stored it in location 2012
and created an entry in the map, mapping 45
to 2012
. If the software is now moved in memory, what used to be at location 2012
will no longer be at 2012
, but in a new location, and OS has to update the map accordingly to map 45
to the new address, so that the software can get the expected data (123
) when it queries for memory location 45
. As far as the software is concerned, all it knows is that address 45
contains the data 123
!)! Imagine a process that is referencing a local variable i
. By the time it is accessed again, its address has changed, and it won't be able to find it any more. The same will hold for all functions, objects, variables, basically everything has an address, and moving a process will mean changing the address of all of them. Which leads us to:
Problem 2: You cannot move a process. The values of all variables, functions and objects within that process have hardcoded values as
spat out by the compiler during compilation, the process depends on
them being at the same location during its lifetime, and changing them is expensive. As a result,
processes leave behind big "holes
" when they exit. This is called
External Fragmentation
.
Fine. Suppose somehow, by some miraculous manner, you do manage to move the processes up. Now there is 700 MB
of free space at the bottom:
Opera smoothly fits in at the bottom. Now your RAM looks like this:
Good. Everything is looking fine. However, there is not much space left, and now you need to launch Chrome again, a known memory-hog! It needs lots of memory to start, and you have hardly any left...Except.. you now notice that some of the processes, which were initially occupying large space, now is not needing much space. May be you have stopped your video in VLC, hence it is still occupying some space, but not as much as it required while running a high resolution video. Similarly for Notepad and Photos. Your RAM now looks like this:
Holes
, once again! Back to square one! Except, previously, the holes occurred due to processes terminating, now it is due to processes requiring less space than before! And you again have the same problem, the holes
combined yield more space than required, but they are scattered around, not much of use in isolation. So you have to move those processes again, an expensive operation, and a very frequent one at that, since processes will frequently reduce in size over their lifetime.
Problem 3: Processes, over their lifetime, may reduce in size, leaving behind unused space, which if needed to be used, will require
the expensive operation of moving many processes. This is called
Internal Fragmentation
.
Fine, so now, your OS does the required thing, moves processes around and start Chrome and after some time, your RAM looks like this:
Cool. Now suppose you again resume watching Avatar in VLC. Its memory requirement will shoot up! But...there is no space left for it to grow, as Notepad is snuggled at its bottom. So, again, all processes has to move below until VLC has found sufficient space!
Problem 4: If processes needs to grow, it will be a very expensive operation
Fine. Now suppose, Photos is being used to load some photos from an external hard disk. Accessing hard-disk takes you from the realm of caches and RAM to that of disk, which is slower by orders of magnitudes. Painfully, irrevocably, transcendentally slower. It is an I/O operation, which means it is not CPU bound (it is rather the exact opposite), which means it does not need to occupy RAM right now. However, it still occupies RAM stubbornly. If you want to launch Firefox in the meantime, you can't, because there is not much memory available, whereas if Photos was taken out of memory for the duration of its I/O bound activity, it would have freed lot of memory, followed by (expensive) compaction, followed by Firefox fitting in.
Problem 5: I/O bound jobs keep on occupying RAM, leading to under-utilization of RAM, which could have been used by CPU bound jobs in the meantime.
So, as we can see, we have so many problems even with the approach of virtual memory.
There are two approaches to tackle these problems - paging
and segmentation
. Let us discuss paging
. In this approach, the virtual address space of a process is mapped to the physical memory in chunks - called pages
. A typical page
size is 4 kB
. The mapping is maintained by something called a page table
, given a virtual address, all now we have to do is find out which page
the address belong to, then from the page table
, find the corresponding location for that page
in actual physical memory (known as frame
), and given that the offset of the virtual address within the page
is same for the page
as well as the frame
, find out the actual address by adding that offset to the address returned by the page table
. For example:
On the left is the virtual address space of a process. Say the virtual address space requires 40 units of memory. If the physical address space (on the right) had 40 units of memory as well, it would have been possible to map all location from the left to a location on the right, and we would have been so happy. But as ill luck would have it, not only does the physical memory have less (24 here) memory units available, it has to be shared between multiple processes as well! Fine, let's see how we make do with it.
When the process starts, say a memory access request for location 35
is made. Here the page size is 8
(each page
contains 8
locations, the entire virtual address space of 40
locations thus contains 5
pages). So this location belongs to page no. 4
(35/8
). Within this page
, this location has an offset of 3
(35%8
). So this location can be specified by the tuple (pageIndex, offset)
= (4,3)
. This is just the starting, so no part of the process is stored in the actual physical memory yet. So the page table
, which maintains a mapping of the pages on the left to the actual pages on the right (where they are called frames
) is currently empty. So OS relinquishes the CPU, lets a device driver access the disk and fetch the page no. 4
for this process (basically a memory chunk from the program on the disk whose addresses range from 32
to 39
). When it arrives, OS allocates the page somewhere in the RAM, say first frame itself, and the page table
for this process takes note that page 4
maps to frame 0
in the RAM. Now the data is finally there in the physical memory. OS again queries the page table for the tuple (4,3)
, and this time, page table says that page 4
is already mapped to frame 0
in the RAM. So OS simply goes to the 0
th frame in RAM, accesses the data at offset 3
in that frame (Take a moment to understand this. The entire page
, which was fetched from disk, is moved to frame
. So whatever the offset of an individual memory location in a page was, it will be the same in the frame as well, since within the page
/frame
, the memory unit still resides at the same place relatively!), and returns the data! Because the data was not found in memory at first query itself, but rather had to be fetched from disk to be loaded into memory, it constitutes a miss.
Fine. Now suppose, a memory access for location 28
is made. It boils down to (3,4)
. Page table
right now has only one entry, mapping page 4
to frame 0
. So this is again a miss, the process relinquishes the CPU, device driver fetches the page from disk, process regains control of CPU again, and its page table
is updated. Say now the page 3
is mapped to frame 1
in the RAM. So (3,4)
becomes (1,4)
, and the data at that location in RAM is returned. Good. In this way, suppose the next memory access is for location 8
, which translates to (1,0)
. Page 1
is not in memory yet, the same procedure is repeated, and the page
is allocated at frame 2
in RAM. Now the RAM-process mapping looks like the picture above. At this point in time, the RAM, which had only 24 units of memory available, is filled up. Suppose the next memory access request for this process is from address 30
. It maps to (3,6)
, and page table
says that page 3
is in RAM, and it maps to frame 1
. Yay! So the data is fetched from RAM location (1,6)
, and returned. This constitutes a hit, as data required can be obtained directly from RAM, thus being very fast. Similarly, the next few access requests, say for locations 11
, 32
, 26
, 27
all are hits, i.e. data requested by the process is found directly in the RAM without needing to look elsewhere.
Now suppose a memory access request for location 3
comes. It translates to (0,3)
, and page table
for this process, which currently has 3 entries, for pages 1
, 3
and 4
says that this page is not in memory. Like previous cases, it is fetched from disk, however, unlike previous cases, RAM is filled up! So what to do now? Here lies the beauty of virtual memory, a frame from the RAM is evicted! (Various factors govern which frame is to be evicted. It may be LRU
based, where the frame which was least recently accessed for a process is to be evicted. It may be first-come-first-evicted
basis, where the frame which allocated longest time ago, is evicted, etc.) So some frame is evicted. Say frame 1 (just randomly choosing it). However, that frame
is mapped to some page
! (Currently, it is mapped by the page table to page 3
of our one and only one process). So that process has to be told this tragic news, that one frame
, which unfortunate belongs to you, is to be evicted from RAM to make room for another pages
. The process has to ensure that it updates its page table
with this information, that is, removing the entry for that page-frame duo, so that the next time a request is made for that page
, it right tells the process that this page
is no longer in memory, and has to be fetched from disk. Good. So frame 1
is evicted, page 0
is brought in and placed there in the RAM, and the entry for page 3
is removed, and replaced by page 0
mapping to the same frame 1
. So now our mapping looks like this (note the colour change in the second frame
on the right side):
Saw what just happened? The process had to grow, it needed more space than the available RAM, but unlike our earlier scenario where every process in the RAM had to move to accommodate a growing process, here it happened by just one page
replacement! This was made possible by the fact that the memory for a process no longer needs to be contiguous, it can reside at different places in chunks, OS maintains the information as to where they are, and when required, they are appropriately queried. Note: you might be thinking, huh, what if most of the times it is a miss
, and the data has to be constantly loaded from disk into memory? Yes, theoretically, it is possible, but most compilers are designed in such a manner that follows locality of reference
, i.e. if data from some memory location is used, the next data needed will be located somewhere very close, perhaps from the same page
, the page
which was just loaded into memory. As a result, the next miss will happen after quite some time, most of the upcoming memory requirements will be met by the page just brought in, or the pages already in memory which were recently used. The exact same principle allows us to evict the least recently used page
as well, with the logic that what has not been used in a while, is not likely to be used in a while as well. However, it is not always so, and in exceptional cases, yes, performance may suffer. More about it later.
Solution to Problem 4: Processes can now grow easily, if space problem is faced, all it requires is to do a simple page
replacement, without moving any other process.
Solution to Problem 1: A process can access unlimited memory. When more memory than available is needed, the disk is used as backup, the new data required is loaded into memory from the disk, and the least recently used data frame
(or page
) is moved to disk. This can go on infinitely, and since disk space is cheap and virtually unlimited, it gives an illusion of unlimited memory. Another reason for the name Virtual Memory
, it gives you illusion of memory which is not really available!
Cool. Earlier we were facing a problem where even though a process reduces in size, the empty space is difficult to be reclaimed by other processes (because it would require costly compaction). Now it is easy, when a process becomes smaller in size, many of its pages
are no longer used, so when other processes need more memory, a simple LRU
based eviction automatically evicts those less-used pages
from RAM, and replaces them with the new pages from the other processes (and of course updating the page tables
of all those processes as well as the original process which now requires less space), all these without any costly compaction operation!
Solution to Problem 3: Whenever processes reduce in size, its frames
in RAM will be less used, so a simple LRU
based eviction can evict those pages out and replace them with pages
required by new processes, thus avoiding Internal Fragmentation
without need for compaction
.
As for problem 2, take a moment to understand this, the scenario itself is completely removed! There is no need to move a process to accommodate a new process, because now the entire process never needs to fit at once, only certain pages of it need to fit ad hoc, that happens by evicting frames
from RAM. Everything happens in units of pages
, thus there is no concept of hole
now, and hence no question of anything moving! May be 10 pages
had to be moved because of this new requirement, there are thousands of pages
which are left untouched. Whereas, earlier, all processes (every bit of them) had to be moved!
Solution to Problem 2: To accommodate a new process, data from only less recently used parts of other processes have to be evicted as required, and this happens in fixed size units called pages
. Thus there is no possibility of hole
or External Fragmentation
with this system.
Now when the process needs to do some I/O operation, it can relinquish CPU easily! OS simply evicts all its pages
from the RAM (perhaps store it in some cache) while new processes occupy the RAM in the meantime. When the I/O operation is done, OS simply restores those pages
to the RAM (of course by replacing the pages
from some other processes, may be from the ones which replaced the original process, or may be from some which themselves need to do I/O now, and hence can relinquish the memory!)
Solution to Problem 5: When a process is doing I/O operations, it can easily give up RAM usage, which can be utilized by other processes. This leads to proper utilization of RAM.
And of course, now no process is accessing the RAM directly. Each process is accessing a virtual memory location, which is mapped to a physical RAM address and maintained by the page-table
of that process. The mapping is OS-backed, OS lets the process know which frame is empty so that a new page for a process can be fitted there. Since this memory allocation is overseen by the OS itself, it can easily ensure that no process encroaches upon the contents of another process by allocating only empty frames from RAM, or upon encroaching upon the contents of another process in the RAM, communicate to the process to update it page-table
.
Solution to Original Problem: There is no possibility of a process accessing the contents of another process, since the entire allocation is managed by the OS itself, and every process runs in its own sandboxed virtual address space.
So paging
(among other techniques), in conjunction with virtual memory, is what powers today's softwares running on OS-es! This frees the software developer from worrying about how much memory is available on the user's device, where to store the data, how to prevent other processes from corrupting their software's data, etc. However, it is of course, not full-proof. There are flaws:
Paging
is, ultimately, giving user the illusion of infinite memory by using disk as secondary backup. Retrieving data from secondary storage to fit into memory (called page swap
, and the event of not finding the desired page in RAM is called page fault
) is expensive as it is an IO operation. This slows down the process. Several such page swaps happen in succession, and the process becomes painfully slow. Ever seen your software running fine and dandy, and suddenly it becomes so slow that it nearly hangs, or leaves you with no option that to restart it? Possibly too many page swaps were happening, making it slow (called thrashing
).
So coming back to OP,
Why do we need the virtual memory for executing a process? - As the answer explains at length, to give softwares the illusion of the device/OS having infinite memory, so that any software, big or small, can be run, without worrying about memory allocation, or other processes corrupting its data, even when running in parallel. It is a concept, implemented in practice through various techniques, one of which, as described here, is Paging. It may also be Segmentation.
Where does this virtual memory stand when the process (program) from the external hard drive is brought to the main memory (physical memory) for the execution? - Virtual memory doesn't stand anywhere per se, it is an abstraction, always present, when the software/process/program is booted, a new page table is created for it, and it contains the mapping from the addresses spat out by that process to the actual physical address in RAM. Since the addresses spat out by the process are not real addresses, in one sense, they are, actually, what you can say, the virtual memory
.
Who takes care of the virtual memory and what is the size of the virtual memory? - It is taken care of by, in tandem, the OS and the software. Imagine a function in your code (which eventually compiled and made into the executable that spawned the process) which contains a local variable - an int i
. When the code executes, i
gets a memory address within the stack of the function. That function is itself stored as an object somewhere else. These addresses are compiler generated (the compiler which compiled your code into the executable) - virtual addresses. When executed, i
has to reside somewhere in actual physical address for duration of that function at least (unless it is a static variable!), so OS maps the compiler generated virtual address of i
into an actual physical address, so that whenever, within that function, some code requires the value of i
, that process can query the OS for that virtual address, and OS in turn can query the physical a
Filter rows which contain a certain string
Solution
It is possible to use str_detect
of the stringr
package included in the tidyverse
package. str_detect
returns True
or False
as to whether the specified vector contains some specific string. It is possible to filter using this boolean value. See Introduction to stringr for details about stringr
package.
library(tidyverse)
# - Attaching packages -------------------- tidyverse 1.2.1 -
# ? ggplot2 2.2.1 ? purrr 0.2.4
# ? tibble 1.4.2 ? dplyr 0.7.4
# ? tidyr 0.7.2 ? stringr 1.2.0
# ? readr 1.1.1 ? forcats 0.3.0
# - Conflicts --------------------- tidyverse_conflicts() -
# ? dplyr::filter() masks stats::filter()
# ? dplyr::lag() masks stats::lag()
mtcars$type <- rownames(mtcars)
mtcars %>%
filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl disp hp drat wt qsec vs am gear carb type
# 1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4
# 2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Mazda RX4 Wag
# 3 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla
# 4 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Toyota Corona
The good things about Stringr
We should use rather stringr::str_detect()
than base::grepl()
. This is because there are the following reasons.
- The functions provided by the
stringr
package start with the prefix str_
, which makes the code easier to read.
- The first argument of the functions of
stringr
package is always the data.frame (or value), then comes the parameters.(Thank you Paolo)
object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"
Benchmark
The results of the benchmark test are as follows. For large dataframe, str_detect
is faster.
library(rbenchmark)
library(tidyverse)
# The data. Data expo 09. ASA Statistics Computing and Graphics
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728 29
benchmark(
"str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
"grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
replications = 10,
columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2 grepl 10 16.480 1.513 16.195 0.248
# 1 str_detect 10 10.891 1.000 9.594 1.281
How to use bitmask?
Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45
unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));
The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.
get user timezone
This will get you the timezone as a PHP variable.
I wrote a function using jQuery and PHP. This is tested, and does work!
On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:
<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head>
section, first of all you need to include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head>
section, paste this jQuery:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://example.com/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the url to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this:
(create a new file called timezone.php and point to it with the above url)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.
You can read more about this on my blog
Spring Boot - Error creating bean with name 'dataSource' defined in class path resource
Give you something different, when you encounter this kind of error, cannot create
bean datasource in a test case.
It might be caused by some reasons:
- No datasource, you will need to create your datasource, h2 in-memory datasource or whatever, or you can choose the way like
exclude={datasource··}
.
- You have your datasource, like MySQL, but it still not work. It was caused by class
AutoConfigureTestDatabase
, It will choose a datasource for you which may cause ambiguity.
Solution: add @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
to avoid replace the default datasource.
Unit Testing: DateTime.Now
The best strategy is to wrap the current time in an abstraction and inject that abstraction into the consumer.
Alternatively, you can also define a time abstraction as an Ambient Context:
public abstract class TimeProvider
{
private static TimeProvider current =
DefaultTimeProvider.Instance;
public static TimeProvider Current
{
get { return TimeProvider.current; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
TimeProvider.current = value;
}
}
public abstract DateTime UtcNow { get; }
public static void ResetToDefault()
{
TimeProvider.current = DefaultTimeProvider.Instance;
}
}
This will enable you to consume it like this:
var now = TimeProvider.Current.UtcNow;
In a unit test, you can replace TimeProvider.Current
with a Test Double/Mock object. Example using Moq:
var timeMock = new Mock<TimeProvider>();
timeMock.SetupGet(tp => tp.UtcNow).Returns(new DateTime(2010, 3, 11));
TimeProvider.Current = timeMock.Object;
However, when unit testing with static state, always remember to tear down your fixture by calling TimeProvider.ResetToDefault()
.
How to check if variable's type matches Type stored in a variable
The other answers all contain significant omissions.
The is
operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:
class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.
But checking for type identity with reflection checks for identity, not for compatibility
bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal
or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an
If that's not what you want, then you probably want IsAssignableFrom:
bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.
or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A
Check if a variable is null in plsql
In PL/SQL you can't use operators such as '=' or '<>' to test for NULL
because all comparisons to NULL
return NULL
. To compare something against NULL
you need to use the special operators IS NULL
or IS NOT NULL
which are there for precisely this purpose. Thus, instead of writing
IF var = NULL THEN...
you should write
IF VAR IS NULL THEN...
In the case you've given you also have the option of using the NVL
built-in function. NVL
takes two arguments, the first being a variable and the second being a value (constant or computed). NVL
looks at its first argument and, if it finds that the first argument is NULL
, returns the second argument. If the first argument to NVL
is not NULL
, the first argument is returned. So you could rewrite
IF var IS NULL THEN
var := 5;
END IF;
as
var := NVL(var, 5);
I hope this helps.
EDIT
And because it's nearly ten years since I wrote this answer, let's celebrate by expanding it just a bit.
The COALESCE
function is the ANSI equivalent of Oracle's NVL
. It differs from NVL
in a couple of IMO good ways:
It takes any number of arguments, and returns the first one which is not NULL. If all the arguments passed to COALESCE
are NULL, it returns NULL.
In contrast to NVL
, COALESCE
only evaluates arguments if it must, while NVL
evaluates both of its arguments and then determines if the first one is NULL, etc. So COALESCE
can be more efficient, because it doesn't spend time evaluating things which won't be used (and which can potentially cause unwanted side effects), but it also means that COALESCE
is not a 100% straightforward drop-in replacement for NVL
.
Change class on mouseover in directive
In general I fully agree with Jason's use of css selector, but in some cases you may not want to change the css, e.g. when using a 3rd party css-template, and rather prefer to add/remove a class on the element.
The following sample shows a simple way of adding/removing a class on ng-mouseenter/mouseleave:
<div ng-app>
<div
class="italic"
ng-class="{red: hover}"
ng-init="hover = false"
ng-mouseenter="hover = true"
ng-mouseleave="hover = false">
Test 1 2 3.
</div>
</div>
with some styling:
.red {
background-color: red;
}
.italic {
font-style: italic;
color: black;
}
See running example here: jsfiddle sample
Styling on hovering is a view concern. Although the solution above sets a "hover" property in the current scope, the controller does not need to be concerned about this.
Get environment variable value in Dockerfile
Load environment variables from a file you create at runtime.
export MYVAR="my_var_outside"
cat > build/env.sh <<EOF
MYVAR=${MYVAR}
EOF
... then in the Dockerfile
ADD build /build
RUN /build/test.sh
where test.sh loads MYVAR from env.sh
#!/bin/bash
. /build/env.sh
echo $MYVAR > /tmp/testfile
Adobe Acrobat Pro make all pages the same dimension
With Mac OS X and the more recent versions of Acrobat Pro, the PDF printer option does not work. What does work is doing basically the same thing in Preview App. Open the multi page file in Preview, select File>Print. In the Print dialog set your sheet size as if you are using a printer. You may want to select "Auto Rotate", "Scale to Fit" and "Print Entire Image". Then in the lower left corner is the drop button "PDF" and in that menu select "Save as PDF". Give it a new file name, click Save and then you can open the resulting file in whatever PDF app you want and the sheet sizes are the same.
The import org.junit cannot be resolved
You need to add junit
library to the classpath of your project. There are several choices to achieve it depending on your development setup.
Command line: In the case of command line invocations, you will have to add junit.jar
to the classpath of your application with java -cp /path/to/junit.jar
. Take a look at the answers here.
Using eclipse: Eclipse distributions are bundled with this library and this is how you can use it for your project. Right click on the eclipse project and navigate:
Properties -> Java Build Path -> Libraries -> Add Library -> JUnit ->
Junit 3/4
In the scenarios where you want to use a different version of the jar, instead of clicking on Add Library above you should click on Add External Jar and locate the library on the file system.
Spring Data JPA - "No Property Found for Type" Exception
Since your JPA repository name is UserBoardRepository, your custom Interface name should be UserBoardRepositoryCustom (it should end with 'Custom') and your implementation class name should be UserBoardRepositoryImpl (should end with Impl; you can set it with a different postfix using the repository-impl-postfix property)
How to import a class from default package
I can give you this suggestion,
As far as know from my C and C++ Programming experience,
Once, when I had the same kinda problem, I solved it by changing the dll written structure in ".C" File by changing the name of the function which implemented the JNI native functionality.
for example, If you would like to add your program in the package "com.mypackage",
You change the prototype of the JNI implementing ".C" File's function/method to this one:
JNIEXPORT jint JNICALL
Java_com_mypackage_Calculations_Calculate(JNIEnv *env, jobject obj, jint contextId)
{
//code goes here
}
JNIEXPORT jdouble JNICALL
Java_com_mypackage_Calculations_GetProgress(JNIEnv *env, jobject obj, jint contextId)
{
//code goes here
}
Since I am new to delphi, I can not guarantee you but will say this finally, (I learned few things after googling about Delphi and JNI):
Ask those people (If you are not the one) who provided the Delphi implementation of the native code to change the function names to something like this:
function Java_com_mypackage_Calculations_Calculate(PEnv: PJNIEnv; Obj: JObject; contextId: JInt):JInt; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
//Any variables you might be interested in
begin
//Some code goes here
end;
function Java_com_mypackage_Calculations_GetProgress(PEnv: PJNIEnv; Obj: JObject; contextId: JInt):JDouble; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
//Any variables you might be interested in
begin
//Some code goes here
end;
But, A final advice: Although you (If you are the delphi programmer) or them will change the prototypes of these functions and recompile the dll file, once the dll file is compiled, you will not be able to change the package name of your "Java" file again & again.
Because, this will again require you or them to change the prototypes of the functions in delphi with changed prefixes (e.g. JAVA_yourpackage_with_underscores_for_inner_packages_JavaFileName_MethodName)
I think this solves the problem.
Thanks and regards,
Harshal Malshe
How can I create a border around an Android LinearLayout?
Try This in your res/drawable
<?xml version="1.0" encoding="UTF-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:shape="rectangle">
<padding android:left="15dp"
android:right="15dp"
android:top="15dp"
android:bottom="15dp"/>
<stroke android:width="10dp"
android:color="@color/colorPrimary"/>
</shape>
</item><item android:left="-5dp"
android:right="-5dp"
android:top="-5dp"
android:bottom="-5dp">
<shape android:shape="rectangle">
<solid android:color="@color/background" />
</shape></item></layer-list>
How to concatenate strings in twig
In Symfony you can use this for protocol and host:
{{ app.request.schemeAndHttpHost }}
Though @alessandro1997 gave a perfect answer about concatenation.
Using Bootstrap Modal window as PartialView
I use AJAX to do this. You have your partial with your typical twitter modal template html:
<div class="container">
<!-- Modal -->
<div class="modal fade" id="LocationNumberModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">
Serial Numbers
</h4>
</div>
<div class="modal-body">
<span id="test"></span>
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
</div>
Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..
And the JSON Method in Controller:
public JsonResult LocationNumberModal(string partNumber = "")
{
//Business Layer/DAL to get information
return Json(new {
LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
},
JsonRequestBehavior.AllowGet
);
}
And then, in the view using your modal: You can package the AJAX in your partial and call @{Html.RenderPartial... Or you can have a placeholder with a div:
<div id="LocationNumberModalContainer"></div>
then your ajax:
function LocationNumberModal() {
var partNumber = "1234";
var src = '@Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
+ '?partNumber='' + partNumber;
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#LocationNumberModalContainer").html(data.LocationModal);
$('#LocationNumberModal').modal('show');
}
});
};
Then the button to your modal:
<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>
CSS3 :unchecked pseudo-class
There is no :unchecked pseudo class however if you use the :checked pseudo class and the sibling selector you can differentiate between both states. I believe all of the latest browsers support the :checked pseudo class, you can find more info from this resource: http://www.whatstyle.net/articles/18/pretty_form_controls_with_css
Your going to get better browser support with jquery... you can use a click function to detect when the click happens and if its checked or not, then you can add a class or remove a class as necessary...
Checkbox for nullable boolean
For me the solution was to change the view model. Consider you are searching for invoices. These invoices can be paid or not. So your search has three options: Paid, Unpaid, or "I don't Care".
I had this originally set as a bool? field:
public bool? PaidInvoices { get; set; }
This made me stumble onto this question. I ended up created an Enum type and I handled this as follows:
@Html.RadioButtonFor(m => m.PaidInvoices, PaidStatus.NotSpecified, new { @checked = true })
@Html.RadioButtonFor(m => m.PaidInvoices, PaidStatus.Yes)
@Html.RadioButtonFor(m => m.PaidInvoices, PaidStatus.No)
Of course I had them wrapped in labels and had text specified, I just mean here's another option to consider.
How to provide user name and password when connecting to a network share
I liked Mark Brackett's answer so much that I did my own quick implementation. Here it is if anyone else needs it in a hurry:
public class NetworkConnection : IDisposable
{
string _networkName;
public NetworkConnection(string networkName,
NetworkCredential credentials)
{
_networkName = networkName;
var netResource = new NetResource()
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName
};
var userName = string.IsNullOrEmpty(credentials.Domain)
? credentials.UserName
: string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);
var result = WNetAddConnection2(
netResource,
credentials.Password,
userName,
0);
if (result != 0)
{
throw new Win32Exception(result);
}
}
~NetworkConnection()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
WNetCancelConnection2(_networkName, 0, true);
}
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(NetResource netResource,
string password, string username, int flags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string name, int flags,
bool force);
}
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public ResourceScope Scope;
public ResourceType ResourceType;
public ResourceDisplaytype DisplayType;
public int Usage;
public string LocalName;
public string RemoteName;
public string Comment;
public string Provider;
}
public enum ResourceScope : int
{
Connected = 1,
GlobalNetwork,
Remembered,
Recent,
Context
};
public enum ResourceType : int
{
Any = 0,
Disk = 1,
Print = 2,
Reserved = 8,
}
public enum ResourceDisplaytype : int
{
Generic = 0x0,
Domain = 0x01,
Server = 0x02,
Share = 0x03,
File = 0x04,
Group = 0x05,
Network = 0x06,
Root = 0x07,
Shareadmin = 0x08,
Directory = 0x09,
Tree = 0x0a,
Ndscontainer = 0x0b
}
Check if certain value is contained in a dataframe column in pandas
I think you need str.contains
, if you need rows where values of column date
contains string 07311954
:
print df[df['date'].astype(str).str.contains('07311954')]
Or if type
of date
column is string
:
print df[df['date'].str.contains('07311954')]
If you want check last 4 digits for string
1954
in column date
:
print df[df['date'].astype(str).str[-4:].str.contains('1954')]
Sample:
print df['date']
0 8152007
1 9262007
2 7311954
3 2252011
4 2012011
5 2012011
6 2222011
7 2282011
Name: date, dtype: int64
print df['date'].astype(str).str[-4:].str.contains('1954')
0 False
1 False
2 True
3 False
4 False
5 False
6 False
7 False
Name: date, dtype: bool
print df[df['date'].astype(str).str[-4:].str.contains('1954')]
cmte_id trans_typ entity_typ state employer occupation date \
2 C00119040 24K CCM MD NaN NaN 7311954
amount fec_id cand_id
2 1000 C00140715 H2MD05155
How do I resize a Google Map with JavaScript after it has loaded?
The popular answer google.maps.event.trigger(map, "resize");
didn't work for me alone.
Here was a trick that assured that the page had loaded and that the map had loaded as well. By setting a listener and listening for the idle state of the map you can then call the event trigger to resize.
$(document).ready(function() {
google.maps.event.addListener(map, "idle", function(){
google.maps.event.trigger(map, 'resize');
});
});
This was my answer that worked for me.
what is difference between success and .done() method of $.ajax
success
only fires if the AJAX call is successful, i.e. ultimately returns a HTTP 200 status. error
fires if it fails and complete
when the request finishes, regardless of success.
In jQuery 1.8 on the jqXHR
object (returned by $.ajax
) success
was replaced with done
, error
with fail
and complete
with always
.
However you should still be able to initialise the AJAX request with the old syntax. So these do similar things:
// set success action before making the request
$.ajax({
url: '...',
success: function(){
alert('AJAX successful');
}
});
// set success action just after starting the request
var jqxhr = $.ajax( "..." )
.done(function() { alert("success"); });
This change is for compatibility with jQuery 1.5's deferred object. Deferred (and now Promise
, which has full native browser support in Chrome and FX) allow you to chain asynchronous actions:
$.ajax("parent").
done(function(p) { return $.ajax("child/" + p.id); }).
done(someOtherDeferredFunction).
done(function(c) { alert("success: " + c.name); });
This chain of functions is easier to maintain than a nested pyramid of callbacks you get with success
.
However, please note that done
is now deprecated in favour of the Promise
syntax that uses then
instead:
$.ajax("parent").
then(function(p) { return $.ajax("child/" + p.id); }).
then(someOtherDeferredFunction).
then(function(c) { alert("success: " + c.name); }).
catch(function(err) { alert("error: " + err.message); });
This is worth adopting because async
and await
extend promises improved syntax (and error handling):
try {
var p = await $.ajax("parent");
var x = await $.ajax("child/" + p.id);
var c = await someOtherDeferredFunction(x);
alert("success: " + c.name);
}
catch(err) {
alert("error: " + err.message);
}
How to append something to an array?
you can do it using new javascript Es 6 feature :
// initialize array
var arr = [
"Hi",
"Hello",
"Bangladesh"
];
// append new value to the array
arr= [...arr , "Feni"];
// or you can put a variable value
var testValue = "Cool";
arr = [...arr , testValue ];
console.log(arr);
// final output [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]
Turn Pandas Multi-Index into column
As @cs95 mentioned in a comment, to drop only one level, use:
df.reset_index(level=[...])
This avoids having to redefine your desired index after reset.
How to reload a page after the OK click on the Alert Page
Try this code..
IN PHP Code
echo "<script type='text/javascript'>".
"alert('Success to add the task to a project.');
location.reload;".
"</script>";
IN Javascript
function refresh()
{
alert("click ok to refresh page");
location.reload();
}
Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf
The most upvoted answer is not implementing a real slide in/out (or down/up), as:
- It's not doing a soft transition on the height attribute. At time zero the element already has the 100% of its height producing a sudden glitch on the elements below it.
- When sliding out/up, the element does a
translateY(-100%)
and then suddenly disappears, causing another glitch on the elements below it.
You can implement a slide in and slide out like so:
my-component.ts
import { animate, style, transition, trigger } from '@angular/animations';
@Component({
...
animations: [
trigger('slideDownUp', [
transition(':enter', [style({ height: 0 }), animate(500)]),
transition(':leave', [animate(500, style({ height: 0 }))]),
]),
],
})
my-component.html
<div @slideDownUp *ngIf="isShowing" class="box">
I am the content of the div!
</div>
my-component.scss
.box {
overflow: hidden;
}
Python Checking a string's first and last character
You are testing against the string minus the last character:
>>> '"xxx"'[:-1]
'"xxx'
Note how the last character, the "
, is not part of the output of the slice.
I think you wanted just to test against the last character; use [-1:]
to slice for just the last element.
However, there is no need to slice here; just use str.startswith()
and str.endswith()
directly.
How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?
CREATE FUNCTION [dbo].[_ICAN_FN_IntToTime](@Num INT)
RETURNS NVARCHAR(13)
AS
-------------------------------------------------------------------------------------------------------------------
--INVENTIVE:Keyvan ARYAEE-MOEEN
-------------------------------------------------------------------------------------------------------------------
BEGIN
DECLARE @Hour VARCHAR(10)=CAST(@Num/3600 AS VARCHAR(2))
DECLARE @Minute VARCHAR(10)=CAST((@Num-@Hour*3600)/60 AS VARCHAR(2))
DECLARE @Time VARCHAR(13)=CASE WHEN @Hour<10 THEN '0'+@Hour ELSE @Hour END+':'+CASE WHEN @Minute<10 THEN '0'+@Minute ELSE @Minute END+':00.000'
RETURN @Time
END
-------------------------------------------------------------------------------------------------------------------
--SELECT dbo._ICAN_FN_IntToTime(25500)
-------------------------------------------------------------------------------------------------------------------
Javascript to open popup window and disable parent window
var popupWindow=null;
function popup()
{
popupWindow = window.open('child_page.html','name','width=200,height=200');
}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
and then declare these functions in the body tag of parent window
<body onFocus="parent_disable();" onclick="parent_disable();">
As you requested here is the complete html code of the parent window
<html>
<head>
<script type="text/javascript">
var popupWindow=null;
function child_open()
{
popupWindow =window.open('new.jsp',"_blank","directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");
}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
</script>
</head>
<body onFocus="parent_disable();" onclick="parent_disable();">
<a href="javascript:child_open()">Click me</a>
</body>
</html>
Content of new.jsp below
<html>
<body>
I am child
</body>
</html>
Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)
What to do if i have to processed even more that 500000 records ?
There are a few ways, to increase the java heap size for your app where a few have suggested already. Your app need to remove the elements from your adddressMap as your app add new element into it and so you won't encounter oom if there are more records coming in. Look for producer-consumer if you are interested.
What is the difference between Integrated Security = True and Integrated Security = SSPI?
Note that connection strings are specific to what and how you are connecting to data. These are connecting to the same database but the first is using .NET Framework Data Provider for SQL Server. Integrated Security=True will not work for OleDb.
- Data Source=.;Initial Catalog=aspnetdb;Integrated Security=True
- Provider=SQLOLEDB;Data Source=.;Integrated Security=SSPI;Initial Catalog=aspnetdb
When in doubt use the Visual Studio Server Explorer Data Connections.
How to sort a list of lists by a specific index of the inner list?
**old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
#let's assume we want to sort lists by last value ( old_list[2] )
new_list = sorted(old_list, key=lambda x: x[2])**
correct me if i'm wrong but isnt the 'x[2]' calling the 3rd item in the list, not the 3rd item in the nested list? should it be x[2][2]?
How to sort a Pandas DataFrame by index?
Dataframes have a sort_index
method which returns a copy by default. Pass inplace=True
to operate in place.
import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())
Gives me:
A
1 4
29 2
100 1
150 5
234 3
fatal: early EOF fatal: index-pack failed
I have the same problem. Following the first step above i was able to clone, but I cannot do anything else. Can't fetch, pull or checkout old branches.
Each command runs much slower than usual, then dies after compressing the objects.
I:\dev [master +0 ~6 -0]> git fetch --unshallow
remote: Counting objects: 645483, done.
remote: Compressing objects: 100% (136865/136865), done.
error: RPC failed; result=18, HTTP code = 20082 MiB | 6.26 MiB/s
fatal: early EOF
fatal: The remote end hung up unexpectedly
fatal: index-pack failed
This also happens when your ref's are using too much memory. Pruning the memory fixed this for me. Just add a limit to what you fetching like so ->
git fetch --depth=100
This will fetch the files but with the last 100 edits in their histories.
After this, you can do any command just fine and at normal speed.
How to run or debug php on Visual Studio Code (VSCode)
The best solution for me was to add a key binding to run PHP code directly in the terminal
To do so you just need to download terminal-command-keys
from VS code extensions marketplace:
Then got to File>Preferences>Keyboard Shortcuts and click on the following icon at the upper right corner:
It will open up the keybindings.json
file
Add the following settings
[
{
"key": "ctrl+s",
"command":"terminalCommandKeys.run",
"when": "editorLangId == php",
"args": {
"cmd":"php ${file}",
"newTerminal":true,
"saveAllfiles": true,
"showTerminal": true,
}
}
]
key is the shortcut to run your PHP file (I use ctrl+s) you can change it as you wish
when to run different commands for different file types (I set it for PHP files only) vscode's "when" clauses
See the full settings documentation from here
That's it, I hope it helps.
Excel: Searching for multiple terms in a cell
In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH
), using named ranges and the EVALUATE
function as I found from this link.
For example, I put the following terms as text in a cell, $G$1
:
"PRB", "utilization", "alignment", "spectrum"
Then, I defined a named range named search_terms
for that cell as described in the link above and shown in the figure below:
In the Refers to:
field I put the following:
=EVALUATE("{" & TDoc_List!$G$1 & "}")
The above EVALUATE
expression is simple used to emulate the literal string
{"PRB", "utilization", "alignment", "spectrum"}
to be used as input to the SEARCH
function: using a direct reference to the SINGLE cell $G$1
(augmented with the curly braces in that case) inside SEARCH
does not work, hence the use of named ranges and EVALUATE
.
The trick now consists in replacing the direct reference to $G$1
by the EVALUATE
-augmented named range search_terms
.
It really works, and shows once more how powerful Excel really is!
Hope this helps.
How to make HTTP Post request with JSON body in Swift
let url = URL(string: "url")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
let postString = "ChangeAccordingtoyourdata=\(paramOne)&ChangeAccordingtoyourdata2=\(paramTwo)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
SVProgressHUD.showError(withStatus: "Request has not submitted successfully.\nPlease try after some time")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
SVProgressHUD.showSuccess(withStatus: "Request has submitted successfully.\nPlease wait for a while")
DispatchQueue.main.async {
// enter code
}
}
task.resume()
Set the maximum character length of a UITextField in Swift
Your view controller should conform to UITextFieldDelegate
, like below:
class MyViewController: UIViewController, UITextFieldDelegate {
}
Set the delegate of your textfield: myTextField.delegate = self
Implement the method in your view controller : textField(_:shouldChangeCharactersInRange:replacementString:)
All together:
class MyViewController: UIViewController,UITextFieldDelegate //set delegate to class
@IBOutlet var mytextField: UITextField // textfield variable
override func viewDidLoad() {
super.viewDidLoad()
mytextField.delegate = self //set delegate
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool
{
let maxLength = 4
let currentString: NSString = textField.text
let newString: NSString =
currentString.stringByReplacingCharactersInRange(range, withString: string)
return newString.length <= maxLength
}
For Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLength = 1
let currentString: NSString = (textField.text ?? "") as NSString
let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString
return newString.length <= maxLength
}
Allowing only a specified set of characters to be entered into a given text field
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var result = true
if mytextField == numberField {
if count(string) > 0 {
let disallowedCharacterSet = NSCharacterSet(charactersInString: "0123456789.-").invertedSet
let replacementStringIsLegal = string.rangeOfCharacterFromSet(disallowedCharacterSet) == nil
result = replacementStringIsLegal
}
}
return result
}
How to program an iOS text field that takes only numeric input with a maximum length
Get array of object's keys
Summary
For getting all of the keys of an Object you can use Object.keys()
. Object.keys()
takes an object as an argument and returns an array of all the keys.
Example:
_x000D_
_x000D_
const object = {_x000D_
a: 'string1',_x000D_
b: 42,_x000D_
c: 34_x000D_
};_x000D_
_x000D_
const keys = Object.keys(object)_x000D_
_x000D_
console.log(keys);_x000D_
_x000D_
console.log(keys.length) // we can easily access the total amount of properties the object has
_x000D_
_x000D_
_x000D_
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
Getting the values with: Object.values()
The complementary function of Object.keys()
is Object.values()
. This function takes an object as an argument and returns an array of values. For example:
_x000D_
_x000D_
const object = {_x000D_
a: 'random',_x000D_
b: 22,_x000D_
c: true_x000D_
};_x000D_
_x000D_
_x000D_
console.log(Object.values(object));
_x000D_
_x000D_
_x000D_
Which keycode for escape key with jQuery
(Answer extracted from my previous comment)
You need to use keyup
rather than keypress
. e.g.:
$(document).keyup(function(e) {
if (e.which == 13) $('.save').click(); // enter
if (e.which == 27) $('.cancel').click(); // esc
});
keypress
doesn't seem to be handled consistently between browsers (try out the demo at http://api.jquery.com/keypress in IE vs Chrome vs Firefox. Sometimes keypress
doesn't register, and the values for both 'which' and 'keyCode' vary) whereas keyup
is consistent.
Since there was some discussion of e.which
vs e.keyCode
: Note that e.which
is the jquery-normalized value and is the one recommended for use:
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
(from http://api.jquery.com/event.which/)
Is it possible to cast a Stream in Java 8?
Late to the party, but I think it is a useful answer.
flatMap
would be the shortest way to do it.
Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())
If o
is a Client
then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream<Client>
.
Opening a CHM file produces: "navigation to the webpage was canceled"
There are apparently different levels of authentication. Most articles I read tell you to set the MaxAllowedZone to '1' which means that local machine zone and intranet zone are allowed but '4' allows access for 'all' zones.
For more info, read this article:
https://support.microsoft.com/en-us/kb/892675
This is how my registry looks (I wasn't sure it would work with the wild cards but it seems to work for me):
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000004
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"UrlAllowList"="\\\\<network_path_root>;\\\\<network_path_root>\*;\\ies-inc.local;http://www.*;http://*;https://www.*;https://*;"
As an additional note, weirdly the "UrlAllowList" key was required to make this work on another PC but not my test one. It's probably not required at all but when I added it, it fixed the problem. The user may have not closed the original file or something like that. So just a consideration. I suggest try the least and test it, then add if needed. Once you confirm, you can deploy if needed. Good Luck!
Edit: P.S. Another method that worked was mapping the path to the network locally by using mklink /d (symbolic linking in Windows 7 or newer) but mapping a network drive letter (Z: for testing) did not work. Just food for thought and I did not have to 'Unblock' any files. Also the accepted 'Solution' did not resolve the issue for me.
Fixed size div?
You can set the height
and width
of your divs
with css
.
<style type="text/css">
.box {
height: 150px;
width: 150px;
}
</style>
Is this what you're looking for?
C# Collection was modified; enumeration operation may not execute
I suspect the error is caused by this:
foreach (KeyValuePair<int, int> kvp in rankings)
rankings is a dictionary, which is IEnumerable. By using it in a foreach loop, you're specifying that you want each KeyValuePair from the dictionary in a deferred manner. That is, the next KeyValuePair is not returned until your loop iterates again.
But you're modifying the dictionary inside your loop:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
which isn't allowed...so you get the exception.
You could simply do this
foreach (KeyValuePair<int, int> kvp in rankings.ToArray())
Testing the type of a DOM element in JavaScript
You can use typeof(N)
to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.
In that case, use the elem.tagName
or elem.nodeName
property.
if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.
Foreign key constraint may cause cycles or multiple cascade paths?
My solution to this problem encountered using ASP.NET Core 2.0 and EF Core 2.0 was to perform the following in order:
Run update-database
command in Package Management Console (PMC) to create the database (this results in the "Introducing FOREIGN KEY constraint ... may cause cycles or multiple cascade paths." error)
Run script-migration -Idempotent
command in PMC to create a script that can be run regardless of the existing tables/constraints
Take the resulting script and find ON DELETE CASCADE
and replace with ON DELETE NO ACTION
Execute the modified SQL against the database
Now, your migrations should be up-to-date and the cascading deletes should not occur.
Too bad I was not able to find any way to do this in Entity Framework Core 2.0.
Good luck!
How do I run a bat file in the background from another bat file?
Actually, the following works fine for me and creates new windows:
test.cmd:
@echo off
start test2.cmd
start test3.cmd
echo Foo
pause
test2.cmd
@echo off
echo Test 2
pause
exit
test3.cmd
@echo off
echo Test 3
pause
exit
Combine that with parameters to start
, such as /min
, as Moshe pointed out if you don't want the new windows to spawn in front of you.
Formatting Phone Numbers in PHP
Check Phone number
$phone = '+385 99 1234 1234'
$str = preg_match('/^\+?\d{1,3}[\s-]?\d{1,3}[\s-]?\d{1,4}[\s-]?\d{1,4}$/', $phone);
if($str){
return true;
}else{
return false;
}
How do I correct "Commit Failed. File xxx is out of date. xxx path not found."
Apparently SVN is not a very reliable program. I had the same problem (using SVN with Turtoise) and solved it by saving the .cs file's content and then going back 1 revision. This showed conflicts like this:
"<<<<<<< filename my changes
=======
code merged from repository
revision "
while I haven't done anything special (just once set back a revision).
I replaced the content of this file with the saved content, saved, and then selected via TortoiseSVN ? Resolved.
I could then commit the modifications to the repository.
When to use static classes in C#
I only use static classes for helper methods, but with the advent of C# 3.0, I'd rather use extension methods for those.
I rarely use static classes methods for the same reasons why I rarely use the singleton "design pattern".
Linux/Unix command to determine if process is running?
The following shell function, being only based on POSIX standard commands and options should work on most (if not any) Unix and linux system. :
isPidRunning() {
cmd=`
PATH=\`getconf PATH\` export PATH
ps -e -o pid= -o comm= |
awk '$2 ~ "^.*/'"$1"'$" || $2 ~ "^'"$1"'$" {print $1,$2}'
`
[ -n "$cmd" ] &&
printf "%s is running\n%s\n\n" "$1" "$cmd" ||
printf "%s is not running\n\n" $1
[ -n "$cmd" ]
}
$ isPidRunning httpd
httpd is running
586 /usr/apache/bin/httpd
588 /usr/apache/bin/httpd
$ isPidRunning ksh
ksh is running
5230 ksh
$ isPidRunning bash
bash is not running
Note that it will choke when passed the dubious "0]" command name and will also fail to identify processes having an embedded space in their names.
Note too that the most upvoted and accepted solution demands non portable ps
options and gratuitously uses a shell that is, despite its popularity, not guaranteed to be present on every Unix/Linux machine (bash
)
Moment.js - How to convert date string into date?
if you have a string of date, then you should try this.
const FORMAT = "YYYY ddd MMM DD HH:mm";
const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300
const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019
or try this :
const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);
Bootstrap 3: Text overlay on image
try the following example.
Image overlay with text on image.
demo
<div class="thumbnail">
<img src="https://s3.amazonaws.com/discount_now_staging/uploads/ed964a11-e089-4c61-b927-9623a3fe9dcb/direct_uploader_2F50cc1daf-465f-48f0-8417-b04ac68a999d_2FN_19_jewelry.jpg" alt="..." />
<div class="caption post-content">
</div>
<div class="details">
<h3>Robots!</h3>
<p>Lorem ipsum dolor sit amet</p>
</div>
</div>
css
.post-content {
background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
opacity: 0.5;
top:0;
left:0;
min-width: 500px;
min-height: 500px;
position: absolute;
color: #ffffff;
}
.thumbnail{
position:relative;
}
.details {
position: absolute;
z-index: 2;
top: 0;
color: #ffffff;
}
Any way to make plot points in scatterplot more transparent in R?
Otherwise, you have function alpha
in package scales
in which you can directly input your vector of colors (even if they are factors as in your example):
library(scales)
cols <- cut(z, 6, labels = c("pink", "red", "yellow", "blue", "green", "purple"))
plot(x, y, main= "Fragment recruitment plot - FR-HIT",
ylab = "Percent identity", xlab = "Base pair position",
col = alpha(cols, 0.4), pch=16)
# For an alpha of 0.4, i. e. an opacity of 40%.
Java Compare Two List's object values?
String myData1 = list1.toString();
String myData2 = list2.toString()
return myData1.equals(myData2);
where :
list1 - List<MyData>
list2 - List<MyData>
Comparing the String worked for me. Also NOTE I had overridden toString() method in MyData class.
Resetting a form in Angular 2 after submit
When I was going through the Angular basics guide on forms, and hit the resetting of forms section, I was very much left in surprise when I read the following in regards to the solution they give.
This is a temporary workaround while we await a proper form reset feature.
I personally haven't tested if the workaround they provided works (i assume it does), but I believe it is not neat, and that there must be a better way to go about the issue.
According to the FormGroup API (which is marked as stable) there already is a 'reset' method.
I tried the following. In my template.html file i had
<form (ngSubmit)="register(); registrationForm.reset();" #registrationForm="ngForm">
...
</form>
Notice that in the form element, I've initialised a template reference variable 'registrationForm' and initialized it to the ngForm Directive, which "governs the form as a whole". This gave me access to the methods and attributes of the governing FormGroup, including the reset() method.
Binding this method call to the ngSubmit event as show above reset the form (including pristine, dirty, model states etc) after the register() method is completed. For a demo this is ok, however it isn't very helpful for real world applications.
Imagine the register() method performs a call to the server. We want to reset the form when we know that the server responded back that everything is OK. Updating the code to the following caters for this scenario.
In my template.html file :
<form (ngSubmit)="register(registrationForm);" #registrationForm="ngForm">
...
</form>
And in my component.ts file :
@Component({
...
})
export class RegistrationComponent {
register(form: FormGroup) {
...
// Somewhere within the asynchronous call resolve function
form.reset();
}
}
Passing the 'registrationForm' reference to the method would allow us to call the reset method at the point of execution that we want to.
Hope this helps you in any way. :)
Note: This approach is based on Angular 2.0.0-rc.5
Format JavaScript date as yyyy-mm-dd
Just leverage the built-in toISOString
method that brings your date to the ISO 8601 format:
yourDate.toISOString().split('T')[0]
Where yourDate is your date object.
Edit: @exbuddha wrote this to handle time zone in the comments:
const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
If condition inside of map() React
There are two syntax errors in your ternary conditional:
- remove the keyword
if
. Check the correct syntax here.
You are missing a parenthesis in your code. If you format it like this:
{(this.props.schema.collectionName.length < 0 ?
(<Expandable></Expandable>)
: (<h1>hejsan</h1>)
)}
Hope this works!
How to read data when some numbers contain commas as thousand separator?
I think preprocessing is the way to go. You could use Notepad++ which has a regular expression replace option.
For example, if your file were like this:
"1,234","123","1,234"
"234","123","1,234"
123,456,789
Then, you could use the regular expression "([0-9]+),([0-9]+)"
and replace it with \1\2
1234,"123",1234
"234","123",1234
123,456,789
Then you could use x <- read.csv(file="x.csv",header=FALSE)
to read the file.
How to make Sonar ignore some classes for codeCoverage metric?
When using sonar-scanner for swift, use sonar.coverage.exclusions in your sonar-project.properties to exclude any file for only code coverage. If you want to exclude files from analysis as well, you can use sonar.exclusions. This has worked for me in swift
sonar.coverage.exclusions=**/*ViewController.swift,**/*Cell.swift,**/*View.swift
set environment variable in python script
Compact solution (provided you don't need other environment variables):
call('sqsub -np {} /homedir/anotherdir/executable'.format(var1).split(),
env=dict(LD_LIBRARY_PATH=my_path))
Using the env command line tool:
call('env LD_LIBRARY_PATH=my_path sqsub -np {} /homedir/anotherdir/executable'.format(var1).split())
Example of Named Pipes
You can actually write to a named pipe using its name, btw.
Open a command shell as Administrator to get around the default "Access is denied" error:
echo Hello > \\.\pipe\PipeName
How to change the colors of a PNG image easily?
If you are like me and Photoshop is out of your price range or just overkill for what you need. Acorn 5 is a much cheaper version of Photoshop with a lot of the same features. One of those features being a color change option. You can import all of the basic image formats including SVG and PNG. The color editing software works great and allows for basic color selection, RBG selection, hex code, or even a color grabber if you do not know the color. These color features, plus a whole lot image editing features, is definitely worth the $30. The only downside is that is currently only available on Mac.
How to use SVN, Branch? Tag? Trunk?
I asked myself the same questions when we came to implement Subversion here -- about 20 developers spread across 4 - 6 projects. I didn't find any one good source with ''the answer''. Here are some parts of how our answer has developed over the last 3 years:
-- commit as often as is useful; our rule of thumb is commit whenever you have done sufficient work that it would be a problem having to re-do it if the modifications got lost; sometimes I commit every 15 minutes or so, other times it might be days (yes, sometimes it takes me a day to write 1 line of code)
-- we use branches, as one of your earlier answers suggested, for different development paths; right now for one of our programs we have 3 active branches: 1 for the main development, 1 for the as-yet-unfinished effort to parallelise the program, and 1 for the effort to revise it to use XML input and output files;
-- we scarcely use tags, though we think we ought to use them to identify releases to production;
Think of development proceeding along a single path. At some time or state of development marketing decide to release the first version of the product, so you plant a flag in the path labelled '1' (or '1.0' or what have you). At some other time some bright spark decides to parallelise the program, but decides that that will take weeks and that people want to keep going down the main path in the meantime. So you build a fork in the path and different people wander off down the different forks.
The flags in the road are called 'tags' ,and the forks in the road are where 'branches' divide. Occasionally, also, branches come back together.
-- we put all material necessary to build an executable (or system) into the repository; That means at least source code and make file (or project files for Visual Studio). But when we have icons and config files and all that other stuff, that goes into the repository. Some documentation finds its way into the repo; certainly any documentation such as help files which might be integral to the program does, and it's a useful place to put developer documentation.
We even put Windows executables for our production releases in there, to provide a single location for people looking for software -- our Linux releases go to a server so don't need to be stored.
-- we don't require that the repository at all times be capable of delivering a latest version which builds and executes; some projects work that way, some don't; the decision rests with the project manager and depends on many factors but I think it breaks down when making major changes to a program.
create array from mysql query php
You do need to iterate through...
$typeArray = array();
$query = "select * from whatever";
$result = mysql_query($query);
if ($result) {
while ($record = mysql_fetch_array($results)) $typeArray[] = $record['type'];
}
Android Stop Emulator from Command Line
Sometimes the command
adb -s emulator-5554 emu kill
did not work on my CI servers or desktops, for unknown reason.
I think on Windows it's OK to kill the process of qemu, just like
Taskkill /IM qemu-system-x86_64.exe /F /T
Wait until all promises complete even if some rejected
Benjamin's answer offers a great abstraction for solving this issue, but I was hoping for a less abstracted solution. The explicit way to to resolve this issue is to simply call .catch
on the internal promises, and return the error from their callback.
let a = new Promise((res, rej) => res('Resolved!')),
b = new Promise((res, rej) => rej('Rejected!')),
c = a.catch(e => { console.log('"a" failed.'); return e; }),
d = b.catch(e => { console.log('"b" failed.'); return e; });
Promise.all([c, d])
.then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
.catch(err => console.log('Catch', err));
Promise.all([a.catch(e => e), b.catch(e => e)])
.then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
.catch(err => console.log('Catch', err));
Taking this one step further, you could write a generic catch handler that looks like this:
const catchHandler = error => ({ payload: error, resolved: false });
then you can do
> Promise.all([a, b].map(promise => promise.catch(catchHandler))
.then(results => console.log(results))
.catch(() => console.log('Promise.all failed'))
< [ 'Resolved!', { payload: Promise, resolved: false } ]
The problem with this is that the caught values will have a different interface than the non-caught values, so to clean this up you might do something like:
const successHandler = result => ({ payload: result, resolved: true });
So now you can do this:
> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
.then(results => console.log(results.filter(result => result.resolved))
.catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]
Then to keep it DRY, you get to Benjamin's answer:
const reflect = promise => promise
.then(successHandler)
.catch(catchHander)
where it now looks like
> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
.then(results => console.log(results.filter(result => result.resolved))
.catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]
The benefits of the second solution are that its abstracted and DRY. The downside is you have more code, and you have to remember to reflect all your promises to make things consistent.
I would characterize my solution as explicit and KISS, but indeed less robust. The interface doesn't guarantee that you know exactly whether the promise succeeded or failed.
For example you might have this:
const a = Promise.resolve(new Error('Not beaking, just bad'));
const b = Promise.reject(new Error('This actually didnt work'));
This won't get caught by a.catch
, so
> Promise.all([a, b].map(promise => promise.catch(e => e))
.then(results => console.log(results))
< [ Error, Error ]
There's no way to tell which one was fatal and which was wasn't. If that's important then you're going to want to enforce and interface that tracks whether it was successful or not (which reflect
does).
If you just want to handle errors gracefully, then you can just treat errors as undefined values:
> Promise.all([a.catch(() => undefined), b.catch(() => undefined)])
.then((results) => console.log('Known values: ', results.filter(x => typeof x !== 'undefined')))
< [ 'Resolved!' ]
In my case, I don't need to know the error or how it failed--I just care whether I have the value or not. I'll let the function that generates the promise worry about logging the specific error.
const apiMethod = () => fetch()
.catch(error => {
console.log(error.message);
throw error;
});
That way, the rest of the application can ignore its error if it wants, and treat it as an undefined value if it wants.
I want my high level functions to fail safely and not worry about the details on why its dependencies failed, and I also prefer KISS to DRY when I have to make that tradeoff--which is ultimately why I opted to not use reflect
.
How to draw circle by canvas in Android?
If you are using your own CustomView extending View class, you need to call canvas.invalidate() method which will internally call onDraw method. You can use default API for canvas to draw a circle. The x, y cordinate define the center of the circle. You can also define color and styling in paint & pass the paint object.
public class CustomView extends View {
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
setupPaint();
}
}
Define default paint settings and canvas (Initialise paint in constructor so that you can reuse the same object everywhere and change only specific settings wherever required)
private Paint drawPaint;
// Setup paint with color and stroke styles
private void setupPaint() {
drawPaint = new Paint();
drawPaint.setColor(Color.BLUE);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(5);
drawPaint.setStyle(Paint.Style.FILL_AND_STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}
And initialise canvas object
private Canvas canvas;
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.canvas = canvas;
canvas.drawCircle(xCordinate, yCordinate, RADIUS, drawPaint);
}
And finally, for every view refresh or new draw on the screen, you need to call invalidate method. Remember your entire view is redrawn, hence this is an expensive call. Make sure you do only the necessary operations in onDraw
canvas.invalidate();
For more details on canvas drawing refer https://medium.com/@mayuri.k18/android-canvas-for-drawing-and-custom-views-e1a3e90d468b
How to see tomcat is running or not
Go to the start menu. Open up cmd (command prompt) and type in the following.
wmic process list brief | find /i "tomcat"
This would tell you if the tomcat is running or not.
GoogleMaps API KEY for testing
Updated Answer
As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.
This answer is no longer valid
As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.
Moving up one directory in Python
In Python 3.4 pathlib was introduced:
>>> from pathlib import Path
>>> p = Path('/etc/usr/lib')
>>> p
PosixPath('/etc/usr/lib')
>>> p.parent
PosixPath('/etc/usr')
It also comes with many other helpful features e.g. for joining paths using slashes or easily walking the directory tree.
For more information refer to the docs or this blog post, which covers the differences between os.path and pathlib.
How can I do GUI programming in C?
C is more of a hardware programming language, there are easy GUI builders for C, GTK, Glade, etc. The problem is making a program in C that is the easy part, making a GUI that is a easy part, the hard part is to combine both, to interface between your program and the GUI is a headache, and different GUI use different ways, some threw global variables, some use slots. It would be nice to have a GUI builder that would bind easily your C program variables, and outputs. CLI programming is easy when you overcome memory allocation and pointers, GUI you can use a IDE that uses drag and drop. But all around I think it could be simpler.
How do I check for null values in JavaScript?
Strict equality operator:-
We can check null by ===
if ( value === null ){
}
Just by using if
if( value ) {
}
will evaluate to true if value is not:
- null
- undefined
- NaN
- empty string ("")
- false
- 0
SQL Server : export query as a .txt file
You can use windows Powershell to execute a query and output it to a text file
Invoke-Sqlcmd -Query "Select * from database" -ServerInstance "Servername\SQL2008" -Database "DbName" > c:\Users\outputFileName.txt
How do you increase the max number of concurrent connections in Apache?
Here's a detailed explanation about the calculation of MaxClients and MaxRequestsPerChild
http://web.archive.org/web/20160415001028/http://www.genericarticles.com/mediawiki/index.php?title=How_to_optimize_apache_web_server_for_maximum_concurrent_connections_or_increase_max_clients_in_apache
ServerLimit 16
StartServers 2
MaxClients 200
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers
parameter. Then each process will start 25 threads determined by ThreadsPerChild
parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50. Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit
parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. But if number defined in MaxClients
is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients
. This also means that if I set MaxClients
to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient
parameter. In this case, we need to also increase ServerLimit
to 1000/25 i.e. MaxClients/ThreadsPerChild=40
So this is the optmized configuration to server 1000 clients
<IfModule mpm_worker_module>
ServerLimit 40
StartServers 2
MaxClients 1000
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestsPerChild 0
</IfModule>
Styling the last td in a table with css
This is the code that will add border for all the nodes and will remove the border for the last node(TD).
<style type="text/css">
body {
font-family:arial;font-size: 8pt;
}
table td{
border-right: #666 1px solid
}
table td {
h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : 'border-right: 0px solid' ) );
}
</style>
<table>
<tr>
<td>Home</td>
<td>sunil</td>
<td>Kumar</td>
<td>Rayadurg</td>
<td>Five</td>
<td>Six</td>
</tr>
</table>
Enjoy ...
I want the same instead of border I wanted it using images ... :-)
Getting a map() to return a list in Python 3.x
list(map(chr, [66, 53, 0, 94]))
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
"Make an iterator"
means it will return an iterator.
"that computes the function using arguments from each of the iterables"
means that the next() function of the iterator will take one value of each iterables and pass each of them to one positional parameter of the function.
So you get an iterator from the map() funtion and jsut pass it to the list() builtin function or use list comprehensions.
Importing a CSV file into a sqlite3 database table using Python
With this you can do joins on CSVs as well:
import sqlite3
import os
import pandas as pd
from typing import List
class CSVDriver:
def __init__(self, table_dir_path: str):
self.table_dir_path = table_dir_path # where tables (ie. csv files) are located
self._con = None
@property
def con(self) -> sqlite3.Connection:
"""Make a singleton connection to an in-memory SQLite database"""
if not self._con:
self._con = sqlite3.connect(":memory:")
return self._con
def _exists(self, table: str) -> bool:
query = """
SELECT name
FROM sqlite_master
WHERE type ='table'
AND name NOT LIKE 'sqlite_%';
"""
tables = self.con.execute(query).fetchall()
return table in tables
def _load_table_to_mem(self, table: str, sep: str = None) -> None:
"""
Load a CSV into an in-memory SQLite database
sep is set to None in order to force pandas to auto-detect the delimiter
"""
if self._exists(table):
return
file_name = table + ".csv"
path = os.path.join(self.table_dir_path, file_name)
if not os.path.exists(path):
raise ValueError(f"CSV table {table} does not exist in {self.table_dir_path}")
df = pd.read_csv(path, sep=sep, engine="python") # set engine to python to skip pandas' warning
df.to_sql(table, self.con, if_exists='replace', index=False, chunksize=10000)
def query(self, query: str) -> List[tuple]:
"""
Run an SQL query on CSV file(s).
Tables are loaded from table_dir_path
"""
tables = extract_tables(query)
for table in tables:
self._load_table_to_mem(table)
cursor = self.con.cursor()
cursor.execute(query)
records = cursor.fetchall()
return records
extract_tables():
import sqlparse
from sqlparse.sql import IdentifierList, Identifier, Function
from sqlparse.tokens import Keyword, DML
from collections import namedtuple
import itertools
class Reference(namedtuple('Reference', ['schema', 'name', 'alias', 'is_function'])):
__slots__ = ()
def has_alias(self):
return self.alias is not None
@property
def is_query_alias(self):
return self.name is None and self.alias is not None
@property
def is_table_alias(self):
return self.name is not None and self.alias is not None and not self.is_function
@property
def full_name(self):
if self.schema is None:
return self.name
else:
return self.schema + '.' + self.name
def _is_subselect(parsed):
if not parsed.is_group:
return False
for item in parsed.tokens:
if item.ttype is DML and item.value.upper() in ('SELECT', 'INSERT',
'UPDATE', 'CREATE', 'DELETE'):
return True
return False
def _identifier_is_function(identifier):
return any(isinstance(t, Function) for t in identifier.tokens)
def _extract_from_part(parsed):
tbl_prefix_seen = False
for item in parsed.tokens:
if item.is_group:
for x in _extract_from_part(item):
yield x
if tbl_prefix_seen:
if _is_subselect(item):
for x in _extract_from_part(item):
yield x
# An incomplete nested select won't be recognized correctly as a
# sub-select. eg: 'SELECT * FROM (SELECT id FROM user'. This causes
# the second FROM to trigger this elif condition resulting in a
# StopIteration. So we need to ignore the keyword if the keyword
# FROM.
# Also 'SELECT * FROM abc JOIN def' will trigger this elif
# condition. So we need to ignore the keyword JOIN and its variants
# INNER JOIN, FULL OUTER JOIN, etc.
elif item.ttype is Keyword and (
not item.value.upper() == 'FROM') and (
not item.value.upper().endswith('JOIN')):
tbl_prefix_seen = False
else:
yield item
elif item.ttype is Keyword or item.ttype is Keyword.DML:
item_val = item.value.upper()
if (item_val in ('COPY', 'FROM', 'INTO', 'UPDATE', 'TABLE') or
item_val.endswith('JOIN')):
tbl_prefix_seen = True
# 'SELECT a, FROM abc' will detect FROM as part of the column list.
# So this check here is necessary.
elif isinstance(item, IdentifierList):
for identifier in item.get_identifiers():
if (identifier.ttype is Keyword and
identifier.value.upper() == 'FROM'):
tbl_prefix_seen = True
break
def _extract_table_identifiers(token_stream):
for item in token_stream:
if isinstance(item, IdentifierList):
for ident in item.get_identifiers():
try:
alias = ident.get_alias()
schema_name = ident.get_parent_name()
real_name = ident.get_real_name()
except AttributeError:
continue
if real_name:
yield Reference(schema_name, real_name,
alias, _identifier_is_function(ident))
elif isinstance(item, Identifier):
yield Reference(item.get_parent_name(), item.get_real_name(),
item.get_alias(), _identifier_is_function(item))
elif isinstance(item, Function):
yield Reference(item.get_parent_name(), item.get_real_name(),
item.get_alias(), _identifier_is_function(item))
def extract_tables(sql):
# let's handle multiple statements in one sql string
extracted_tables = []
statements = list(sqlparse.parse(sql))
for statement in statements:
stream = _extract_from_part(statement)
extracted_tables.append([ref.name for ref in _extract_table_identifiers(stream)])
return list(itertools.chain(*extracted_tables))
Example (assuming account.csv
and tojoin.csv
exist in /path/to/files
):
db_path = r"/path/to/files"
driver = CSVDriver(db_path)
query = """
SELECT tojoin.col_to_join
FROM account
LEFT JOIN tojoin
ON account.a = tojoin.a
"""
driver.query(query)
how to take user input in Array using java?
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
How can I pipe stderr, and not stdout?
First redirect stderr to stdout — the pipe; then redirect stdout to /dev/null
(without changing where stderr is going):
command 2>&1 >/dev/null | grep 'something'
For the details of I/O redirection in all its variety, see the chapter on Redirections in the Bash reference manual.
Note that the sequence of I/O redirections is interpreted left-to-right, but pipes are set up before the I/O redirections are interpreted. File descriptors such as 1 and 2 are references to open file descriptions. The operation 2>&1
makes file descriptor 2 aka stderr refer to the same open file description as file descriptor 1 aka stdout is currently referring to (see dup2()
and open()
). The operation >/dev/null
then changes file descriptor 1 so that it refers to an open file description for /dev/null
, but that doesn't change the fact that file descriptor 2 refers to the open file description which file descriptor 1 was originally pointing to — namely, the pipe.
What's the most concise way to read query parameters in AngularJS?
It can be done by two ways:
- Using
$routeParams
Best and recommended solution is to use $routeParams
into your controller.
It Requires the ngRoute
module to be installed.
function MyController($scope, $routeParams) {
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
// $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
var search = $routeParams.search;
}
- Using
$location.search()
.
There is a caveat here. It will work only with HTML5 mode. By default, it does not work for the URL which does not have hash(#
) in it http://localhost/test?param1=abc¶m2=def
You can make it work by adding #/
in the URL. http://localhost/test#/?param1=abc¶m2=def
$location.search()
to return an object like:
{
param1: 'abc',
param2: 'def'
}
Rename MySQL database
I don't think you can do this. Basic answers will work in many cases, and in others cause data corruptions. A strategy needs to be chosen based on heuristic analysis of your database. That is the reason this feature was implemented, and then removed. [doc]
You'll need to dump all object types in that database, create the newly named one and then import the dump. If this is a live system you'll need to take it down. If you cannot, then you will need to setup replication from this database to the new one.
If you want to see the commands that could do this, @satishD has the details, which conveys some of the challenges around which you'll need to build a strategy that matches your target database.
parse html string with jquery
I'm not a 100% sure, but won't
$(data)
produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.
EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)
$("img", data).attr ("src")
if you want to access the src-attribute. If your data is just text, it would probably work to do
$("img", $(data)).attr ("src")
nginx 502 bad gateway
You have to match the settings for PHP-FPM and Nginx to communicate over sockets or TCP.
So go to /etc/php5/fpm/pool.d/www.conf
and look for this line:
listen = /var/run/php5-fpm.sock
Then go to /etc/nginx/nginx.conf
Look for this:
upstream php {
server unix:/var/run/php5-fpm.socket;
}
Match those values and you should be all set.
How Do I Insert a Byte[] Into an SQL Server VARBINARY Column
check this image link for all steps
https://drive.google.com/open?id=0B0-Ll2y6vo_sQ29hYndnbGZVZms
STEP1: I created a field of type varbinary in table
STEP2: I created a stored procedure to accept a parameter of type sql_variant
STEP3: In my front end asp.net page, I created a sql data source parameter of object type
<tr>
<td>
UPLOAD DOCUMENT</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" />
<asp:SqlDataSource ID="sqldsFileUploadConn" runat="server"
ConnectionString="<%$ ConnectionStrings: %>"
InsertCommand="ph_SaveDocument"
InsertCommandType="StoredProcedure">
<InsertParameters>
<asp:Parameter Name="DocBinaryForm" Type="Object" />
</InsertParameters>
</asp:SqlDataSource>
</td>
<td>
</td>
</tr>
STEP 4: In my code behind, I try to upload the FileBytes from FileUpload Control via this stored procedure call using a sql data source control
Dim filebytes As Object
filebytes = FileUpload1.FileBytes()
sqldsFileUploadConn.InsertParameters("DocBinaryForm").DefaultValue = filebytes.ToString
Dim uploadstatus As Int16 = sqldsFileUploadConn.Insert()
' ... code continues ... '