SELECT * from employees
WHERE NOT EXISTS (SELECT name FROM eotm_dyn)
Never returns any records unless eotm_dyn
is empty. You need to some kind of criteria on SELECT name FROM eotm_dyn
like
SELECT * from employees
WHERE NOT EXISTS (
SELECT name FROM eotm_dyn WHERE eotm_dyn.employeeid = employees.employeeid
)
assuming that the two tables are linked by a foreign key relationship. At this point you could use a variety of other options including a LEFT JOIN. The optimizer will typically handle them the same in most cases, however.
Contains is used in Linq ,Just like Like is used in SQL .
string _search="/12/";
. . .
.Where(s => s.Hierarchy.Contains(_search))
You can write your SQL script in Linq as Following :
var result= Organizations.Join(OrganizationsHierarchy.Where(s=>s.Hierarchy.Contains("/12/")),s=>s.Id,s=>s.OrganizationsId,(org,orgH)=>new {org,orgH});
You can use the jps
utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class.
Then use the Windows task manager to terminate the process. If you want to do it on the command line, use
TASKKILL /PID %PID%
run:
rbenv init
After I ran that, when i set my local rbenv version:
rbenv local 2.4.0
then my ruby -v
and my rbenv local
versions coincided.
Note: You might also want to exit the directory you're in and then go back into it, i've noticed that was necessary for me in order to get things to work.
In recent JavaScript release there is new chaining operator introduced, which is most probably best way to check if property exists else it will give you undefined
see example below
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
We can replace this old syntax
if (response && response.data && response.data.someData && response.data.someData.someMoreData) {}
with this neater syntax
if( response?.data?.someData?.someMoreData) {}
This syntax is not supported in IE, Opera, safari & samsund android
for more detail you can check this URL
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
I ran into this issue and found that mysqlclient
needs to know where to find openssl, and OSX hides this by default.
Locate openssl with brew info openssl
, and then add the path to your openssl
bin to your PATH:
export PATH="/usr/local/opt/openssl/bin:$PATH"
I recommend adding that to your .zshrc or .bashrc so you don't need to worry about it in the future. Then, with that variable exported (which may meed closing and re-opening your bash session), add two more env variables:
# in terminal
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"
Then, finally, run:
pipenv install mysqlclient
and it should install just fine.
Source: https://medium.com/@shandou/pipenv-install-mysqlclient-on-macosx-7c253b0112f2
For floating point code, the <= comparison may indeed be slower (by one instruction) even on modern architectures. Here's the first function:
int compare_strict(double a, double b) { return a < b; }
On PowerPC, first this performs a floating point comparison (which updates cr
, the condition register), then moves the condition register to a GPR, shifts the "compared less than" bit into place, and then returns. It takes four instructions.
Now consider this function instead:
int compare_loose(double a, double b) { return a <= b; }
This requires the same work as compare_strict
above, but now there's two bits of interest: "was less than" and "was equal to." This requires an extra instruction (cror
- condition register bitwise OR) to combine these two bits into one. So compare_loose
requires five instructions, while compare_strict
requires four.
You might think that the compiler could optimize the second function like so:
int compare_loose(double a, double b) { return ! (a > b); }
However this will incorrectly handle NaNs. NaN1 <= NaN2
and NaN1 > NaN2
need to both evaluate to false.
This should work:
int hh, mm, ss;
struct tm when = {0};
sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);
when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;
time_t converted;
converted = mktime(&when);
Modify as needed.
encapsulate all of your js code within a window.onload function. I had a similar issue. Everything is loaded asynchronously in javascript so some parts load quicker than others, including your browser. Putting all of your code inside the onload function will ensure everything your code will need from the browser will be ready to use before attempting to execute.
If you want to support more than one space at a time, or support any whitespace, you can do this:
NSString* noSpaces =
[[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:@""];
Creating an isolate scope is undesirable. I would avoid using the scope attribute and do something like this. scope:true gives you a new child scope but not isolate. Then use parse to point a local scope variable to the same object the user has supplied to the ngModel attribute.
app.directive('myDir', ['$parse', function ($parse) {
return {
restrict: 'EA',
scope: true,
link: function (scope, elem, attrs) {
if(!attrs.ngModel) {return;}
var model = $parse(attrs.ngModel);
scope.model = model(scope);
}
};
}]);
Inline Javascript:
<button onclick="window.location='http://www.example.com';">Visit Page Now</button>
Defining a function in Javascript:
<script>
function visitPage(){
window.location='http://www.example.com';
}
</script>
<button onclick="visitPage();">Visit Page Now</button>
or in Jquery
<button id="some_id">Visit Page Now</button>
$('#some_id').click(function() {
window.location='http://www.example.com';
});
The answer is correct, however the perl documentation on how to handle deadlocks is a bit sparse and perhaps confusing with PrintError, RaiseError and HandleError options. It seems that rather than going with HandleError, use on Print and Raise and then use something like Try:Tiny to wrap your code and check for errors. The below code gives an example where the db code is inside a while loop that will re-execute an errored sql statement every 3 seconds. The catch block gets $_ which is the specific err message. I pass this to a handler function "dbi_err_handler" which checks $_ against a host of errors and returns 1 if the code should continue (thereby breaking the loop) or 0 if its a deadlock and should be retried...
$sth = $dbh->prepare($strsql);
my $db_res=0;
while($db_res==0)
{
$db_res=1;
try{$sth->execute($param1,$param2);}
catch
{
print "caught $_ in insertion to hd_item_upc for upc $upc\n";
$db_res=dbi_err_handler($_);
if($db_res==0){sleep 3;}
}
}
dbi_err_handler should have at least the following:
sub dbi_err_handler
{
my($message) = @_;
if($message=~ m/DBD::mysql::st execute failed: Deadlock found when trying to get lock; try restarting transaction/)
{
$caught=1;
$retval=0; # we'll check this value and sleep/re-execute if necessary
}
return $retval;
}
You should include other errors you wish to handle and set $retval depending on whether you'd like to re-execute or continue..
Hope this helps someone -
RunOnUIThread didn't seem to work for me but the following ended up solving my issues.
_ = MainThread.InvokeOnMainThreadAsync(async () =>
{
this.LoadApplication(Startup.Init(this.ConfigureServices));
var authenticationService = App.ServiceProvider.GetService<AuthenticationService>();
if (authenticationService.AuthenticationResult == null)
{
await authenticationService.AuthenticateAsync(AuthenticationUserFlow.SignUpSignIn, CrossCurrentActivity.Current.Activity).ConfigureAwait(false);
}
});
Within the Startup.Init method there is ReactiveUI routing and this needs to be invoked on the main thread. This Invoke method also accepts async/await better than RunOnUIThread.
So anywhere I need to invoke methods on the mainthread I use this.
Please comment on this if anyone knows something I don't and can help me improve my application.
<?php
$terms = get_the_terms( $post->ID, 'taxonomy');
foreach ( $terms as $term ) {
$termID[] = $term->term_id;
}
echo $termID[0];
?>
To dynamically change the color of a text box goto properties, goto font/Color and set the following expression
=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)
Same way for tolerance
=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")
In terms of performance my favorite answer would be:
b.extend(a)
Check how the related alternatives compare with each other in terms of performance:
In [1]: import timeit
In [2]: timeit.timeit('b.extend(a)', setup='b=[];a=range(0,10)', number=100000000)
Out[2]: 9.623248100280762
In [3]: timeit.timeit('b = a[:]', setup='b=[];a=range(0,10)', number=100000000)
Out[3]: 10.84756088256836
In [4]: timeit.timeit('b = list(a)', setup='b=[];a=range(0,10)', number=100000000)
Out[4]: 21.46313500404358
In [5]: timeit.timeit('b = [elem for elem in a]', setup='b=[];a=range(0,10)', number=100000000)
Out[5]: 66.99795293807983
In [6]: timeit.timeit('for elem in a: b.append(elem)', setup='b=[];a=range(0,10)', number=100000000)
Out[6]: 67.9775960445404
In [7]: timeit.timeit('b = deepcopy(a)', setup='from copy import deepcopy; b=[];a=range(0,10)', number=100000000)
Out[7]: 1216.1108016967773
An earlier comment on an answer said it, but it is easy to miss among all the other answers.
When using bash:
echo this file: "$BASH_SOURCE"
echo this dir: "$(dirname "$BASH_SOURCE")"
Use this format: ${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}
Which will give you: 2018-01-16T08:32:28.75Z
while ($personCount < 10) {
$result .= ($personCount++)." people ";
}
echo $result;
Why not use commands.getoutput() instead?
import commands
text = "Mario Balotelli"
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)
You should do ex.StackTrace instead of ex.ToString()
Similar to unutbu above, you could also use applymap
as follows:
import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
df = df.applymap("${0:.2f}".format)
Just wanted to say Magnus' answer above did it for me, but for the second "overlay" that needs to be "overflow"
helpers : {
overlay : {
css : { 'overflow' : 'hidden' }
}
}
If you don't want to use a library, this should cover most/all of the same form element types.
function serialize(form) {
if (!form || !form.elements) return;
var serial = [], i, j, first;
var add = function (name, value) {
serial.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
}
var elems = form.elements;
for (i = 0; i < elems.length; i += 1, first = false) {
if (elems[i].name.length > 0) { /* don't include unnamed elements */
switch (elems[i].type) {
case 'select-one': first = true;
case 'select-multiple':
for (j = 0; j < elems[i].options.length; j += 1)
if (elems[i].options[j].selected) {
add(elems[i].name, elems[i].options[j].value);
if (first) break; /* stop searching for select-one */
}
break;
case 'checkbox':
case 'radio': if (!elems[i].checked) break; /* else continue */
default: add(elems[i].name, elems[i].value); break;
}
}
}
return serial.join('&');
}
I also had the problem.
I was able to solve by changing compileSdkVersion
and targetSdkVersion
to latest version.
Resized VM with more memory fixed this issue.
This works perfectly for me...
echo nl2br("\n");
Reference: http://www.w3schools.com/php/func_string_nl2br.asp
Hope it helps :)
I hope the below example will provide more clarity.
package main
type EmployeeManager struct{
category string
city string
calculateSalary func() int64
}
func NewEmployeeManager() (*EmployeeManager,error){
return &EmployeeManager{
category : "MANAGEMENT",
city : "NY",
calculateSalary: func() int64 {
var calculatedSalary int64
// some formula
return calculatedSalary
},
},nil
}
func (self *EmployeeManager) emWithSalaryCalculation(){
self.calculateSalary = func() int64 {
var calculatedSalary int64
// some new formula
return calculatedSalary
}
}
func updateEmployeeInfo(em EmployeeManager){
// Some code
}
func processEmployee(){
updateEmployeeInfo(struct {
category string
city string
calculateSalary func() int64
}{category: "", city: "", calculateSalary: func() int64 {
var calculatedSalary int64
// some new formula
return calculatedSalary
}})
}
Since you're using PHP, you will probably need to use the CURLOPT_PORT
option, like so:
curl_setopt($ch, CURLOPT_PORT, 11740);
Bear in mind, you may face problems with SELinux:
You're probably using
document.getElementById('element').innerHTML = "New content"
Try this instead:
document.getElementById('element').innerHTML += "New content"
Or, preferably, use DOM Manipulation:
document.getElementById('element').appendChild(document.createElement("div"))
Dom manipulation would be preferred compared to using innerHTML
, because innerHTML
simply dumps a string into the document. The browser will have to reparse the entire document to get it's stucture.
If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:
my_arr.resize()
This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time. Hope this helped. Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.
Use this, from here:
function insertAtCaret(areaId, text) {_x000D_
var txtarea = document.getElementById(areaId);_x000D_
if (!txtarea) {_x000D_
return;_x000D_
}_x000D_
_x000D_
var scrollPos = txtarea.scrollTop;_x000D_
var strPos = 0;_x000D_
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?_x000D_
"ff" : (document.selection ? "ie" : false));_x000D_
if (br == "ie") {_x000D_
txtarea.focus();_x000D_
var range = document.selection.createRange();_x000D_
range.moveStart('character', -txtarea.value.length);_x000D_
strPos = range.text.length;_x000D_
} else if (br == "ff") {_x000D_
strPos = txtarea.selectionStart;_x000D_
}_x000D_
_x000D_
var front = (txtarea.value).substring(0, strPos);_x000D_
var back = (txtarea.value).substring(strPos, txtarea.value.length);_x000D_
txtarea.value = front + text + back;_x000D_
strPos = strPos + text.length;_x000D_
if (br == "ie") {_x000D_
txtarea.focus();_x000D_
var ieRange = document.selection.createRange();_x000D_
ieRange.moveStart('character', -txtarea.value.length);_x000D_
ieRange.moveStart('character', strPos);_x000D_
ieRange.moveEnd('character', 0);_x000D_
ieRange.select();_x000D_
} else if (br == "ff") {_x000D_
txtarea.selectionStart = strPos;_x000D_
txtarea.selectionEnd = strPos;_x000D_
txtarea.focus();_x000D_
}_x000D_
_x000D_
txtarea.scrollTop = scrollPos;_x000D_
}
_x000D_
<textarea id="textareaid"></textarea>_x000D_
<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>
_x000D_
Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get
>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160
There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.
If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).
Use transform: scale(0.8);
with the value you need instead of 0.8
Have a look at ImmutableMap JavaDoc: doc
There is information about that there:
Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.
You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.
MyLocation is a Swift iOS Demo.
You can use this demo for the following:
Show the current location.
Choose other location: in this case stop tracking the location.
Add a push pin to a MKMapView(iOS) when touching.
You can set a variable in the view file, but it will be printed just as you set it. Anyway, there is a workaround. You can set the variable inside an unused section. Example:
@section('someSection')
{{ $yourVar = 'Your value' }}
@endsection
Then {{ $yourVar }}
will print Your value
anywhere you want it to, but you don't get the output when you save the variable.
EDIT: naming the section is required otherwise an exception will be thrown.
You could use this Visual Studio VB.Net code to get the encoding:
Dim strEncryptionType As String = String.Empty
Dim myStreamRdr As System.IO.StreamReader = New System.IO.StreamReader(myFileName, True)
Dim myString As String = myStreamRdr.ReadToEnd()
strEncryptionType = myStreamRdr.CurrentEncoding.EncodingName
/*
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# dejavu sans
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
/*default version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans.ttf'); /* IE9 Compat Modes */
src:
local('DejaVu Sans'),
local('DejaVu-Sans'), /* Duplicated name with hyphen */
url('dejavu/DejaVuSans.ttf')
format('truetype');
}
/*bold version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-Bold.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-Bold.ttf')
format('truetype');
font-weight: bold;
}
/*italic version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-Oblique.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-Oblique.ttf')
format('truetype');
font-style: italic;
}
/*bold italic version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-BoldOblique.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-BoldOblique.ttf')
format('truetype');
font-weight: bold;
font-style: italic;
}
Its a bit late to anwser, but I hope my answer been useful for someone, who needs to select Composite foreign keys.
SELECT
"C"."CONSTRAINT_NAME",
"C"."OWNER" AS "SCHEMA_NAME",
"C"."TABLE_NAME",
"COL"."COLUMN_NAME",
"REF_COL"."OWNER" AS "REF_SCHEMA_NAME",
"REF_COL"."TABLE_NAME" AS "REF_TABLE_NAME",
"REF_COL"."COLUMN_NAME" AS "REF_COLUMN_NAME"
FROM
"USER_CONSTRAINTS" "C"
INNER JOIN "USER_CONS_COLUMNS" "COL" ON "COL"."OWNER" = "C"."OWNER"
AND "COL"."CONSTRAINT_NAME" = "C"."CONSTRAINT_NAME"
INNER JOIN "USER_CONS_COLUMNS" "REF_COL" ON "REF_COL"."OWNER" = "C"."R_OWNER"
AND "REF_COL"."CONSTRAINT_NAME" = "C"."R_CONSTRAINT_NAME"
AND "REF_COL"."POSITION" = "COL"."POSITION"
WHERE "C"."TABLE_NAME" = 'TableName' AND "C"."CONSTRAINT_TYPE" = 'R'
Use LEFT combined with CHARINDEX:
UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0
Note that the WHERE clause skips updating rows in which there is no semicolon.
Here is some code to verify the SQL above works:
declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part;'
union all select 7, ';' -- test semicolon by itself
UPDATE @MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0
select * from @MyTable
I get the following results:
id MyText
-- -------------------------
1 some text
2 text again
3 text without a semicolon
4 NULL
5 (empty string)
6 test 3 semicolons
7 (empty string)
The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment
is an empty array.
So you should move your script after the html element is available.
Also, getElementsByClassName
returns html collection, so if you need to add event Listener to an element, you will need to do something like following
comment[0].addEventListener('click' , showComment , false ) ;
If you want to add event listener to all the elements, then you will need to loop through them
for (var i = 0 ; i < comment.length; i++) {
comment[i].addEventListener('click' , showComment , false ) ;
}
If you're a fan of NumPy
ish syntax, then there's tensor.shape
.
In [3]: ar = torch.rand(3, 3)
In [4]: ar.shape
Out[4]: torch.Size([3, 3])
# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]
# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]
# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]
P.S.: Note that tensor.shape
is an alias to tensor.size()
, though tensor.shape
is an attribute of the tensor in question whereas tensor.size()
is a function.
github gist https://gist.github.com/anjia0532/da4a17f848468de5a374c860b17607e7
#set $token "?"; # deprecated
set $token ""; # declar token is ""(empty str) for original request without args,because $is_args concat any var will be `?`
if ($is_args) { # if the request has args update token to "&"
set $token "&";
}
location /test {
set $args "${args}${token}k1=v1&k2=v2"; # update original append custom params with $token
# if no args $is_args is empty str,else it's "?"
# http is scheme
# service is upstream server
#proxy_pass http://service/$uri$is_args$args; # deprecated remove `/`
proxy_pass http://service$uri$is_args$args; # proxy pass
}
#http://localhost/test?foo=bar ==> http://service/test?foo=bar&k1=v1&k2=v2
#http://localhost/test/ ==> http://service/test?k1=v1&k2=v2
If origin
points to a bare repository on disk, this error can happen if that directory has been moved (even if you update the working copy's remotes). For example
$ mv /path/to/origin /somewhere/else
$ git remote set-url origin /somewhere/else
$ git diff origin/master
fatal: ambiguous argument 'origin': unknown revision or path not in the working tree.
Pulling once from the new origin
solves the problem:
$ git stash
$ git pull origin master
$ git stash pop
You just need to add these 3 lines of code. Replace the icon with your own icon. If you want to generate icons use this
getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back_arrow);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
Alternative answer: if it's a Huawei device and you have implemented requirements needed for Oreo 8 Android and there are still issues only with Huawei devices than it's only device issue, you can read https://dontkillmyapp.com/huawei
ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT primary key FIRST
Vertical align, dynamic height combined with absolute position is except some special conditions not possible without a few lines of JS (eg. jQuery). (can possibly be solved with backend code in some cases, or min-height combined with sensible top or margin styles, but not perfect)
I mostly only use absolute position when something is supposed to "popup" in relation to something else which is in the float, I think that's the best way to use it so you don't have to fiddle with things like this.
No offense, but most answers in here are way off.
Here are the steps:
click File > Import. The Import window opens.
Under Select an import source, click J2EE > App Client JAR file.
Click Next.
In the Application Client file field, enter the location and name of the application client JAR file that you want to import. You can click the Browse button to select the JAR file from the file system.
In the Application Client project field, type a new project name or select an application client project from the drop-down list. If you type a new name in this field, the application client project will be created based on the version of the application client JAR file, and it will use the default location.
In the Target runtime drop-down list, select the application server that you want to target for your development. This selection affects the run time settings by modifying the class path entries for the project.
If you want to add the new module to an enterprise application project, select the Add project to an EAR check box and then select an existing enterprise application project from the list or create a new one by clicking New.
Note: If you type a new enterprise application project name, the enterprise application project will be created in the default location with the lowest compatible J2EE version based on the version of the project being created. If you want to specify a different version or a different location for the enterprise application, you must use the New Enterprise Application Project wizard.
Click Finish to import the application client JAR file.
I use the following script
$ echo "foo.tar.gz"|rev|cut -d"." -f3-|rev
foo
Go to android studio -> AVD manager -> Select your AVD and wipe user data
No need to re-install the entire AVD.
You may well want to use JSON-P instead (see below). First a quick explanation.
The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest
) rather than the standard XMLHttpRequest
that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com
).
To get the JSON data you're requesting, you basically have three options:
If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)
Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax
call (just set dataType
to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:
{"weather": "Dreary start but soon brightening into a fine summer day."}
Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:
jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
That's it. JSON-P is very broadly compatible (because it works via JavaScript script
tags). JSON-P is only for GET
, though, not POST
(again because it works via script
tags).
Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:
A. The browser will send your server a "preflight" message using the OPTIONS
HTTP verb (method). It will contain the various headers it would send with the GET
or POST
as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET
or POST
), and "Access-Control-Request-Headers" (the headers it wants to send).
B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.
C. The browser will look at your response and see whether it's allowed to send you the actual GET
or POST
. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.
D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.
In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):
// Find out what the request is asking for
corsOrigin = get_request_header("Origin")
corsMethod = get_request_header("Access-Control-Request-Method")
corsHeaders = get_request_header("Access-Control-Request-Headers")
if corsOrigin is null or "null" {
// Requests from a `file://` path seem to come through without an
// origin or with "null" (literally) as the origin.
// In my case, for testing, I wanted to allow those and so I output
// "*", but you may want to go another way.
corsOrigin = "*"
}
// Decide whether to accept that request with those headers
// If so:
// Respond with headers saying what's allowed (here we're just echoing what they
// asked for, except we may be using "*" [all] instead of the actual origin for
// the "Access-Control-Allow-Origin" one)
set_response_header("Access-Control-Allow-Origin", corsOrigin)
set_response_header("Access-Control-Allow-Methods", corsMethod)
set_response_header("Access-Control-Allow-Headers", corsHeaders)
if the HTTP request method is "OPTIONS" {
// Done, no body in response to OPTIONS
stop
}
// Process the GET or POST here; output the body of the response
Again stressing that this is pseudo-code.
Take the width of the table and divide it by the number of cell ().
PerformanceTable {width:500px;}
PerformanceTable.td {width:100px;}
If the table dynamically widens or shrinks you could dynamically increase the cell size with a little javascript.
UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'
Now rows that were like
http://www.example.com/articles/updates/43
will be
http://www.example.com/articles/news/43
plot(t)
is in this case the same as
plot(t[[1]], t[[2]])
As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1
:
> length(t)
[1] 4
> length(1)
[1] 1
In your second example you plot a list with elements named x
and y
, both vectors of length 2,
so plot
plots these two vectors.
Edit:
If you want to plot lines use
plot(t, type="l")
I had the same problem (Python 2.7 Linux), I have found the solution and i would like to share it. In my case i had the structure below:
Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py
In 'main.py' I had tried unsuccessfully all the combinations bellow:
from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...
The solution was much more simple than I thought. I renamed the folder "Booklet" into "booklet" and that's it. Now Python can import the class Question normally by using in 'main.py' the code:
from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass
From this I can conclude that Package-Names (folders) like 'booklet' must start from lower-case, else Python confuses it with Class names and Filenames.
Apparently, this was not your problem, but John Fouhy's answer is very good and this thread has almost anything that can cause this issue. So, this is one more thing and I hope that maybe this could help others.
Here's how to disable minification on a per-bundle basis:
bundles.Add(new StyleBundleRaw("~/Content/foobarcss").Include("/some/path/foobar.css"));
bundles.Add(new ScriptBundleRaw("~/Bundles/foobarjs").Include("/some/path/foobar.js"));
Sidenote: The paths used for your bundles must not coincide with any actual path in your published builds otherwise nothing will work. Also make sure to avoid using .js, .css and/or '.' and '_' anywhere in the name of the bundle. Keep the name as simple and as straightforward as possible, like in the example above.
The helper classes are shown below. Notice that in order to make these classes future-proof we surgically remove the js/css minifying instances instead of using .clear() and we also insert a mime-type-setter transformation without which production builds are bound to run into trouble especially when it comes to properly handing over css-bundles (firefox and chrome reject css bundles with mime-type set to "text/html" which is the default):
internal sealed class StyleBundleRaw : StyleBundle
{
private static readonly BundleMimeType CssContentMimeType = new BundleMimeType("text/css");
public StyleBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
{
}
public StyleBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
{
Transforms.Add(CssContentMimeType); //0 vital
Transforms.Remove(Transforms.FirstOrDefault(x => x is CssMinify)); //0
}
//0 the guys at redmond in their infinite wisdom plugged the mimetype "text/css" right into cssminify upon unwiring the minifier we
// need to somehow reenable the cssbundle to specify its mimetype otherwise it will advertise itself as html and wont load
}
internal sealed class ScriptBundleRaw : ScriptBundle
{
private static readonly BundleMimeType JsContentMimeType = new BundleMimeType("text/javascript");
public ScriptBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
{
}
public ScriptBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
{
Transforms.Add(JsContentMimeType); //0 vital
Transforms.Remove(Transforms.FirstOrDefault(x => x is JsMinify)); //0
}
//0 the guys at redmond in their infinite wisdom plugged the mimetype "text/javascript" right into jsminify upon unwiring the minifier we need
// to somehow reenable the jsbundle to specify its mimetype otherwise it will advertise itself as html causing it to be become unloadable by the browsers in published production builds
}
internal sealed class BundleMimeType : IBundleTransform
{
private readonly string _mimeType;
public BundleMimeType(string mimeType) { _mimeType = mimeType; }
public void Process(BundleContext context, BundleResponse response)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (response == null)
throw new ArgumentNullException(nameof(response));
response.ContentType = _mimeType;
}
}
To make this whole thing work you need to install (via nuget):
WebGrease 1.6.0+ Microsoft.AspNet.Web.Optimization 1.1.3+
And your web.config should be enriched like so:
<runtime>
[...]
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
</dependentAssembly>
[...]
</runtime>
<!-- setting mimetypes like we do right below is absolutely vital for published builds because for some reason the -->
<!-- iis servers in production environments somehow dont know how to handle otf eot and other font related files -->
<system.webServer>
[...]
<staticContent>
<!-- in case iis already has these mime types -->
<remove fileExtension=".otf" />
<remove fileExtension=".eot" />
<remove fileExtension=".ttf" />
<remove fileExtension=".woff" />
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".otf" mimeType="font/otf" />
<mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
<mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>
<!-- also vital otherwise published builds wont work https://stackoverflow.com/a/13597128/863651 -->
<modules runAllManagedModulesForAllRequests="true">
<remove name="BundleModule" />
<add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>
[...]
</system.webServer>
Note that you might have to take extra steps to make your css-bundles work in terms of fonts etc. But that's a different story.
You could use .each()
with .children()
and a selector within the parenthesis:
//Grab Each Instance of Box.
$(".box").each(function(i){
//For Each Instance, grab a child called .something1. Fade It Out.
$(this).children(".something1").fadeOut();
});
see my answer here:
How can I get the current date and time in UTC or GMT in Java?
I've fully tested it by changing the timezones on the emulator
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
With different domains, it is not possible to call methods or access the iframe's content document directly.
You have to use cross-document messaging.
For example in the top window:
myIframe.contentWindow.postMessage('hello', '*');
and in the iframe:
window.onmessage = function(e){
if (e.data == 'hello') {
alert('It works!');
}
};
If you are posting message from iframe to parent window
window.top.postMessage('hello', '*')
You need to update Anaconda using:
conda update
and
conda update anaconda-navigator
Try these commands on anaconda prompt and then try to launch navigator from the prompt itself using following command:
anaconda-navigator
If still the problem doesn't get solved, share the anaconda prompt logs here if they have any errors.
screen.orientation.lock('landscape');
Will force it to change to and stay in landscape mode. Tested on Nexus 5.
As other people have answered, .cshtml
(or .vbhtml
if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx
extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.
This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.
Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.
The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.
In 1985, individuals from companies throughout the computer industry joined together to develop the POSIX (Portable Operating System Interface for Computer Environments) standard, which is based largely on the UNIX System V Interface Definition (SVID) and other earlier standardization efforts. These efforts were spurred by the U.S. government, which needed a standard computing environment to minimize its training and procurement costs. Released in 1988, POSIX is a group of IEEE standards that define the API, shell, and utility interfaces for an operating system. Although aimed at UNIX-like systems, the standards can apply to any compatible operating system. Now that these stan- dards have gained acceptance, software developers are able to develop applications that run on all conforming versions of UNIX, Linux, and other operating systems.
From the book: A Practical Guide To Linux
Log4j entry
#- File to log to and log format
log4j.appender.file.File=${LOG_PATH}/mylogfile.log
Java program
String log4jConfPath = "path/log4j.properties";
File log4jFile = new File(log4jConfPath);
if (log4jFile.exists()) {
System.setProperty("LOG_PATH", "c:/temp/");
PropertyConfigurator.configure(log4jFile.getAbsolutePath());
logger.trace("test123");
}
As mentioned, you simply want the standard R apply
function applied to columns (MARGIN=2
):
wifi[,4:9] <- apply(wifi[,4:9], MARGIN=2, FUN=A)
Or, for short:
wifi[,4:9] <- apply(wifi[,4:9], 2, A)
This updates columns 4:9 in-place using the A()
function. Now, let's assume that na.rm
is an argument to A()
, which it probably should be. We can pass na.rm=T
to remove NA values from the computation like so:
wifi[,4:9] <- apply(wifi[,4:9], MARGIN=2, FUN=A, na.rm=T)
The same is true for any other arguments you want to pass to your custom function.
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
I had the same problem.
As a Git-newbie, I thought it was complete FUBAR.
Solution: Somewhat like @bara suggested + created a local backup branch
# Rewind to commit just before the pushed-and-amended one.
# Replace <hash> with the needed hash.
# --soft means: leave all the changes there, so nothing is lost.
git reset --soft <hash>
# Create new branch, just for a backup, still having all changes in it.
# The branch was feature/1234, new one - feature/1234-gone-bad
git checkout -b feature/1234-gone-bad
# Commit all the changes (all the mess) not to lose it & not to carry around
git commit -a -m "feature/1234 backup"
# Switch back to the original branch
git checkout feature/1234
# Pull the from remote (named 'origin'), thus 'repairing' our main problem
git pull origin/feature/1234
# Now you have a clean-and-non-diverged branch and a backup of the local changes.
# Check the needed files from the backup branch
git checkout feature/1234-gone-bad -- the/path/to/file.php
Maybe it's not a fast and clean solution, and I lost my history (1 commit instead of 5), but it saved a day's work.
Some of these problems may be due to controls resizing themselves when populated. I tend to the turn the IntegralHeight property of controls such as list boxes from True (default) to False to prevent automated resizing of the control height at runtime.
This REGEX is a patch from @Aamir answer that worked for me
/((?:(?:http?|ftp)[s]*:\/\/)?[a-z0-9-%\/\&=?\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?)/gi
It matches these URL formats
C# is a programming language, .NET is the framework that the language is built on.
Use the css property overflow . For example:
.item{
width : 100px;
overflow:hidden;
}
The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.
I hope this helps.
Work with checkboxes using observables
You could even choose to use a behaviourSubject
to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$
observable.
In your component.ts:
public isChecked$ = new BehaviorSubject(false);
toggleChecked() {
this.isChecked$.next(!this.isChecked$.value)
}
In your template
<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">
That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f()
function
create function f() returns integer as $$
select 1;
$$ language sql;
is called as
select f(1);
It will error out with
ERROR: function f(integer) does not exist
LINE 1: select f(1);
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
because there is no f()
function that takes an integer as argument.
So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.
typeperf "\processor(_total)\% processor time"
does work on Win7, you just need to extract the percent value yourself from the last quoted string.
The only tool I know is Vera. Haven't used it, though, so can't comment how viable it is. Demo looks promising.
Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active
active is pseudo.
Reference:
http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!
Your code:
The code that you're having the basic but helpfull. And yes :active
will only occur once the click event is triggered.
button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}
button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}
This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a
tag.
How to use CSS:
You can use :focus
too. :focus
would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus
to make the buttons change.
What JS would do:
The JavaScript's jQuery library is going to help us for this code. Here is the example:
$('button').click(function () {
$(this).css('border', '1px solid red');
}
This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:
$('button').click(function () {
$(this).css('border', '1px solid red');
// find any other button with a specific id, and change it back to white like
$('button#red').css('border', '1px solid white');
}
This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)
Hope you get the answer. Good luck! Cheers.
If you want to use Java 8 streams and are allergic to while
loops, you could try this:
public static int countPattern(String references, Pattern referencePattern) {
Matcher matcher = referencePattern.matcher(references);
return Stream.iterate(0, i -> i + 1)
.filter(i -> !matcher.find())
.findFirst()
.get();
}
Disclaimer: this only works for disjoint matches.
Example:
public static void main(String[] args) throws ParseException {
Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
System.out.println(countPattern("[ ]", referencePattern));
}
This prints out:
2
0
1
0
This is a solution for disjoint matches with streams:
public static int countPattern(String references, Pattern referencePattern) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
new Iterator<Integer>() {
Matcher matcher = referencePattern.matcher(references);
int from = 0;
@Override
public boolean hasNext() {
return matcher.find(from);
}
@Override
public Integer next() {
from = matcher.start() + 1;
return 1;
}
},
Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}
#footer:after
{
content: "";
width: 40px;
height: 3px;
background-color: #529600;
left: 0;
position: relative;
display: block;
top: 10px;
}
I want to mention one important note regarding req.query
, because currently I am working on pagination functionality based on req.query
and I have one interesting example to demonstrate to you...
Example:
// Fetching patients from the database
exports.getPatients = (req, res, next) => {
const pageSize = +req.query.pageSize;
const currentPage = +req.query.currentPage;
const patientQuery = Patient.find();
let fetchedPatients;
// If pageSize and currentPage are not undefined (if they are both set and contain valid values)
if(pageSize && currentPage) {
/**
* Construct two different queries
* - Fetch all patients
* - Adjusted one to only fetch a selected slice of patients for a given page
*/
patientQuery
/**
* This means I will not retrieve all patients I find, but I will skip the first "n" patients
* For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
*
* Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
* so I want to skip (7 * (2 - 1)) => 7 items
*/
.skip(pageSize * (currentPage - 1))
/**
* Narrow dont the amound documents I retreive for the current page
* Limits the amount of returned documents
*
* For example: If I got 7 items per page, then I want to limit the query to only
* return 7 items.
*/
.limit(pageSize);
}
patientQuery.then(documents => {
res.status(200).json({
message: 'Patients fetched successfully',
patients: documents
});
});
};
You will noticed +
sign in front of req.query.pageSize
and req.query.currentPage
Why? If you delete +
in this case, you will get an error, and that error will be thrown because we will use invalid type (with error message 'limit' field must be numeric).
Important: By default if you extracting something from these query parameters, it will always be a string, because it's coming the URL and it's treated as a text.
If we need to work with numbers, and convert query statements from text to number, we can simply add a plus sign in front of statement.
DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";
// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");
Ref: http://www.csharp-examples.net/dataview-rowfilter/
http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx
Note that the default when you make a class is not public as far as packages are considered. Make sure that you actually write public class [MyClass] {
when defining your class. I've made this mistake more times than I care to admit.
Make a call to the DB searching with myid (Id of the row) and get back specific columns:
var columns = db.Notifications
.Where(x => x.Id == myid)
.Select(n => new { n.NotificationTitle,
n.NotificationDescription,
n.NotificationOrder });
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
If you mean you want to fetch everything from the beginning up to a particular point, Charles Bailey's answer is perfect. If you want to do the reverse and retrieve a subset of the history going back from the current date, you can use git clone --depth [N]
where N is the number of revs of history you want. However:
--depth
Create a shallow clone with a history truncated to the specified number of revisions. A shallow repository has a number of limitations (you cannot clone or fetch from it, nor push from nor into it), but is adequate if you are only interested in the recent history of a large project with a long history, and would want to send in fixes as patches.
First export the schema metadata:
expdp dumpfile=filename logfile=logname directory=dir_name schemas=schema_name
and then import by using the sqlfile
option (it will not import data it will just write the schema DDL to that file)
impdp dumpfile=filename logfile=logname directory=dir_name sqlfile=ddl.sql
It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:
ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;
@Adrian's answer is perfectly suitable, I just wanted to share another way of achieving the same result:
select nvl(a.id, b.id)
from a full outer join b on a.id = b.id
order by b.id;
To change the encoding of your database:
Make sure the client encoding is set correctly during all this.
Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php
The shorthand for an if else structure works as expected in JSX
this.props.hasImage ? <MyImage /> : <SomeotherElement>
You can find other options on this blogpost of DevNacho, but it's more common to do it with the shorthand. If you need to have a bigger if clause you should write a function that returns or component A or component B.
for example:
this.setState({overlayHovered: true});
renderComponentByState({overlayHovered}){
if(overlayHovered) {
return <overlayHoveredComponent />
}else{
return <overlayNotHoveredComponent />
}
}
You can destructure your overlayHovered from this.state if you give it as parameter. Then execute that function in your render() method:
renderComponentByState(this.state)
It turns out Java does not accept a bare Date value as DateTime. Using LocalDate instead of LocalDateTime solves the issue:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);
Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.
Another way is to pass a list of lists to a one-argument routine:
import os
from multiprocessing import Pool
def task(args):
print "PID =", os.getpid(), ", arg1 =", args[0], ", arg2 =", args[1]
pool = Pool()
pool.map(task, [
[1,2],
[3,4],
[5,6],
[7,8]
])
One can than construct a list lists of arguments with one's favorite method.
you can actually do it with numpy:
import numpy as np
a = np.fromstring('hi', dtype=np.uint8)
print(a)
You can use this code to open in new tab..
function openWindow( url )
{
window.open(url, '_blank');
window.focus();
}
I got it from stackoverflow..
hey I had a similar issue. I wanted to display a list view that didn't scroll and I found that manipulating the parameters worked but was inefficient and would behave differently on different devices.. as a result, this is a piece of my schedule code which actually does this very efficiently.
db = new dbhelper(this);
cursor = db.dbCursor();
int count = cursor.getCount();
if (count > 0)
{
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.layoutId);
startManagingCursor(YOUR_CURSOR);
YOUR_ADAPTER(**or SimpleCursorAdapter **) adapter = new YOUR_ADAPTER(this,
R.layout.itemLayout, cursor, arrayOrWhatever, R.id.textViewId,
this.getApplication());
int i;
for (i = 0; i < count; i++){
View listItem = adapter.getView(i,null,null);
linearLayout.addView(listItem);
}
}
Note: if you use this, notifyDataSetChanged();
will not work as intended as the views will not be redrawn.
Do this if you need a work around
adapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
removeAndRedrawViews();
}
});
A Callback function is a method that is passed into a routine, and called at some point by the routine to which it is passed.
This is very useful for making reusable software. For example, many operating system APIs (such as the Windows API) use callbacks heavily.
For example, if you wanted to work with files in a folder - you can call an API function, with your own routine, and your routine gets run once per file in the specified folder. This allows the API to be very flexible.
Yes its possible Here the code is
const fs = require('fs')
let data = "Learning how to write in a file."
fs.writeFile('Output.txt', data, (err) => {
// In case of a error throw err.
if (err) throw err;
})
_x000D_
right way is
import datetime
isinstance(x, datetime.date)
When I try this on my machine it works fine. You need to look into why datetime.date
is not a class. Are you perhaps masking it with something else? or not referencing it correctly for your import?
In order to perform chmod, you need to be owner of the file you are trying to modify, or the root user.
You can use LINQ-to-DataSet
with Enumerable.Any
:
String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));
Another approach is to use DataTable.Select
:
DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
// do something...
}
Q: what if we do not know the columns Headers and we want to find if any cell value
PEPSI
exist in any rows'c columns? I can loop it all to find out but is there a better way? –
Yes, you can use this query:
DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
.Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));
You could just check if the value is not zero.
if ((Int32)(letter & Letters.AB) != 0) { }
But I would consider it a better solution to introduce a new enumeration value with value zero and compare agains this enumeration value (if possible because you must be able to modify the enumeration).
[Flags]
enum Letters
{
None = 0,
A = 1,
B = 2,
C = 4,
AB = A | B,
All = AB | C
}
if (letter != Letters.None) { }
UPDATE
Missread the question - fixed the first suggestion and just ignore the second suggestion.
An other approach after trying the solutions below. When you need it clear, just initialise your list to new clear new list.
List<ModelData> dataLists = new ArrayList<>();
RaporAdapter adapter = new RaporAdapter(AyrintiliRapor.this, dataLists);
listview.setAdapter(adapter);
Or set visibility to Gone / Invisible up to need
img_pdf.setVisibility(View.INVISIBLE);
Update: this no longer works with other apps' activities as of Android 5.0
Here's a good way to do it using the activity manager. You basically get the runningTasks from the activity manager. It will always return the currently active task first. From there you can get the topActivity.
There's an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first.
Once you have that you can get a ComponentName object by requesting the topActivity from your list.
Here's an example.
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
Log.d("topActivity", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());
ComponentName componentInfo = taskInfo.get(0).topActivity;
componentInfo.getPackageName();
You will need the following permission on your manifest:
<uses-permission android:name="android.permission.GET_TASKS"/>
In your example propertyInfo.GetValue(this, null)
should work. Consider altering GetNamesAndTypesAndValues()
as follows:
public void GetNamesAndTypesAndValues()
{
foreach (PropertyInfo propertyInfo in allClassProperties)
{
Console.WriteLine("{0} [type = {1}] [value = {2}]",
propertyInfo.Name,
propertyInfo.PropertyType,
propertyInfo.GetValue(this, null));
}
}
This post helped me understand concerns.
# app/models/trader.rb
class Trader
include Shared::Schedule
end
# app/models/concerns/shared/schedule.rb
module Shared::Schedule
extend ActiveSupport::Concern
...
end
To work around this problem, use SQL statements to make the changes to the metadata structure of a table.
This problem occurs when "Prevent saving changes that require table re-creation" option is enabled.
Source: Error message when you try to save a table in SQL Server 2008: "Saving changes is not permitted"
A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid*
Files.
See Appendix C - Fatal Error Log
Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:
If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.
Another (probably not production-ready or recommended) method I just came up with is to concat the values to a string and count this string distinctively:
SELECT count(DISTINCT concat(id, name, address)) FROM mytable;
As of today (April 2016), the code in the previous solution doesn't work, I think it is possible to inject window directly into App.ts and then gather the values you need into a service for global access in the App, but if you prefer to create and inject your own service, a way simpler solution is this.
https://gist.github.com/WilldelaVega777/9afcbd6cc661f4107c2b74dd6090cebf
//--------------------------------------------------------------------------------------------------
// Imports Section:
//--------------------------------------------------------------------------------------------------
import {Injectable} from 'angular2/core'
import {window} from 'angular2/src/facade/browser';
//--------------------------------------------------------------------------------------------------
// Service Class:
//--------------------------------------------------------------------------------------------------
@Injectable()
export class WindowService
{
//----------------------------------------------------------------------------------------------
// Constructor Method Section:
//----------------------------------------------------------------------------------------------
constructor(){}
//----------------------------------------------------------------------------------------------
// Public Properties Section:
//----------------------------------------------------------------------------------------------
get nativeWindow() : Window
{
return window;
}
}
You can use
var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)
FXCop typically prefers OrdinalIgnoreCase
. But your requirements may vary.
For English there is very little difference. It is when you wander into languages that have different written language constructs that this becomes an issue. I am not experienced enough to give you more than that.
OrdinalIgnoreCase
The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames. http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx
InvariantCultureIgnoreCase
The StringComparer returned by the InvariantCultureIgnoreCase property compares strings in a linguistically relevant manner that ignores case, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures. http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx
The invariant culture is the CultureInfo object returned by the InvariantCulture property.
The InvariantCultureIgnoreCase property actually returns an instance of an anonymous class derived from the StringComparer class.
SELECT *
FROM table1
WHERE CONVERT(varchar(10),columnDatetime,121) =
CONVERT(varchar(10),CONVERT('14 AUG 2008' ,smalldatetime),121)
This will convert the datatime and the string into varchars of the format "YYYY-MM-DD".
This is very ugly, but should work
To add .pch file-
1) Add new .pch file to your project->New file->other->PCH file
2) Goto your project's build setting.
3) Search "prefix header". You can find that under Apple LLVM.
4) Paste this in the field $(SRCROOT)/yourPrefixHeaderFileName.pch
5) Clean and build the project. That's it!!!
Another way:
$('#select').empty().append($('<option>').text('---------').attr('value',''));
Under this link, there are good practices https://api.jquery.com/select/
To run once, daily at 10PM you should do something like this:
0 22 * * *
Full size image: http://i.stack.imgur.com/BeXHD.jpg
Source: softpanorama.org
Make a service call like this:
public async void SaveActivationCode(ActivationCodes objAC)
{
var client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);
HttpResponseMessage response = await client.PutAsJsonAsync(serviceAddress + "/SaveActivationCode" + "?apiKey=445-65-1216", objAC);
}
And Service method like this:
public HttpResponseMessage PutSaveActivationCode(ActivationCodes objAC)
{
}
PutAsJsonAsync takes care of Serialization and deserialization over the network
To include native libraries you need:
To create jar file, use the following snippet:
task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
destinationDir file("$buildDir/native-libs")
baseName 'native-libs'
extension 'jar'
from fileTree(dir: 'libs', include: '**/*.so')
into 'lib/'
}
tasks.withType(Compile) {
compileTask -> compileTask.dependsOn(nativeLibsToJar)
}
To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:
compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
The default HTML editor (for static HTML) doesn't have a design view. To set the default editor to the Web forms editor which does have a design view,
Open with
HTML (web forms) editor
Set as default
OK
buttonOnce you have done that, all you need to do is click on design
or split
view as shown below:
Your logic is backwards.
SELECT
*
FROM
`test_table`
WHERE
start_date NOT BETWEEN CAST('2009-12-15' AS DATE) and CAST('2010-01-02' AS DATE)
AND end_date NOT BETWEEN CAST('2009-12-15' AS DATE) and CAST('2010-01-02' AS DATE)
You can assign one color to every functionality to make it more useful.
#define Color_Red "\33[0:31m\\]" // Color Start
#define Color_end "\33[0m\\]" // To flush out prev settings
#define LOG_RED(X) printf("%s %s %s",Color_Red,X,Color_end)
foo()
{
LOG_RED("This is in Red Color");
}
Like wise you can select different color codes and make this more generic.
Also, you need to do something like this in config.xml if you are developing a customized module
<frontend>
<layout>
<updates>
<hpcustomer>
<file>hpcustomer.xml</file>
</hpcustomer>
</updates>
</layout>
</frontend>
I can modify the table field's datatype, with these following query: and also in the Oracle DB,
ALTER TABLE table_name
MODIFY column_name datatype;
This is possible to do without an iframe
specifically. jQuery is utilised since it's mentioned in the title.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Load remote content into object element</title>
</head>
<body>
<div id="siteloader"></div>?
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$("#siteloader").html('<object data="http://tired.com/">');
</script>
</body>
</html>
Try scaling down the emulator, it makes it a bit faster, even if it doesn't it really feels faster.
Just to make a proper answer from the @Eddy Hernandez's comment and which is very correct since Alpine comes with ash not bash.
The question now referes to Starting a shell in the Docker Alpine container which implies using sh
or ash
or /bin/sh
or /bin/ash/
.
Based on the OP's question:
docker run image sh -c "cd /path/to/somewhere && python a.py"
Use UITextView instead of UILabel and it has a property to convert your text to hyperlink
Swift code:
yourTextView.editable = false
yourTextView.dataDetectorTypes = UIDataDetectorTypes.All
//or
yourTextView.dataDetectorTypes = UIDataDetectorTypes.PhoneNumber
//or
yourTextView.dataDetectorTypes = UIDataDetectorTypes.Link
I'd just add to the answers the "why?".
.
is standard member access operator that has a higher precedence than *
pointer operator.
When you are trying to access a struct's internals and you wrote it as *foo.bar
then the compiler would think to want a 'bar' element of 'foo' (which is an address in memory) and obviously that mere address does not have any members.
Thus you need to ask the compiler to first dereference whith (*foo)
and then access the member element: (*foo).bar
, which is a bit clumsy to write so the good folks have come up with a shorthand version: foo->bar
which is sort of member access by pointer operator.
break ends execution of the current for, foreach, while, do-while or switch structure.
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
So depending on your need, you can reset the position currently being executed in your code to a different level of the current nesting.
Also, see here for an artical detailing Break vs Continue with a number of examples
Just found a way how to do it:
Just add the paths to the /app/start/global.php
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/controllers/product',
app_path().'/models',
app_path().'/database/seeds',
));
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.
private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);
public static Document loadXMLFrom(String xml) throws Exception {
InputSource is= new InputSource(new StringReader(xml));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = null;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
return doc;
}
See query:
SELECT * FROM Table1 WHERE
id NOT IN (SELECT
e.id
FROM
Table1 e
INNER JOIN
Table2 s ON e.id = s.id);
Conceptually would be: Fetching the matching records in subquery and then in main query fetching the records which are not in subquery.
Using Async task
call when you want to download file : new DownloadFileFromURL().execute(file_url);
public class MainActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "http://www.qwikisoft.com/demo/ashade/20001.kml";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadFileFromURL().execute(file_url);
}
/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/2011.kml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
}
if not working in 4.0 then add:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
This will get you count:
get-alias | measure
You can work with the result as with object:
$m = get-alias | measure
$m.Count
And if you would like to have aliases in some variable also, you can use Tee-Object:
$m = get-alias | tee -Variable aliases | measure
$m.Count
$aliases
Some more info on Measure-Object cmdlet is on Technet.
Do not confuse it with Measure-Command cmdlet which is for time measuring. (again on Technet)
const date = moment(YOUR_DATE)
return (moment().diff(date, 'days') >= 2) ? date.fromNow() : date.calendar().split(' ')[0]
In addition, strip has some variations:
Remove spaces in the BEGINNING and END of a string:
sentence= sentence.strip()
Remove spaces in the BEGINNING of a string:
sentence = sentence.lstrip()
Remove spaces in the END of a string:
sentence= sentence.rstrip()
All three string functions strip
lstrip
, and rstrip
can take parameters of the string to strip, with the default being all white space. This can be helpful when you are working with something particular, for example, you could remove only spaces but not newlines:
" 1. Step 1\n".strip(" ")
Or you could remove extra commas when reading in a string list:
"1,2,3,".strip(",")
Update (2008-09-19 10:05) - Solution:
My Solution: Social engineering, I dug real hard and found someone who knew the schema name.
Technical Solution: Searching the .dmp file did yield the schema name.
Once I knew the schema name, I searched the dump file and learned where to find it.
Places the Schemas name were seen, in the .dmp file:
<OWNER_NAME>SOURCE_SCHEMA</OWNER_NAME>
This was seen before each table name/definition.
SCHEMA_LIST 'SOURCE_SCHEMA'
This was seen near the end of the .dmp.
Interestingly enough, around the SCHEMA_LIST 'SOURCE_SCHEMA'
section, it also had the command line used to create the dump, directories used, par files used, windows version it was run on, and export session settings (language, date formats).
So, problem solved :)
setting the text to sam textview twice is overwritting the first written text. So the second time when we use settext we just append the new string like
textview.append("Step Two: fry egg");
Protocol Buffers seems to have a more compact representation, but that's only an impression I get from reading the Thrift whitepaper. In their own words:
We decided against some extreme storage optimizations (i.e. packing small integers into ASCII or using a 7-bit continuation format) for the sake of simplicity and clarity in the code. These alterations can easily be made if and when we encounter a performance-critical use case that demands them.
Also, it may just be my impression, but Protocol Buffers seems to have some thicker abstractions around struct versioning. Thrift does have some versioning support, but it takes a bit of effort to make it happen.
The HTC devices have the PCSII.apk
which allow them to select usb connect mode. For your device, you can set it manually:
Use SQLite Editor to open /data/data/com.android.providers.setting/databases/settings.db
open table secure
turn settings starting with mount_ums_
to 0, then restart devices.
UPDATE: If it still doesn't work, try turning on debug mode.
you can use style
<td colspan="2">
<div style="float:left; width:80px"><asp:Label ID="Label6" runat="server" Text="Label"></asp:Label></div>
<div style="float: right; width:100px">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</div>
<div style="clear:both"></div>
</td>
The answer is NO, but...
You may confused because of the behavior of fgets()
From http://www.cplusplus.com/reference/cstdio/fgets/ :
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
gets()
dangerousThe first internet worm (the Morris Internet Worm) escaped about 30 years ago (1988-11-02), and it used gets()
and a buffer overflow as one of its methods of propagating from system to system. The basic problem is that the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.
You should forget you ever heard that gets()
existed.
The C11 standard ISO/IEC 9899:2011 eliminated gets()
as a standard function, which is A Good Thing™ (it was formally marked as 'obsolescent' and 'deprecated' in ISO/IEC 9899:1999/Cor.3:2007 — Technical Corrigendum 3 for C99, and then removed in C11). Sadly, it will remain in libraries for many years (meaning 'decades') for reasons of backwards compatibility. If it were up to me, the implementation of gets()
would become:
char *gets(char *buffer)
{
assert(buffer != 0);
abort();
return 0;
}
Given that your code will crash anyway, sooner or later, it is better to head the trouble off sooner rather than later. I'd be prepared to add an error message:
fputs("obsolete and dangerous function gets() called\n", stderr);
Modern versions of the Linux compilation system generates warnings if you link gets()
— and also for some other functions that also have security problems (mktemp()
, …).
gets()
As everyone else said, the canonical alternative to gets()
is fgets()
specifying stdin
as the file stream.
char buffer[BUFSIZ];
while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
...process line of data...
}
What no-one else yet mentioned is that gets()
does not include the newline but fgets()
does. So, you might need to use a wrapper around fgets()
that deletes the newline:
char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
if (fgets(buffer, buflen, fp) != 0)
{
size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n')
buffer[len-1] = '\0';
return buffer;
}
return 0;
}
Or, better:
char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
if (fgets(buffer, buflen, fp) != 0)
{
buffer[strcspn(buffer, "\n")] = '\0';
return buffer;
}
return 0;
}
Also, as caf points out in a comment and paxdiablo shows in his answer, with fgets()
you might have data left over on a line. My wrapper code leaves that data to be read next time; you can readily modify it to gobble the rest of the line of data if you prefer:
if (len > 0 && buffer[len-1] == '\n')
buffer[len-1] = '\0';
else
{
int ch;
while ((ch = getc(fp)) != EOF && ch != '\n')
;
}
The residual problem is how to report the three different result states — EOF or error, line read and not truncated, and partial line read but data was truncated.
This problem doesn't arise with gets()
because it doesn't know where your buffer ends and merrily tramples beyond the end, wreaking havoc on your beautifully tended memory layout, often messing up the return stack (a Stack Overflow) if the buffer is allocated on the stack, or trampling over the control information if the buffer is dynamically allocated, or copying data over other precious global (or module) variables if the buffer is statically allocated. None of these is a good idea — they epitomize the phrase 'undefined behaviour`.
There is also the TR 24731-1 (Technical Report from the C Standard Committee) which provides safer alternatives to a variety of functions, including gets()
:
§6.5.4.1 The
gets_s
functionSynopsis
#define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h> char *gets_s(char *s, rsize_t n);
Runtime-constraints
s
shall not be a null pointer.n
shall neither be equal to zero nor be greater than RSIZE_MAX. A new-line character, end-of-file, or read error shall occur within readingn-1
characters fromstdin
.25)3 If there is a runtime-constraint violation,
s[0]
is set to the null character, and characters are read and discarded fromstdin
until a new-line character is read, or end-of-file or a read error occurs.Description
4 The
gets_s
function reads at most one less than the number of characters specified byn
from the stream pointed to bystdin
, into the array pointed to bys
. No additional characters are read after a new-line character (which is discarded) or after end-of-file. The discarded new-line character does not count towards number of characters read. A null character is written immediately after the last character read into the array.5 If end-of-file is encountered and no characters have been read into the array, or if a read error occurs during the operation, then
s[0]
is set to the null character, and the other elements ofs
take unspecified values.Recommended practice
6 The
fgets
function allows properly-written programs to safely process input lines too long to store in the result array. In general this requires that callers offgets
pay attention to the presence or absence of a new-line character in the result array. Consider usingfgets
(along with any needed processing based on new-line characters) instead ofgets_s
.25) The
gets_s
function, unlikegets
, makes it a runtime-constraint violation for a line of input to overflow the buffer to store it. Unlikefgets
,gets_s
maintains a one-to-one relationship between input lines and successful calls togets_s
. Programs that usegets
expect such a relationship.
The Microsoft Visual Studio compilers implement an approximation to the TR 24731-1 standard, but there are differences between the signatures implemented by Microsoft and those in the TR.
The C11 standard, ISO/IEC 9899-2011, includes TR24731 in Annex K as an optional part of the library. Unfortunately, it is seldom implemented on Unix-like systems.
getline()
— POSIXPOSIX 2008 also provides a safe alternative to gets()
called getline()
. It allocates space for the line dynamically, so you end up needing to free it. It removes the limitation on line length, therefore. It also returns the length of the data that was read, or -1
(and not EOF
!), which means that null bytes in the input can be handled reliably. There is also a 'choose your own single-character delimiter' variation called getdelim()
; this can be useful if you are dealing with the output from find -print0
where the ends of the file names are marked with an ASCII NUL '\0'
character, for example.
An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation.
A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.
So for example:
public abstract class myBase
{
//If you derive from this class you must implement this method. notice we have no method body here either
public abstract void YouMustImplement();
//If you derive from this class you can change the behavior but are not required to
public virtual void YouCanOverride()
{
}
}
public class MyBase
{
//This will not compile because you cannot have an abstract method in a non-abstract class
public abstract void YouMustImplement();
}
ASP.NET 4 introduces a new code nugget syntax <%: %>
. Essentially, <%: foo %>
translates to <%= HttpUtility.HtmlEncode(foo) %>
. The team is trying to get developers to use <%: %>
instead of <%= %>
wherever possible to prevent XSS.
However, this introduces the problem that if a code nugget already encodes its result, the <%: %>
syntax will re-encode it. This is solved by the introduction of the IHtmlString interface (new in .NET 4). If the foo() in <%: foo() %>
returns an IHtmlString, the <%: %>
syntax will not re-encode it.
MVC 2's helpers return MvcHtmlString, which on ASP.NET 4 implements the interface IHtmlString. Therefore when developers use <%: Html.*() %>
in ASP.NET 4, the result won't be double-encoded.
Edit:
An immediate benefit of this new syntax is that your views are a little cleaner. For example, you can write <%: ViewData["anything"] %>
instead of <%= Html.Encode(ViewData["anything"]) %>
.
As already mentioned, there is no difference, if you create a file with .jsx
or .js
.
I would like to bring another expect of creating the files as .jsx
while creating a component.
This is not mandatory, but an architectural approach that we can follow. So, in large projects we divide our components as Presentational components or Container components. Just to brief, in container components we write the logic to get data for the component and render the Presentational component with props. In presentational components, we usually donot write functional logic, presentational components are used to represent the UI with required props.
So, if you check the definition on JSX in React documents.
It says,
const element = <h1>Hello, world!</h1>;
It is called JSX, and it is a syntax extension to JavaScript.
We recommend using it with React to describe what the UI should look like.
JSX may remind you of a template language, but it comes with the full power of JavaScript.
JSX produces React “elements”. Instead of artificially separating technologies by putting
markup and logic in separate files, React separates concerns with loosely coupled units
called “components” that contain both.
React doesn’t require using JSX, but most people find it helpful as a visual aid when
working with UI inside the JavaScript code. It also allows React to show more useful
error and warning messages.
It means, It's not mandatory but you can think of creating presentational components with '.jsx' as it actually binds the props with the UI. and container components, as .js
files as those contains logic to get the data.
It's a convention that you can follow while creating the .jsx
or .js
files, to logically and physically separate the code.
In addition to @Boaz's and @vegemite4me's answers....
By implementing ImplicitNamingStrategy
you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder
during Hibernate's initialization:
metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());
It works for @UniqueConstraint
, but not for @Column(unique = true)
, which always generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).
There is a bug report to solve this issue, so if you can, please vote there to have this implemented. Here: https://hibernate.atlassian.net/browse/HHH-11586
Thanks.
I liked paxdiablo's script, but wanted a version that ran indefinitely. This version runs ping until a connection is established and then prints a message saying so.
echo "Testing..."
PING_CMD="ping -t 3 -c 1 google.com > /dev/null 2>&1"
eval $PING_CMD
if [[ $? -eq 0 ]]; then
echo "Already connected."
else
echo -n "Waiting for connection..."
while true; do
eval $PING_CMD
if [[ $? -eq 0 ]]; then
echo
echo Connected.
break
else
sleep 0.5
echo -n .
fi
done
fi
I also have a Gist of this script which I'll update with fixes and improvements as needed.
If you are using SQL Server try this:
SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())
Based on your update it would be:
SELECT * FROM FB WHERE Dte < DATEADD(month, -2, GETDATE())
I think you can use Array.Copy for this. It takes a source index and destination index so you should be able to append the one array to the other. If you need to go more complex than just appending one to the other, this may not be the right tool for you.
If you mean using an attribute selector, sure, why not:
[data-role="page"] {
/* Styles */
}
There are a variety of attribute selectors you can use for various scenarios which are all covered in the document I link to. Note that, despite custom data attributes being a "new HTML5 feature",
browsers typically don't have any problems supporting non-standard attributes, so you should be able to filter them with attribute selectors; and
you don't have to worry about CSS validation either, as CSS doesn't care about non-namespaced attribute names as long as they don't break the selector syntax.
Yes, class can have a private constructor. It is needed as to disallow to access the constructor from other classes and remain it accessible within defined class.
Why would you want objects of your class to only be created internally? This could be done for any reason, but one possible reason is that you want to implement a singleton. A singleton is a design pattern that allows only one instance of your class to be created, and this can be accomplished by using a private constructor.
JQuery uses CSS selectors to select elements, so you just need to use more than one rule by separating them with commas, as so:
a=$('[myc="blue"], [myid="1"], [myid="3"]');
Edit:
Sorry, you wanted blue and 1 or 3. How about:
a=$('[myc="blue"][myid="1"], [myid="3"]');
Putting the two attribute selectors together gives you AND, using a comma gives you OR.
Swift version:
In your child ViewController:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.backItem?.title = "TEXT"
}
For plain html you don't require any npm package or middleware
just use this:
app.get('/', function(req, res) {
res.sendFile('index.html');
});
if you guys want to make a non-overflow scrollview or listview, just but it on a RelativeLayout with a topview and bottomview on top and bottom for it:
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/topview"
android:layout_below="@+id/bottomview" >
That depends on what you mean by delete. An array has a fixed size, so deleting doesn't really make sense.
If you want to remove element i
, one option would be to move all elements j > i
one position to the left (a[j - 1] = a[j]
for all j
, or using Array.Copy
) and then resize the array using ReDim Preserve.
So, unless you are forced to use an array by some external constraint, consider using a data structure more suitable for adding and removing items. List<T>, for example, also uses an array internally but takes care of all the resizing issues itself: For removing items, it uses the algorithm mentioned above (without the ReDim), which is why List<T>.RemoveAt
is an O(n) operation.
There's a whole lot of different collection classes in the System.Collections.Generic namespace, optimized for different use cases. If removing items frequently is a requirement, there are lots of better options than an array (or even List<T>
).
Go to bin directory of postgres db such as /opt/postgresql/bin
& run below command :
[...bin]# ./psql --version
psql (PostgreSQL) 9.0.4
Here you go . .
In terms of performance measurement, if you are considering the time performance then the Integer.toString(i); is expensive if you are calling less than 100 million times. Else if it is more than 100 million calls then the new Integer(10).toString() will perform better.
Below is the code through u can try to measure the performance,
public static void main(String args[]) {
int MAX_ITERATION = 10000000;
long starttime = System.currentTimeMillis();
for (int i = 0; i < MAX_ITERATION; ++i) {
String s = Integer.toString(10);
}
long endtime = System.currentTimeMillis();
System.out.println("diff1: " + (endtime-starttime));
starttime = System.currentTimeMillis();
for (int i = 0; i < MAX_ITERATION; ++i) {
String s1 = new Integer(10).toString();
}
endtime = System.currentTimeMillis();
System.out.println("diff2: " + (endtime-starttime));
}
In terms of memory, the
new Integer(i).toString();
will take more memory as it will create the object each time, so memory fragmentation will happen.
Just do:
echo substr($string, 0, -3);
You don't need to use a strlen
call, since, as noted in the substr docs:
If length is given and is negative, then that many characters will be omitted from the end of string
I got this error when I set up a local repository first. Then I went to GitHub and created a new repository. Then I ran
git remote add origin <repository url>
When I tried to push or pull, I got the same fatal: unrelated_histories
error every time.
Here is how I fixed it:
git pull origin master --allow-unrelated-histories
git merge origin origin/master
... add and commit here...
git push origin master
In plain-old JavaScript you can do this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'text') {
alert(inputs[i].value);
}
}
In jQuery, you would just do:
// select all inputs of type 'text' on the page
$("input:text")
// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();
Using JSTL:
<c:set var="message" value='${requestScope["Error_Message"]}' />
Here var sets the variable name and request.getAttribute is equal to requestScope. But it's not essential. ${Error_Message} will give you the same outcome. It'll search every scope. If you want to do some operation with content you take from Error_Message you have to do it using message. like below one.
<c:out value="${message}"/>
Not an answer to the very question but perhaps an idea for the underlying task:
When your site logic should not show a certain element, you could insert an invisible "flag" element that you check for.
if condition
renderElement()
else
renderElementNotShownFlag() // used by Selenium test
My answer: most users complains about maven because they were looking for its pros, but don't have time (or they don't want endure) in setting up their "company environment". That's a personal choice, it can depend from personal patience, the job environment(bosses never understand that a well done thing waste less time than an eternal bugfix cycle), etc..
However, In the following cases you can have only maven on your workstation without getting mad:
The problems starts to come when you want more, like create your wrappers to standard frameworks classes, or reusable component libraries, you always want to use a set of plugins you like, etc..
In that case you have to invest your time in learning: I read in previous posts that someone talk about wasting half day or 2 days...that is not enough, at all: we are talking about modify your poms continuously for at least 1 month.
If you wanna use maven in complex projects, you should in order:
To have all these setted up... well, you can even spend months at the beginning, but once you get used to that, you will speed up a lot your development.
Personally I didn't use Gradle yet, I don't know if it's better or worst than Maven.
To avoid leaving the file open, it is best to pass a block to File.open. This way, the file will be closed after the block executes.
contents = File.open('path-to-file.tar.gz', 'rb') { |f| f.read }
You may want to create a subRepeater.
<asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
<ItemTemplate>
<span><%# Eval("Name") %></span>
</ItemTemplate>
</asp:Repeater>
You can also cast your fields
<%# ((ArrayFields)Container.DataItem).Fields[0].Name %>
Finally you could do a little CSV Function and write out your fields with a function
<%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>
public string GetAsCsv(IEnumerable<Fields> fields)
{
var builder = new StringBuilder();
foreach(var f in fields)
{
builder.Append(f);
builder.Append(",");
}
builder.Remove(builder.Length - 1);
return builder.ToString();
}
Try this:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class WriteImage
{
public static void main( String[] args )
{
BufferedImage image = null;
try {
URL url = new URL("URL_IMAGE");
image = ImageIO.read(url);
ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
ImageIO.write(image, "gif",new File("C:\\out.gif"));
ImageIO.write(image, "png",new File("C:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.getfullname = function () {
return `${this.firstname} ${this.lastname}`;
};
let that = this;
this.sayHi = function() {
console.log(`i am this , ${this.firstname}`);
console.log(`i am that , ${that.firstname}`);
};
}
let thisss = new Person('thatbetty', 'thatzhao');
let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};
thisss.sayHi.call(thatt);
As a comment, I had to allow a customer to execute a class in a jar which meant that the manifest file couldn't be modified (they couldn't be expected to do that). Thanks to the post by Anthony and samy-delux's comment, this is what the customer can now run to access the main of the specific class:
java -cp c:\path\to\jar\jarFile.jar com.utils.classpath -e -v textString
Use the rename
utility:
rc@bvm3:/tmp/foo $ touch 05_h.png 06_h.png
rc@bvm3:/tmp/foo $ rename 's/_h/_half/' *
rc@bvm3:/tmp/foo $ ls -l
total 0
-rw-r--r-- 1 rc rc 0 2011-09-17 00:15 05_half.png
-rw-r--r-- 1 rc rc 0 2011-09-17 00:15 06_half.png
Launch Developer command line "As an Administrator". This account has full access to Security log
According to oracle online documentation
ORA-12541: TNS:no listener
Cause: The connection request could not be completed because the listener is not running.
Action: Ensure that the supplied destination address matches one of the addresses used by
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on
the remote machine.
Java Reflection is quite powerful and can be very useful. Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
A quick Java Reflection example to show you what using reflection looks like:
Method[] methods = MyObject.class.getMethods();
for(Method method : methods){
System.out.println("method = " + method.getName());
}
This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.
Exactly how all this works is explained here
Edit: After almost 1 year I am editing this answer as while reading about reflection I got few more uses of Reflection.
<bean id="someID" class="com.example.Foo">
<property name="someField" value="someValue" />
</bean>
When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument "com.example.Foo" to instantiate that Class.
It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.
For Private methods,
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
For private fields,
Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
With Luxon (https://github.com/moment/luxon) :
import { DateTime } from 'luxon';
const week: number = DateTime.fromJSDate(new Date()).weekNumber;
Use schema name with period in psql command to obtain information about this schema.
Setup:
test=# create schema test_schema;
CREATE SCHEMA
test=# create table test_schema.test_table (id int);
CREATE TABLE
test=# create table test_schema.test_table_2 (id int);
CREATE TABLE
Show list of relations in test_schema
:
test=# \dt test_schema.
List of relations
Schema | Name | Type | Owner
-------------+--------------+-------+----------
test_schema | test_table | table | postgres
test_schema | test_table_2 | table | postgres
(2 rows)
Show test_schema.test_table
definition:
test=# \d test_schema.test_table
Table "test_schema.test_table"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Show all tables in test_schema
:
test=# \d test_schema.
Table "test_schema.test_table"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Table "test_schema.test_table_2"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
etc...
The actual problem of this error has nothing to do with file_get_content, the problem is the requested url if the url is not throwing content of the page and redirecting the request to some where else file_get_content says "Failed to open stream", just before file_get_contents check whether the url is working and not redirecting, here is the code:
function checkRedirect404($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
// line endings is the wonkiest piece of this whole thing
$out = str_replace("\r", "", $out);
// only look at the headers
$headers_end = strpos($out, "\n\n");
if( $headers_end !== false ) {
$out = substr($out, 0, $headers_end);
}
$headers = explode("\n", $out);
foreach($headers as $header) {
if( substr($header, 0, 10) == "Location: " ) {
$target = substr($header, 10);
//echo "Redirects: $target<br>";
return true;
}
}
return false;
}
IIUC you want the number of different ID
for every domain
, then you can try this:
output = df.drop_duplicates()
output.groupby('domain').size()
output:
domain
facebook.com 1
google.com 1
twitter.com 2
vk.com 3
dtype: int64
You could also use value_counts
, which is slightly less efficient.But the best is Jezrael's answer using nunique
:
%timeit df.drop_duplicates().groupby('domain').size()
1000 loops, best of 3: 939 µs per loop
%timeit df.drop_duplicates().domain.value_counts()
1000 loops, best of 3: 1.1 ms per loop
%timeit df.groupby('domain')['ID'].nunique()
1000 loops, best of 3: 440 µs per loop
Look here: http://www.w3schools.com/tags/tag_p.asp
The p element automatically creates some space before and after itself. The space is automatically applied by the browser, or you can specify it in a style sheet.
you could remove the extra space by using css
p {
margin: 0px;
padding: 0px;
}
or use the element <span>
which has no default margins and is an inline element.
You can use \
to indicate that any line of Ruby continues on the next line. This works with strings too:
string = "this is a \
string that spans lines"
puts string.inspect
will output "this is a string that spans lines"
in Winforms, there is a Screen class you can use to get data about screen dimensions and color depth for all displays connected to the computer. Here's the docs page: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx
CHANGING the screen resolution is trickier. There is a Resolution third party class that wraps the native code you'd otherwise hook into. Use its CResolution nested class to set the screen resolution to a new height and width; but understand that doing this will only work for height/width combinations the display actually supports (800x600, 1024x768, etc, not 817x435).
Say the list is like below
iterator = [None, 1, 2, 0, '', None, False, {}, (), []]
This will return only those items whose bool(item) is True
print filter(lambda item: item, iterator)
# [1, 2]
This is equivalent to
print [item for item in iterator if item]
To just filter None:
print filter(lambda item: item is not None, iterator)
# [1, 2, 0, '', False, {}, (), []]
Equivalent to:
print [item for item in iterator if item is not None]
To get all the items that evaluate to False
print filter(lambda item: not item, iterator)
# Will print [None, '', 0, None, False, {}, (), []]
I suggest using vlookup function to get the nearest match.
Prepare data range and name it: 'numberRange':
Select the range. Go to menu: Data ? Named ranges... ? define the new named range.
Use this simple formula:
=VLOOKUP(A2,numberRange,2)
This way you can ommit errors, and easily correct the result.
Check this out. The author provides a simple but elegant solution which doesn't require any 3rd party library. http://www.ksmpartners.com/2013/08/nicely-formatted-tabular-output-in-java/
in the file .eslintrc.json in side roles add this code it will solve this issue
"rules": {
"prettier/prettier": ["error",{
"endOfLine": "auto"}
]
}
I agree with the points dnmckee mentions, plus:
too late to answer but I found the solution.
When you define you own html form then you miss authentication token string that should be sent to controller for security reasons. But when you use rails form helper to generate a form you get something like following
<form accept-charset="UTF-8" action="/login/signin" method="post">
<div style="display:none">
<input name="utf8" type="hidden" value="✓">
<input name="authenticity_token" type="hidden"
value="x37DrAAwyIIb7s+w2+AdoCR8cAJIpQhIetKRrPgG5VA=">
.
.
.
</div>
</form>
So the solution to the problem is either to add authenticity_token field or use rails form helpers rather then removing , downgrading or upgrading rails.
sudo add-apt-repository ppa:deadsnakes
sudo apt-get update
sudo apt-get install python3.5 python3.5-tk
# or 2.7, 3.6 etc
# sudo apt-get install python2.7 python2.7-tk
# mouse_position.py
import Tkinter
p=Tkinter.Tk()
print(p.winfo_pointerxy()
Or with one-liner from the command line:
python -c "import Tkinter; p=Tkinter.Tk(); print(p.winfo_pointerxy())"
(1377, 379)
One can issue the SQL*Plus command SET TIMING ON
to get wall-clock times, but one can't take, for example, fetch time out of that trivially.
The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY
will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.
Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".
Some shortcut is to create a NumberFormatInfo class, set its NumberDecimalSeparator property to "." and use the class as parameter to ToString() method whenever u need it.
using System.Globalization;
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
value.ToString(nfi);
This worked for me:
[XmlInclude(typeof(BankPayment))]
[Serializable]
public abstract class Payment { }
[Serializable]
public class BankPayment : Payment {}
[Serializable]
public class Payments : List<Payment>{}
XmlSerializer serializer = new XmlSerializer(typeof(Payments), new Type[]{typeof(Payment)});