NO, you can't do it other way than so.
Using description instead of desc for table2,
update
table1
set
value = (select code from table2 where description = table1.value)
where
exists (select 1 from table2 where description = table1.value)
and
table1.updatetype = 'blah'
;
All the other answers about setting only the JAVA_HOME
are not entirely right. Eclipse does namely not consult the JAVA_HOME
. Look closer at the error message:
...in your current PATH
It literally said PATH
, not JAVA_HOME
.
Rightclick My Computer and choose Properties (or press Winkey+Pause), go to the tab Advanced, click the button Environment Variables, in the System Variables list at the bottom select Path
(no, not Classpath
), click Edit and add ;c:\path\to\jdk\bin
to the end of the value.
Alternatively and if not present, you can also add JAVA_HOME
environment variable and make use of it in the PATH
. In the same dialogue click New and add JAVA_HOME
with the value of c:\path\to\jdk
. Then you can add ;%JAVA_HOME%\bin
to end of the value of the Path
setting.
You may want to consider a library to handle the deep link to your app:
https://github.com/airbnb/DeepLinkDispatch
You can add the intent filter on an annotated Activity like people suggested above. It will handle the routing and parsing of parameters for all of your deep links. For example, your MainActivity might have something like this:
@DeepLink("somePath/{useful_info_for_anton_app}")
public class MainActivity extends Activity {
...
}
It can also handle query parameters as well.
Without use ID (<tbody id="tbodyid">
) , it is a great way to cope with this issue
$('#table1').find("tr:gt(0)").remove();
PS:To remove specific row number as following example
$('#table1 tr').eq(1).remove();
or
$('#tr:nth-child(2)').remove();
Try using this attribute, for example for password min length:
[StringLength(100, ErrorMessage = "???????????? ????? ?????? 20 ????????", MinimumLength = User.PasswordMinLength)]
I struggled with this plugin for a while on Rails, and then someone gemified it obsoleting all the code I had created.
Although it looks like you're not using this in Rails, however if anyone is using it checkout this gem. The source is here --> jQueryFileUpload Rails.
Update:
In order to satisfy the commenter I've updated my answer. Essentially "use this gem, here is the source code" If it disappears then do it the long way.
I usually approach it like this:
char[] c = text.ToCharArray();
for (i=0; i<c.Length; i++)
{
if (c[i]>'9' || c[i]<'0') // use any rules of your choice
{
c[i]=' '; // put in any character you like
}
}
// the new string can have the same name, or a new variable
String text=new string(c);
On MAC High Sierra (10.13.6)
cd /Users/vkrishna/.sqldeveloper/18.2.0
nano product.conf
on the last line add
AddVMOption -Duser.language=en
Save the file and restart.
=======================================
If you are using standalone Oracle Data Modeller
find ~/ -name "datamodeler.conf"
and edit this file
cd /Users/vkrishna//Desktop/OracleDataModeler-18.2.0.179.0756.app/Contents/Resources/datamodeler/datamodeler/bin/
Add somewhere in the last
AddVMOption -Duser.language=en
save and restart, done!
This isn't as good an answer as using the special built-in __subclasses__()
class method which @unutbu mentions, so I present it merely as an exercise. The subclasses()
function defined returns a dictionary which maps all the subclass names to the subclasses themselves.
def traced_subclass(baseclass):
class _SubclassTracer(type):
def __new__(cls, classname, bases, classdict):
obj = type(classname, bases, classdict)
if baseclass in bases: # sanity check
attrname = '_%s__derived' % baseclass.__name__
derived = getattr(baseclass, attrname, {})
derived.update( {classname:obj} )
setattr(baseclass, attrname, derived)
return obj
return _SubclassTracer
def subclasses(baseclass):
attrname = '_%s__derived' % baseclass.__name__
return getattr(baseclass, attrname, None)
class BaseClass(object):
pass
class SubclassA(BaseClass):
__metaclass__ = traced_subclass(BaseClass)
class SubclassB(BaseClass):
__metaclass__ = traced_subclass(BaseClass)
print subclasses(BaseClass)
Output:
{'SubclassB': <class '__main__.SubclassB'>,
'SubclassA': <class '__main__.SubclassA'>}
The most elegant solution to this problem is here.
Original answer remains, but this is a messy solution:
If you want to change the PYTHONPATH
used in a virtualenv, you can add the following line to your virtualenv's bin/activate
file:
export PYTHONPATH="/the/path/you/want"
This way, the new PYTHONPATH
will be set each time you use this virtualenv.
EDIT: (to answer @RamRachum's comment)
To have it restored to its original value on deactivate
, you could add
export OLD_PYTHONPATH="$PYTHONPATH"
before the previously mentioned line, and add the following line to your bin/postdeactivate
script.
export PYTHONPATH="$OLD_PYTHONPATH"
The simplest way is with the pkill
command.
In your case:
pkill -9 -t pts/6
pkill -9 -t pts/9
pkill -9 -t pts/10
Regarding tty sessions, the commands below are always useful:
w
- shows active terminal sessions
tty
- shows your current terminal session (so you won't close it by accident)
last | grep logged
- shows currently logged users
Sometimes we want to close all sessions of an idle user (ie. when connections are lost abruptly).
pkill -u username
- kills all sessions of 'username' user.
And sometimes when we want to kill all our own sessions except the current one, so I made a script for it. There are some cosmetics and some interactivity (to avoid accidental running on the script).
#!/bin/bash
MYUSER=`whoami`
MYSESSION=`tty | cut -d"/" -f3-`
OTHERSESSIONS=`w $MYUSER | grep "^$MYUSER" | grep -v "$MYSESSION" | cut -d" " -f2`
printf "\e[33mCurrent session\e[0m: $MYUSER[$MYSESSION]\n"
if [[ ! -z $OTHERSESSIONS ]]; then
printf "\e[33mOther sessions:\e[0m\n"
w $MYUSER | egrep "LOGIN@|^$MYUSER" | grep -v "$MYSESSION" | column -t
echo ----------
read -p "Do you want to force close all your other sessions? [Y]Yes/[N]No: " answer
answer=`echo $answer | tr A-Z a-z`
confirm=("y" "yes")
if [[ "${confirm[@]}" =~ "$answer" ]]; then
for SESSION in $OTHERSESSIONS
do
pkill -9 -t $SESSION
echo Session $SESSION closed.
done
fi
else
echo "There are no other sessions for the user '$MYUSER'".
fi
[label setText:@"Value: %.2f", myNumber];
I'm using intelliJ 15 community edition and I'm able to right click a file and select 'add to .gitignore'
Try this:
@IBAction func close() {
dismiss(animated: true, completion: nil)
}
It’s a name for the ::
operator in PHP. It literally means "double colon". For some reason they named it in Hebrew. Check your code syntax, and put a ::
where appropriate :-)
Try
gdb --args InsertionSortWithErrors arg1toinsort arg2toinsort
<!-- index.php -->
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myForm">
<input type="text" name="fname" id="fname"/>
<input type="submit" name="click" value="button" />
</form>
<script>
$(document).ready(function(){
$(function(){
$("#myForm").submit(function(event){
event.preventDefault();
$.ajax({
method: 'POST',
url: 'submit.php',
dataType: "json",
contentType: "application/json",
data : $('#myForm').serialize(),
success: function(data){
alert(data);
},
error: function(xhr, desc, err){
console.log(err);
}
});
});
});
});
</script>
</body>
</html>
<!-- submit.php -->
<?php
$value ="call";
header('Content-Type: application/json');
echo json_encode($value);
?>
There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do
conda create -n python2 python=2.7 anaconda
This will create an environment named python2
that contains the Python 2.7 version of Anaconda. You can activate this environment with
source activate python2
This will put that environment (typically ~/anaconda/envs/python2
) in front in your PATH
, so that when you type python
at the terminal it will load the Python from that environment.
If you don't want all of Anaconda, you can replace anaconda
in the command above with whatever packages you want. You can use conda
to install packages in that environment later, either by using the -n python2
flag to conda
, or by activating the environment.
In the aspx page load event, add an onkeypress
to the box.
this.TextBox1.Attributes.Add(
"onkeypress", "button_click(this,'" + this.Button1.ClientID + "')");
Then add this javascript to evaluate the key press, and if it is "enter," click the right button.
<script>
function button_click(objTextBox,objBtnID)
{
if(window.event.keyCode==13)
{
document.getElementById(objBtnID).focus();
document.getElementById(objBtnID).click();
}
}
</script>
You probably would have specified a wrong package and the package hierarchy would not be right. Look below
The ide would highlight the wrong path in that case.
I think the main difference I can describe relates to record oriented vs. column oriented formats. Record oriented formats are what we're all used to -- text files, delimited formats like CSV, TSV. AVRO is slightly cooler than those because it can change schema over time, e.g. adding or removing columns from a record. Other tricks of various formats (especially including compression) involve whether a format can be split -- that is, can you read a block of records from anywhere in the dataset and still know it's schema? But here's more detail on columnar formats like Parquet.
Parquet, and other columnar formats handle a common Hadoop situation very efficiently. It is common to have tables (datasets) having many more columns than you would expect in a well-designed relational database -- a hundred or two hundred columns is not unusual. This is so because we often use Hadoop as a place to denormalize data from relational formats -- yes, you get lots of repeated values and many tables all flattened into a single one. But it becomes much easier to query since all the joins are worked out. There are other advantages such as retaining state-in-time data. So anyway it's common to have a boatload of columns in a table.
Let's say there are 132 columns, and some of them are really long text fields, each different column one following the other and use up maybe 10K per record.
While querying these tables is easy with SQL standpoint, it's common that you'll want to get some range of records based on only a few of those hundred-plus columns. For example, you might want all of the records in February and March for customers with sales > $500.
To do this in a row format the query would need to scan every record of the dataset. Read the first row, parse the record into fields (columns) and get the date and sales columns, include it in your result if it satisfies the condition. Repeat. If you have 10 years (120 months) of history, you're reading every single record just to find 2 of those months. Of course this is a great opportunity to use a partition on year and month, but even so, you're reading and parsing 10K of each record/row for those two months just to find whether the customer's sales are > $500.
In a columnar format, each column (field) of a record is stored with others of its kind, spread all over many different blocks on the disk -- columns for year together, columns for month together, columns for customer employee handbook (or other long text), and all the others that make those records so huge all in their own separate place on the disk, and of course columns for sales together. Well heck, date and months are numbers, and so are sales -- they are just a few bytes. Wouldn't it be great if we only had to read a few bytes for each record to determine which records matched our query? Columnar storage to the rescue!
Even without partitions, scanning the small fields needed to satisfy our query is super-fast -- they are all in order by record, and all the same size, so the disk seeks over much less data checking for included records. No need to read through that employee handbook and other long text fields -- just ignore them. So, by grouping columns with each other, instead of rows, you can almost always scan less data. Win!
But wait, it gets better. If your query only needed to know those values and a few more (let's say 10 of the 132 columns) and didn't care about that employee handbook column, once it had picked the right records to return, it would now only have to go back to the 10 columns it needed to render the results, ignoring the other 122 of the 132 in our dataset. Again, we skip a lot of reading.
(Note: for this reason, columnar formats are a lousy choice when doing straight transformations, for example, if you're joining all of two tables into one big(ger) result set that you're saving as a new table, the sources are going to get scanned completely anyway, so there's not a lot of benefit in read performance, and because columnar formats need to remember more about the where stuff is, they use more memory than a similar row format).
One more benefit of columnar: data is spread around. To get a single record, you can have 132 workers each read (and write) data from/to 132 different places on 132 blocks of data. Yay for parallelization!
And now for the clincher: compression algorithms work much better when it can find repeating patterns. You could compress AABBBBBBCCCCCCCCCCCCCCCC
as 2A6B16C
but ABCABCBCBCBCCCCCCCCCCCCCC
wouldn't get as small (well, actually, in this case it would, but trust me :-) ). So once again, less reading. And writing too.
So we read a lot less data to answer common queries, it's potentially faster to read and write in parallel, and compression tends to work much better.
Columnar is great when your input side is large, and your output is a filtered subset: from big to little is great. Not as beneficial when the input and outputs are about the same.
But in our case, Impala took our old Hive queries that ran in 5, 10, 20 or 30 minutes, and finished most in a few seconds or a minute.
Hope this helps answer at least part of your question!
This is what you want
function isANumber(str){
return !/\D/.test(str);
}
$('.class[value=3]').prop('checked', true);
An alternative to GETDATE() is CURRENT_TIMESTAMP. Does the exact same thing.
There is another way to throw this error.
Keep in mind that the path to the model is case sensitive.
In this similar example involving the "Category" model, the error was thrown under these conditions:
1) The require statement was mentioned in two files: ..category.js and ..index.js 2) I the first, the case was correct, in the second file it was not as follows:
category.js
index.js
Set full screen this way,
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
android.widget.LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) videoView.getLayoutParams();
params.width = metrics.widthPixels;
params.height = metrics.heightPixels;
params.leftMargin = 0;
videoView.setLayoutParams(params);
And back to original size, this way.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
android.widget.LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) videoView.getLayoutParams();
params.width = (int)(300*metrics.density);
params.height = (int)(250*metrics.density);
params.leftMargin = 30;
videoView.setLayoutParams(params);
select ROUND(CASE
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0) from Tablename where ID="123"
Complete working code would look like this:
<script>
$(document).ready(function(){
setInterval(function(){
$("#here").load(window.location.href + " #here" );
}, 3000);
});
</script>
<div id="here">dynamic content ?</div>
self reloading div container refreshing every 3 sec.
Use spread Operator to get your desired result
var arrayFromSet = [...set];
to debug your react native app just go to the following address:
localhost:8081/debugger-ui in your default browser(chrome) and open developer tools to debug your react native app
Lines 1,2,3,4 will call the default constructor. They are different in the essence as 1,2 are dynamically created object and 3,4 are statically created objects.
In Line 7, you create an object inside the argument call. So its an error.
And Lines 5 and 6 are invitation for memory leak.
In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.
Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$var
notation but Javascript doesn't need to because property keys are interchangeable with array keys.
var id = "abc";
var mine = {};
mine[id] = 123;
console.log(mine.abc);
gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.
var mine = {};
mine.abc = 123;
console.log(mine["a"+"bc"]);
I like Postgresql Maestro. I also use their version for MySql. I'm pretty statisfied with their product. Or you can use the free tool PgAdmin.
the difference r
:
r
called explicitly while methods implicitaly.ActiveModel::Dirty
didn't work for me because the @model.update_attributes()
hid the changes. So this is how I detected changes it in an update
method in a controller:
def update
@model = Model.find(params[:id])
detect_changes
if @model.update_attributes(params[:model])
do_stuff if attr_changed?
end
end
private
def detect_changes
@changed = []
@changed << :attr if @model.attr != params[:model][:attr]
end
def attr_changed?
@changed.include :attr
end
If you're trying to detect a lot of attribute changes it could get messy though. Probably shouldn't do this in a controller, but meh.
in my case I added such cyclic resource:
<drawable name="above_shadow">@drawable/above_shadow</drawable>
then changed to
<drawable name="some_name">@drawable/other_name</drawable>
and it worked
The accepted answer didn't work with my form, even when I stripped it down to the bare minimum and copied & pasted the code. If anyone else is having this problem, please give my solution a try. Basically, you set Top and Left to 50% as the OP did, but offset the form's container with negative margins on the top and left equal to 50% of the div's height and width, respectively. This moves the center point of the Top and Left coordinates to the center of the form. I will stress that the height and width of the form must be specified (not relative). In this example, a 300x300px form div with margins of -150px on the top and left is perfectly centered no matter the window size:
HTML
<body>
<div class="login_div">
<form class="login_form" action="#">
</form>
</div>
</body>
CSS
.login_div {
position: absolute;
width: 300px;
height: 300px;
/* Center form on page horizontally & vertically */
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -150px;
}
.login_form {
width: 300px;
height: 300px;
background: gray;
border-radius: 10px;
margin: 0;
padding: 0;
}
Now, for those wondering why I used a container for the form, it's because I like to have the option of placing other elements in the form's vicinity and having them centered as well. The form container is completely unnecessary in this example, but would definitely be useful in other cases. Hope this helps!
The first arg that you give to grep needs to evaluate as true or false to indicate whether there was a match. So it should be:
# note that grep returns a list, so $matched needs to be in brackets to get the
# actual value, otherwise $matched will just contain the number of matches
if (my ($matched) = grep $_ eq $match, @array) {
print "found it: $matched\n";
}
If you need to match on a lot of different values, it might also be worth for you to consider putting the array
data into a hash
, since hashes allow you to do this efficiently without having to iterate through the list.
# convert array to a hash with the array elements as the hash keys and the values are simply 1
my %hash = map {$_ => 1} @array;
# check if the hash contains $match
if (defined $hash{$match}) {
print "found it\n";
}
Its not very object oriented: One reason statics might be considered "evil" by some people is they are contrary the object-oriented paradigm. In particular, it violates the principle that data is encapsulated in objects (that can be extended, information hiding, etc). Statics, in the way you are describing using them, are essentially to use them as a global variable to avoid dealing with issues like scope. However, global variables is one of the defining characteristics of procedural or imperative programming paradigm, not a characteristic of "good" object oriented code. This is not to say the procedural paradigm is bad, but I get the impression your supervisor expects you to be writing "good object oriented code" and you're really wanting to write "good procedural code".
There are many gotchyas in Java when you start using statics that are not always immediately obvious. For example, if you have two copies of your program running in the same VM, will they shre the static variable's value and mess with the state of each other? Or what happens when you extend the class, can you override the static member? Is your VM running out of memory because you have insane numbers of statics and that memory cannot be reclaimed for other needed instance objects?
Object Lifetime: Additionally, statics have a lifetime that matches the entire runtime of the program. This means, even once you're done using your class, the memory from all those static variables cannot be garbage collected. If, for example, instead, you made your variables non-static, and in your main() function you made a single instance of your class, and then asked your class to execute a particular function 10,000 times, once those 10,000 calls were done, and you delete your references to the single instance, all your static variables could be garbage collected and reused.
Prevents certain re-use: Also, static methods cannot be used to implement an interface, so static methods can prevent certain object oriented features from being usable.
Other Options: If efficiency is your primary concern, there might be other better ways to solve the speed problem than considering only the advantage of invocation being usually faster than creation. Consider whether the transient or volatile modifiers are needed anywhere. To preserve the ability to be inlined, a method could be marked as final instead of static. Method parameters and other variables can be marked final to permit certain compiler optimiazations based on assumptions about what can change those variables. An instance object could be reused multiple times rather than creating a new instance each time. There may be compliler optimization switches that should be turned on for the app in general. Perhaps, the design should be set up so that the 10,000 runs can be multi-threaded and take advantage of multi-processor cores. If portablity isn't a concern, maybe a native method would get you better speed than your statics do.
If for some reason you do not want multiple copies of an object, the singleton design pattern, has advantages over static objects, such as thread-safety (presuming your singleton is coded well), permitting lazy-initialization, guaranteeing the object has been properly initialized when it is used, sub-classing, advantages in testing and refactoring your code, not to mention, if at some point you change your mind about only wanting one instance of an object it is MUCH easier to remove the code to prevent duplicate instances than it is to refactor all your static variable code to use instance variables. I've had to do that before, its not fun, and you end up having to edit a lot more classes, which increases your risk of introducing new bugs...so much better to set things up "right" the first time, even if it seems like it has its disadvantages. For me, the re-work required should you decide down the road you need multiple copies of something is probably one of most compelling reasons to use statics as infrequently as possible. And thus I would also disagree with your statement that statics reduce inter-dependencies, I think you will end up with code that is more coupled if you have lots of statics that can be directly accessed, rather than an object that "knows how to do something" on itself.
Just do it:
Use memory.limit()
. You can increase the default using this command, memory.limit(size=2500)
, where the size is in MB. You need to be using 64-bit in order to take real advantage of this.
One other suggestion is to use memory efficient objects wherever possible: for instance, use a matrix instead of a data.frame.
You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)
That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:
int main()
{
for(;;)
{
printf ("%ld\n", time(NULL));
printf ("%f\n", time(NULL));
sleep(1);
}
return 0;
}
The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.
How about this?
<ul>
<?php while ($items = array_pop($lists)) { ?>
<ul>
<?php foreach ($items as $item) { ?>
<li><?= $item ?></li>
<?php
}//foreach
}//while ?>
We can still use the more widely-used braces and, at the same time, increase readability.
You can already do this with module-level variables. Modules are the same no matter what module they're being imported from. So you can make the variable a module-level variable in whatever module it makes sense to put it in, and access it or assign to it from other modules. It would be better to call a function to set the variable's value, or to make it a property of some singleton object. That way if you end up needing to run some code when the variable's changed, you can do so without breaking your module's external interface.
It's not usually a great way to do things — using globals seldom is — but I think this is the cleanest way to do it.
Open ThisWorkbook.Path & "\template.txt" For Output As #1
Print #1, strContent
Close #1
Open
statement Print #
statementClose
statementPrint
StatementWorkbook.Path
propertySorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Use isinstance(object, type)
. As above this is easy to use if you know the correct type
, e.g.,
isinstance('dog', str) ## gives bool True
But for more esoteric objects, this can be difficult to use. For example:
import numpy as np
a = np.array([1,2,3])
isinstance(a,np.array) ## breaks
but you can do this trick:
y = type(np.array([1]))
isinstance(a,y) ## gives bool True
So I recommend instantiating a variable (y
in this case) with a type of the object you want to check (e.g., type(np.array())
), then using isinstance
.
String is given as immutable by Sun micro systems,because string can used to store as key in map collection. StringBuffer is mutable .That is the reason,It cannot be used as key in map object
Sadly none of the solutions worked for me! I solved my problem by uninstalling existing APK from my phone and it all started working perfectly!
This started happening after I've updated android studio to latest version.
I am using below code for today and database date.
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20
According to the documentation, the first argument can be any of the following:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
What about
string s = "Hello Marco !";
s = s.Substring(0, s.Length - 2);
Try this:
class Flonetwork(Object):
def __init__(self,adj = {},flow={}):
self.adj = adj
self.flow = flow
Another command line tool is my new Xidel. It also supports XPath 2 and XQuery, contrary to the already mentioned xpath/xmlstarlet.
The title can be read like:
xidel xhtmlfile.xhtml -e /html/head/title > titleOfXHTMLPage.txt
And it also has a cool feature to export multiple variables to bash. For example
eval $(xidel xhtmlfile.xhtml -e 'title := //title, imgcount := count(//img)' --output-format bash )
sets $title
to the title and $imgcount
to the number of images in the file, which should be as flexible as parsing it directly in bash.
Not sure I understand the question correctly.
From what I gather, you want to be able to assign a value to Domain if it is null and also what to check if $args2 is supplied and according to the value, execute a certain code?
I changed the code to reassemble the assumptions made above.
Function DoStuff($computername, $arg2, $domain)
{
if($domain -ne $null)
{
$domain = "Domain1"
}
if($arg2 -eq $null)
{
}
else
{
}
}
DoStuff -computername "Test" -arg2 "" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Test" -domain ""
DoStuff -computername "Test" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Domain2"
Did that help?
if using /bin/sh
you can use:
if [ <condition> ] && [ <condition> ]; then
...
fi
if using /bin/bash
you can use:
if [[ <condition> && <condition> ]]; then
...
fi
Yes we can check the length of queue object created from collections.
from collections import deque
class Queue():
def __init__(self,batchSize=32):
#self.batchSie = batchSize
self._queue = deque(maxlen=batchSize)
def enqueue(self, items):
''' Appending the items to the queue'''
self._queue.append(items)
def dequeue(self):
'''remoe the items from the top if the queue becomes full '''
return self._queue.popleft()
Creating an object of class
q = Queue(batchSize=64)
q.enqueue([1,2])
q.enqueue([2,3])
q.enqueue([1,4])
q.enqueue([1,22])
Now retrieving the length of the queue
#check the len of queue
print(len(q._queue))
#you can print the content of the queue
print(q._queue)
#Can check the content of the queue
print(q.dequeue())
#Check the length of retrieved item
print(len(q.dequeue()))
check the results in attached screen shot
Hope this helps...
You can use an extension method like this:
internal static class ArrayExt
{
public static IEnumerable<int> Indices(this Array array, int dimension)
{
for (var i = array.GetLowerBound(dimension); i <= array.GetUpperBound(dimension); i++)
{
yield return i;
}
}
}
And then:
int[,] array = { { 1, 2, 3 }, { 4, 5, 6 } };
foreach (var i in array.Indices(0))
{
foreach (var j in array.Indices(1))
{
Console.Write(array[i, j]);
}
Console.WriteLine();
}
It will be a bit slower than using for loops but probably not an issue in most cases. Not sure if it makes things more readable.
Note that c# arrays can be other than zero-based so you can use a for loop like this:
int[,] array = { { 1, 2, 3 }, { 4, 5, 6 } };
for (var i = array.GetLowerBound(0); i <= array.GetUpperBound(0); i++)
{
for (var j= array.GetLowerBound(1); j <= array.GetUpperBound(1); j++)
{
Console.Write(array[i, j]);
}
Console.WriteLine();
}
typeof
is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof
is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.
GetType()
is a method you call on individual objects, to get the execution-time type of the object.
Note that unless you only want exactly instances of TextBox
(rather than instances of subclasses) you'd usually use:
if (myControl is TextBox)
{
// Whatever
}
Or
TextBox tb = myControl as TextBox;
if (tb != null)
{
// Use tb
}
#Single line
'''
multi-line
comment
'''
"""
also,
multi-line comment
"""
You can use this variant:
import lombok.Getter;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
//...
@JsonProperty(value = "rr") // for deserialization
@Getter(onMethod_ = {@JsonGetter(value = "r")}) // for serialization
private String rrrr;
with Lombok getter
It prints 47.48000 if you use another MathContext:
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64);
Just pick the context you need.
String a="string with multi spaces ";
//or this
String b= a.replaceAll("\\s+"," ");
String c= a.replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ");
//it work fine with any spaces
*don't forget space in sting b
A simple answer is to add checked
attributes within a checkbox:
$('input[id='+$(this).attr("id")+']').attr("checked", "checked");
I had the same error : The type 'MyCustomDerivedFactory' exists in both and My ServiceHost and ServiceHostFactory derived classes where in the App_Code folder of my WCF service project. Adding
<configuration>
<system.web>
<compilation batch="false" />
</system.web>
<configuration>
didn't solve the error but moving my ServiceHost and ServiceHostFactory derived classes in a separate Class library project did it.
You can use the attribute selector,
input[name="goButton"] {_x000D_
background: red;_x000D_
}
_x000D_
<input name="goButton">
_x000D_
Be aware that it isn't supported in IE6.
Update: In 2016 you can pretty much use them as you want, since IE6 is dead. http://quirksmode.org/css/selectors/
A StringBuffer is used to create a single string from many strings, e.g. when you want to append parts of a String in a loop.
You should use a StringBuilder instead of a StringBuffer when you have only a single Thread accessing the StringBuffer, since the StringBuilder is not synchronized and thus faster.
AFAIK there is no upper limit for String size in Java as a language, but the JVMs probably have an upper limit.
I had a similar issues once. I deleted the primary key from TABLE A but when I was trying to delete the foreign key column from table B I was shown the above same error.
You can't drop the foreign key using the column name and to bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming or deleting the attribute.
for (Tweet : tweets){ ...
should really be
for(Tweet tweet: tweets){...
I would recommend a wrapper that will handle value being changed. For example you can have JavaScript function, like this:
?function Variable(initVal, onChange)
{
this.val = initVal; //Value to be stored in this object
this.onChange = onChange; //OnChange handler
//This method returns stored value
this.GetValue = function()
{
return this.val;
}
//This method changes the value and calls the given handler
this.SetValue = function(value)
{
this.val = value;
this.onChange();
}
}
And then you can make an object out of it that will hold value that you want to monitor, and also a function that will be called when the value gets changed. For example, if you want to be alerted when the value changes, and initial value is 10, you would write code like this:
var myVar = new Variable(10, function(){alert("Value changed!");});
Handler function(){alert("Value changed!");}
will be called (if you look at the code) when SetValue()
is called.
You can get value like so:
alert(myVar.GetValue());
You can set value like so:
myVar.SetValue(12);
And immediately after, an alert will be shown on the screen. See how it works: http://jsfiddle.net/cDJsB/
As detailed in the Oracle Java SE Support Roadmap
After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive
Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe
(64-bit is named jdk-7u80-windows-x64.exe
.
Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget
to grab the file without signing in.
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"
Another way:
var testStr = "This is a test";
if(testStr.contains("test")){
alert("String Found");
}
** Tested on Firefox, Safari 6 and Chrome 36 **
The tool that richardtz suggests is excellent.
Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.
You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge
You can you with your source folder so whenever you build, those files are automatically copied to the classes directory.
Instead of using properties file, use XML file.
If the data is too small, you can even use web.xml for accessing the properties.
Please note that any of these approach will require app server restart for changes to be reflected.
Try this:
div.container {
max-width: 200px;//real picture size
max-height: 100px;
}
/* resize images */
div.container img {
width: 100%;
height: auto;
}
Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.
The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the close button ('X').
$(window).on('mouseover', (function () {
window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
return "";
}
var prevKey="";
$(document).keydown(function (e) {
if (e.key=="F5") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
window.onbeforeunload = ConfirmLeave;
}
prevKey = e.key.toUpperCase();
});
The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().
ORA-01031: insufficient privileges
happens when the object exists in the schema but do not have any access to that object.
ORA-00942: table or view does not exist
happens when the object does not exist in the current schema. If the object exists in another schema, you need to access it using .. Still you can get insufficient privileges error if the owner has not given access to the calling schema.
No it's not always wrong. If your loop condition is "while we haven't tried to read past end of file" then you use while (!feof(f))
. This is however not a common loop condition - usually you want to test for something else (such as "can I read more"). while (!feof(f))
isn't wrong, it's just used wrong.
hmmm, you can do it with a list comprehension. This would only make sense if you had a real range.. but it does do the job:
print([a for i in range(0,1) if b])
or using just those two variables:
print([a for a in range(a,a+1) if b])
Adding to @gojomo you could use :after
pseudo element for the additional element. The only caveat is that you'll need to define your innerText
in a data-text
attribute since CSS has limited content
functions.
s {_x000D_
color: red;_x000D_
text-align: -1000em;_x000D_
overflow: hidden;_x000D_
}_x000D_
s:after {_x000D_
color: black;_x000D_
content: attr(data-text);_x000D_
}
_x000D_
<s data-text="Strikethrough">Strikethrough</s>
_x000D_
You can use font-weight:100
or lighter: this is working with i.e. Opera 16 and older, but I do not know why the h1
tags in Firefox are bolder, sorry.
I just discovered the Hmisc package:
Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.
library(Hmisc)
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th
Just do-
Select (Getdate()+360) As MyDate
There is no need to use dateadd function for adding or subtracting days from a given date. For adding years, months, hours you need the dateadd function.
Late answer - I found the other answers useful - and wanted to add a bit extra.
How do I dump preprocessor macros coming from a particular header file?
echo "#include <sys/socket.h>" | gcc -E -dM -
or (thanks to @mymedia for the suggestion):
gcc -E -dM -include sys/socket.h - < /dev/null
In particular, I wanted to see what SOMAXCONN was defined to on my system. I know I could just open up the standard header file, but sometimes I have to search around a bit to find the header file locations. Instead I can just use this one-liner:
$ gcc -E -dM -include sys/socket.h - < /dev/null | grep SOMAXCONN
#define SOMAXCONN 128
$
Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:
SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;
So we have a table called Jokes with columns JScore and JDate.
Firstly: The >>>
code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this:
>>> 4+5
9
Here we see that the line that starts with >>>
is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Python interpreter, which is why it's done like that.
You never enter the >>>
part into a .py
file.
That takes care of your syntax error.
Secondly, ctypes is just one of several ways of wrapping Python libraries. Other ways are SWIG, which will look at your Python library and generate a Python C extension module that exposes the C API. Another way is to use Cython.
They all have benefits and drawbacks.
SWIG will only expose your C API to Python. That means you don't get any objects or anything, you'll have to make a separate Python file doing that. It is however common to have a module called say "wowza" and a SWIG module called "_wowza" that is the wrapper around the C API. This is a nice and easy way of doing things.
Cython generates a C-Extension file. It has the benefit that all of the Python code you write is made into C, so the objects you write are also in C, which can be a performance improvement. But you'll have to learn how it interfaces with C so it's a little bit extra work to learn how to use it.
ctypes have the benefit that there is no C-code to compile, so it's very nice to use for wrapping standard libraries written by someone else, and already exists in binary versions for Windows and OS X.
eval isn't always evil. There are times where it's perfectly appropriate.
However, eval is currently and historically massively over-used by people who don't know what they're doing. That includes people writing JavaScript tutorials, unfortunately, and in some cases this can indeed have security consequences - or, more often, simple bugs. So the more we can do to throw a question mark over eval, the better. Any time you use eval you need to sanity-check what you're doing, because chances are you could be doing it a better, safer, cleaner way.
To give an all-too-typical example, to set the colour of an element with an id stored in the variable 'potato':
eval('document.' + potato + '.style.color = "red"');
If the authors of the kind of code above had a clue about the basics of how JavaScript objects work, they'd have realised that square brackets can be used instead of literal dot-names, obviating the need for eval:
document[potato].style.color = 'red';
...which is much easier to read as well as less potentially buggy.
(But then, someone who /really/ knew what they were doing would say:
document.getElementById(potato).style.color = 'red';
which is more reliable than the dodgy old trick of accessing DOM elements straight out of the document object.)
If you do not need the recording and playback functionality in your app, using off-the-shelf streaming app and player is a reasonable choice.
If you do need them to be in your app, however, you will have to look into MediaRecorder API (for the server/camera app) and MediaPlayer (for client/player app).
Quick sample code for the server:
// this is your network socket
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// this is the unofficially supported MPEG2TS format, suitable for streaming (Android 3.0+)
mMediaRecorder.setOutputFormat(8);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mediaRecorder.setOutputFile(pfd.getFileDescriptor());
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
mMediaRecorder.prepare();
mMediaRecorder.start();
On the player side it is a bit tricky, you could try this:
// this is your network socket, connected to the server
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pfd.getFileDescriptor());
mMediaPlayer.prepare();
mMediaPlayer.start();
Unfortunately mediaplayer tends to not like this, so you have a couple of options: either (a) save data from socket to file and (after you have a bit of data) play with mediaplayer from file, or (b) make a tiny http proxy that runs locally and can accept mediaplayer's GET request, reply with HTTP headers, and then copy data from the remote server to it. For (a) you would create the mediaplayer with a file path or file url, for (b) give it a http url pointing to your proxy.
See also:
There are 3 ways to pass data from Parent to Children
Through Children Router Resolver if you have to receive different data
this.data = this.route.snaphsot.data['dataFromResolver'];
Through Parent Router Resolver if your have to receive the same data from parent
this.data = this.route.parent.snaphsot.data['dataFromResolver'];
Note1: You can read about resolver here. There is also an example of resolver and how to register the resolver into the module and then retrieve data from resolver into the component. The resolver registration is the same on the parent and child.
Note2: You can read about ActivatedRoute here to be able to get data from router
I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)
So I worked out at the end that you cannot uninstall 3.4 as it is default on Ubuntu.
All I did was simply remove Jupyter
and then alias python=python2.7
and install all packages on Python 2.7 again.
Arguably, I can install virtualenv
but me and my colleagues are only using 2.7. I am just going to be lazy in this case :)
Using jQuery appendTo try this:
var holdyDiv = $('<div></div>').attr('id', 'holdy');
holdyDiv.appendTo('body');
Here's my solution
# ...
RUN mkdir -p /opt
ADD initd.sh /opt/
RUN chmod +x /opt/initd.sh
ENTRYPOINT ["/opt/initd.sh"]
initd.sh
file#!/bin/bash
...
/etc/init.d/gearman-job-server start
/etc/init.d/supervisor start
#very important!!!
/bin/bash
exec
or attach
:Use exec (preferred) and run:
docker run --name $CONTAINER_NAME -dt $IMAGE_NAME
then
docker exec -it $CONTAINER_NAME /bin/bash
and use CTRL + D to detach
Use attach and run:
docker run --name $CONTAINER_NAME -dit $IMAGE_NAME
then
docker attach $CONTAINER_NAME
and use CTRL + P and CTRL + Q to detach
Note: The difference between options is in parameter -i
After checking all of these answers above without luck, the folling code worked for me to solve the problem:
$(".ui-dialog").dialog("close");
Maybe this will be also a good try if you seek for alternatives.
Simple solution that worked for me -- quoted $@
Test(){
set -x
grep "$@" /etc/hosts
set +x
}
Test -i "3 rb"
+ grep -i '3 rb' /etc/hosts
I could verify the actual grep command (thanks to set -x).
Old Answer it is kind of confusing. It gives you the LOCATIONS (all of them) of where your statment is true.
so:
>>> a = np.arange(100)
>>> np.where(a > 30)
(array([31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
99]),)
>>> np.where(a == 90)
(array([90]),)
a = a*40
>>> np.where(a > 1000)
(array([26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
94, 95, 96, 97, 98, 99]),)
>>> a[25]
1000
>>> a[26]
1040
I use it as an alternative to list.index(), but it has many other uses as well. I have never used it with 2D arrays.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
New Answer It seems that the person was asking something more fundamental.
The question was how could YOU implement something that allows a function (such as where) to know what was requested.
First note that calling any of the comparison operators do an interesting thing.
a > 1000
array([False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True`, True, True, True, True, True, True, True, True, True], dtype=bool)`
This is done by overloading the "__gt__" method. For instance:
>>> class demo(object):
def __gt__(self, item):
print item
>>> a = demo()
>>> a > 4
4
As you can see, "a > 4" was valid code.
You can get a full list and documentation of all overloaded functions here: http://docs.python.org/reference/datamodel.html
Something that is incredible is how simple it is to do this. ALL operations in python are done in such a way. Saying a > b is equivalent to a.gt(b)!
you can declare a Numpy array dynamically for 1 dimension as shown below:
import numpy as np
n = 2
new_table = np.empty(shape=[n,1])
new_table[0,0] = 2
new_table[1,0] = 3
print(new_table)
The above example assumes we know we need to have 1 column but we want to allocate the number of rows dynamically (in this case the number or rows required is equal to 2)
output is shown below:
[[2.] [3.]]
Anything using the managed environment (which includes anything written in C# and VB.NET) requires the .NET framework. You can simply redistribute your .EXE in that scenario, but they'll need to install the appropriate framework if they don't already have it.
In many cases, when we are inside a string we are enclosed by a double quote, or while writing a statement we don't want to press escape and go to end of that line with arrow key and press the semicolon(;
) just to end the line. Write the following line inside your vimrc file:
imap <C-l> <Esc>$a
What does the line say? It maps Ctrl+l to a series of commands. It is equivalent to you pressing Esc (command mode), $ (end of line), a (append) at once.
It is better to use the for...of statement, if the string contains unicode characters, because of the different byte size.
for(var c of "tree ?") { console.log(c); }
//"A".length === 3
You are facing issue in
s1.name="Paolo";
because, in the LHS, you're using an array type, which is not assignable.
To elaborate, from C11
, chapter §6.5.16
assignment operator shall have a modifiable lvalue as its left operand.
and, regarding the modifiable lvalue, from chapter §6.3.2.1
A modifiable lvalue is an lvalue that does not have array type, [...]
You need to use strcpy()
to copy into the array.
That said, data s1 = {"Paolo", "Rossi", 19};
works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9
Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]
This worked for me:
.env
file and be sure APP_DEBUG=true
.env
file) change reemplace 127.0.0.1
for localhost
for check if your DB credential are corrects. config
folder and do. the step #2.$watch
first parameter can also be a function.
$scope.$watch(function watchBothItems() {
return itemsCombinedValue();
}, function whenItemsChange() {
//stuff
});
If your two combined values are simple, the first parameter is just an angular expression normally. For example, firstName and lastName:
$scope.$watch('firstName + lastName', function() {
//stuff
});
Many ways this can be achieved.
Simple approach should be taking Substring
of an input string.
var result = input.Substring(input.Length - 3);
Another approach using Regular Expression
to extract last 3 characters.
var result = Regex.Match(input,@"(.{3})\s*$");
Working Demo
select your table -> view dependencies -> Objects that depend on
If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:
import subprocess
# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"
# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"
subprocess.Popen([python_bin, script_file])
However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py
script:
# Doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
execfile(activate_this_file, dict(__file__=activate_this_file))
Another solution could be, that you deleted a file from your Project by just removing it in your file system, instead of removing it within your project.
A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form
I'm using contentEditable
to allow rich text editing in my app. I don't know how it slips through, but when an image is inserted, and then resized (by dragging the anchors on its side), it generates something like this:
<img style="width:55px;height:55px" width="100" height="100" src="pic.gif" border=0/>
(subsequent testing shown that inserted images did not contain this "rogue" style attr+param).
When rendered by the browser (IE7), the width and height in the style overrides the img width/height param (so the image is shown like how I wanted it.. resized to 55px x 55px. So everything went well so it seems.
When I output the page to a ms-word document via setting the mime type application/msword or pasting the browser rendering to msword document, all the images reverted back to its default size. I finally found out that msword is discarding the style and using the img width and height tag (which has the value of the original image size).
Took me a while to found this out. Anyway... I've coded a javascript function to traverse all tags and "transferring" the img style.width and style.height values into the img.width and img.height, then clearing both the values in style, before I proceed saving this piece of html/richtext data into the database.
cheers.
opps.. my answer is.. no. leave both attributes directly under img, rather than style.
I encountered this when using scrapy and fetching a zipped csvfile without having a correct middleware to unzip the response body before handing it to the csvreader. Hence the file was not really a csv file and threw the line contains NULL byte
error accordingly.
A simplified version of the accepted answer (third point), just worked for me.
function run_cmd(cmd, args, callBack ) {
var spawn = require('child_process').spawn;
var child = spawn(cmd, args);
var resp = "";
child.stdout.on('data', function (buffer) { resp += buffer.toString() });
child.stdout.on('end', function() { callBack (resp) });
} // ()
Usage:
run_cmd( "ls", ["-l"], function(text) { console.log (text) });
run_cmd( "hostname", [], function(text) { console.log (text) });
SELECT <rows> FROM TABLE_NAME WHERE ROWID=(SELECT MIN(ROWID) FROM TABLE_NAME)
UNION
SELECT <rows> FROM TABLE_NAME WHERE ROWID=(SELECT MAX(ROWID) FROM TABLE_NAME)
or
SELECT * FROM TABLE_NAME WHERE ROWID=(SELECT MIN(ROWID) FROM TABLE_NAME)
OR ROWID=(SELECT MAX(ROWID) FROM TABLE_NAME)
If you absolutely must use Scanner, then you must set its delimiter via its useDelimiter(...)
method. Else it will default to using all white space as its delimiter. Better though as has already been stated -- use a CSV library since this is what they do best.
For example, this delimiter will split on commas with or without surrounding whitespace:
scanner.useDelimiter("\\s*,\\s*");
Please check out the java.util.Scanner API for more on this.
HTML :
<div class="span4">
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
</div>
</div>
CSS :
.panel-height {
height: 100px; / change according to your requirement/
}
The answer of Steve is correct, but it doesn't work for integers less than 1.
Here an updated version that does work for negatives:
int digits = n == 0 ? 1 : Math.Floor(Math.Log10(Math.Abs(n)) + 1)
I had the same problem and this is my solution. I had the following code:
se.GiftDescription = rs.getString(1);
se.GiftAmount = rs.getInt(2);
And I changed it to:
se.GiftDescription = rs.getString("DESCRIPTION");
se.GiftAmount = rs.getInt("AMOUNT");
And the problem was, after I restarted my PC, the column positions changed. That's why I got this error.
This worked for me and was as easy as adding a gradle dependancy:
https://bintray.com/seesaa/maven/opencv#
https://github.com/seesaa/opencv-android
The one caveat being that I had to use a hardware debugging device as arm emulators were running too slow for me (as AVD Manager says they will), and, as described at the repo README, this version does not include x86 or x86_64 support.
It seems to build and the suggested test:
static {
OpenCVLoader.initDebug();
}
spits out a bunch of output that looks about right to me.
Prevents previous data from been resubmitted. Tested in Firefox and Safari.
top.frames.location.href = top.frames.location.href;
Same as the other answers (disabled isn't sent to the server, readonly is) but some browsers prevent highlighting of a disabled form, while read-only can still be highlighted (and copied).
http://www.w3schools.com/tags/att_input_disabled.asp
http://www.w3schools.com/tags/att_input_readonly.asp
A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it.
make sure you are passing string to "replace" method. Had same issue and solved it by passing string. You can also make it to string using toString() method.
A linq-to-sql query isn't executed as code, but rather translated into SQL. Sometimes this is a "leaky abstraction" that yields unexpected behaviour.
One such case is null handling, where there can be unexpected nulls in different places. ...DefaultIfEmpty(0).Sum(0)
can help in this (quite simple) case, where there might be no elements and sql's SUM
returns null
whereas c# expect 0.
A more general approach is to use ??
which will be translated to COALESCE
whenever there is a risk that the generated SQL returns an unexpected null:
var creditsSum = (from u in context.User
join ch in context.CreditHistory on u.ID equals ch.UserID
where u.ID == userID
select (int?)ch.Amount).Sum() ?? 0;
This first casts to int?
to tell the C# compiler that this expression can indeed return null
, even though Sum()
returns an int
. Then we use the normal ??
operator to handle the null
case.
Based on this answer, I wrote a blog post with details for both LINQ to SQL and LINQ to Entities.
serialVersionUID
facilitates versioning of serialized data. Its value is stored with the data when serializing. When de-serializing, the same version is checked to see how the serialized data matches the current code.
If you want to version your data, you normally start with a serialVersionUID
of 0, and bump it with every structural change to your class which alters the serialized data (adding or removing non-transient fields).
The built-in de-serialization mechanism (in.defaultReadObject()
) will refuse to de-serialize from old versions of the data. But if you want to you can define your own readObject()-function which can read back old data. This custom code can then check the serialVersionUID
in order to know which version the data is in and decide how to de-serialize it. This versioning technique is useful if you store serialized data which survives several versions of your code.
But storing serialized data for such a long time span is not very common. It is far more common to use the serialization mechanism to temporarily write data to for instance a cache or send it over the network to another program with the same version of the relevant parts of the codebase.
In this case you are not interested in maintaining backwards compatibility. You are only concerned with making sure that the code bases which are communicating indeed have the same versions of relevant classes. In order to facilitate such a check, you must maintain the serialVersionUID
just like before and not forget to update it when making changes to your classes.
If you do forget to update the field, you might end up with two different versions of a class with different structure but with the same serialVersionUID
. If this happens, the default mechanism (in.defaultReadObject()
) will not detect any difference, and try to de-serialize incompatible data. Now you might end up with a cryptic runtime error or silent failure (null fields). These types of errors might be hard to find.
So to help this usecase, the Java platform offers you a choice of not setting the serialVersionUID
manually. Instead, a hash of the class structure will be generated at compile-time and used as id. This mechanism will make sure that you never have different class structures with the same id, and so you will not get these hard-to-trace runtime serialization failures mentioned above.
But there is a backside to the auto-generated id strategy. Namely that the generated ids for the same class might differ between compilers (as mentioned by Jon Skeet above). So if you communicate serialized data between code compiled with different compilers, it is recommended to maintain the ids manually anyway.
And if you are backwards-compatible with your data like in the first use case mentioned, you also probably want to maintain the id yourself. This in order to get readable ids and have greater control over when and how they change.
Fix This issue by this command
In Windows Platform
cd android && gradlew clean && cd..
In Mac Platform
cd android && ./gradlew clean && cd ..
The only way to do everything you asked for is to require an internet access and verification with a server. The application needs to sign in to the server with the key, and then you need to store the session details, like the IP address. This will prevent the key from being used on several different machines. This is usually not very popular with the users of the application, and unless this is a very expensive and complicated application it's not worth it.
You could just have a license key for the application, and then check client side if the key is good, but it is easy to distribute this key to other users, and with a decompiler new keys can be generated.
This question doesn't really have anything to do with how require()
works. Basically, whatever you set module.exports
to in your module will be returned from the require()
call for it.
This would be equivalent to:
var square = function(width) {
return {
area: function() {
return width * width;
}
};
}
There is no need for the new
keyword when calling square
. You aren't returning the function instance itself from square
, you are returning a new object at the end. Therefore, you can simply call this function directly.
For more intricate arguments around new
, check this out: Is JavaScript's "new" keyword considered harmful?
To discover any constraints used, use the code below:
-- Set the long data type for display purposes to 500000.
SET LONG 500000
-- Define a session scope variable.
VARIABLE output CLOB
-- Query the table definition through the <code>DBMS_METADATA</code> package.
SELECT dbms_metadata.get_ddl('TABLE','[Table Described]') INTO :output FROM dual;
This essentially shows a create statement for how the referenced table is made. By knowing how the table is created, you can see all of the table constraints.
Answer taken from Michael McLaughlin's blog: http://michaelmclaughlin.info/db1/lesson-5-querying-data/lab-5-querying-data/ From his Database Design I class.
Additionally to the answer of @tkruse and @Yishai:
I do this way to conditionally skip test methods especially for Parameterized
tests, if a test method should only run for some test data records.
public class MyTest {
// get current test method
@Rule public TestName testName = new TestName();
@Before
public void setUp() {
org.junit.Assume.assumeTrue(new Function<String, Boolean>() {
@Override
public Boolean apply(String testMethod) {
if (testMethod.startsWith("testMyMethod")) {
return <some condition>;
}
return true;
}
}.apply(testName.getMethodName()));
... continue setup ...
}
}
It could be related with your Java version. Go ahead and download the Database version which includes Java.
However, if you are configuring a local development workstation I recommend you to download the Express Edition.
Here is the link: http://www.oracle.com/technetwork/products/express-edition/downloads/index-083047.html
or google this: OracleXE112_Win64
Good luck!
You can iterate DataTable
like this:
private void button1_Click(object sender, EventArgs e)
{
for(int i = 0; i< dt.Rows.Count;i++)
for (int j = 0; j <dt.Columns.Count ; j++)
{
object o = dt.Rows[i].ItemArray[j];
//if you want to get the string
//string s = o = dt.Rows[i].ItemArray[j].ToString();
}
}
Depending on the type of the data in the DataTable
cell, you can cast the object to whatever you want.
You can't use AJAX to fetch files from the user machine. This is absolutely the wrong way to go about it.
Use the FileReader API:
<input type="file" id="file input">
js:
console.log(document.getElementById("file input").files); // list of File objects
var file = document.getElementById("file input").files[0];
var reader = new FileReader();
content = reader.readAsText(file);
console.log(content);
Then parse content
as CSV. Keep in mind that your parser currently does not deal with escaped values in CSV like: value1,value2,"value 3","value ""4"""
The readarray
command (also spelled mapfile
) was introduced in bash 4.0.
readarray -t a < /path/to/filename
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);
startActivity(in);
This is an explicit intent to start secondscreen activity.
I just add this line to all my pyspark scripts on top just below the import statements.
SparkSession.builder.getOrCreate().sparkContext.setLogLevel("ERROR")
example header of my pyspark scripts
from pyspark.sql import SparkSession, functions as fs
SparkSession.builder.getOrCreate().sparkContext.setLogLevel("ERROR")
As of Spring 5.1 you can use HttpHeaders.setBasicAuth
Create Basic Authorization header:
String username = "willie";
String password = ":p@ssword";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
...other headers goes here...
Pass the headers to the RestTemplate:
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();
Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.
See here for the groupid/artifactid.
It's part of the Oracle analytic functions.
It can be much simpler than what you are doing.
HTML:
<input id="myField" type="text" name="email"/>
JavaScript:
// getting the value
var email = $("#myField").val();
// setting the value
$("#myField").val( "new value here" );
Similarly in Java, you can create a S4 class in R that encapsulates your information:
setClass(Class="Person",
representation(
height="numeric",
age="numeric"
)
)
Then your function can return an instance of this class:
myFunction = function(age=28, height=176){
return(new("Person",
age=age,
height=height))
}
and you can access your information:
aPerson = myFunction()
aPerson@age
aPerson@height
This can be done in java 8 using Stream.
import java.util.stream.Stream;
String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());
If I understand you correctly, this should do the trick. You'll need add using System.IO
at the top of your file if you don't already have it.
public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
try
{
using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(byteArray, 0, byteArray.Length);
return true;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in process: {0}", ex);
return false;
}
}
Check your PrimeNumberModelTests
Target Settings.
If you can't see PrimeNumberModel.swift
file in Build Phases/Compile Sources
, add it.
If you are using eclipse to start the server then check for the server location being used and the deployment path:
In my case changing this to Tomcat installation
instead of workspace metadata
worked for me.
Adding text to current cursor position involves two steps:
Demo: https://codepen.io/anon/pen/qZXmgN
Tested in Chrome 48, Firefox 45, IE 11 and Edge 25
JS:
function addTextAtCaret(textAreaId, text) {
var textArea = document.getElementById(textAreaId);
var cursorPosition = textArea.selectionStart;
addTextAtCursorPosition(textArea, cursorPosition, text);
updateCursorPosition(cursorPosition, text, textArea);
}
function addTextAtCursorPosition(textArea, cursorPosition, text) {
var front = (textArea.value).substring(0, cursorPosition);
var back = (textArea.value).substring(cursorPosition, textArea.value.length);
textArea.value = front + text + back;
}
function updateCursorPosition(cursorPosition, text, textArea) {
cursorPosition = cursorPosition + text.length;
textArea.selectionStart = cursorPosition;
textArea.selectionEnd = cursorPosition;
textArea.focus();
}
HTML:
<div>
<button type="button" onclick="addTextAtCaret('textArea','Apple')">Insert Apple!</button>
<button type="button" onclick="addTextAtCaret('textArea','Mango')">Insert Mango!</button>
<button type="button" onclick="addTextAtCaret('textArea','Orange')">Insert Orange!</button>
</div>
<textarea id="textArea" rows="20" cols="50"></textarea>
For enterprise applications it should be noted that you should not be handling https in your code. It should be auto upgraded via IIS or nginx. The app shouldn't know about what protocols are used.
Have been fighting this all morning and now have it solved and why it happened. Posting with the hope it helps others
I installed the Krypton.Toolkit which added the tools to the Visual studio toolbox automatically. I then added the tools to the designer, which automatically added the dll to the projrect references, however the toolkit was marked as CopyLocal=false
I built an installer, using all dlls in the release build folder (of course the above dll wasn't there).
Setting copylocal=true, then rebuilding the installer, everything worked fine.
Try these:
Table definition:
DROP TABLE IF EXISTS category;
CREATE TABLE category (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20),
parent_id INT,
CONSTRAINT fk_category_parent FOREIGN KEY (parent_id)
REFERENCES category (id)
) engine=innodb;
Experimental rows:
INSERT INTO category VALUES
(19, 'category1', NULL),
(20, 'category2', 19),
(21, 'category3', 20),
(22, 'category4', 21),
(23, 'categoryA', 19),
(24, 'categoryB', 23),
(25, 'categoryC', 23),
(26, 'categoryD', 24);
Recursive Stored procedure:
DROP PROCEDURE IF EXISTS getpath;
DELIMITER $$
CREATE PROCEDURE getpath(IN cat_id INT, OUT path TEXT)
BEGIN
DECLARE catname VARCHAR(20);
DECLARE temppath TEXT;
DECLARE tempparent INT;
SET max_sp_recursion_depth = 255;
SELECT name, parent_id FROM category WHERE id=cat_id INTO catname, tempparent;
IF tempparent IS NULL
THEN
SET path = catname;
ELSE
CALL getpath(tempparent, temppath);
SET path = CONCAT(temppath, '/', catname);
END IF;
END$$
DELIMITER ;
Wrapper function for the stored procedure:
DROP FUNCTION IF EXISTS getpath;
DELIMITER $$
CREATE FUNCTION getpath(cat_id INT) RETURNS TEXT DETERMINISTIC
BEGIN
DECLARE res TEXT;
CALL getpath(cat_id, res);
RETURN res;
END$$
DELIMITER ;
Select example:
SELECT id, name, getpath(id) AS path FROM category;
Output:
+----+-----------+-----------------------------------------+
| id | name | path |
+----+-----------+-----------------------------------------+
| 19 | category1 | category1 |
| 20 | category2 | category1/category2 |
| 21 | category3 | category1/category2/category3 |
| 22 | category4 | category1/category2/category3/category4 |
| 23 | categoryA | category1/categoryA |
| 24 | categoryB | category1/categoryA/categoryB |
| 25 | categoryC | category1/categoryA/categoryC |
| 26 | categoryD | category1/categoryA/categoryB/categoryD |
+----+-----------+-----------------------------------------+
Filtering rows with certain path:
SELECT id, name, getpath(id) AS path FROM category HAVING path LIKE 'category1/category2%';
Output:
+----+-----------+-----------------------------------------+
| id | name | path |
+----+-----------+-----------------------------------------+
| 20 | category2 | category1/category2 |
| 21 | category3 | category1/category2/category3 |
| 22 | category4 | category1/category2/category3/category4 |
+----+-----------+-----------------------------------------+
I have given a simple code to upload files from Javascript browser to AWS S3 and list the all files in S3 bucket.
Steps:
To know how to create Create IdentityPoolId http://docs.aws.amazon.com/cognito/latest/developerguide/identity-pools.html
Goto S3's console page and open cors configuration from bucket properties and write following XML code into that.
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Create HTML file containing following code change the credentials, open file in browser and enjoy.
<script type="text/javascript">
AWS.config.region = 'ap-north-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'ap-north-1:*****-*****',
});
var bucket = new AWS.S3({
params: {
Bucket: 'MyBucket'
}
});
var fileChooser = document.getElementById('file-chooser');
var button = document.getElementById('upload-button');
var results = document.getElementById('results');
function upload() {
var file = fileChooser.files[0];
console.log(file.name);
if (file) {
results.innerHTML = '';
var params = {
Key: n + '.pdf',
ContentType: file.type,
Body: file
};
bucket.upload(params, function(err, data) {
results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';
});
} else {
results.innerHTML = 'Nothing to upload.';
} }
</script>
<body>
<input type="file" id="file-chooser" />
<input type="button" onclick="upload()" value="Upload to S3">
<div id="results"></div>
</body>
COPY <all> <the> <things> <last-arg-is-destination>
But here is an important excerpt from the docs:
If you have multiple Dockerfile steps that use different files from your context, COPY them individually, rather than all at once. This ensures that each step’s build cache is only invalidated (forcing the step to be re-run) if the specifically required files change.
https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy
Although this is an old question, there are several of us still struggle to find an answer. At least I did. Please don't follow all the lengthy solutions. You could simply login to your mysql as root without providing any password (provided it is a fresh installation or you haven't changed the password since your installation) by adding sudo before your mysql command.
$sudo mysql -uroot -p
mysql>
This is because mysql changed the security model in one of the latest versions.
Hope this helps
Try this, with strings:
set "var=string1string2string3"
and with string variables:
set "var=%string1%%string2%%string3%"
On Windows 7 for example, the following set of commands/operations could be used.
Create an personal environment variable, double backslashes are mandatory:
%NPM_HOME%
C:\\SomeFolder\\SubFolder\\
Now, set the config values to the new folders (examplary file names):
npm config set prefix "%NPM_HOME%\\npm"
npm config set cache "%NPM_HOME%\\npm-cache"
npm config set tmp "%NPM_HOME%\\temp"
Optionally, you can purge the contents of the original folders before the config is changed.
Delete the npm-cache npm cache clear
List the npm modules npm -g ls
Delete the npm modules
npm -g rm name_of_package1 name_of_package2
print locals()
edit continued from comment.
To make it look a little prettier when printing:
import sys, pprint
sys.displayhook = pprint.pprint
locals()
That should give you a more vertical printout.
<form action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
<button type="submit" name="ok">OK</button>
</form>
<?php
if(isset($_POST['ok'])){
echo $_POST['subject'];
}
?>
Just in case this helps someone, I was getting this error because I completely missed the stated fact that the scope prefix must not be used when calling a local scope. So if you defined a local scope in your model like this:
public function scopeRecentFirst($query)
{
return $query->orderBy('updated_at', 'desc');
}
You should call it like:
$CurrentUsers = \App\Models\Users::recentFirst()->get();
Note that the prefix scope
is not present in the call.
Old question but I should warn:
.split('')
You'll get weird results with non-BMP (non-Basic-Multilingual-Plane) character sets.
Reason is that methods like .split()
and .charCodeAt()
only respect the characters with a code point below 65536; bec. higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters.
''.length // —> 6
''.split('') // —> ["?", "?", "?", "?", "?", "?"]
''.length // —> 2
''.split('') // —> ["?", "?"]
Using the spread operator:
let arr = [...str];
Or Array.from
let arr = Array.from(str);
Or split
with the new u
RegExp flag:
let arr = str.split(/(?!$)/u);
Examples:
[...''] // —> ["", "", ""]
[...''] // —> ["", "", ""]
I came up with this function that internally uses MDN example to get the correct code point of each character.
function stringToArray() {
var i = 0,
arr = [],
codePoint;
while (!isNaN(codePoint = knownCharCodeAt(str, i))) {
arr.push(String.fromCodePoint(codePoint));
i++;
}
return arr;
}
This requires knownCharCodeAt()
function and for some browsers; a String.fromCodePoint()
polyfill.
if (!String.fromCodePoint) {
// ES6 Unicode Shims 0.1 , © 2012 Steven Levithan , MIT License
String.fromCodePoint = function fromCodePoint () {
var chars = [], point, offset, units, i;
for (i = 0; i < arguments.length; ++i) {
point = arguments[i];
offset = point - 0x10000;
units = point > 0xFFFF ? [0xD800 + (offset >> 10), 0xDC00 + (offset & 0x3FF)] : [point];
chars.push(String.fromCharCode.apply(null, units));
}
return chars.join("");
}
}
Examples:
stringToArray('') // —> ["", "", ""]
stringToArray('') // —> ["", "", ""]
Note: str[index]
(ES5) and str.charAt(index)
will also return weird results with non-BMP charsets. e.g. ''.charAt(0)
returns "?"
.
UPDATE: Read this nice article about JS and unicode.
numpy.ndarray()
is a class, while numpy.array()
is a method / function to create ndarray
.
In numpy docs if you want to create an array from ndarray
class you can do it with 2 ways as quoted:
1- using array()
, zeros()
or empty()
methods:
Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)
) for instantiating an array.
2- from ndarray
class directly:
There are two modes of creating an array using __new__
:
If buffer is None, then only shape, dtype, and order are used.
If buffer is an object exposing the buffer interface, then all keywords are interpreted.
The example below gives a random array because we didn't assign buffer value:
np.ndarray(shape=(2,2), dtype=float, order='F', buffer=None) array([[ -1.13698227e+002, 4.25087011e-303], [ 2.88528414e-306, 3.27025015e-309]]) #random
another example is to assign array object to the buffer example:
>>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3])
from above example we notice that we can't assign a list to "buffer" and we had to use numpy.array() to return ndarray object for the buffer
Conclusion: use numpy.array()
if you want to make a numpy.ndarray()
object"
Android Studio 3.5.3
Find the Memory Settings (Cmd + Shift + A on Mac or click on Help and start typing "Memory Settings") under Preferences/ Settings and increase the IDE Heap Size and/ or the Daemon Heap Size to your satisfaction
command `< file`
will pass file contents to the command on stdin, but will strip newlines, meaning you couldn't iterate over each line individually. For that you could write a script with a 'for' loop:
for line in `cat input_file`; do some_command "$line"; done
Or (the multi-line variant):
for line in `cat input_file`
do
some_command "$line"
done
Or (multi-line variant with $()
instead of ``
):
for line in $(cat input_file)
do
some_command "$line"
done
Best example is here
thanks #define SIZE 10
void size(int arr[SIZE])
{
printf("size of array is:%d\n",sizeof(arr));
}
int main()
{
int arr[SIZE];
size(arr);
return 0;
}
Your JSON is not correct. Instead of
JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString()); // <-- toString()
parent.put("auth", auth.toString()); // <-- toString()
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
write
JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred);
parent.put("auth", auth);
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
So, the JSONObject.toString() should be called only once for the outer object.
Another thing (most probably not your problem, but I'd like to mention it):
To be sure not to run into encoding problems, you should specify the encoding, if it is not UTF-8
:
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
// ...
OutputStream os = con.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();
Look at the link, there is an answer for your question.
Sending Email in Android using JavaMail API without using the default/built-in app
I have used Meld once, which seemed very nice, and I may try more often. vimdiff works well, if you know vim well. Lastly I would mention I've found xxdiff does a reasonable job for a quick comparison. There are many diff programs out there which do a good job.
Use encodeURI()
in client JS and use URLDecoder.decode()
in server Java side works.
Example:
Javascript:
$.getJSON(
url,
{
"user": encodeURI(JSON.stringify(user))
},
onSuccess
);
Java:
java.net.URLDecoder.decode(params.user, "UTF-8");
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
most simple answer
<a onclick="window.open(this.href,'_blank');return false;" href="http://www.foracure.org.au">Some Other Site</a>
it will work
This will force the DefaultWebProxy
to use default credentials, similar effect as done through UseDefaultCredentials = true
.
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
Hence all newly created WebRequest
instances will use default proxy which has been configured to use proxy's default credentials.
CONVERT(VARCHAR(32), HashBytes('MD5', '[email protected]'), 2)
for those looking for a way to mock POST
HttpServletRequest with Json payload, the below is in Kotlin, but the key take away here is the DelegatingServetInputStream when you want to mock the request.getInputStream
from the HttpServletRequest
@Mock
private lateinit var request: HttpServletRequest
@Mock
private lateinit var response: HttpServletResponse
@Mock
private lateinit var chain: FilterChain
@InjectMocks
private lateinit var filter: ValidationFilter
@Test
fun `continue filter chain with valid json payload`() {
val payload = """{
"firstName":"aB",
"middleName":"asdadsa",
"lastName":"asdsada",
"dob":null,
"gender":"male"
}""".trimMargin()
whenever(request.requestURL).
thenReturn(StringBuffer("/profile/personal-details"))
whenever(request.method).
thenReturn("PUT")
whenever(request.inputStream).
thenReturn(DelegatingServletInputStream(ByteArrayInputStream(payload.toByteArray())))
filter.doFilter(request, response, chain)
verify(chain).doFilter(request, response)
}
With Node and HTML alone you won't be able to achieve what you intend to; it's not like using PHP, where you could do something like <title> <?php echo $custom_title; ?>
, without any other stuff installed.
To do what you want using Node, you can either use something that's called a 'templating' engine (like Jade, check this out) or use some HTTP requests in Javascript to get your data from the server and use it to replace parts of the HTML with it.
Both require some extra work; it's not as plug'n'play as PHP when it comes to doing stuff like you want.
I assume that REALLY you get object from server and want to get object on output
Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])
var data = { 5: { "ID": "0", "Status": "Valid" } }; // some OBJECT from server response_x000D_
_x000D_
data = { ...data,_x000D_
0: { "ID": "1", "Status": "Valid" },_x000D_
1: { "ID": "2", "Status": "Invalid" },_x000D_
2: { "ID": "3", "Status": "Valid" }_x000D_
}_x000D_
_x000D_
// solution 1: where output is sorted filtred array_x000D_
let arr=Object.keys(data).filter(k=> data[k].Status!='Invalid').map(k=>data[k]).sort((a,b)=>+a.ID-b.ID);_x000D_
_x000D_
// solution2: where output is filtered object_x000D_
Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])_x000D_
_x000D_
// show_x000D_
console.log('Object',data);_x000D_
console.log('Array ',arr);
_x000D_
Take a look at this tutorial for how to use SQL inside VBA:
http://www.ehow.com/how_7148832_access-vba-query-results.html
For a query that won't return results, use (reference here):
DoCmd.RunSQL
For one that will, use (reference here):
Dim dBase As Database
dBase.OpenRecordset
To get the post by George Howarth working properly with more than one replacement you need to remove the break, assign the output to a variable ($line) and then output the variable:
$lookupTable = @{
'something1' = 'something1aa'
'something2' = 'something2bb'
'something3' = 'something3cc'
'something4' = 'something4dd'
'something5' = 'something5dsf'
'something6' = 'something6dfsfds'
}
$original_file = 'path\filename.abc'
$destination_file = 'path\filename.abc.new'
Get-Content -Path $original_file | ForEach-Object {
$line = $_
$lookupTable.GetEnumerator() | ForEach-Object {
if ($line -match $_.Key)
{
$line = $line -replace $_.Key, $_.Value
}
}
$line
} | Set-Content -Path $destination_file
Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy
It seems that ssh is not installed on your computer.
You can install openssh from here : http://openssh.en.softonic.com/download
Than you will have to geneate your ssh-key. There's a good tutorial about this here:
https://help.github.com/articles/generating-ssh-keys#platform-windows
To deploy, you just have to push your code over git. Something like this:
git push fort master
If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.
The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication
In case you use Spring Test try org.springframework.test.util.ReflectionTestUtils
ReflectionTestUtils.setField(testObject, "person", mockedPerson);
The <ul>
element has browser inherent padding & margin by default. In your case, Use
#footer ul {
margin: 0; /* To remove default bottom margin */
padding: 0; /* To remove default left padding */
}
or a CSS browser reset ( https://cssreset.com/ ) to deal with this.
If you are seeing(3 messages are hidden by filters. Show all messages.) then click on show all message link in Chrome dev tool console.
Because if this option enabled by mistake the console.log("")
message will show but this will in in hidden state.
I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:
Some modern browsers (Firefox, Safari, and Opera, but not Chrome) support the special "back/forward" cache (I'll call it bfcache, which is a term invented by Mozilla), involved when the user navigates Back. Unlike the regular (HTTP) cache, it captures the complete state of the page (including the state of JS, DOM). This allows it to re-load the page quicker and exactly as the user left it.
The load
event is not supposed to fire when the page is loaded from this bfcache. For example, if you created your UI in the "load" handler, and the "load" event was fired once on the initial load, and the second time when the page was re-loaded from the bfcache, the page would end up with duplicate UI elements.
This is also why adding the "unload" handler stops the page from being stored in the bfcache (thus making it slower to navigate back to) -- the unload handler could perform clean-up tasks, which could leave the page in unworkable state.
For pages that need to know when they're being navigated away/back to, Firefox 1.5+ and the version of Safari with the fix for bug 28758 support special events called "pageshow" and "pagehide".
References:
I don't know any MATLAB and I've never used it, but it seems to me you are dividing. Why? Something like this will be much faster:
d = 1/norm(V)
V1 = V * d
You can add position: fixed;
with top left right bottom 0
attribute, that solution work on older browsers too.
If you want to embed it, add position: absolute;
to the wrapper, and position: relative
to the div outside of the wrapper.
.wrapper {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
_x000D_
display: grid;_x000D_
border-style: solid;_x000D_
border-color: red;_x000D_
grid-template-columns: repeat(3, 1fr);_x000D_
grid-template-rows: repeat(3, 1fr);_x000D_
grid-gap: 10px;_x000D_
}_x000D_
.one {_x000D_
border-style: solid;_x000D_
border-color: blue;_x000D_
grid-column: 1 / 3;_x000D_
grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
border-style: solid;_x000D_
border-color: yellow;_x000D_
grid-column: 2 / 4;_x000D_
grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
border-style: solid;_x000D_
border-color: violet;_x000D_
grid-row: 2 / 5;_x000D_
grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
border-style: solid;_x000D_
border-color: aqua;_x000D_
grid-column: 3;_x000D_
grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
border-style: solid;_x000D_
border-color: green;_x000D_
grid-column: 2;_x000D_
grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
border-style: solid;_x000D_
border-color: purple;_x000D_
grid-column: 3;_x000D_
grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
<div class="one">One</div>_x000D_
<div class="two">Two</div>_x000D_
<div class="three">Three</div>_x000D_
<div class="four">Four</div>_x000D_
<div class="five">Five</div>_x000D_
<div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
And many lines may look like this. The html here is sample only.
var div = document.createElement("div");
div.innerHTML =
'<div class="slideshow-container">\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">1 / 3</div>\n' +
'<img src="image1.jpg" style="width:100%">\n' +
'<div class="text">Caption Text</div>\n' +
'</div>\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">2 / 3</div>\n' +
'<img src="image2.jpg" style="width:100%">\n' +
'<div class="text">Caption Two</div>\n' +
'</div>\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">3 / 3</div>\n' +
'<img src="image3.jpg" style="width:100%">\n' +
'<div class="text">Caption Three</div>\n' +
'</div>\n' +
'<a class="prev" onclick="plusSlides(-1)">❮</a>\n' +
'<a class="next" onclick="plusSlides(1)">❯</a>\n' +
'</div>\n' +
'<br>\n' +
'<div style="text-align:center">\n' +
'<span class="dot" onclick="currentSlide(1)"></span> \n' +
'<span class="dot" onclick="currentSlide(2)"></span> \n' +
'<span class="dot" onclick="currentSlide(3)"></span> \n' +
'</div>\n';
document.body.appendChild(div);
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i) {
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
var a = $('<a/>')
.addClass('ui-all')
.text( this )
.appendTo(li);
});
You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml
The most common type are:
Type application
application/java-archive
application/EDI-X12
application/EDIFACT
application/javascript
application/octet-stream
application/ogg
application/pdf
application/xhtml+xml
application/x-shockwave-flash
application/json
application/ld+json
application/xml
application/zip
application/x-www-form-urlencoded
Type audio
audio/mpeg
audio/x-ms-wma
audio/vnd.rn-realaudio
audio/x-wav
Type image
image/gif
image/jpeg
image/png
image/tiff
image/vnd.microsoft.icon
image/x-icon
image/vnd.djvu
image/svg+xml
Type multipart
multipart/mixed
multipart/alternative
multipart/related (using by MHTML (HTML mail).)
multipart/form-data
Type text
text/css
text/csv
text/html
text/javascript (obsolete)
text/plain
text/xml
Type video
video/mpeg
video/mp4
video/quicktime
video/x-ms-wmv
video/x-msvideo
video/x-flv
video/webm
Type vnd :
application/vnd.android.package-archive
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.graphics
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.mozilla.xul+xml
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {_x000D_
var target = $(e.target).attr("href") // activated tab_x000D_
alert(target);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="myTab" class="nav nav-tabs">_x000D_
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>_x000D_
<li class=""><a href="#profile" data-toggle="tab">Profile</a></li>_x000D_
</ul>_x000D_
<div id="myTabContent" class="tab-content">_x000D_
<div class="tab-pane fade active in" id="home">_x000D_
home tab!_x000D_
</div>_x000D_
<div class="tab-pane fade" id="profile">_x000D_
profile tab!_x000D_
</div>_x000D_
</div>
_x000D_
.h files, or header files, are used to list the publicly accessible instance variables and and methods in the class declaration. .cpp files, or implementation files, are used to actually implement those methods and use those instance variables.
The reason they are separate is because .h files aren't compiled into binary code while .cpp files are. Take a library, for example. Say you are the author and you don't want it to be open source. So you distribute the compiled binary library and the header files to your customers. That allows them to easily see all the information about your library's classes they can use without being able to see how you implemented those methods. They are more for the people using your code rather than the compiler. As was said before: it's the convention.
You probably need to change your mount command from:
[root@localhost Desktop]# sudo mount -t vboxsf D:\share_folder_vm \share_folder
to:
[root@localhost Desktop]# sudo mount -t vboxsf share_name \share_folder
where share_name is the "Name" of the share in the VirtualBox -> Shared Folders -> Folder List list box. The argument you have ("D:\share_folder_vm") is the "Path" of the share on the host, not the "Name".
If you are using dj-database-url check the schema in your DATABASES
https://github.com/kennethreitz/dj-database-url
MySQL is
'default': dj_database_url.config(default='mysql://USER:PASSWORD@localhost:PORT/NAME')
It solves the same error even without the PORT
You set the password with:
mysql -u user -p
When Steve Wozniak built his first Apple II he liked to show it off with a Breakout game in Apple Basic, typed in on the spot. I think it actually was around 10 lines; I wish I had it to paste in here. You could probably also do it in a system like Processing.
To create a new branch (locally):
With the commit hash (or part of it)
git checkout -b new_branch 6e559cb
or to go back 4 commits from HEAD
git checkout -b new_branch HEAD~4
Once your new branch is created (locally), you might want to replicate this change on a remote of the same name: How can I push my changes to a remote branch
For discarding the last three commits, see Lunaryorn's answer below.
For moving your current branch HEAD to the specified commit without creating a new branch, see Arpiagar's answer below.
You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.
var testDateUtc = moment.utc("2015-01-30 10:00:00");
var localDate = moment(testDateUtc).local();
From there you can use any of the functions you might expect:
var s = localDate.format("YYYY-MM-DD HH:mm:ss");
var d = localDate.toDate();
// etc...
Note that by passing testDateUtc
, which is a moment
object, back into the moment()
constructor, it creates a clone. Otherwise, when you called .local()
, it would also change the testDateUtc
value, instead of just the localDate
value. Moments are mutable.
Also note that if your original input contains a time zone offset such as +00:00
or Z
, then you can just parse it directly with moment
. You don't need to use .utc
or .local
. For example:
var localDate = moment("2015-01-30T10:00:00Z");
$(function() {
$("#MyTextBox").blur();
});
Try this:
System.Reflection.Assembly.GetExecutingAssembly()
This returns you a System.Reflection.Assembly
instance that has all the data you could ever want to know about the current application. I think that the Location
property might get what you are after specifically.
myDbContext.Database.SetCommandTimeout(999);
Where myDbContext is your DbContext instance, and 999 is the timeout value in seconds.
(Syntax current as of Entity Framework Core 3.1)
Try this:
DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
.AddSeconds(-DateTime.Now.Second);
Output will be like:
07/29/2015 00:00:00
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
There are many ways to move repositories around, git bundle
is a nice way if you have insufficient network availability. Since a Git repository is really just a directory full of files, you can "clone" a repository by making a copy of the .git
directory in whatever way suits you best.
The most efficient way is to use an external repository somewhere (use GitHub or set up Gitosis), and then git push
.
You might find it easier to understand by using a simple subquery
SELECT `settings`.*, (
SELECT `value` FROM `character_settings`
WHERE `character_settings`.`setting_id` = `settings`.`id`
AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`
The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.
Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.
SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'
The client_id
and client_secret
, by default, should go in the Authorization header, not the form-urlencoded body.
client_id
and client_secret
, with a colon between them: [email protected]:12345678
.YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==
Authorization: Basic YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==