Just to close this
foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Changes to this
foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
//textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
textBox3.Text += string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
First of all, your description is misleading. Double
is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:
$s = sprintf('%02d', $digit);
For more information, refer to the documentation of sprintf
.
So nicer with Kotlin suger:
private fun isSomePackageInstalled(context: Context, packageName: String): Boolean {
val packageManager = context.packageManager
return runCatching { packageManager.getPackageInfo(packageName, 0) }.isSuccess
}
create or replace procedure delete_duplicate_enq as
cursor c1 is
select *
from enquiry;
begin
for z in c1 loop
delete enquiry
where enquiry.enquiryno = z.enquiryno
and rowid > any
(select rowid
from enquiry
where enquiry.enquiryno = z.enquiryno);
end loop;
end delete_duplicate_enq;
Return true if the input year is a leap year
Basic modern day code:
If year mod 4 = 0, then leap year
if year mod 100 then normal year
if year mod 400 then leap year
else normal year
Todays rule started 1582 AD Julian calendar rule with every 4th year started 46BC but is not coherent before 10 AD as declared by Cesar. They did however add some leap years every 3rd year now and then in the years before: Leap years were therefore 45 BC, 42 BC, 39 BC, 36 BC, 33 BC, 30 BC, 27 BC, 24 BC, 21 BC, 18 BC, 15 BC, 12 BC, 9 BC, 8 AD, 12 AD Before year 45BC leap year was not added.
The year 0 do not exist as it is ...2BC 1BC 1AD 2AD... for some calculation this can be an issue.
function isLeapYear(year: Integer): Boolean;
begin
result := false;
if year > 1582 then // Todays calendar rule was started in year 1582
result := ((year mod 4 = 0) and (not(year mod 100 = 0))) or (year mod 400 = 0)
else if year > 10 then // Between year 10 and year 1582 every 4th year was a leap year
result := year mod 4 = 0
else //Between year -45 and year 10 only certain years was leap year, every 3rd year but the entire time
case year of
-45, -42, -39, -36, -33, -30, -27, -24, -21, -18, -15, -12, -9:
result := true;
end;
end;
This is the best solution I came up with taking hints from @Vinayak's answer. All the other solutions have different drawbacks.
First of all create a function like this.
void addClickEffect(View view)
{
Drawable drawableNormal = view.getBackground();
Drawable drawablePressed = view.getBackground().getConstantState().newDrawable();
drawablePressed.mutate();
drawablePressed.setColorFilter(Color.argb(50, 0, 0, 0), PorterDuff.Mode.SRC_ATOP);
StateListDrawable listDrawable = new StateListDrawable();
listDrawable.addState(new int[] {android.R.attr.state_pressed}, drawablePressed);
listDrawable.addState(new int[] {}, drawableNormal);
view.setBackground(listDrawable);
}
Explanation:
getConstantState().newDrawable() is used to clone the existing Drawable otherwise the same drawable will be used. Read more from here: Android: Cloning a drawable in order to make a StateListDrawable with filters
mutate() is used to make the Drawable clone not share its state with other instances of Drawable. Read more about it here: https://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()
Usage:
You can pass any type of View (Button, ImageButton, View etc) as the parameter to the function and they will get the click effect applied to them.
addClickEffect(myButton);
addClickEffect(myImageButton);
tty: teletype. Usually refers to the serial ports of a computer, to which terminals were attached.
pty: pseudoteletype. Kernel provided pseudoserial port connected to programs emulating terminals, such as xterm, or screen.
It's known issue that passing shared_ptr by value has a cost and should be avoided if possible.
The cost of passing by shared_ptr
Most of the time passing shared_ptr by reference, and even better by const reference, would do.
The cpp core guideline has a specific rule for passing shared_ptr
R.34: Take a shared_ptr parameter to express that a function is part owner
void share(shared_ptr<widget>); // share -- "will" retain refcount
An example of when passing shared_ptr by value is really necessary is when the caller passes a shared object to an asynchronous callee - ie the caller goes out of scope before the callee completes its job. The callee must "extend" the lifetime of the shared object by taking a share_ptr by value. In this case, passing a reference to shared_ptr won't do.
The same goes for passing a shared object to a work thread.
There is the potential for a subtle bug in your code.
[UPDATE: Since he's using map.remove() this description isn't totally valid. I missed that fact the first time thru. :( Thanks to the question's author for pointing that out. I'm leaving the rest as is, but changed the lead statement to say there is potentially a bug.]
In doWork() you get the List value from the Map in a thread-safe way. Afterward, however, you are accessing that list in an unsafe matter. For instance, one thread may be using the list in doWork() while another thread invokes synchronizedMap.get(key).add(value) in addToMap(). Those two access are not synchronized. The rule of thumb is that a collection's thread-safe guarantees don't extend to the keys or values they store.
You could fix this by inserting a synchronized list into the map like
List<String> valuesList = new ArrayList<String>();
valuesList.add(value);
synchronizedMap.put(key, Collections.synchronizedList(valuesList)); // sync'd list
Alternatively you could synchronize on the map while you access the list in doWork():
public void doWork(String key) {
List<String> values = null;
while ((values = synchronizedMap.remove(key)) != null) {
synchronized (synchronizedMap) {
//do something with values
}
}
}
The last option will limit concurrency a bit, but is somewhat clearer IMO.
Also, a quick note about ConcurrentHashMap. This is a really useful class, but is not always an appropriate replacement for synchronized HashMaps. Quoting from its Javadocs,
This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.
In other words, putIfAbsent() is great for atomic inserts but does not guarantee other parts of the map won't change during that call; it guarantees only atomicity. In your sample program, you are relying on the synchronization details of (a synchronized) HashMap for things other than put()s.
Last thing. :) This great quote from Java Concurrency in Practice always helps me in designing an debugging multi-threaded programs.
For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held.
I had the same problem. The problem with the Sublime Text's default console is that it does not support input.
To solve it, you have to install a package called SublimeREPL. SublimeREPL provides a Python interpreter which accepts input.
There is an article that explains the solution in detail.
We can hide close button on form by setting this.ControlBox=false;
Note that this hides all of those sizing buttons. Not just the X. In some cases that may be fine.
Ditto for @Andreas_D, in addition if you say update Spring from 1 version to another in your project without doing a clean, you'll wind up with both in your artifact. Ran into this a lot when doing Flex development with Maven.
Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.
I see most people confused about tf.shape(tensor)
and tensor.get_shape()
Let's make it clear:
tf.shape
tf.shape
is used for dynamic shape. If your tensor's shape is changable, use it.
An example: a input is an image with changable width and height, we want resize it to half of its size, then we can write something like:
new_height = tf.shape(image)[0] / 2
tensor.get_shape
tensor.get_shape
is used for fixed shapes, which means the tensor's shape can be deduced in the graph.
Conclusion:
tf.shape
can be used almost anywhere, but t.get_shape
only for shapes can be deduced from graph.
Try doing this instead:
function enable(id)
{
var eleman = document.getElementById(id);
eleman.removeAttribute("disabled");
}
To enable an element you have to remove the disabled attribute. Setting it to false still means it is disabled.
Like other answers I set org.gradle.java.home property in gradle.properties file. But path with \ separators did not work (building on windows 10):
Java home supplied via 'org.gradle.java.home' is invalid. Invalid directory: C:Program FilesJavajdk1.8.0_65
So instead of
org.gradle.java.home=C:\Program Files\Java\jdk1.8.0_65
i had to use
org.gradle.java.home=C:/Program Files/Java/jdk1.8.0_65
then the build was successful
Problem is that project is build with JRE instead of JDK and since I was building it from eclipse this also worked:
Go to Run type services.msc
. Check whether MySQL services is running or not. If not, start it manually. Once it started, type mysqlshow
to test the service.
If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.
Something like:
$("#fbss").keypress(function() {
if($(this).val().length > 1) {
// Enable submit button
} else {
// Disable submit button
}
});
You can do:
getMap(locations.toArray(new WorldLocation[locations.size()]));
or
getMap(locations.toArray(new WorldLocation[0]));
or
getMap(new WorldLocation[locations.size()]);
@SuppressWarnings("unchecked")
is needed to remove the ide warning.
I have constructed a simple self checking php file, it only allows real loading by humans, and not robots like ( online source code viewer's ) ..
I'm not sure about View Source from Chrome, but it does block access to the html... Not just obfuscation, it uses a bounce back submittance to validate loads.
The short code was still visible in source viewers, so i obfuscated it also...
The page is loaded and bounces back, the bounce gets the real page, not the loader !
// Create A New File called ( lock.php )
Copy this into it....
<?php
// PAGE SOURCE GUARD by Elijah Cuff.
if (!hasParam('bounce'))
{
echo "
<script type='text/javascript'>
<!--
eval(unescape('%66%75%6e%63%74%69%6f%6e%20%63%36%36%32%32%30%36%62%32%63%28%73%29%20%7b%0a%09%76%61%72%20%72%20%3d%20%22%22%3b%0a%09%76%61%72%20%74%6d%70%20%3d%20%73%2e%73%70%6c%69%74%28%22%37%36%33%33%31%37%31%22%29%3b%0a%09%73%20%3d%20%75%6e%65%73%63%61%70%65%28%74%6d%70%5b%30%5d%29%3b%0a%09%6b%20%3d%20%75%6e%65%73%63%61%70%65%28%74%6d%70%5b%31%5d%20%2b%20%22%35%37%35%31%36%35%22%29%3b%0a%09%66%6f%72%28%20%76%61%72%20%69%20%3d%20%30%3b%20%69%20%3c%20%73%2e%6c%65%6e%67%74%68%3b%20%69%2b%2b%29%20%7b%0a%09%09%72%20%2b%3d%20%53%74%72%69%6e%67%2e%66%72%6f%6d%43%68%61%72%43%6f%64%65%28%28%70%61%72%73%65%49%6e%74%28%6b%2e%63%68%61%72%41%74%28%69%25%6b%2e%6c%65%6e%67%74%68%29%29%5e%73%2e%63%68%61%72%43%6f%64%65%41%74%28%69%29%29%2b%2d%36%29%3b%0a%09%7d%0a%09%72%65%74%75%72%6e%20%72%3b%0a%7d%0a'));
eval(unescape('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%63%36%36%32%32%30%36%62%32%63%28%27') + '%47%67%7f%76%73%44%15%15%45%69%74%7e%76%23%7a%6e%7f%6f%75%6c%46%2f%73%74%7f%7f%2d%2f%6a%6f%42%28%7e%62%7a%2d%45%15%15%47%66%71%73%7a%7a%20%7f%78%73%6a%45%2d%6b%66%6f%6f%6a%74%2e%23%73%62%72%6d%46%2d%61%70%7e%75%69%6d%2d%21%79%66%74%7e%6e%4a%2d%32%29%44%44%30%68%71%77%7d%7f%41%1a%15%47%34%6c%73%7d%74%41%12%16%47%7c%60%7d%6a%77%7a%42%16%17%23%7c%69%71%6f%7c%78%31%78%6b%7c%5f%68%76%6a%73%7e%7f%27%69%7e%75%69%7c%6a%72%71%2f%29%23%84%1a%15%23%6b%75%6f%7e%74%6e%75%7c%31%68%62%7f%4e%73%6b%75%6e%73%7f%49%79%4a%6f%27%67%28%79%67%7b%67%2a%2a%35%7f%7e%6d%7a%6a%7f%2f%2f%47%16%17%23%27%85%37%23%33%33%33%2e%41%15%15%45%30%78%6f%7d%6a%7f%7f%41%12%10%44%30%69%7f%72%74%417633171%35%39%35%35%31%30%36' + unescape('%27%29%29%3b'));
// -->
</script>
<noscript><i>Javascript required</i></noscript>
";
exit;
}
function hasParam($param)
{
return isset($_POST[$param]);
}
?>
NOW ADD THIS TO THE VERY TOP OF
EVERY PAGE .. Example....
<?php
// use require for more security...
include('lock.php');
?>
<HTML>
etc.. etc...
I think that what happens is this:
focus()
UI tasks related to pre-focus
callbacks
select()
UI tasks related to focus (which unselect again)
A workaround may be calling the select() asynchronously, so that it runs completely after focus():
$("input[type=text]").focus(function() {
var save_this = $(this);
window.setTimeout (function(){
save_this.select();
},100);
});
Recently I was playing with this method too. I wrote a memoized algorithm to calcualte Fibonacci numbers which could serve as another illustration on how to use the method.
We can start by defining a map and putting the values in it for the base cases, namely, fibonnaci(0)
and fibonacci(1)
:
private static Map<Integer,Long> memo = new HashMap<>();
static {
memo.put(0,0L); //fibonacci(0)
memo.put(1,1L); //fibonacci(1)
}
And for the inductive step all we have to do is redefine our Fibonacci function as follows:
public static long fibonacci(int x) {
return memo.computeIfAbsent(x, n -> fibonacci(n-2) + fibonacci(n-1));
}
As you can see, the method computeIfAbsent
will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map. This represents a significant improvement over the traditional, tree recursive algorithm.
A very portable version (even to legacy bourne shell):
if [ "$varA" = 1 -a \( "$varB" = "t1" -o "$varB" = "t2" \) ]
then do-something
fi
This has the additional quality of running only one subprocess at most (which is the process [
), whatever the shell flavor.
Replace =
with -eq
if variables contain numeric values, e.g.
3 -eq 03
is true, but3 = 03
is false. (string comparison)Microsoft Visual C++ Compiler for Python 2.7
from https://www.microsoft.com/en-in/download/details.aspx?id=44266 - this package contains the compiler and set of system headers necessary for producing binary wheels for Python 2.7 packages.pip install ez_setup
pip install unroll
(It will start installing numpy, music21, decorator, imageio, tqdm, moviepy, unroll
) # Please be patient for music21
installationPython 2.7.11 64 bit used
I'd thoroughly recommend reading the articles Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes [dead link, copy at the Internet Archive] and How To Safely Store A Password.
Lots of coders, myself included, think they understand security and hashing. Sadly most of us just don't.
The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
UPDATE:
As written in this answer,
Stackdriver Logging is the preferred method of logging now.
Use console.log()
to log to Stackdriver.
Logger.log
will either send you an email (eventually) of errors that have happened in your scripts, or, if you are running things from the Script Editor
, you can view the log from the last run function by going to View->Logs
(still in script editor). Again, that will only show you anything that was logged from the last function you ran from inside Script Editor
.
The script I was trying to get working had to do with spreadsheets - I made a spreadsheet todo-checklist type thing that sorted items by priorities and such.
The only triggers I installed for that script were the onOpen and onEdit triggers. Debugging the onEdit trigger was the hardest one to figure out, because I kept thinking that if I set a breakpoint in my onEdit function, opened the spreadsheet, edited a cell, that my breakpoint would be triggered. This is not the case.
To simulate having edited a cell, I did end up having to do something in the actual spreadsheet though. All I did was make sure the cell that I wanted it to treat as "edited" was selected, then in Script Editor
, I would go to Run->onEdit
. Then my breakpoint would be hit.
However, I did have to stop using the event argument that gets passed into the onEdit function - you can't simulate that by doing Run->onEdit
. Any info I needed from the spreadsheet, like which cell was selected, etc, I had to figure out manually.
Anyways, long answer, but I figured it out eventually.
EDIT:
If you want to see the todo checklist I made, you can check it out here
(yes, I know anybody can edit it - that's the point of sharing it!)
I was hoping it'd let you see the script as well. Since you can't see it there, here it is:
function onOpen() {
setCheckboxes();
};
function setCheckboxes() {
var checklist = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("checklist");
var checklist_data_range = checklist.getDataRange();
var checklist_num_rows = checklist_data_range.getNumRows();
Logger.log("checklist num rows: " + checklist_num_rows);
var coredata = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("core_data");
var coredata_data_range = coredata.getDataRange();
for(var i = 0 ; i < checklist_num_rows-1; i++) {
var split = checklist_data_range.getCell(i+2, 3).getValue().split(" || ");
var item_id = split[split.length - 1];
if(item_id != "") {
item_id = parseInt(item_id);
Logger.log("setting value at ("+(i+2)+",2) to " + coredata_data_range.getCell(item_id+1, 3).getValue());
checklist_data_range.getCell(i+2,2).setValue(coredata_data_range.getCell(item_id+1, 3).getValue());
}
}
}
function onEdit() {
Logger.log("TESTING TESTING ON EDIT");
var active_sheet = SpreadsheetApp.getActiveSheet();
if(active_sheet.getName() == "checklist") {
var active_range = SpreadsheetApp.getActiveSheet().getActiveRange();
Logger.log("active_range: " + active_range);
Logger.log("active range col: " + active_range.getColumn() + "active range row: " + active_range.getRow());
Logger.log("active_range.value: " + active_range.getCell(1, 1).getValue());
Logger.log("active_range. colidx: " + active_range.getColumnIndex());
if(active_range.getCell(1,1).getValue() == "?" || active_range.getCell(1,1).getValue() == "?") {
Logger.log("made it!");
var next_cell = active_sheet.getRange(active_range.getRow(), active_range.getColumn()+1, 1, 1).getCell(1,1);
var val = next_cell.getValue();
Logger.log("val: " + val);
var splits = val.split(" || ");
var item_id = splits[splits.length-1];
Logger.log("item_id: " + item_id);
var core_data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("core_data");
var sheet_data_range = core_data.getDataRange();
var num_rows = sheet_data_range.getNumRows();
var sheet_values = sheet_data_range.getValues();
Logger.log("num_rows: " + num_rows);
for(var i = 0; i < num_rows; i++) {
Logger.log("sheet_values[" + (i) + "][" + (8) + "] = " + sheet_values[i][8]);
if(sheet_values[i][8] == item_id) {
Logger.log("found it! tyring to set it...");
sheet_data_range.getCell(i+1, 2+1).setValue(active_range.getCell(1,1).getValue());
}
}
}
}
setCheckboxes();
};
One reason: the literal 0
has a bad tendency to acquire the type int
, e.g. in perfect argument forwarding or more in general as argument with templated type.
Another reason: readability and clarity of code.
Try either killall -15 mongod/ killall mongod Even after this if this doesnt work then remove the db storage folder by typing the following commands sudo rm -rf /data/db sudo mkdir /data/db sudo chmod 777 /data/db
Although the answers are 100% correct, a small suggestion to improve null
case handling of the list itself with Optional:
List<String> listOfStuffFiltered = Optional.ofNullable(listOfStuff)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
The part Optional.ofNullable(listOfStuff).orElseGet(Collections::emptyList)
will allow you to handle nicely the case when listOfStuff
is null and return an emptyList instead of failing with NullPointerException.
Short and sweet. This was my solution when doing codeAcademy course. Prints a string in rev order.
def reverse(text):
string = ""
for i in range(len(text)-1,-1,-1):
string += text[i]
return string
Use test()
method :
var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
Let's say you stage
a whole directory via git add <folder>
, but you want to exclude a file from the staged list (i.e. the list that generates when running git status
) and keep the modifications within the excluded file (you were working on something and it's not ready for commit, but you don't want to lose your work...). You could simply use:
git reset <file>
When you run git status
, you will see that whatever file(s) you reset
are unstaged
and the rest of the files you added
are still in the staged
list.
Use ampersand to specify the parent selector.
SCSS syntax:
p {
margin: 2em auto;
> a {
color: red;
}
&:before {
content: "";
}
&:after {
content: "* * *";
}
}
You didn't join the table in your query.
Your original query will always return nothing unless there are no records at all in eotm_dyn
, in which case it will return everything.
Assuming these tables should be joined on employeeID
, use the following:
SELECT *
FROM employees e
WHERE NOT EXISTS
(
SELECT null
FROM eotm_dyn d
WHERE d.employeeID = e.id
)
You can join these tables with a LEFT JOIN
keyword and filter out the NULL
's, but this will likely be less efficient than using NOT EXISTS
.
Adding onto @demented hedgehog answer on using find()
In terms of efficiency
It may be worth first checking to see if s1 is in s2 before calling find()
.
This can be more efficient if you know that most of the times s1 won't be a substring of s2
Since the in
operator is very efficient
s1 in s2
It can be more efficient to convert:
index = s2.find(s1)
to
index = -1
if s1 in s2:
index = s2.find(s1)
This is useful for when find()
is going to be returning -1 a lot.
I found it substantially faster since find()
was being called many times in my algorithm, so I thought it was worth mentioning
Before I continue, I must warn you that itoa
is NOT an ANSI function — it's not a standard C function. You should use sprintf
to convert an int
into a string.
itoa
takes three arguments.
char *
variable, so you should pass in a normal sized char array and it will work fine.The function returns a pointer to its second argument — where it has stored the converted string.
itoa
is a very useful function, which is supported by some compilers - it's a shame it isn't support by all, unlike atoi
.
If you still want to use itoa
, here is how should you use it. Otherwise, you have another option using sprintf
(as long as you want base 8, 10 or 16 output):
char str[5];
printf("15 in binary is %s\n", itoa(15, str, 2));
There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).
Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.
Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.
Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
Left outer join - A left outer join will give all rows in A, plus any common rows in B.
Full outer join - A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versay
If you want multiple string replacement:
NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo
It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.
A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?
Settings > Applications > Unknown sources...
Edit
Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive
I usually prefer running my python scripts on python native IDLE interactive shell rather than from command prompt or something like that. I've tried it, and it works for me. Just open "Run > Run...", then paste the code below
python -m idlelib.idle -r "$(FULL_CURRENT_PATH)"
After that, you can save it with your hotkey.
You must ensure your desired python is added and registered in your environment variables.
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
At first check the type of columns which you want to merge. You will see one of them is string where other one is int
. Then convert it to int as following code:
df["something"] = df["something"].astype(int)
merged = df.merge[df1, on="something"]
It is an old thread, but in the current version (as of 1-feb-2017), it easy to replace datasets plotted on chart.js:
suppose your new x-axis values are in array x and y-axis values are in array y, you can use below code to update the chart.
var x = [1,2,3];
var y = [1,1,1];
chart.data.datasets[0].data = y;
chart.data.labels = x;
chart.update();
You have several options if you use BufferedReader
. This buffered reader is faster than Reader so you can wrap it.
BufferedReader reader = new BufferedReader(new FileReader(path));
reader.read(char[] buffer);
this reads line into char array. You have similar options. Look at documentation.
try to insert your img
inside your h4
DEMO
<h4 class='liketext'><img style='height: 24px; width: 24px; margin-right: 4px;' src='design/like.png'/>$likes</h4>
<h4 class='liketext'> <img style='height: 24px; width: 24px; margin-right: 4px;' src='design/dislike.png'/>$dislikes</h4>?
I had the exact same error but with slightly different format and root-cause, and since this is the first Q&A that pops up when you search for "time data does not match format", I thought I'd leave the mistake I made for future viewers:
My initial code:
start = datetime.strptime('05-SEP-19 00.00.00.000 AM', '%d-%b-%y %I.%M.%S.%f %p')
Where I used %I
to parse the hours and %p
to parse 'AM/PM'.
The error:
ValueError: time data '05-SEP-19 00.00.00.000000 AM' does not match format '%d-%b-%y %I.%M.%S.%f %p'
I was going through the datetime docs and finally realized in 12-hour format %I
, there is no 00... once I changed 00.00.00
to 12.00.00
, the problem was resolved.
So it's either 01-12 using %I
with %p
, or 00-23 using %H
.
Very well done and answered here - http://www.sitepoint.com/css3-transform-background-image/
#myelement:before
{
content: "";
position: absolute;
width: 200%;
height: 200%;
top: -50%;
left: -50%;
z-index: -1;
background: url(background.png) 0 0 repeat;
-webkit-transform: rotate(30deg);
-moz-transform: rotate(30deg);
-ms-transform: rotate(30deg);
-o-transform: rotate(30deg);
transform: rotate(30deg);
}
Sorry a bit late to the party and a bit surprised that nobody mentioned the drop method:
ex="test1, test2, test3, test4, test5"
ex.split(",").drop(1).join(",")
=> "test2,test3,test4,test5"
As others have said, CGFloat is a float on 32-bit systems and a double on 64-bit systems. However, the decision to do that was inherited from OS X, where it was made based on the performance characteristics of early PowerPC CPUs. In other words, you should not think that float is for 32-bit CPUs and double is for 64-bit CPUs. (I believe, Apple's ARM processors were able to process doubles long before they went 64-bit.) The main performance hit of using doubles is that they use twice the memory and therefore might be slower if you are doing a lot of floating point operations.
If I understand correctly you want to change the CSS style of an element by clicking an item in a ul
list. Am I right?
HTML:
<div class="results" style="background-color:Red;">
</div>
<ul class="colors-list">
<li>Red</li>
<li>Blue</li>
<li>#ffee99</li>
</ul>
jquery
$('.colors-list li').click(function(e){
var color = $(this).text();
$('.results').css('background-color',color);
});
Note that jquery can use addClass
, removeClass
and toggleClass
if you want to use classes rather than inline styling. This means that you can do something like that:
$('.results').addClass('selected');
And define the 'selected' styling in the CSS.
Working example: http://jsfiddle.net/uuJmP/
you can use enumerate keeping the ind/index of the elements is in vm, if you make vm
a set you will also have 0(1)
lookups:
vm = {-1, -1, -1, -1}
print([ind if q in vm else 9999 for ind,ele in enumerate(vm) ])
Also if you want to save some money you don't must buy a Mac. There is other ways how to do it:
1.) You can use practically any OS to run latest MacOS in virtual machine (look at YouTube). I am using this method really long time without any problems on windows with VMWare.
2.) Hackintosh. Install MacOS to your PC. You must have compatible components, but if you have, this is the best way, because you eliminate the lags in VM... I am using this in this time. Perfect. On my laptop, but please don't tell this to Apple, because practically this is illegal
3.) If you are making simple apps with minimum UI, you can use Theos. Also with Theos you can create cydia tweaks. Only one problem: codesign. If you want to publish app on App Store you still must have MacOS, but if you want to make app in home you can use CydiaImpactor to sign the apps with Apple ID.
I used all of this ways and all is working. By my VM is best solution if you don't want to spend lot of time by installing Hackintosh.
A very short solution I use to allow a header file to contain the extern reference or actual implementation of an object. The file that actually contains the object just does #define GLOBAL_FOO_IMPLEMENTATION
. Then when I add a new object to this file it shows up in that file also without me having to copy and paste the definition.
I use this pattern across multiple files. So in order to keep things as self contained as possible, I just reuse the single GLOBAL macro in each header. My header looks like this:
//file foo_globals.h
#pragma once
#include "foo.h" //contains definition of foo
#ifdef GLOBAL
#undef GLOBAL
#endif
#ifdef GLOBAL_FOO_IMPLEMENTATION
#define GLOBAL
#else
#define GLOBAL extern
#endif
GLOBAL Foo foo1;
GLOBAL Foo foo2;
//file main.cpp
#define GLOBAL_FOO_IMPLEMENTATION
#include "foo_globals.h"
//file uses_extern_foo.cpp
#include "foo_globals.h
You can use the DOMSubtreeModified event
$(something).bind('DOMSubtreeModified' ...
But this will fire even if the dimensions don't change, and reassigning the position whenever it fires can take a performance hit. In my experience using this method, checking whether the dimensions have changed is less expensive and so you might consider combining the two.
Or if you are directly altering the div (rather than the div being altered by user input in unpredictable ways, like if it is contentEditable), you can simply fire a custom event whenever you do so.
Downside: IE and Opera don't implement this event.
Can't hurt to post another view since there's still not an official way to do this. Wrote a lightweight jQuery plugin with which you can define a background radial gradient and a transition speed. This basic usage will then let it fade in, optimised with requestAnimationFrame (very smooth) :
$('#element').gradientFade({
duration: 2000,
from: '(20,20,20,1)',
to: '(120,120,120,0)'
});
http://codepen.io/Shikkediel/pen/xbRaZz?editors=001
Keeps original background and all properties intact. Also has highlight tracking as a setting :
I am using php 7.3.8 on a manjaro and I was working with Persian content. This solved my problem:
$html = 'hi</b><p>????<div>?????9 ?';
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
print $doc->saveHTML($doc->documentElement) . PHP_EOL . PHP_EOL;
This might not be appropriate for your application, but you could always try a native call (using jni or jna), or exec a platform-specific command and read the output before falling back to list().length. On *nix, you could exec ls -1a | wc -l
(note - that's dash-one-a for the first command, and dash-lowercase-L for the second). Not sure what would be right on windows - perhaps just a dir
and look for the summary.
Before bothering with something like this I'd strongly recommend you create a directory with a very large number of files and just see if list().length really does take too long. As this blogger suggests, you may not want to sweat this.
I'd probably go with Varkhan's answer myself.
for Ruby 1.9+ use colon.
gem install sinatra:1.4.4 prawn:0.13.0
Whilst not perfect, here's something I knocked up for TSQL - could be easily tweaked for other flavors... If nothing else it will give you a start point for your own improvements :)
This does an OK job on data types and output parameters etc similar to using "execute stored procedure" in SSMS. We mostly used SPs so the "text" command doesn't account for parameters etc
public static String ParameterValueForSQL(this SqlParameter sp)
{
String retval = "";
switch (sp.SqlDbType)
{
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.NText:
case SqlDbType.NVarChar:
case SqlDbType.Text:
case SqlDbType.Time:
case SqlDbType.VarChar:
case SqlDbType.Xml:
case SqlDbType.Date:
case SqlDbType.DateTime:
case SqlDbType.DateTime2:
case SqlDbType.DateTimeOffset:
retval = "'" + sp.Value.ToString().Replace("'", "''") + "'";
break;
case SqlDbType.Bit:
retval = (sp.Value.ToBooleanOrDefault(false)) ? "1" : "0";
break;
default:
retval = sp.Value.ToString().Replace("'", "''");
break;
}
return retval;
}
public static String CommandAsSql(this SqlCommand sc)
{
StringBuilder sql = new StringBuilder();
Boolean FirstParam = true;
sql.AppendLine("use " + sc.Connection.Database + ";");
switch (sc.CommandType)
{
case CommandType.StoredProcedure:
sql.AppendLine("declare @return_value int;");
foreach (SqlParameter sp in sc.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
sql.Append("declare " + sp.ParameterName + "\t" + sp.SqlDbType.ToString() + "\t= ");
sql.AppendLine(((sp.Direction == ParameterDirection.Output) ? "null" : sp.ParameterValueForSQL()) + ";");
}
}
sql.AppendLine("exec [" + sc.CommandText + "]");
foreach (SqlParameter sp in sc.Parameters)
{
if (sp.Direction != ParameterDirection.ReturnValue)
{
sql.Append((FirstParam) ? "\t" : "\t, ");
if (FirstParam) FirstParam = false;
if (sp.Direction == ParameterDirection.Input)
sql.AppendLine(sp.ParameterName + " = " + sp.ParameterValueForSQL());
else
sql.AppendLine(sp.ParameterName + " = " + sp.ParameterName + " output");
}
}
sql.AppendLine(";");
sql.AppendLine("select 'Return Value' = convert(varchar, @return_value);");
foreach (SqlParameter sp in sc.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
sql.AppendLine("select '" + sp.ParameterName + "' = convert(varchar, " + sp.ParameterName + ");");
}
}
break;
case CommandType.Text:
sql.AppendLine(sc.CommandText);
break;
}
return sql.ToString();
}
this generates output along these lines...
use dbMyDatabase;
declare @return_value int;
declare @OutTotalRows BigInt = null;
exec [spMyStoredProc]
@InEmployeeID = 1000686
, @InPageSize = 20
, @InPage = 1
, @OutTotalRows = @OutTotalRows output
;
select 'Return Value' = convert(varchar, @return_value);
select '@OutTotalRows' = convert(varchar, @OutTotalRows);
I have created a simple MySQL procedure as given below:
DELIMITER //
CREATE PROCEDURE GetAllListings()
BEGIN
SELECT nid, type, title FROM node where type = 'lms_listing' order by nid desc;
END //
DELIMITER;
Kindly follow this. After the procedure created, you can see the same and execute it.
There are several rules ( applied in this order ) :
!important
always takes precedence.In your case its rule 3 that applies.
Specificity for single selectors from highest to lowest:
#main
selects <div id="main">
).myclass
), attribute selectors (ex.: [href=^https:]
) and pseudo-classes (ex.: :hover
)div
) and pseudo-elements (ex.: ::before
)To compare the specificity of two combined selectors, compare the number of occurences of single selectors of each of the specificity groups above.
Example: compare #nav ul li a:hover
to #nav ul li.active a::after
#nav
):hover
and .active
)ul li a
) for the first and 4 for the second (ul li a ::after
), thus the second combined selector is more specific.You need to add a name
attribute.
Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3
.
In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]
) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.
Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs
For PHP you can use:
<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
Sometimes I prefer dynamic objects:
public JsonResult GetJson()
{
string res;
WebClient client = new WebClient();
// Download string
string value = client.DownloadString("https://api.instagram.com/v1/users/000000000/media/recent/?client_id=clientId");
// Write values
res = value;
dynamic dyn = JsonConvert.DeserializeObject(res);
var lstInstagramObjects = new List<InstagramModel>();
foreach(var obj in dyn.data)
{
lstInstagramObjects.Add(new InstagramModel()
{
Link = (obj.link != null) ? obj.link.ToString() : "",
VideoUrl = (obj.videos != null) ? obj.videos.standard_resolution.url.ToString() : "",
CommentsCount = int.Parse(obj.comments.count.ToString()),
LikesCount = int.Parse(obj.likes.count.ToString()),
CreatedTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((double.Parse(obj.created_time.ToString()))),
ImageUrl = (obj.images != null) ? obj.images.standard_resolution.url.ToString() : "",
User = new InstagramModel.UserAccount()
{
username = obj.user.username,
website = obj.user.website,
profile_picture = obj.user.profile_picture,
full_name = obj.user.full_name,
bio = obj.user.bio,
id = obj.user.id
}
});
}
return Json(lstInstagramObjects, JsonRequestBehavior.AllowGet);
}
Context: I was having a similar issue "Command CompileStoryboard failed with a nonzero exit code" after trying to build an iOS flutter app with the latest and Android studio and XCode 11.3 (new installation on Mojave). This was an existing flutter android app I had built with Android studio on Windows 10.
Tried and failed: Command+Shift+K, Command+B, Delete Derived data, SWIFT_ENABLE_BATCH_MODE = NO
Solution: - Open Finder and Navigate to project name > ios > Runner > Base.Iproj - Delete .storyboard files (main and launch) - Open terminal and run "flutter create ." - Open Xcode and run
The best answer to the question should be "As an employee, it's important I write it so that my meaning is clear while maintaining efficiency where necessary for performance." Here's how I'd write it:
function atLeastTwoAreTrue(a, b, c) {
return (a && b) || (b && c) || (a && c);
}
In reality, the test is so contrived that writing a method that's the fastest, most cryptic possible is perfect acceptable if you accomodate it with a simple comment. But, in general, in this one-liner world, we need more readable code in this world. :-)
Can someone point to an RFC indicating that a URL with a space must be encoded?
URIs, and thus URLs, are defined in RFC 3986.
If you look at the grammar defined over there you will eventually note that a space character never can be part of a syntactically legal URL, thus the term "URL with a space" is a contradiction in itself.
There is no such thing as an int
in Javascript. All Numbers
are actually doubles behind the scenes* so you can't rely on the type system to issue a rounding order for you as you can in C or C#.
You don't need to worry about precision issues (since doubles correctly represent any integer up to 2^53) but you really are stuck with using Math.floor (or other equivalent tricks) if you want to round to the nearest integer.
*Most JS engines use native ints when they can but all in all JS numbers must still have double semantics.
The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept="image/png". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you might have to accept a generic MIME type.
Additionally, it appears that most browsers may not honor this attribute.
The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.
Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is ".drp". This is probably going to be much more supported than the accept attribute.
Well, first you need to request the username of the user from the session in your controller action like this:
$username=$this->get('security.context')->getToken()->getUser()->getUserName();
then do a query to the db and get your object with regular dql like
$em = $this->get('doctrine.orm.entity_manager');
"SELECT u FROM Acme\AuctionBundle\Entity\User u where u.username=".$username;
$q=$em->createQuery($query);
$user=$q->getResult();
the $user should now hold the user with this username ( you could also use other fields of course)
...but you will have to first configure your /app/config/security.yml configuration to use the appropriate field for your security provider like so:
security:
provider:
example:
entity: {class Acme\AuctionBundle\Entity\User, property: username}
hope this helps!
This is a warning for usual. You can either disable it by
#pragma warning(disable:4996)
or simply use fopen_s like Microsoft has intended.
But be sure to use the pragma before other headers.
client text protocol
POST http://127.0.0.1/bom/create HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.25.0
Accept: */*
Postman-Token: 50ecfbfe-741f-4a2b-a3d3-cdf162ada27f
Host: 127.0.0.1
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 405
{
"fwoid": 1,
"list": [
{
"bomIndex": "10001",
"desc": "?GH 1.25 13pin ???? ??",
"pn": "084.0001.0036",
"preUse": 1,
"type": "?? ???-??PCB??"
},
{
"bomIndex": "10002",
"desc": "????-?????",
"pn": "Z.08.013.0051",
"preUse": 1,
"type": "E060A0302301"
}
]
}
HTTP/1.1 200 OK
Connection: keep-alive
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: application/json
Date: Mon, 01 Jun 2020 11:23:42 GMT
Content-Length: 40
{"code":"0","message":"BOM????"}
a springboot Controller code as below:
@PostMapping("/bom/create")
@ApiOperation(value = "??BOM")
@BusinessOperation(module = "BOM",methods = "??BOM")
public JsonResult save(@RequestBody BOMSaveQuery query)
{
return bomService.saveBomList(query);
}
when i debug on loopback interface,it works ok. while deploy on internet server via bat command, i got an error
ServletInvocableHandlerMethod - Could not resolve parameter [0] in public XXXController.save(com.h2.mes.query.BOMSaveQuery): JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] WARN o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])]
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - Completed 400 BAD_REQUEST
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - "ERROR" dispatch for POST "/error", parameters={}
add a jvm arguement works for me. java -Dfile.encoding=UTF-8
You need to use absolutely-positioned CSS over a relatively-positioned img
tag. The article Text Blocks Over Image gives a step-by-step example for placing text over an image.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
This is the important plugin that should be in pom.xml. I spent my two days debugging and researching. This was the solution. This is Apache plugin to tell maven to use the the given Compiler.
If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.
The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html
private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
public int compare(String str1, String str2) {
return ComparisonChain.start().
compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
compare(str1,str2).
result();
}
};
Collections.sort(list, stringAlphabeticalComparator);
The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:
"AA","Aa","aa","Development","development"
If you want to open binary files (in CentOS 7):
strings <binary_filename>
I guess you probably are running the preview of VS2013 Ultimate, because it is not present in my professional preview. But looking online I found that the feature is called Code Information Indicators
or CodeLens
, and can be located under
Tools ? Options ? Text Editor ? All Languages ? CodeLens
(for RC/final version)
or
Tools ? Options ? Text Editor ? All Languages ? Code Information Indicators
(for preview version)
That was according to this link. It seems to be pretty well hidden.
In Visual Studio 2013 RTM, you can also get to the CodeLens options by right clicking the indicators themselves in the editor:
documented in the Q&A section of the msdn CodeLens documentation
I do the following in my application:
Process process = new Process();
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = arguments;
process.StartInfo.ErrorDialog = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
process.Start();
process.WaitForExit(1000 * 60 * 5); // Wait up to five minutes.
There are a few extra features in there which you might find useful...
You can use the CSS Toggle Switch library. Just include the CSS and program the JS yourself: http://ghinda.net/css-toggle-switch/bootstrap.html
for (int i=0;i<word.length();i++){
int counter=0;
for (int j=0;j<word.length();j++){
if(word.charAt(i)==word.charAt(j))
counter++;
}// inner for
JOptionPane.showMessageDialog( null,word.charAt(i)+" found "+ counter +" times");
}// outer for
In Excel VBA, this function will give you the content of any cell in any worksheet.
Function getCellContent(Byref ws As Worksheet, ByVal rowindex As Integer, ByVal colindex As Integer) as String
getCellContent = CStr(ws.Cells(rowindex, colindex))
End Function
So if you want to check the value of cells, just put the function in a loop, give it the reference to the worksheet you want and the row index and column index of the cell. Row index and column index both start from 1, meaning that cell A1 will be ws.Cells(1,1) and so on.
I would suggest:
df.loc[index_position, "column_name"] = some_value
Just for the most popular linux Ubuntu
& it's bash
:
Check which shell are you using? Mostly below works, else see this:
echo $0
If above prints bash
, then below will work:
printf "hello with no new line printed at end"
OR
echo -n "hello with no new line printed at end"
in EXCEL 2013 i had to use IF function 2 times: 1st to identify error with ISERROR and 2nd to identify the specific type of error by ERROR.TYPE=3 in order to address this type of error. This way you can differentiate between error you want and other types.
I found a way of resizing font size according to div size, without any JavaScript. I don't know how much efficient it's, but it nicely gets the job done.
Embed a SVG element inside the required div, and then use a foreignObject tag inside which you can use HTML elements. A sample code snippet that got my job done is given below.
<!-- The SVG element given below should be place inside required div tag -->
<svg viewBox='0 2 108.5 29' xmlns='http://www.w3.org/2000/svg'>
<!-- The below tag allows adding HTML elements inside SVG tag -->
<foreignObject x='5' y='0' width='93.5%' height='100%'>
<!-- The below tag can be styled using CSS classes or style attributes -->
<div xmlns='http://www.w3.org/1999/xhtml' style='text-overflow: ellipsis; overflow: hidden; white-space: nowrap;'>
Required text goes here
</div>
</foreignObject>
</svg>
All the viewBox, x, y, width and height values can be changed according to requirement.
Text can be defined inside the SVG element itself, but when the text overflows, ellipsis can't be added to SVG text. So, HTML element(s) are defined inside a foreignObject
element, and text-overflow styles are added to that/those element(s).
Using the lodash library you can write shorter
_({ "a":4, "b":0.5 , "c":0.35, "d":5 }).values().max();
I wanted to give you an example for using memoization to compute Fibonacci as this will allow you to compute significantly larger numbers using recursion:
cache = {}
def fib_dp(n):
if n in cache:
return cache[n]
if n == 0: return 0
elif n == 1: return 1
else:
value = fib_dp(n-1) + fib_dp(n-2)
cache[n] = value
return value
print(fib_dp(998))
This is still recursive, but uses a simple hashtable that allows the reuse of previously calculated Fibonacci numbers instead of doing them again.
Standard UITableViewCell already contains UIImageView that appears to the left to all your labels if its image is set. You can access it using imageView property:
cell.imageView.image = someImage;
If for some reason standard behavior does not suit your needs (note that you can customize properties of that standard image view) then you can add your own UIImageView to the cell as Aman suggested in his answer. But in that approach you'll have to manage cell's layout yourself (e.g. make sure that cell labels do not overlap image). And do not add subviews to the cell directly - add them to cell's contentView:
// DO NOT!
[cell addSubview:imv];
// DO:
[cell.contentView addSubview:imv];
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
where entityManagerFactory
is an JPA EntityManagerFactory
.
call function on load:
<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">
get video duration
var video = document.getElementById("video");
var duration = video.duration;
The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.
For IE, I found that changing
.flex > div
{
flex: 1 0 50%;
}
to
.flex > div
{
flex: 1 0 45%;
}
seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.
In the case of Firefox I solved it by adding
display: inline-block;
to the items.
SQL Server stored procedure:
CREATE PROCEDURE [dbo].[INS_MEM_BASIC]
@na varchar(50),
@occ varchar(50),
@New_MEM_BASIC_ID int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Mem_Basic
VALUES (@na, @occ)
SELECT @New_MEM_BASIC_ID = SCOPE_IDENTITY()
END
C# code:
public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
// values 0 --> -99 are SQL reserved.
int new_MEM_BASIC_ID = -1971;
SqlConnection SQLconn = new SqlConnection(Config.ConnectionString);
SqlCommand cmd = new SqlCommand("INS_MEM_BASIC", SQLconn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter outPutVal = new SqlParameter("@New_MEM_BASIC_ID", SqlDbType.Int);
outPutVal.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outPutVal);
cmd.Parameters.Add("@na", SqlDbType.Int).Value = Mem_NA;
cmd.Parameters.Add("@occ", SqlDbType.Int).Value = Mem_Occ;
SQLconn.Open();
cmd.ExecuteNonQuery();
SQLconn.Close();
if (outPutVal.Value != DBNull.Value) new_MEM_BASIC_ID = Convert.ToInt32(outPutVal.Value);
return new_MEM_BASIC_ID;
}
I hope these will help to you ....
You can also use this if you want ...
public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
using (SqlConnection con=new SqlConnection(Config.ConnectionString))
{
int newID;
var cmd = "INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT CAST(scope_identity() AS int)";
using(SqlCommand cmd=new SqlCommand(cmd, con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
newID = (int)insertCommand.ExecuteScalar();
if (con.State == System.Data.ConnectionState.Open) con.Close();
return newID;
}
}
}
Thanks for above answers, with the help of those, after certain R&D for xamarin.android MVVMCross application, below worked
Flag specified for activity in method OnCreate
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
this.Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
}
For each MvxActivity, Theme is mentioned as below
[Activity(
LaunchMode = LaunchMode.SingleTop,
ScreenOrientation = ScreenOrientation.Portrait,
Theme = "@style/Theme.Splash",
Name = "MyView"
)]
My SplashStyle.xml looks like as below
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Splash" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:statusBarColor">@color/app_red</item>
<item name="android:colorPrimaryDark">@color/app_red</item>
</style>
</resources>
And I have V7 appcompact referred.
If you want your code to pick a specific range of digits, be sure to use the &&
operator instead of the ||
.
if (x >= 4 && x <= 9) {_x000D_
// do something_x000D_
} else {_x000D_
// do something else_x000D_
}_x000D_
_x000D_
// be sure not to do this_x000D_
_x000D_
if (x >= 4 || x <= 9) {_x000D_
// do something_x000D_
} else {_x000D_
// do something else_x000D_
}
_x000D_
IMHO, there is not much difference in case of web application if you look at it from the angle of responsibility assignment. However, keep the clarity in the layer. Keep anything purely for the presentation purpose in the presentation layer, like the control and code specific to the web controls. Just keep your entities in the business layer and all features (like add, edit, delete) etc in the business layer. However rendering them onto the browser to be handled in the presentation layer. For .Net, the ASP.NET MVC pattern is very good in terms of keeping the layers separated. Look into the MVC pattern.
I know I'm late to the party, but whatever; I have this in my .vimrc:
nnoremap <C-d> :copy .<CR>
vnoremap <C-d> :copy '><CR>
the :copy
command just copies the selected line or the range (always whole lines) to below the line number given as its argument.
In normal mode what this does is copy .
copy this line to just below this line.
And in visual mode it turns into '<,'> copy '>
copy from start of selection to end of selection to the line below end of selection.
This is a tool that will help you, i installed it myself
Here is the link
Be careful, because none of these methods work with a large number of files. Personally, I used this line:
for i in $(ls | grep ".txt");do cat $i >> output.txt;done
EDIT: As someone said in the comments, you can replace $(ls | grep ".txt")
with $(ls *.txt)
EDIT: thanks to @gnourf_gnourf expertise, the use of glob is the correct way to iterate over files in a directory. Consequently, blasphemous expressions like $(ls | grep ".txt")
must be replaced by *.txt
(see the article here).
Good Solution
for i in *.txt;do cat $i >> output.txt;done
For simplicity's sake: newList = list(set(oldList))
But there are better options out there if you'd like to get speed/ordering/optimization instead: http://www.peterbe.com/plog/uniqifiers-benchmark
according to High Performance MySQL book:
VARCHAR stores variable-length character strings and is the most common string data type. It can require less storage space than fixed-length types, because it uses only as much space as it needs (i.e., less space is used to store shorter values). The exception is a MyISAM table created with ROW_FORMAT=FIXED, which uses a fixed amount of space on disk for each row and can thus waste space. VARCHAR helps performance because it saves space.
CHAR is fixed-length: MySQL always allocates enough space for the specified number of characters. When storing a CHAR value, MySQL removes any trailing spaces. (This was also true of VARCHAR in MySQL 4.1 and older versions—CHAR and VAR CHAR were logically identical and differed only in storage format.) Values are padded with spaces as needed for comparisons.
I had a similar issue. The root cause was that the sending IP was not in the range of white-listed IPs on the receiving server. So, all requests for communication were killed by the receiving site.
Replace
import { Router, Route, Link, browserHistory } from 'react-router';
With
import { BrowserRouter as Router, Route } from 'react-router-dom';
It will start working. It is because react-router-dom exports BrowserRouter
Make sure you register Spring's CharacterEncodingFilter
in your web.xml
(must be the first filter in that file).
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
If you are on Tomcat you might not have set the URIEncoding
in your server.xml
. If you don't set it to UTF-8 it won't work. Definitely keep the CharacterEncodingFilter
. Nevertheless, here's a concise checklist to follow. It will definitely guide you to make this work.
onMeasure()
is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent
situation than a wrap_content
situation). These constraints are packaged up into the MeasureSpec
values that are passed into the method. Here is a rough correlation of the mode values:
layout_width
or layout_height
value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent
is used, to set the size exactly to the parent view (this is layout dependent in the framework).layout_width
or layout_height
value was set to match_parent
or wrap_content
where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.layout_width
or layout_height
value was set to wrap_content
with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.The contract that exists with onMeasure()
is that setMeasuredDimension()
MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View
, which is why it is safe to call super
instead if that fits your use case.
Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content
in both directions, your view may not show up at all because the framework doesn't know how large it is!
Generally, if you are overriding View
and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 100;
int desiredHeight = 100;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
//MUST CALL THIS
setMeasuredDimension(width, height);
}
Hope that Helps.
For basic URL resolution, use a command line fetcher like wget
or curl
to do the testing, rather than a manual browser. Then you don't have to clear any cache; just up arrow and Enter in a shell to re-run your test fetches.
In GNU Awk 4.1.0 (released 2013) and later, it has the option of "inplace" file editing:
[...] The "inplace" extension, built using the new facility, can be used to simulate the GNU "
sed -i
" feature. [...]
Example usage:
$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1 file2 file3
To keep the backup:
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{ gsub(/foo/, "bar") }
> { print }' file1 file2 file3
Your not applying Date formator. rather you are just parsing the date. to get output in this format
yyyy-MM-dd HH:mm:ss.SSSSSS
we have to use format() method here is full example:-
Here is full example:-
it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS
and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {
public static void main(String args[]) throws ParseException {
SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");
System.out.println(thisDate);
System.out.println("----------------------------");
System.out.println("After applying formating :");
String strDateOutput = changeFormat.format(temp);
System.out.println(strDateOutput);
}
}
WebDriver's driver.switchTo().frame()
method takes one of the three possible arguments:
Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index
0
, the second at index1
and the third at index2
. Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that frame.
Select a frame by its name or ID. Frames located by matching name attributes are always given precedence over those matched by ID.
A previously found WebElement
.
Select a frame using its previously located WebElement.
Get the frame by it's id/name or locate it by driver.findElement()
and you'll be good.
Which of these three approaches is most suited for the task?
Depends on the task :-) To match exactly all Latin characters and their accented versions, the Unicode ranges probably provide the best solution. They might be extended to all non-whitespace characters, which could be done using the \S
character class.
I'm forcing a field in a UI to match the format:
last_name, first_name
(last [comma space] first)
The most basic problem I'm seeing here are not diacritics, but whitespaces. There are a few names that consist of multiple words, e.g. for titles. So you should go with the most generic, that is allowing everything but the comma that distinguishes first from last name:
/[^,]+,\s[^,]+/
But your second solution with the .
character class is just as fine, you only might need to care about multiple commata then.
use from configurations must be very very easy like this :
var config = new MiniConfig("setting.conf");
config.AddOrUpdate("port", "1580");
if (config.TryGet("port", out int port)) // if config exist
{
Console.Write(port);
}
for more details see MiniConfig
f = open('C:\\Users\\Pooja\\Desktop\\trolldata.csv')
Use '\\' for python program in Python version 3 and above.. Error will be resolved..
Firstly, it probably depends which version of Solaris you're running, but also what hardware you have.
On SPARC at least, you have psrinfo
to show you processor information, which run on its own will show you the number of CPU
s the machine sees. psrinfo -p
shows you the number of physical processors installed. From that you can deduce the number of threads/cores per physical processors.
prtdiag
will display a fair bit of info about the hardware in your machine. It looks like on a V240 you do get memory channel info from prtdiag
, but you don't on a T2000. I guess that's an architecture issue between UltraSPARC IIIi and UltraSPARC T1.
I've just created a javascript shim to achieve this goal. Take a look if you want, it's a proof-of-concept, but take care: it's a early version and still needs some work.
Support for multi-root workspaces is now enabled by default in the latest stable release [November 2017 release].
The File > Add Folder to Workspace
command brings up an Open Folder dialog to select the new folder.
Opera, ffs.
if (window["CanvasRenderingContext2D"]) {
/** @expose */
CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
if (w < 2*r) r = w/2;
if (h < 2*r) r = h/2;
this.beginPath();
if (r < 1) {
this.rect(x, y, w, h);
} else {
if (window["opera"]) {
this.moveTo(x+r, y);
this.arcTo(x+r, y, x, y+r, r);
this.lineTo(x, y+h-r);
this.arcTo(x, y+h-r, x+r, y+h, r);
this.lineTo(x+w-r, y+h);
this.arcTo(x+w-r, y+h, x+w, y+h-r, r);
this.lineTo(x+w, y+r);
this.arcTo(x+w, y+r, x+w-r, y, r);
} else {
this.moveTo(x+r, y);
this.arcTo(x+w, y, x+w, y+h, r);
this.arcTo(x+w, y+h, x, y+h, r);
this.arcTo(x, y+h, x, y, r);
this.arcTo(x, y, x+w, y, r);
}
}
this.closePath();
};
/** @expose */
CanvasRenderingContext2D.prototype.fillRoundRect = function(x, y, w, h, r) {
this.roundRect(x, y, w, h, r);
this.fill();
};
/** @expose */
CanvasRenderingContext2D.prototype.strokeRoundRect = function(x, y, w, h, r) {
this.roundRect(x, y, w, h, r);
this.stroke();
};
}
Since Opera is going WebKit, this should also remain valid in the legacy case.
Series.apply(func, convert_dtype=True, args=(), **kwds)
args : tuple
x = my_series.apply(my_function, args = (arg1,))
According to documentation class date
is a parent for class datetime
. And isinstance()
method will give you True
in all cases. If you need to distinguish datetime
from date
you should check name of the class
import datetime
datetime.datetime.now().__class__.__name__ == 'date' #False
datetime.datetime.now().__class__.__name__ == 'datetime' #True
datetime.date.today().__class__.__name__ == 'date' #True
datetime.date.today().__class__.__name__ == 'datetime' #False
I've faced with this problem when i have different formatting rules for dates and dates with time
Keystore is used to store private key and identity certificates that a specific program should present to both parties (server or client) for verification.
Truststore is used to store certificates from Certified Authorities (CA) that verify the certificate presented by the server in SSL connection.
This article for reference https://www.educative.io/edpresso/keystore-vs-truststore
If you are using it to skip part of a large script for debugging (see Karl Nicoll's comment), then if false could be a good option (not sure if "false" is always available, for me it is in /bin/false):
# ... Code I want to run here ...
if false; then
# ... Code I want to skip here ...
fi
# ... I want to resume here ...
The difficulty comes in when it's time to rip out your debugging code. The "if false" construct is pretty straightforward and memorable, but how do you find the matching fi? If your editor allows you to block indent, you could indent the skipped block (then you'll want to put it back when you're done). Or a comment on the fi line, but it would have to be something you'll remember, which I suspect will be very programmer-dependent.
If you don't have Your own Data Class, then you can design your map as follows
Map<Integer, Object> map=new HashMap<Integer, Object>();
Here don't forget to use "instanceof" operator while retrieving the values from MAP.
If you have your own Data class then then you can design your map as follows
Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapTest {
public static void main(String[] args) {
Map<Integer,Demo> map=new HashMap<Integer, Demo>();
Demo d1= new Demo(1,"hi",new Date(),1,1);
Demo d2= new Demo(2,"this",new Date(),2,1);
Demo d3= new Demo(3,"is",new Date(),3,1);
Demo d4= new Demo(4,"mytest",new Date(),4,1);
//adding values to map
map.put(d1.getKey(), d1);
map.put(d2.getKey(), d2);
map.put(d3.getKey(), d3);
map.put(d4.getKey(), d4);
//retrieving values from map
Set<Integer> keySet= map.keySet();
for(int i:keySet){
System.out.println(map.get(i));
}
//searching key on map
System.out.println(map.containsKey(d1.getKey()));
//searching value on map
System.out.println(map.containsValue(d1));
}
}
class Demo{
private int key;
private String message;
private Date time;
private int count;
private int version;
public Demo(int key,String message, Date time, int count, int version){
this.key=key;
this.message = message;
this.time = time;
this.count = count;
this.version = version;
}
public String getMessage() {
return message;
}
public Date getTime() {
return time;
}
public int getCount() {
return count;
}
public int getVersion() {
return version;
}
public int getKey() {
return key;
}
@Override
public String toString() {
return "Demo [message=" + message + ", time=" + time
+ ", count=" + count + ", version=" + version + "]";
}
}
Improving and Simplifying @Nate's answer:
jQuery.fn.extend({
toggleText: function (a, b){
var that = this;
if (that.text() != a && that.text() != b){
that.text(a);
}
else
if (that.text() == a){
that.text(b);
}
else
if (that.text() == b){
that.text(a);
}
return this;
}
});
Use as:
$("#YourElementId").toggleText('After', 'Before');
I had a similar problem and a solution I found (forgot where I found it) is this:
Array.from(Array(mynumber), (val, index) => index + 1)
protected void UpdateButton_Click(object sender, EventArgs e)
{
var values = string.Format("Name={0}&Family={1}&Id={2}", NameToUpdateTextBox.Text, FamilyToUpdateTextBox.Text, IdToUpdateTextBox.Text);
var bytes = Encoding.ASCII.GetBytes(values);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://localhost:51436/api/employees"));
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
var response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
UpdateResponseLabel.Text = "Update completed";
else
UpdateResponseLabel.Text = "Error in update";
}
Here, Environment.NewLine doesn't worked.
I put a "<br/>" in a string and worked.
Ex:
ltrYourLiteral.Text = "First line.<br/>Second Line.";
The PIL distribution is mispackaged for egg installation.
Install Pillow instead, the friendly PIL fork.
Use the std::vector
class from the standard library.
It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.
You can implement a class that holds the fields you have in your JSON
class MyData
{
public string t;
public bool a;
public object[] data;
public string[][] type;
}
and then use the generic version of DeserializeObject:
MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
// Do something with typeStr
}
Documentation: Serializing and Deserializing JSON
The other option for using PHP scripts sans extension is
Options +MultiViews
Or even just following in the directories .htaccess
:
DefaultType application/x-httpd-php
The latter allows having all filenames without extension script
being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).
This seems to be what you're looking for:
g <- ggplot(x, aes(reorder(variable, value), value))
g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()
The reorder()
function will reorder your x axis items according to the value
of variable
.
Please take a look here:
1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.
2) Step-by-step tutorial how to use serial ports on windows
3) You can use this literally on MinGW
Here's some very, very simple code (without any error handling or settings):
#include <windows.h>
/* ... */
// Open serial port
HANDLE serialHandle;
serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);
GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);
// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(serialHandle, &timeout);
Now you can use WriteFile()
/ ReadFile()
to write / read bytes.
Don't forget to close your connection:
CloseHandle(serialHandle);
print type(variable_name)
I also highly recommend the IPython interactive interpreter when dealing with questions like this. It lets you type variable_name?
and will return a whole list of information about the object including the type and the doc string for the type.
e.g.
In [9]: var = 123
In [10]: var?
Type: int
Base Class: <type 'int'>
String Form: 123
Namespace: Interactive
Docstring:
int(x[, base]) -> integer
Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead.
tl;dr version: use ~/.zshrc
And read the man page to understand the differences between:
~/.zshrc
,~/.zshenv
and~/.zprofile
.
In my comment attached to the answer kev gave, I said:
This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.
This turns out to be partially incorrect: /etc/profile
may be sourced by zsh
. However, this only occurs if zsh
is "invoked as sh
or ksh
"; in these compatibility modes:
The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].
The ArchWiki ZSH link says:
At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login
This implys that /etc/profile
is always read by zsh
at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH
set in /etc/profile
do not make it to my zsh sessions).
where exactly should I be placing my rvm, python, node etc additions to my $PATH?
Generally, I would export my $PATH
from ~/.zshrc
, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc
is read for interactive shells, which may or may not suit your needs - if you want the $PATH
for every zsh
shell invoked by you (both interactive
and not, both login
and not, etc), then ~/.zshenv
is a better option.
Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?
There's a bunch of files read on startup (check the linked man
pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv
not existing - if you need it, make it, and it will be read.
.bashrc
and .bash_profile
are not read by zsh
, unless you explicitly source them from ~/.zshrc
or similar; the syntax between bash
and zsh
is not always compatible. Both .bashrc
and .bash_profile
are designed for bash
settings, not zsh
settings.
unset
doesn't change the index, but array_splice
does:
$arrayName = array('1' => 'somevalue',
'2' => 'somevalue1',
'3' => 'somevalue3',
500 => 'somevalue500',
);
echo $arrayName['500'];
//somevalue500
array_splice($arrayName, 1, 2);
print_r($arrayName);
//Array ( [0] => somevalue [1] => somevalue500 )
$arrayName = array( '1' => 'somevalue',
'2' => 'somevalue1',
'3' => 'somevalue3',
500 => 'somevalue500',
);
echo $arrayName['500'];
//somevalue500
unset($arrayName[1]);
print_r($arrayName);
//Array ( [0] => somevalue [1] => somevalue500 )
Generic
C code. Using 1 byte input data num as example.
unsigned char num = 0xaa; // 1010 1010 (aa) -> 0101 0101 (55)
int s = sizeof(num) * 8; // get number of bits
int i, x, y, p;
int var = 0; // make var data type to be equal or larger than num
for (i = 0; i < (s / 2); i++) {
// extract bit on the left, from MSB
p = s - i - 1;
x = num & (1 << p);
x = x >> p;
printf("x: %d\n", x);
// extract bit on the right, from LSB
y = num & (1 << i);
y = y >> i;
printf("y: %d\n", y);
var = var | (x << i); // apply x
var = var | (y << p); // apply y
}
printf("new: 0x%x\n", new);
I know you asked about GCD, but if you wanted, NSOperationQueue
also handles this sort of stuff really gracefully, e.g.:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Starting 3");
}];
NSOperation *operation;
operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Starting 1");
sleep(7);
NSLog(@"Finishing 1");
}];
[completionOperation addDependency:operation];
[queue addOperation:operation];
operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Starting 2");
sleep(5);
NSLog(@"Finishing 2");
}];
[completionOperation addDependency:operation];
[queue addOperation:operation];
[queue addOperation:completionOperation];
The objectsAreSame
function mentioned in @JasonBunting's answer works fine for me. However, there's a little problem: If x[propertyName]
and y[propertyName]
are objects (typeof x[propertyName] == 'object'
), you'll need to call the function recursively in order to compare them.
Off the cuff, it feels like your project is connected to an older version of the Play Services library project. The recommended approach, by Google, is for you to find the library project in the SDK and make a local copy. This does mean, though, that any time you update the Play Services library project through the SDK Manager, you also need to replace your copy with a fresh copy.
onclick buttons c2
to fetch and change the color of action bar and notification bar according to button's background, hope this helps
int color = c2.getBackground()).getColor();
int colorlighter = -color * 40 / 100 + color;
getWindow().setNavigationBarColor(colorlighter);
getWindow().setStatusBarColor(colorlighter);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(color));
colorlighter
is used to set color of notification bar a little lighter than action bar
color
is the background color of button c2
, according to which we change our color.
I had the same problem, and I've found here a solution:
http://ubuntuincident.wordpress.com/2011/04/15/scraping-ajax-web-pages/
So, to use Crowbar, the tool from here:
http://simile.mit.edu/wiki/Crowbar (now (2015-12) 404s)
wayback machine link:
http://web.archive.org/web/20140421160451/http://simile.mit.edu/wiki/Crowbar
It gave me the faulty, invalid HTML.
Tim Storer wrote a more flexible and nicer looking timeline.sty
(Internet Archive Wayback Machine link, as original is gone). In addition, the line is horizontal rather than vertical. So for instance:
\begin{timeline}{2008}{2010}{50}{250}
\MonthAndYearEvent{4}{2008}{First Podcast}
\MonthAndYearEvent{7}{2008}{Private Beta}
\MonthAndYearEvent{9}{2008}{Public Beta}
\YearEvent{2009}{IPO?}
\end{timeline}
produces a timeline that looks like this:
2008 2010
· · April, 2008 First Podcast ·
· July, 2008 Private Beta
· September, 2008 Public Beta
· 2009 IPO?
Personally, I find this a more pleasing solution than the other answers. But I also find myself modifying the code to get something closer to what I think a timeline should look like. So there's not definitive solution in my opinion.
if you have just two parameters you can do this:
$.getJSON('/url-you-are-posting-to',data,function(result){
//do something useful with returned result//
result.variable-in-result;
});
I had this problem while inheriting from ApiController instead of the regular Controller class. I solved it by using var container = Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);
I followed this thread How to get Request Querystring values?
EDIT: After trying to filter through the container I was getting odd error messages. After going to my project properties and I unchecked the Optimize Code checkbox which changed so that all of a sudden the parameters in my controller where filled up from the url as I wanted.
Hopefully this will help someone with the same problem..
I came up with an generic, interesting solution to this problem:
class SafeInvocator(object):
def __init__(self, module):
self._module = module
def _safe(self, func):
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
return None
return inner
def __getattr__(self, item):
obj = getattr(self.module, item)
return self._safe(obj) if hasattr(obj, '__call__') else obj
and you can use it like so:
safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
# do something
I would like to answer this to improve upon the accepted answer.
To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.
function stringToBool(val) {
return (val + '').toLowerCase() === 'true';
}
JSPerf
the _timestamp didn't work out for me,
this query does work for me:
(as in mconlin's answer)
{
"query": {
"match_all": {}
},
"size": "1",
"sort": [
{
"@timestamp": {
"order": "desc"
}
}
]
}
Could be trivial but the _timestamp answer didn't gave an error but not a good result either...
Hope to help someone...
(kibana/elastic 5.0.4)
S.
And for Windows 8.1/10 OS Users just open cmd (command prompt)
write this : C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36-32\Scripts
then
just write this : pip3 install
{name of package}
Hint: the location of folder Python36-32
may get different for new python 3.x versions
jmh is a recent addition to OpenJDK and has been written by some performance engineers from Oracle. Certainly worth a look.
The jmh is a Java harness for building, running, and analysing nano/micro/macro benchmarks written in Java and other languages targetting the JVM.
Very interesting pieces of information buried in the sample tests comments.
See also:
Here is a working version with your bugs removed.
$url = 'http://dynupdate.no-ip.com/ip.php';
$proxy = '127.0.0.1:8888';
//$proxyauth = 'user:password';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
echo $curl_scraped_page;
I have added CURLOPT_PROXYUSERPWD
in case any of your proxies require a user name and password.
I set CURLOPT_RETURNTRANSFER
to 1, so that the data will be returned to $curl_scraped_page
variable.
I removed a second extra curl_exec($ch);
which would stop the variable being returned.
I consolidated your proxy IP and port into one setting.
I also removed CURLOPT_HTTPPROXYTUNNEL
and CURLOPT_CUSTOMREQUEST
as it was the default.
If you don't want the headers returned, comment out CURLOPT_HEADER
.
To disable the proxy simply set it to null.
curl_setopt($ch, CURLOPT_PROXY, null);
Any questions feel free to ask, I work with cURL
every day.
Take a look at the other tokenizing options that nltk provides here. For example, you can define a tokenizer that picks out sequences of alphanumeric characters as tokens and drops everything else:
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
tokenizer.tokenize('Eighty-seven miles to go, yet. Onward!')
Output:
['Eighty', 'seven', 'miles', 'to', 'go', 'yet', 'Onward']
Stored procedure is the best way to do it. Because Meherzad's solution would work only if the data follows the same order.
If we have a table structure like this
col1 | col2 | col3
-----+------+------
3 | k | 7
5 | d | 3
1 | a | 5
6 | o | 2
2 | 0 | 8
It wont work. SQL Fiddle Demo
Here is a sample procedure code to achieve the same.
delimiter //
CREATE PROCEDURE chainReaction
(
in inputNo int
)
BEGIN
declare final_id int default NULL;
SELECT col3
INTO final_id
FROM table1
WHERE col1 = inputNo;
IF( final_id is not null) THEN
INSERT INTO results(SELECT col1, col2, col3 FROM table1 WHERE col1 = inputNo);
CALL chainReaction(final_id);
end if;
END//
delimiter ;
call chainReaction(1);
SELECT * FROM results;
DROP TABLE if exists results;
I was running into this problem as well.
I was able to resolve the issue by running sn -i <KeyFile> <ContainerName>
(installs key pair into a named container).
sn
is usually installed as part of a Windows SDK. For example C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\sn.exe
. Most likely this location is not on the search path for your standard environment. However, the "Developer Command Prompt" installed by Visual Studio adds additional information that usually includes the correct location.
Based on your post that would look like
sn -i companyname.pfx VS_KEY_3E185446540E7F7A
This must be run from the location of your PFX file, if you have the solution loaded in VS 2010 you can simply right click on the pfx file from the solution explorer and choose Open Command Prompt which will launch the .net 2010 cmd prompt tool in the correct directory.
Before running this sn command I did re-install the pfx by right clicking on it and choosing install however that did not work. Just something to note as it might be the combination of both that provided the solution.
Hope this helps solve your problem.
Recursive code to explore all the file contained in a directory ('$path' contains the path of the directory):
function explore_directory($path)
{
$scans = scandir($path);
foreach($scans as $scan)
{
$new_path = $path.$scan;
if(is_dir($new_path))
{
$new_path = $new_path."/";
explore_directory($new_path);
}
else // A file
{
/*
Body of code
*/
}
}
}
you can try to install another package:
pip install mysql-connector-python
This package worked fine for me and I got no issues to install.
IOW, extern is redundant, and does nothing.
That is why, 10 years later:
extern
in function declaration for removal;git/git
follows that conclusion and removes extern
from its code (for Git 2.22, Q2 2019).See commit ad6dad0, commit b199d71, commit 5545442 (29 Apr 2019) by Denton Liu (Denton-L
).
(Merged by Junio C Hamano -- gitster
-- in commit 4aeeef3, 13 May 2019)
*.[ch]
: removeextern
from function declarations usingspatch
There has been a push to remove
extern
from function declarations.Remove some instances of "
extern
" for function declarations which are caught by Coccinelle.
Note that Coccinelle has some difficulty with processing functions with__attribute__
or varargs so someextern
declarations are left behind to be dealt with in a future patch.This was the Coccinelle patch used:
@@ type T; identifier f; @@ - extern T f(...);
and it was run with:
$ git ls-files \*.{c,h} | grep -v ^compat/ | xargs spatch --sp-file contrib/coccinelle/noextern.cocci --in-place
This is not always straightforward though:
See commit 7027f50 (04 Sep 2019) by Denton Liu (Denton-L
).
(Merged by Denton Liu -- Denton-L
-- in commit 7027f50, 05 Sep 2019)
compat/*.[ch]
: removeextern
from function declarations using spatchIn 5545442 (
*.[ch]
: removeextern
from function declarations using spatch, 2019-04-29, Git v2.22.0-rc0), we removed externs from function declarations usingspatch
but we intentionally excluded files undercompat/
since some are directly copied from an upstream and we should avoid churning them so that manually merging future updates will be simpler.In the last commit, we determined the files which taken from an upstream so we can exclude them and run
spatch
on the remainder.This was the Coccinelle patch used:
@@ type T; identifier f; @@ - extern T f(...);
and it was run with:
$ git ls-files compat/\*\*.{c,h} | xargs spatch --sp-file contrib/coccinelle/noextern.cocci --in-place $ git checkout -- \ compat/regex/ \ compat/inet_ntop.c \ compat/inet_pton.c \ compat/nedmalloc/ \ compat/obstack.{c,h} \ compat/poll/
Coccinelle has some trouble dealing with
__attribute__
and varargs so we ran the following to ensure that no remaining changes were left behind:$ git ls-files compat/\*\*.{c,h} | xargs sed -i'' -e 's/^\(\s*\)extern \([^(]*([^*]\)/\1\2/' $ git checkout -- \ compat/regex/ \ compat/inet_ntop.c \ compat/inet_pton.c \ compat/nedmalloc/ \ compat/obstack.{c,h} \ compat/poll/
Note that with Git 2.24 (Q4 2019), any spurious extern
is dropped.
See commit 65904b8 (30 Sep 2019) by Emily Shaffer (nasamuffin
).
Helped-by: Jeff King (peff
).
See commit 8464f94 (21 Sep 2019) by Denton Liu (Denton-L
).
Helped-by: Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 59b19bc, 07 Oct 2019)
promisor-remote.h
: dropextern
from function declarationDuring the creation of this file, each time a new function declaration was introduced, it included an
extern
.
However, starting from 5545442 (*.[ch]
: removeextern
from function declarations usingspatch
, 2019-04-29, Git v2.22.0-rc0), we've been actively trying to prevent externs from being used in function declarations because they're unnecessary.Remove these spurious
extern
s.
I prefer to use \c
at the end of the search string:
/copyright\c
You should disable "System Integrity Protection" which is a new feature in El Capitan.
First, you should run the command for rootless config on your terminal
# nvram boot-args="rootless=0"
# reboot
Then, you should run the command below on recovery partition's terminal (Recovery OS)
# csrutil disable
# reboot
I've just solved my problem like that. I'm not sure that the first part is necessary. Try as you like.
--WARNING
You should enable SIP again after everything works;
Simply reboot again into Recovery Mode and run in terminal
# csrutil enable
OK, this is a new tack on solving this problem… My approach is to not use any hooks, but rather use filters and git attributes. What this allows you to do, is setup, on each machine you develop on, a set of filters that will strip extra trailing white space and extra blank lines at the end of files before committing them. Then setup a .gitattributes file that says which types of files the filter should be applied to. The filters have two phases, clean
which is applied when adding files to the index, and smudge
which is applied when adding them to the working directory.
First, tell your global config to use a global attributes file:
git config --global core.attributesfile ~/.gitattributes_global
Now, create the filter:
git config --global filter.fix-eol-eof.clean fixup-eol-eof %f
git config --global filter.fix-eol-eof.smudge cat
git config --global filter.fix-eol-eof.required true
Finally, put the fixup-eol-eof
script somewhere on your path, and make it executable. The script uses sed to do some on the fly editing (remove spaces and blanks at the end of lines, and extraneous blank lines at the end of the file)
fixup-eol-eof should look like this:
#!/bin/bash
sed -e 's/[ ]*$//' -e :a -e '/^\n*$/{$d;N;ba' -e '}' $1
Lastly, create or open ~/.gitattributes_global in your favorite editor and add lines like:
pattern attr1 [attr2 [attr3 […]]]
So if we want to fix the whitespace issue, for all of our c source files we would add a line that looks like this:
*.c filter=fix-eol-eof
The filter has two phases, the clean phase which is applied when things are added to the index or checked in, and the smudge phase when git puts stuff into your working directory. Here, our smudge is just running the contents through the cat
command which should leave them unchanged, with the exception of possibly adding a trailing newline character if there wasn’t one at the end of the file. The clean command is the whitespace filtering which I cobbled together from notes at http://sed.sourceforge.net/sed1line.txt. It seems that it must be put into a shell script, I couldn’t figure out how to inject the sed command, including the sanitation of the extraneous extra lines at the end of the file directly into the git-config file. (You CAN get rid of trailing blanks, however, without the need of a separate sed script, just set the filter.fix-eol-eof
to something like sed 's/[ \t]*$//' %f
where the \t
is an actual tab, by pressing tab.)
The require = true causes an error to be raised if something goes wrong, to keep you out of trouble.
Please forgive me if my language concerning git is imprecise. I think I have a fairly good grasp of the concepts but am still learning the terminology.
You can also load the context while defining the servlet itself (WebApplicationContext)
<servlet>
<servlet-name>admin</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/*.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>admin</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
rather than (ApplicationContext)
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
or can do both together.
Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet
) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet
etc)
Context loaded by ContextLoaderListener
will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.
When I want to take into account extra characters like your commas (in my case each token may be entered with quotes), I'd do a string.replace() to change the other delimiters to blanks and then split on whitespace.
If you are working on your own, and you want the closest thing to OOP as you would find in Java or C# or C++, see the javascript library, CrxOop. CrxOop provides syntax somewhat familiar to Java developers.
Just be careful, Java's OOP is not the same as that found in Javascript. To get the same behavior as in Java, use CrxOop's classes, not CrxOop's structures, and make sure all your methods are virtual. An example of the syntax is,
crx_registerClass("ExampleClass",
{
"VERBOSE": 1,
"public var publicVar": 5,
"private var privateVar": 7,
"public virtual function publicVirtualFunction": function(x)
{
this.publicVar1 = x;
console.log("publicVirtualFunction");
},
"private virtual function privatePureVirtualFunction": 0,
"protected virtual final function protectedVirtualFinalFunction": function()
{
console.log("protectedVirtualFinalFunction");
}
});
crx_registerClass("ExampleSubClass",
{
VERBOSE: 1,
EXTENDS: "ExampleClass",
"public var publicVar": 2,
"private virtual function privatePureVirtualFunction": function(x)
{
this.PARENT.CONSTRUCT(pA);
console.log("ExampleSubClass::privatePureVirtualFunction");
}
});
var gExampleSubClass = crx_new("ExampleSubClass", 4);
console.log(gExampleSubClass.publicVar);
console.log(gExampleSubClass.CAST("ExampleClass").publicVar);
The code is pure javascript, no transpiling. The example is taken from a number of examples from the official documentation.
I've created a class which helps to reduce errors in setting up custom handlers and takes advantage of the system property so there are no issues with calling a method first or not being in the right container. There's also an exception class if you get things wrong:
CustomURLScheme.java:
/*
* The CustomURLScheme class has a static method for adding cutom protocol
* handlers without getting bogged down with other class loaders and having to
* call setURLStreamHandlerFactory before the next guy...
*/
package com.cybernostics.lib.net.customurl;
import java.net.URLStreamHandler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Allows you to add your own URL handler without running into problems
* of race conditions with setURLStream handler.
*
* To add your custom protocol eg myprot://blahblah:
*
* 1) Create a new protocol package which ends in myprot eg com.myfirm.protocols.myprot
* 2) Create a subclass of URLStreamHandler called Handler in this package
* 3) Before you use the protocol, call CustomURLScheme.add(com.myfirm.protocols.myprot.Handler.class);
* @author jasonw
*/
public class CustomURLScheme
{
// this is the package name required to implelent a Handler class
private static Pattern packagePattern = Pattern.compile( "(.+\\.protocols)\\.[^\\.]+" );
/**
* Call this method with your handlerclass
* @param handlerClass
* @throws Exception
*/
public static void add( Class<? extends URLStreamHandler> handlerClass ) throws Exception
{
if ( handlerClass.getSimpleName().equals( "Handler" ) )
{
String pkgName = handlerClass.getPackage().getName();
Matcher m = packagePattern.matcher( pkgName );
if ( m.matches() )
{
String protocolPackage = m.group( 1 );
add( protocolPackage );
}
else
{
throw new CustomURLHandlerException( "Your Handler class package must end in 'protocols.yourprotocolname' eg com.somefirm.blah.protocols.yourprotocol" );
}
}
else
{
throw new CustomURLHandlerException( "Your handler class must be called 'Handler'" );
}
}
private static void add( String handlerPackage )
{
// this property controls where java looks for
// stream handlers - always uses current value.
final String key = "java.protocol.handler.pkgs";
String newValue = handlerPackage;
if ( System.getProperty( key ) != null )
{
final String previousValue = System.getProperty( key );
newValue += "|" + previousValue;
}
System.setProperty( key, newValue );
}
}
CustomURLHandlerException.java:
/*
* Exception if you get things mixed up creating a custom url protocol
*/
package com.cybernostics.lib.net.customurl;
/**
*
* @author jasonw
*/
public class CustomURLHandlerException extends Exception
{
public CustomURLHandlerException(String msg )
{
super( msg );
}
}
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
Would it not be better to use java.util.Observable
and java.util.Observer
that will cause the table to update?
String is a bridge type for NSString, so add
import Cocoa
to your swift file and use all the "old" methods.
I think you just need to remove the space. i.e.
$(".myclass[reference=12345]").css('border', '#000 solid 1px');
There is a fiddle here http://jsfiddle.net/xXEHY/
event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.
$("p").click(function(event)
{ event.stopImmediatePropagation();
});
$("p").click(function(event)
{ // This function won't be executed
$(this).css("color", "#fff7e3");
});
If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.
You can run below commands.
./catalina.sh run
Note: Make sure the port 8080 is open. If not, kill the process that is using 8080 port using sudo kill -9 $(sudo lsof -t -i:8080)
Value exactly equal to 123:
jQuery("#attached_docs[value='123']")
Full reference: http://api.jquery.com/category/selectors/
If you have the option of including a third-party library, it's definitely worth taking a look at Moment.js. It makes working with Date
and DateTime
much, much easier.
For example, seeing if one Date comes after another Date but excluding their times, you would do something like this:
var date1 = new Date(2016,9,20,12,0,0); // October 20, 2016 12:00:00
var date2 = new Date(2016,9,20,12,1,0); // October 20, 2016 12:01:00
// Comparison including time.
moment(date2).isAfter(date1); // => true
// Comparison excluding time.
moment(date2).isAfter(date1, 'day'); // => false
The second parameter you pass into isAfter
is the precision to do the comparison and can be any of year
, month
, week
, day
, hour
, minute
or second
.
With the following, it is easy to link the Cell address...
=SUM(SUMIFS(FAGLL03!$I$4:$I$1048576,FAGLL03!$A$4:$A$1048576,">="&INDIRECT("A"&ROW()),FAGLL03!$A$4:$A$1048576,"<="&INDIRECT("B"&ROW()),FAGLL03!$Q$4:$Q$1048576,E$2))
Can use address / substitute / Column functions as required to use Cell addresses in full DYNAMIC.
typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name
In c# you can simply say:
if (myObj is Car) {
}
This is very simple steps involved as you mentioned you have already installed JAVAEE plugin so the first step for you is go to Windows->Show View->Server
in add select the AppacheTOMcat and select the tomcat version you have downloaded and set the path and start the server after that.
The direct way to write x or y or z == 0
is
if any(map((lambda value: value == 0), (x,y,z))):
pass # write your logic.
But I dont think, you like it. :) And this way is ugly.
The other way (a better) is:
0 in (x, y, z)
BTW lots of if
s could be written as something like this
my_cases = {
0: Mylist.append("c"),
1: Mylist.append("d")
# ..
}
for key in my_cases:
if key in (x,y,z):
my_cases[key]()
break
Had the exact same problem that is described herein. No matter what I did, following the above examples, to change the location of my WSDL file (in our case from a web server), it was still referencing the original location embedded within the source tree of the server process.
After MANY hours trying to debug this, I noticed that the Exception was always being thrown from the exact same line (in my case 41). Finally this morning, I decided to just send my source client code to our trade partner so they can at least understand how the code looks, but perhaps build their own. To my shock and horror I found a bunch of class files mixed in with my .java files within my client source tree. How bizarre!! I suspect these were a byproduct of the JAX-WS client builder tool.
Once I zapped those silly .class files and performed a complete clean and rebuild of the client code, everything works perfectly!! Redonculous!!
YMMV, Andrew
The standard approach is to use the select module.
However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling.
Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.
$('body').on('hidden.bs.modal', '.modal', function () {
$("#mention Id here what you showed inside modal body").empty()
});
Which html element you want to empty like(div,span whatever).
I was looking to do the same thing. problem for me was my url was getting way too long. I found a solution today using Bruno Jouhier's jsUrl.js library.
I haven't tested it very thoroughly yet. However, here is an example showing character lengths of the string output after encoding the same large object using 3 different methods:
jQuery.param
JSON.stringify + encodeURIComponent
JSURL.stringify
clearly JSURL has the most optimized format for urlEncoding a js object.
the thread at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Q shows benchmarks for encoding and parsing.
Note: After testing, it looks like jsurl.js library uses ECMAScript 5 functions such as Object.keys, Array.map, and Array.filter. Therefore, it will only work on modern browsers (no ie 8 and under). However, are polyfills for these functions that would make it compatible with more browsers.
For Kotlin fans:
private fun Bitmap.addOverlay(@DimenRes marginTop: Int, @DimenRes marginLeft: Int, overlay: Bitmap): Bitmap? {
val bitmapWidth = this.width
val bitmapHeight = this.height
val marginLeft = shareBitmapWidth - overlay.width - resources.getDimension(marginLeft)
val finalBitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, this
.config)
val canvas = Canvas(finalBitmap)
canvas.drawBitmap(this, Matrix(), null)
canvas.drawBitmap(overlay, marginLeft, resources.getDimension(marginTop), null)
return finalBitmap
}
bitmap.addOverlay( R.dimen.top_margin, R.dimen.left_margin, overlayBitmap)
To enable deserialization of multiple implementations of interfaces, you can use JsonConverter, but not through an attribute:
Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Converters.Add(new DTOJsonConverter());
Interfaces.IEntity entity = serializer.Deserialize(jsonReader);
DTOJsonConverter maps each interface with a concrete implementation:
class DTOJsonConverter : Newtonsoft.Json.JsonConverter
{
private static readonly string ISCALAR_FULLNAME = typeof(Interfaces.IScalar).FullName;
private static readonly string IENTITY_FULLNAME = typeof(Interfaces.IEntity).FullName;
public override bool CanConvert(Type objectType)
{
if (objectType.FullName == ISCALAR_FULLNAME
|| objectType.FullName == IENTITY_FULLNAME)
{
return true;
}
return false;
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
if (objectType.FullName == ISCALAR_FULLNAME)
return serializer.Deserialize(reader, typeof(DTO.ClientScalar));
else if (objectType.FullName == IENTITY_FULLNAME)
return serializer.Deserialize(reader, typeof(DTO.ClientEntity));
throw new NotSupportedException(string.Format("Type {0} unexpected.", objectType));
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
DTOJsonConverter is required only for the deserializer. The serialization process is unchanged. The Json object do not need to embed concrete types names.
This SO post offers the same solution one step further with a generic JsonConverter.
Make sure you are using Javascript module or not?!
if using js6 modules your html events attributes won't work.
in that case you must bring your function from global scope to module scope. Just add this to your javascript file:
window.functionName= functionName;
example:
<h1 onClick="functionName">some thing</h1>
In bootstrap 4, they have designed a bigger input file.
A simple solution to increase the size input file is to use font-size
:
Add you style, for example:
input[type="file"] {
font-size:35px
}
Otherwise, you can make one custom class and add to input control.
I am not an expert on the python world but I have been using django which is an excellent web framework and can be used to create a restful framework.
To add primary key in the column.
ALTER TABLE table_name ADD PRIMARY KEY (column_name);
To remove primary key from the table.
ALTER TABLE table_name DROP PRIMARY KEY;
You can just do this:
const char *text = "This is my string it is "
"very long";
You can use the jQuery animation for scroll page with a specific duration:
$("html, body").animate({scrollTop: "1024px"}, 5000);
where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.
I did it like this when I wanted a tmiestamp
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
Hope it helps :) As a newbie I think it's self-explanatory
I think you also need import java.text.SimpleDateFormat; header for it to work :))
you can't. foo-bar
is not an identifier. rename the file to foo_bar.py
Edit: If import
is not your goal (as in: you don't care what happens with sys.modules
, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile
# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>>
just fetch specific node data and its working perfect for me
mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.e(TAG, "======="+postSnapshot.child("email").getValue());
Log.e(TAG, "======="+postSnapshot.child("name").getValue());
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});