You can try it by adding
Use aapt
from the SDK like
aapt dump badging yourpkg.apk
This will print the package name together with other info.
the tools is located in
<sdk_home>/build-tools/android-<api_level>
or
<sdk_home>/platform-tools
or
<sdk_home>/platforms/android-<api_level>/tools
Updated according to geniusburger's comment. Thanks!
You can use inWaiting()
to get the amount of bytes available at the input queue.
Then you can use read()
to read the bytes, something like that:
While True:
bytesToRead = ser.inWaiting()
ser.read(bytesToRead)
Why not to use readline()
at this case from Docs:
Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.
You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)
Use the following CSS codes...
text-decoration:underline;
text-decoration-style: dotted;
In my case a URL rewrite rule was messing with my service name, it was rewritten as lowercase and I was getting this error.
Make sure you don't lowercase WCF service calls.
Responsive website by add padding into bottom image height/width x 100 = padding-bottom %:
http://www.outsidethebracket.com/responsive-web-design-fluid-background-images/
More complicated method:
http://voormedia.com/blog/2012/11/responsive-background-images-with-fixed-or-fluid-aspect-ratios
Try to resize background eq Firefox Ctrl + M to see magic nice script i think best one:
http://www.minimit.com/demos/fullscreen-backgrounds-with-centered-content
This should get you started:
set datafile separator ","
plot 'infile' using 0:1
You can use a much simpler formula. I just created a new workbook to test it.
Column A = Date1 | Column B = Date2 | Column C = Date3
Highlight Column A and enter the conditional formatting formula:
=AND(A1>B1,A1<C1)
XmlDocument.Attributes
perhaps? (Which has a method GetNamedItem that will presumably do what you want, although I've always just iterated the attribute collection)
You can make a back-tracker character, ex, you could append any special character say "%" to the end of your string and then check the occurrence of that character.
But this is a very risky way as that character can be in other places also in the char*
char* stringVar = new char[4] ;
stringVar[0] = 'H' ;
stringVar[1] = 'E' ;
stringVar[2] = '$' ; // back-tracker character.
int i = 0 ;
while(1)
{
if (stringVar[i] == '$')
break ;
i++ ;
}
// i is the length of the string.
// you need to make sure, that there is no other $ in the char*
Otherwise define a custom structure to keep track of length and allocate memory.
public Integer binaryToInteger(String binary){
char[] numbers = binary.toCharArray();
Integer result = 0;
int count = 0;
for(int i=numbers.length-1;i>=0;i--){
if(numbers[i]=='1')result+=(int)Math.pow(2, count);
count++;
}
return result;
}
I guess I'm even more bored! Modified Hassan's answer to function correctly.
If it is in the same class it is fine to trust the method.
It is very common to do this. It is good practice to check null values in constructor's and method's arguments to make sure that nobody is passing null values into them (if it is not allowed). Then if you implement your methods in a way that they never set the "start" graph to null, don't check for nulls there.
It is also good practice to implement unit tests for your methods and make sure that they are correctly implemented, so you can trust them.
You can also check it using jQuery.. It's quite easy:
<html>
<head>
<title>jQuery: Check if Textbox is empty</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>
<body>
<form name="form1" method="post" action="">
<label for="city">City:</label>
<input type="text" name="city" id="city">
</form>
<button id="check">Check</button>
<script type="text/javascript">
$('#check').click(function () {
if ($('#city').val() == '') {
alert('Empty!!!');
} else {
alert('Contains: ' + $('#city').val());
}
});
</script>
</body>
</html>
This procedure assumes that:
Of course this is not perfect, but in certain (probably most) cases it will work.
DELIMITER $$
CREATE PROCEDURE DUPLICATE_ROW(copytable VARCHAR(255), primarykey VARCHAR(255), copyid INT, out newid INT)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION SET @error=1;
SET @temptable = '_duplicate_temp_table';
SET @sql_text = CONCAT('CREATE TABLE ', @temptable, ' LIKE ', copytable);
PREPARE stmt FROM @sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql_text = CONCAT('INSERT INTO ', @temptable, ' SELECT * FROM ', copytable, ' where ', primarykey,'=', copyid);
PREPARE stmt FROM @sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql_text = CONCAT('SELECT max(', primarykey, ')+1 FROM ', copytable, ' INTO @newid');
PREPARE stmt FROM @sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql_text = CONCAT('UPDATE ', @temptable, ' SET ', primarykey, '=@newid');
PREPARE stmt FROM @sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql_text = CONCAT('INSERT INTO ', copytable, ' SELECT * FROM ', @temptable, '');
PREPARE stmt FROM @sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql_text = CONCAT('DROP TABLE ', @temptable);
PREPARE stmt FROM @sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SELECT @newid INTO newid;
END $$
DELIMITER ;
CALL DUPLICATE_ROW('table', 'primarykey', 1, @duplicate_id);
SELECT @duplicate_id;
For others that find themselves here, the css I was looking for was
overflow-wrap: break-word;
Which will only break a word if it needs to (the length of the single word is greater than the width of the p), unlike word-break: break-all
which can break the last word of every line.
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
After pasting the code in ThisOutlookSession
module, you must restart Outlook.
Ya mybe u can use document.documentElement.clientWidth to get the device width of client and keep tracking the device width by put on setInterval
just like
setInterval(function(){
width = document.documentElement.clientWidth;
console.log(width);
}, 1000);
As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:
var mahByteArray = new ArrayList<byte>();
If you have a byte array from elsewhere, you can use the AddRange function.
mahByteArray.AddRange(mahOldByteArray);
Then you can use Add() and Insert() to add elements.
mahByteArray.Add(0x00); // Adds 0x00 to the end.
mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.
Need it back in an array? .ToArray() has you covered!
mahOldByteArray = mahByteArray.ToArray();
Here is just a reply from Richard Pickup on LinkedIn to a similar question of mine:
I've used cocos 2dx marmalade and unity on both iOS and android. For 2d games cocos2dx is the way to go every time. Unity is just too much overkill for 2d games and as already stated marmalade is just a thin abstraction layer not really a game engine. You can even run cocos2d on top of marmalade. My approach would be to use cocos2dx on iOS and android then in future run cocosd2dx code on top of marmalade as an easy way to port to bb10 and win phone 7
If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.
Or you can do this way :
((TextView)findViewById(R.id.this_is_the_id_of_textview)).setText("Test");
For others facing this issue in Eclipse even with path set to JDK correctly, you need to remove the other JREs from Installed JREs.
Go to Window -> Preferences -> Java -> Installed JREs
Select unused JREs individually and Remove
It worked for me.
I found your question because I was also fighting with NSAttributedString.
For me, the beginEditing
and endEditing
methods did the trick, like stated in Changing an Attributed String.
Apart from that, the lineSpacing is set with setLineSpacing
on the paragraphStyle.
So you might want to try changing your code to:
NSString *string = @" Hello \n world";
attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineSpacing:20] // Or whatever (positive) value you like...
[attrSting beginEditing];
[attrString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, string.length)];
[attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
[attrString endEditing];
mainTextView.attributedText = attrString;
Didn't test this exact code though, btw, but mine looks nearly the same.
Meanwhile, I've tested it, and, correct me if I'm wrong, the - beginEditing
and - endEditing
calls seem to be of quite an importance.
var mapped = _.reduce({ one: 1, two: 2, three: 3 }, function(obj, val, key) {_x000D_
obj[key] = val*3;_x000D_
return obj;_x000D_
}, {});_x000D_
_x000D_
console.log(mapped);
_x000D_
<script src="http://underscorejs.org/underscore-min.js"></script>_x000D_
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
_x000D_
You can use checkout or co
$ svn co http://example.com/svn/app-name directory-name
Some short codes:-
As already mentioned, Chrome Extensions don't allow to have inline JavaScript due to security reasons so you can try this workaround as well.
HTML file
<!doctype html>
<html>
<head>
<title>
Getting Started Extension's Popup
</title>
<script src="popup.js"></script>
</head>
<body>
<div id="text-holder">ha</div><br />
<a class="clickableBtn">
hyhy
</a>
</body>
</html>
<!doctype html>
popup.js
window.onclick = function(event) {
var target = event.target ;
if(target.matches('.clickableBtn')) {
var clickedEle = document.activeElement.id ;
var ele = document.getElementById(clickedEle);
alert(ele.text);
}
}
Or if you are having a Jquery file included then
window.onclick = function(event) {
var target = event.target ;
if(target.matches('.clickableBtn')) {
alert($(target).text());
}
}
@bduke's answer actually works with a slight tweak.
var index = $("#tabs>div").index($("#simple-tab-2"));
$("#tabs").tabs("select", index);
Above assumes something similar to:
<div id="tabs">
<ul>
<li><a href="#simple-tab-0">Tab 0</a></li>
<li><a href="#simple-tab-1">Tab 1</a></li>
<li><a href="#simple-tab-2">Tab 2</a></li>
<li><a href="#simple-tab-3">Tab 3</a></li>
</ul>
<div id="simple-tab-0"></div>
<div id="simple-tab-1"></div>
<div id="simple-tab-2"></div>
<div id="simple-tab-3"></div>
</div>
jQueryUI now supports calling "select" using the tab's ID/HREF selector, but when constructing the tabs, the "selected" Option still only supports the numeric index.
My vote goes to bdukes for getting me on the right track. Thanks!
You'd need to make the enum expose value
somehow, e.g.
public enum Tax {
NONE(0), SALES(10), IMPORT(5);
private final int value;
private Tax(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
...
public int getTaxValue() {
Tax tax = Tax.NONE; // Or whatever
return tax.getValue();
}
(I've changed the names to be a bit more conventional and readable, btw.)
This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.
Here is a concise way using lambdas and JDK 8 Supplier to fit everything in the outer try:
try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
PreparedStatement stmt = ((Supplier<PreparedStatement>)() -> {
try {
PreparedStatement s = con.prepareStatement("SELECT userid, name, features FROM users WHERE userid = ?");
s.setInt(1, userid);
return s;
} catch (SQLException e) { throw new RuntimeException(e); }
}).get();
ResultSet resultSet = stmt.executeQuery()) {
}
I've used this to solve my similar problem ... displaying an image counter (from an external provider). It did not refresh always correctly. And after a random parameter was added, all works fine :)
I've appended a date string to ensure refresh at least every minute.
sample code (PHP):
$output .= "<img src=\"http://xy.somecounter.com/?id=1234567890&".date(ymdHi)."\" alt=\"somecounter.com\" style=\"border:none;\">";
That results in a src
link like:
http://xy.somecounter.com/?id=1234567890&1207241014
I recently faced this same situation and found an easier inbuilt solution. I am sharing it here so that it might help other people looking for solution.
With OS X Yosemite, Apple has integrated the batch renaming capabilities directly into Finder. Details information is available here. I have copied the steps below as well,
Rename multiple items
Select the items, then Control-click one of them.
In the shortcut menu, select Rename Items.
In the pop-up menu below Rename Folder Items, choose to replace text in the names, add text to the names, or change the name format.
Replace text: Enter the text you want to remove in the Find field, then enter the text you want to add in the “Replace with” field.
Add text: Enter the text to you want to add in the field, then choose to add the text before or after the current name.
Format: Choose a name format for the files, then choose to put the index, counter, or date before or after the name. Enter a name in the Custom Format field, then enter the number you want to start with.
Click Rename.
If you have a common pattern in your files than you can use Replace text otherwise Add text would also do the job.
Use Massif: http://valgrind.org/docs/manual/ms-manual.html
I took a more compact approach to split an input resulting from a text area into a list of string . You can use this if suits your purpose.
the problem is you cannot split by \r\n so i removed the \n beforehand and split only by \r
var serials = model.List.Replace("\n","").Split('\r').ToList<string>();
I like this approach because you can do it in just one line.
in python intended block mean there is every thing must be written in manner in my case I written it this way
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_input.set(operator)
Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code
def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)
if you want use VectorDrawable and ConstraintLayout
<FrameLayout
android:id="@+id/ok_button"
android:layout_width="100dp"
android:layout_height="100dp"
android:foreground="?attr/selectableItemBackgroundBorderless"
android:background="@drawable/circle_button">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/icon_of_button"
android:layout_width="32dp"
android:layout_height="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:srcCompat="@drawable/ic_thumbs_up"/>
<TextView
android:id="@+id/text_of_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/icon_of_button"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="5dp"
android:textColor="@android:color/white"
android:text="ok"
/>
</android.support.constraint.ConstraintLayout>
</FrameLayout>
circle background: circle_button.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="1000dp" />
<solid android:color="#41ba7a" />
<stroke
android:width="2dip"
android:color="#03ae3c" />
<padding
android:bottom="4dp"
android:left="4dp"
android:right="4dp"
android:top="4dp" />
</shape>
I think here "inflating a view" means fetching the layout.xml file drawing a view specified in that xml file and POPULATING ( = inflating ) the parent viewGroup with the created View.
While iterating over a list or array with this method:
ar = [10, 11, 12]
for i in ar:
theSum = theSum + ar[i]
You are actually getting the values of list or array sequentially in i
variable.
If you print the variable i
inside the for loop
. You will get following output:
10
11
12
However, in your code you are confusing i
variable with index value of array. Therefore, while doing ar[i]
will mean ar[10]
for the first iteration. Which is of course index out of range throwing IndexError
Edit You can read this for better understanding of different methods of iterating over array or list in Python
Check if its not already defined, otherwise defines it on the Date prototype:
if (!Date.prototype.addHours) {
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
};
}
You can use this as well
import numpy as np
x=np.array(['1.1', '2.2', '3.3'])
x=np.asfarray(x,float)
If you just need to check if the two strings are exactly same,
text1 = 'apple'
text2 = 'apple'
text1 == text2
The result will be
True
If you need the matching percentage,
import difflib
text1 = 'Since 1958.'
text2 = 'Since 1958'
output = str(int(difflib.SequenceMatcher(None, text1, text2).ratio()*100))
Matching percentage output will be,
'95'
The solution to the problem is:
Find the .gitconfig file
[user] name = 1wQasdTeedFrsweXcs234saS56Scxs5423 email = [email protected] [credential] helper = osxkeychain [url ""] insteadOf = git:// [url "https://"] [url "https://"] insteadOf = git://
there would be a blank url="" replace it with url="https://"
[user]
name = 1wQasdTeedFrsweXcs234saS56Scxs5423
email = [email protected]
[credential]
helper = osxkeychain
[url "https://"]
insteadOf = git://
[url "https://"]
[url "https://"]
insteadOf = git://
This will work :)
Happy Bower-ing
days
, years
, etc., are part of Active Support, So this won't work in irb
, but it should work in rails console
.
I did it this way: Just add the event to any control, set the control's tag, and add a conditional to handle the tooltip for the appropriate control/tag.
private void Info_MouseHover(object sender, EventArgs e)
{
Control senderObject = sender as Control;
string hoveredControl = senderObject.Tag.ToString();
// only instantiate a tooltip if the control's tag contains data
if (hoveredControl != "")
{
ToolTip info = new ToolTip
{
AutomaticDelay = 500
};
string tooltipMessage = string.Empty;
// add all conditionals here to modify message based on the tag
// of the hovered control
if (hoveredControl == "save button")
{
tooltipMessage = "This button will save stuff.";
}
info.SetToolTip(senderObject, tooltipMessage);
}
}
Take a character pointer to store required string.If you have some idea about possible size of string then use function
char *fgets (char *str, int size, FILE* file);`
else you can allocate memory on runtime too using malloc() function which dynamically provides requested memory.
This article helped, it's pretty much what the other answers said but summarize and concise
https://medium.com/@andersongusmao/left-and-right-margins-on-uitableviewcell-595f0ba5f5e6
In it, he only applies them to left and right sides but the UIEdgeInsetsMake
init allows to add padding to all four points.
func UIEdgeInsetsMake(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat) -> UIEdgeInsets
Description
Creates an edge inset for a button or view. An inset is a margin around a rectangle. Positive values represent margins closer to the center of the rectangle, while negative values represent margins further from the center.Parameters
top: The inset at the top of an object.
left: The inset on the left of an object
bottom: The inset on the bottom of an object.
right: The inset on the right of an object.Returns
An inset for a button or view
Note that UIEdgeInsets can also be used to achieve the same.
Xcode 9.3/Swift 4
I realise this is only applicable to a niche of the situations, but within a numpy
context I really like using np.errstate
:
np.sqrt(-1)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
nan
However, using np.errstate
:
with np.errstate(invalid='ignore'):
np.sqrt(-1)
nan
The best part being you can apply this to very specific lines of code only.
hh.exe
(help pages renderer) is capable of opening some simple webpages:
hh http://www.nissan.com
This will work even if browsing is blocked through:
HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer
This is one of the biggest sources of confusion with VB.Net, IMO.
Nothing
in VB.Net is the equivalent of default(T)
in C#: the default value for the given type.
0
for Integer
, False
for Boolean
, DateTime.MinValue
for DateTime
, ... null
value (a reference that refers to, well, nothing).The statement d Is Nothing
is therefore equivalent to d Is DateTime.MinValue
, which obviously does not compile.
Solutions: as others have said
DateTime?
(i.e. Nullable(Of DateTime)
). This is my preferred solution.d = DateTime.MinValue
or equivalently d = Nothing
In the context of the original code, you could use:
Dim d As DateTime? = Nothing
Dim boolNotSet As Boolean = d.HasValue
A more comprehensive explanation can be found on Anthony D. Green's blog
make Sublime Text 3 your default text editor: (Restart required)
defaults write com.apple.LaunchServices LSHandlers -array-add "{LSHandlerContentType=public.plain-text;LSHandlerRoleAll=com.sublimetext.3;}"
make sublime then your default git text editor
git config --global core.editor "subl -W"
Using a void * means that the function can take a pointer that doesn't need to be a specific type. For example, in socket functions, you have
send(void * pData, int nLength)
this means you can call it in many ways, for example
char * data = "blah";
send(data, strlen(data));
POINT p;
p.x = 1;
p.y = 2;
send(&p, sizeof(POINT));
The best approach to this problem is first making the database column UNIQUE
ALTER TABLE table_name ADD UNIQUE KEY
THEN INSERT IGNORE INTO table_name
,the value won't be inserted if it results in a duplicate key/already exists in the table.
Just run the below two lines when you want to exit from the application
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
Port: In simple language, "Port" is a number used by a particular software to identify its data coming from internet.
Each software, like Skype, Chrome, Youtube has its own port number and that's how they know which internet data is for itself.
Socket: "IP address and Port " together is called "Socket". It is used by another computer to send data to one particular computer's particular software.
IP address is used to identify the computer and Port is to identify the software such as IE, Chrome, Skype etc.
In every home, there is one mailbox and multiple people. The mailbox is a host. Your own home mailbox is a localhost. Each person in a home has a room. All letters for that person are sent to his room, hence the room number is a port.
Do not try to prevent SQL injection by sanitizing input data.
Instead, do not allow data to be used in creating your SQL code. Use Prepared Statements (i.e. using parameters in a template query) that uses bound variables. It is the only way to be guaranteed against SQL injection.
Please see my website http://bobby-tables.com/ for more about preventing SQL injection.
I know it's been a little over two years... but I was looking for a way to do this, and wasn't overly happy with the solution posted (it works fine, but I wanted a little more information as the import happens). When combining all the SQL files in to one, you don't get any sort of progress updates.
So I kept digging for an answer and thought this might be a good place to post what I found for future people looking for the same answer. Here's a command line in Windows that will import multiple SQL files from a folder. You run this from the command line while in the directory where mysql.exe is located.
for /f %f in ('dir /b <dir>\<mask>') do mysql --user=<user> --password=<password> <dbname> < <dir>\%f
With some assumed values (as an example):
for /f %f in ('dir /b c:\sqlbackup\*.sql') do mysql --user=mylogin --password=mypass mydb < c:\sqlbackup\%f
If you had two sets of SQL backups in the folder, you could change the *.sql to something more specific (like mydb_*.sql).
l = [1, 2, 3]
print '\n'.join(['%i: %s' % (n, l[n]) for n in xrange(len(l))])
You can use the change command to replace the entire line, and the -i
flag to make the changes in-place. For example, using GNU sed:
sed -i '/TEXT_TO_BE_REPLACED/c\This line is removed by the admin.' /tmp/foo
Filter()
from the base package is the perfect function for that use-case:
You simply have to code:
Filter(is.numeric, x)
It is also much faster than select_if()
:
library(microbenchmark)
microbenchmark(
dplyr::select_if(mtcars, is.numeric),
Filter(is.numeric, mtcars)
)
returns (on my computer) a median of 60 microseconds for Filter
, and 21 000 microseconds for select_if
(350x faster).
For Spark 2.0
# assumes schema has 'age' column
df.select('*', (df.age + 10).alias('agePlusTen'))
You will need to install a local mailserver in order to do this. If you want to send it to external e-mail addresses, it might end up in unwanted e-mails or it may not arrive at all.
A good mailserver which I use (I use it on Linux, but it's also available for Windows) is Axigen: http://www.axigen.com/mail-server/download/
You might need some experience with mailservers to install it, but once it works, you can do anything you want with it.
Quick work around
Simply enclose the list within a new list, as done for col2 in the data frame below. The reason it works is that python takes the outer list (of lists) and converts it into a column as if it were containing normal scalar items, which is lists in our case and not normal scalars.
mydict={'col1':[1,2,3],'col2':[[1, 4], [2, 5], [3, 6]]}
data=pd.DataFrame(mydict)
data
col1 col2
0 1 [1, 4]
1 2 [2, 5]
2 3 [3, 6]
Apparently, action
was required prior to HTML5 (and #
was just a stand in), but you no longer have to use it.
See The Action Attribute:
When specified with no attributes, as below, the data is sent to the same page that the form is present on:
<form>
from IPython import get_ipython;
get_ipython().magic('reset -sf')
I have done this way:
Get Compressed Bitmap from Singleton class:
ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap("Your_Image_Path_Here");
imageView.setImageBitmap(bitmap);
ImageUtils.java:
public class ImageUtils {
public static ImageUtils mInstant;
public static ImageUtils getInstant(){
if(mInstant==null){
mInstant = new ImageUtils();
}
return mInstant;
}
public Bitmap getCompressedBitmap(String imagePath) {
float maxHeight = 1920.0f;
float maxWidth = 1080.0f;
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float imgRatio = (float) actualWidth / (float) actualHeight;
float maxRatio = maxWidth / maxHeight;
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
bmp = BitmapFactory.decodeFile(imagePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
ExifInterface exif = null;
try {
exif = new ExifInterface(imagePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);
byte[] byteArray = out.toByteArray();
Bitmap updatedBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
return updatedBitmap;
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
}
Dimensions are same after compressing Bitmap.
How did I checked ?
Bitmap beforeBitmap = BitmapFactory.decodeFile("Your_Image_Path_Here");
Log.i("Before Compress Dimension", beforeBitmap.getWidth()+"-"+beforeBitmap.getHeight());
Bitmap afterBitmap = ImageUtils.getInstant().getCompressedBitmap("Your_Image_Path_Here");
Log.i("After Compress Dimension", afterBitmap.getWidth() + "-" + afterBitmap.getHeight());
Output:
Before Compress : Dimension: 1080-1452
After Compress : Dimension: 1080-1452
Hope this will help you.
Apparently I don't have enough reputation points to comment on Dansalmo's answer, but it is a good one, though mis-named. His answer is actually a K-combinator.
int K( int a, int b ) {
return a;
}
The JLS is specific about argument evaluation when passing to methods/ctors/etc. (Was this not so in older specs?)
Granted, this is a functional idiom, but it is clear enough to those who recognize it. (If you don't understand code you find, don't mess with it!)
y = K(x, x=y); // swap x and y
The K-combinator is specifically designed for this kind of thing. AFAIK there's no reason it shouldn't pass a code review.
My $0.02.
See https://devcenter.heroku.com/articles/git#deploying-code
$ git push heroku yourbranch:master
git fetch && git checkout branch_name
( "branch_name" here is the name of the branch )
Then you will see message, Switched to a new branch 'branch_name' Branch 'branch_name' set up to track remote branch 'branch_name' from 'origin'.
Get is supposed to return, one and exactly one record, to fix this use filter()
, and then take first element of the queryset returned to get the object you were expecting from get, also it would be useful to check if atleast one record is returned before taking out the first element to avoid IndexError
You could try the following
select case when mydatetime IS NULL THEN '' else convert(varchar(20),@mydatetime,120) end as converted_date from sometable
-- Testing it out could do --
declare @mydatetime datetime
set @mydatetime = GETDATE() -- comment out for null value
--set @mydatetime = GETDATE()
select
case when @mydatetime IS NULL THEN ''
else convert(varchar(20),@mydatetime,120)
end as converted_date
Hope this helps!
INSERT INTO <table> (<date_column>) VALUES ('1/1/2010 12:00')
I had faced same problem because I downloaded TestNG plugin from Eclipse. Here what I did to get the Job done :
After adding TestNG to your project library create one folder in your Project names as lib ( name can be anything ) :
Go to "C:\Program Files\Eclipse\eclipse-java-mars-R-win32-x86_64\eclipse\plugins" location and copy com.beust.jcommander_1.72.0.jar and org.testng_6.14.2.r20180216145.jar file to created folder (lib).
Note : Files are testng.jar and jcommander.jar
That's it !
Let me know if you have any more concerns.
Everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.
Objects that end with the delimiter (/
in most cases) are usually perceived as a folder, but it's not always the case. It depends on the application. Again, in your case, you're interpretting it as a folder. S3 is not. It's just another object.
In your case above, the object users/<user-id>/contacts/<contact-id>/
exists in S3 as a distinct object, but the object users/<user-id>/
does not. That's the difference in your responses. Why they're like that, we cannot tell you, but someone made the object in one case, and didn't in the other. You don't see it in the AWS Management Console because the console is interpreting it as a folder and hiding it from you.
Since S3 just sees these things as objects, it won't "exclude" certain things for you. It's up to the client to deal with the objects as they should be dealt with.
Your Solution
Since you're the one that doesn't want the folder objects, you can exclude it yourself by checking the last character for a /
. If it is, then ignore the object from the response.
Here is an update to Vadim Shender's clever code with tabular output:
import collections
import time
from functools import wraps
PROF_DATA = collections.defaultdict(list)
def profile(fn):
@wraps(fn)
def with_profiling(*args, **kwargs):
start_time = time.time()
ret = fn(*args, **kwargs)
elapsed_time = time.time() - start_time
PROF_DATA[fn.__name__].append(elapsed_time)
return ret
return with_profiling
Metrics = collections.namedtuple("Metrics", "sum_time num_calls min_time max_time avg_time fname")
def print_profile_data():
results = []
for fname, elapsed_times in PROF_DATA.items():
num_calls = len(elapsed_times)
min_time = min(elapsed_times)
max_time = max(elapsed_times)
sum_time = sum(elapsed_times)
avg_time = sum_time / num_calls
metrics = Metrics(sum_time, num_calls, min_time, max_time, avg_time, fname)
results.append(metrics)
total_time = sum([m.sum_time for m in results])
print("\t".join(["Percent", "Sum", "Calls", "Min", "Max", "Mean", "Function"]))
for m in sorted(results, reverse=True):
print("%.1f\t%.3f\t%d\t%.3f\t%.3f\t%.3f\t%s" % (100 * m.sum_time / total_time, m.sum_time, m.num_calls, m.min_time, m.max_time, m.avg_time, m.fname))
print("%.3f Total Time" % total_time)
I was using Maven in eclipse and I did not want to have an additional copy of the properties file in the root folder. You can do the following in eclipse:
In View Replace this:
@Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
With:
@if(@Model.AuditDate.Value != null){@Model.AuditDate.Value.ToString("dd/MM/yyyy")}
else {@Html.DisplayFor(Model => Model.AuditDate)}
Explanation: If the AuditDate value is not null then it will format the date to dd/MM/yyyy, otherwise leave it as it is because it has no value.
I met this issue due to operation system, simple to different platform about JRE implementation.
new SecureRandom(key.getBytes())
will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.
It can easilly be done with ArgueJS:
function myFunction ()
{
arguments = __({myDate: Date, myString: String});
// do stuff
};
You may have this issue as well if you have environment variable GCC_ROOT pointing to a wrong location. Probably simplest fix could be (on *nix like system):
unset GCC_ROOT
in more complicated cases you may need to repoint it to proper location
you can solve it
sudo nano /etc/apache2/ports.conf
and changed Listen to 8080
Who don't you use the jQuery UI DatePicker?
It's configurable to suit pretty much any needs. The only downside is if you're including it with jQuery UI it has a somewhat large footprint..
Some of the file sizes appear to have changed, so they are updated below. Keep in mind these numbers will only be correct for the time they were last updated. Things may have changed since then.
But that's not too bad...
If notepad is already started, you should write:
// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
//...
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
}
GetProcessesByName
returns an array of processes, so you should get the first one (or find the one you want).
If you want to start notepad
and send the key, you should write:
Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
The only situation in which the code may not work is when notepad
is started as Administrator and your application is not.
you can stash the uncommitted changes using "git stash" then checkout to a new branch using "git checkout -b " then apply the stashed commits "git stash apply"
Yes, multiple calls to where() is a perfectly valid way to achieve this.
$this->db->where('username',$username);
$this->db->where('status',$status);
http://www.codeigniter.com/user_guide/database/query_builder.html
I've gotten the following to work:
html {
background:
linear-gradient(rgba(0,184,255,0.45),rgba(0,184,255,0.45)),
url('bgimage.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
The above will produce a nice opaque blue overlay.
If your list-style is inside
then you could remove the bullet and create your own ... e.g. (in scss!)
li {
list-style: none;
&:before {
content: '- ';
}
}
And if you list style is outside
then you could do something like this:
li {
padding-left: 10px;
list-style: none;
&:before {
content: '* '; /* use any character you fancy~! */
position: absolute;
margin-left: -10px;
}
}
looks to me yum install glibc.i686 should have worked. Unless Peter was not root. He has the 64 bit glib installed, he is installing a 32 bit package that requires the 32 bit glib which is glib.i686 for intel processors.
There is one disadvantage you should be aware of: As soon as you out-source files to a CDN (or any other server which doesn't allow scripting) or if your files are cached on a proxy, altering response based on 'Origin' request header will not work.
Put this code above any Soap call:
libxml_disable_entity_loader(false);
Just for the record, there is an alternative solution that does not require javascript. It is a bit of a hack, exploiting the fact that clicking on a label sets the focus on the associated input.
You need a <label>
with a proper for
attribute (points to the input), optionnaly styled like a button (with bootstrap, use btn btn-default
). When the user clicks the label, the dialog opens, example :
<!-- optionnal, to add a bit of style -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- minimal setup -->_x000D_
<label for="exampleInput" class="btn btn-default">_x000D_
Click me_x000D_
</label>_x000D_
<input type="file" id="exampleInput" style="display: none" />
_x000D_
I write this code and It's worked for me .
public static string ExcutePushNotification(string title, string msg, string fcmToken, object data)
{
var serverKey = "AAAA*******************";
var senderId = "3333333333333";
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
httpWebRequest.Method = "POST";
var payload = new
{
notification = new
{
title = title,
body = msg,
sound = "default"
},
data = new
{
info = data
},
to = fcmToken,
priority = "high",
content_available = true,
};
var serializer = new JavaScriptSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = serializer.Serialize(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
It's a hex number and is 16 decimal.
If you had a table that already had a existing constraints based on lets say: name and lastname and you wanted to add one more unique constraint, you had to drop the entire constrain by:
ALTER TABLE your_table DROP CONSTRAINT constraint_name;
Make sure tha the new constraint you wanted to add is unique/ not null ( if its Microsoft Sql, it can contain only one null value) across all data on that table, and then you could re-create it.
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n);
You could specify what branch you want to pull:
git pull origin master
Or you could set it up so that your local master branch tracks github master branch as an upstream:
git branch --set-upstream-to=origin/master master
git pull
This branch tracking is set up for you automatically when you clone a repository (for the default branch only), but if you add a remote to an existing repository you have to set up the tracking yourself. Thankfully, the advice given by git makes that pretty easy to remember how to do.
Height and width are zero because view has not been created by the time you are requesting it's height and width . One simplest solution is
view.post(new Runnable() {
@Override
public void run() {
view.getHeight(); //height is ready
view.getWidth(); //width is ready
}
});
This method is good as compared to other methods as it is short and crisp.
If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:
if (thing && thing.foo)
alert(thing.foo.bar);
I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:
function someFunc(parameterName) {
if (parameterName && parameterName.foo)
alert(parameterName.foo.bar);
}
Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.
Do it like this:
p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)
# get output from process "Something to print"
one_line_output = p.stdout.readline()
# write 'a line\n' to the process
p.stdin.write('a line\n')
# get output from process "not time to break"
one_line_output = p.stdout.readline()
# write "n\n" to that process for if r=='n':
p.stdin.write('n\n')
# read the last output from the process "Exiting"
one_line_output = p.stdout.readline()
What you would do to remove the error:
all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]
But since communicate closes the stdout
and stdin
and stderr
, you can not read or write after you called communicate.
Using solve
with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.
You just need to add 'table-layout: fixed;'
.table {
display: table;
height: 100px;
width: 100%;
table-layout: fixed;
}
To enable CORS, 1.Go to App_Start folder. 2.add the namespace 'using System.Web.Http.Cors'; 3.Open the WebApiConfig.cs file and type the following in a static method.
config.EnableCors(new EnableCorsAttribute("https://localhost:44328",headers:"*", methods:"*"));
_x000D_
Add the HTTP header manager and add in it your API's header names and values. e.g. Content-type, Accept, etc. That will resolve your issue.
Including the fb:app_id
tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.
The fb:admins
tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.
You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins
is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.
fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>
and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>
While pow( base, exp )
is a great suggestion, be aware that it typically works in floating-point.
This may or may not be what you want: on some systems a simple loop multiplying on an accumulator will be faster for integer types.
And for square specifically, you might as well just multiply the numbers together yourself, floating-point or integer; it's not really a decrease in readability (IMHO) and you avoid the performance overhead of a function call.
I was facing the same issue, after trying most of the methods mentioned above I couldn't get the solution. In my case the issue of because of Github changing the name of master
to main
branch.
Go to Setting -> go to GitHub Pages section and change the branch to main:
to
Save it and select a theme, and the website is live.
FileInputStream is an inputStream.
FileInputStream fis = new FileInputStream("c://filename");
InputStream is = fis;
fis.close();
return is;
Of course, this will not do what you want it to do; the stream you return has already been closed. Just return the FileInputStream and be done with it. The calling code should close it.
You can use git-archive, for example:
git archive master | bzip2 > project.tar.bz2
Where master
is the desired branch.
Zero-size array passed to numpy.mean
raises this warning (as indicated in several comments).
For some other candidates:
median
also raises this warning on zero-sized array.other candidates do not raise this warning:
min,argmin
both raise ValueError
on empty arrayrandn
takes *arg
; using randn(*[])
returns a single random numberstd,var
return nan
on an empty arrayThe decode
method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.
unicode().decode()
will perform an implicit encoding of s
using the default (ascii) codec. Verify this like so:
>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)
>>> s.encode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)
The error messages are exactly the same.
For str().encode()
it's the other way around -- it attempts an implicit decoding of s
with the default encoding:
>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
Used like this, str().encode()
is also superfluous.
But there is another application of the latter method that is useful: there are encodings that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way:
>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'
You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate byte
and string
types in Python 3, this is no longer an issue.
No, it only contains a free 30 day trial. But I think there would be a package if you buy Visual Studio + Xamarin.
Following command will let you run something in the background without getting nohup.out:
nohup command |tee &
In this way, you will be able to get console output while running script on the remote server:
You can use BOOL, BOOLEAN data type for storing boolean values.
These types are synonyms for TINYINT(1)
However, the BIT(1) data type makes more sense to store a boolean value (either true[1] or false[0]) but TINYINT(1) is easier to work with when you're outputting the data, querying and so on and to achieve interoperability between MySQL and other databases. You can also check this answer or thread.
MySQL also converts BOOL, BOOLEAN data types to TINYINT(1).
Further, read documentation
looks like you have maven project and so resources are in classpath by
go for
getClass().getResource("classpath:storedProcedures.sql")
on Windows F9 to run single line
Select the lines which you want to run on console and press F9 button for multi line
This was working for me so Try This: $ad->getcodes()->distinct('pid')->count()
if you do any changes on git ignore then you have to clear you git cache also
> git rm -r --cached .
> git add .
> git commit -m 'git cache cleared'
> git push
if want to remove any particular folder or file then
git rm --cached filepath/foldername
This code reads csv to DataTable:
public static DataTable ReadCsv(string path)
{
DataTable result = new DataTable("SomeData");
using (TextFieldParser parser = new TextFieldParser(path))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
bool isFirstRow = true;
//IList<string> headers = new List<string>();
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
if (isFirstRow)
{
foreach (string field in fields)
{
result.Columns.Add(new DataColumn(field, typeof(string)));
}
isFirstRow = false;
}
else
{
int i = 0;
DataRow row = result.NewRow();
foreach (string field in fields)
{
row[i++] = field;
}
result.Rows.Add(row);
}
}
}
return result;
}
Easier solution will be changing this line
ft.replace(R.id.content_frame, A);
to ft.add(R.id.content_frame, A);
And inside your XML layout please use
android:background="@color/white"
android:clickable="true"
android:focusable="true"
Clickable
means that it can be clicked by a pointer device or be tapped by a touch device.
Focusable
means that it can gain the focus from an input device like a keyboard. Input devices like keyboards cannot decide which view to send its input events to based on the inputs itself, so they send them to the view that has focus.
Edit your style.xml
with:
<style name="AppTheme" parent="Base.V21.Theme.AppCompat.Light.Dialog">
Base.V21.Theme.AppCompat.Light.Dialog
provides a android poup-up theme
In cases where you do not have access to the derived class source, but need all the source of the derived class besides the current method, then I would recommended you should also do a derived class and call the implementation of the derived class.
Here is an example:
//No access to the source of the following classes
public class Base
{
public virtual void method1(){ Console.WriteLine("In Base");}
}
public class Derived : Base
{
public override void method1(){ Console.WriteLine("In Derived");}
public void method2(){ Console.WriteLine("Some important method in Derived");}
}
//Here should go your classes
//First do your own derived class
public class MyDerived : Base
{
}
//Then derive from the derived class
//and call the bass class implementation via your derived class
public class specialDerived : Derived
{
public override void method1()
{
MyDerived md = new MyDerived();
//This is actually the base.base class implementation
MyDerived.method1();
}
}
Slight modification of above answer to copy a folder recursively and to accommodate custom destination.
public void copyFileOrDir(String path, String destinationDir) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path,destinationDir);
} else {
String fullPath = destinationDir + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i], destinationDir + path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename, String destinationDir) {
AssetManager assetManager = this.getAssets();
String newFileName = destinationDir + "/" + filename;
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
new File(newFileName).setExecutable(true, false);
}
Python 3 has a built-in support for virtual environments - venv. It might be better to use that instead. Referring to the docs:
Creation of virtual environments is done by executing the pyvenv script:
pyvenv /path/to/new/virtual/environment
Update for Python 3.6 and newer:
As pawciobiel correctly comments, pyvenv
is deprecated as of Python 3.6 and the new way is:
python3 -m venv /path/to/new/virtual/environment
Today I was integrated ng2-file-upload package to my angular 6 application, It was pretty simple, Please find the below high-level code.
import the ng2-file-upload module
app.module.ts
import { FileUploadModule } from 'ng2-file-upload';
------
------
imports: [ FileUploadModule ],
------
------
Component ts file import FileUploader
app.component.ts
import { FileUploader, FileLikeObject } from 'ng2-file-upload';
------
------
const URL = 'http://localhost:3000/fileupload/';
------
------
public uploader: FileUploader = new FileUploader({
url: URL,
disableMultipart : false,
autoUpload: true,
method: 'post',
itemAlias: 'attachment'
});
public onFileSelected(event: EventEmitter<File[]>) {
const file: File = event[0];
console.log(file);
}
------
------
Component HTML add file tag
app.component.html
<input type="file" #fileInput ng2FileSelect [uploader]="uploader" (onFileSelected)="onFileSelected($event)" />
Working Online stackblitz Link: https://ng2-file-upload-example.stackblitz.io
Stackblitz Code example: https://stackblitz.com/edit/ng2-file-upload-example
Official documentation link https://valor-software.com/ng2-file-upload/
Let me throw out some example code that I got from http://www3.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html Then you can play around with different options until you understand it.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Date now = new Date();
//This is just Date's toString method and doesn't involve SimpleDateFormat
System.out.println("toString(): " + now); // dow mon dd hh:mm:ss zzz yyyy
//Shows "Mon Oct 08 08:17:06 EDT 2012"
SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at' h:m:s a z");
System.out.println("Format 1: " + dateFormatter.format(now));
// Shows "Mon, 2012-10-8 at 8:17:6 AM EDT"
dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Format 2: " + dateFormatter.format(now));
// Shows "Mon 2012.10.08 at 08:17:06 AM EDT"
dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
System.out.println("Format 3: " + dateFormatter.format(now));
// Shows "Monday, October 8, 2012"
// SimpleDateFormat can be used to control the date/time display format:
// E (day of week): 3E or fewer (in text xxx), >3E (in full text)
// M (month): M (in number), MM (in number with leading zero)
// 3M: (in text xxx), >3M: (in full text full)
// h (hour): h, hh (with leading zero)
// m (minute)
// s (second)
// a (AM/PM)
// H (hour in 0 to 23)
// z (time zone)
// (there may be more listed under the API - I didn't check)
}
}
Good luck!
@Kunigami: I think you may be mistaken about Guava's newArrayList
method. It does not check whether the Iterable is a List type and simply return the given List as-is. It always creates a new list:
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
// Let ArrayList's sizing logic work, if possible
return (elements instanceof Collection)
? new ArrayList<E>(Collections2.cast(elements))
: newArrayList(elements.iterator());
}
I faced the same issue, after reference somewhere, it worked as below changing:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
if you build an MVC project, its included by default. otherwise, what Nick said.
By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.
So just set it to:
<style name="AppTheme" parent="android:Theme.Holo" />
If you are using jQuery, you don't have to do anything special. Handlers added via $(document).ready()
don't overwrite each other, but rather execute in turn:
$(document).ready(func1)
...
$(document).ready(func2)
If you are not using jQuery, you could use addEventListener
, as demonstrated by Karaxuna, plus attachEvent
for IE<9.
Note that onload
is not equivalent to $(document).ready()
- the former waits for CSS, images... as well, while the latter waits for the DOM tree only. Modern browsers (and IE since IE9) support the DOMContentLoaded
event on the document, which corresponds to the jQuery ready
event, but IE<9 does not.
if(window.addEventListener){
window.addEventListener('load', func1)
}else{
window.attachEvent('onload', func1)
}
...
if(window.addEventListener){
window.addEventListener('load', func2)
}else{
window.attachEvent('onload', func2)
}
If neither option is available (for example, you are not dealing with DOM nodes), you can still do this (I am using onload
as an example, but other options are available for onload
):
var oldOnload1=window.onload;
window.onload=function(){
oldOnload1 && oldOnload1();
func1();
}
...
var oldOnload2=window.onload;
window.onload=function(){
oldOnload2 && oldOnload2();
func2();
}
or, to avoid polluting the global namespace (and likely encountering namespace collisions), using the import/export IIFE pattern:
window.onload=(function(oldLoad){
return function(){
oldLoad && oldLoad();
func1();
}
})(window.onload)
...
window.onload=(function(oldLoad){
return function(){
oldLoad && oldLoad();
func2();
}
})(window.onload)
If we are not sure that the list is sorted, we could use the built-in min()
function, to find the element which has the minimum distance from the specified number.
>>> min(myList, key=lambda x:abs(x-myNumber))
4
Note that it also works with dicts with int keys, like {1: "a", 2: "b"}
. This method takes O(n) time.
If the list is already sorted, or you could pay the price of sorting the array once only, use the bisection method illustrated in @Lauritz's answer which only takes O(log n) time (note however checking if a list is already sorted is O(n) and sorting is O(n log n).)
Your case is not talking about collision resolution, it is simply replacement of older value with a new value for the same key because Java's HashMap
can't contain duplicates (i.e., multiple values) for the same key.
In your example, the value 17 will be simply replaced with 20 for the same key 10 inside the HashMap.
If you are trying to put a different/new value for the same key, it is not the concept of collision resolution, rather it is simply replacing the old value with a new value for the same key. It is how HashMap
has been designed and you can have a look at the below API (emphasis is mine) taken from here.
public V put(K key, V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
On the other hand, collision resolution techniques comes into play only when multiple keys end up with the same hashcode (i.e., they fall in the same bucket location) where an entry is already stored. HashMap
handles the collision resolution by using the concept of chaining i.e., it stores the values in a linked list (or a balanced tree since Java8, depends on the number of entries).
The reason is actually very simple. When using a query parameter you can take in characters such as "/" and your client does not need to html encode them. There are other reasons but that is a simple example. As for when to use a path variable. I would say whenever you are dealing with ids or if the path variable is a direction for a query.
You could try something like this:
SELECT @rn:=@rn+1 as n
FROM (select @rn:=2)t, `order` rows_1, `order` rows_2 --, rows_n as needed...
LIMIT 4
Where order
is just en example of some table with a reasonably large set of rows.
Edit: The original answer was wrong, and any credit should go to David Poor who provided a working example of the same concept
This query will give you a list of email addresses and how many times they're used, with the most used addresses first.
SELECT email,
count(*) AS c
FROM TABLE
GROUP BY email
HAVING c > 1
ORDER BY c DESC
If you want the full rows:
select * from table where email in (
select email from table
group by email having count(*) > 1
)
These paradigms don't have to be mutually exclusive. If you look at python, it supports functions and classes, but at the same time, everything is an object, including functions. You can mix and match functional/oop/procedural style all in one piece of code.
What I mean is, in functional languages (at least in Haskell, the only one I studied) there are no statements! functions are only allowed one expression inside them!! BUT, functions are first-class citizens, you can pass them around as parameters, along with a bunch of other abilities. They can do powerful things with few lines of code.
While in a procedural language like C, the only way you can pass functions around is by using function pointers, and that alone doesn't enable many powerful tasks.
In python, a function is a first-class citizen, but it can contain arbitrary number of statements. So you can have a function that contains procedural code, but you can pass it around just like functional languages.
Same goes for OOP. A language like Java doesn't allow you to write procedures/functions outside of a class. The only way to pass a function around is to wrap it in an object that implements that function, and then pass that object around.
In Python, you don't have this restriction.
ALTER TABLE TABLE_NAME ADD INDEX (COLUMN_NAME);
This did the trick for me (I still was on the master branch):
git reset --hard origin/master
Combining and organizing all the current answers into one answer, then adding my own research:
Brief summary of Microsoft gadget development:
What are they written in? Windows Vista/Seven gadgets are developed in a mix of XML, HTML, CSS, and some IE scripting language. It is also possible to use C# with the latest release of Script#.
How are they packaged/deployed? The actual gadgets are stored in *.gadget files, which are simply the text source files listed above compressed into a single zip file.
Useful references for gadget development:
where do I start? Good introductory references to Windows Vista/Seven gadget development:
If you are willing to use offline resources, this book appears to be an excellent resource:
What do I need to know? Some other useful references; not necessarily instructional
Update: Well, this has proven to be a popular answer~ Sharing my own recent experience with Windows 7 gadget development:
Perhaps the easiest way to get started with Windows 7 gadget development is to modify a gadget that has already been developed. I recently did this myself because I wanted a larger clock gadget. Unable to find any, I tinkered with a copy of the standard Windows clock gadget until it was twice as large. I recommend starting with the clock gadget because it is fairly small and well-written. Here is the process I used:
C:\Program Files\Windows Sidebar\Gadgets\Clock.Gadget\
<name>Clock</name>
This is the name that will be displayed in the "Gadgets Gallery" window.%LOCALAPPDATA%\Microsoft\Windows Sidebar\
)The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.
:: short answer :
:: perl -MCPAN -e "install PAR::Packer"
pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>>
:: long answer - create the following cmd , adjust vars to your taste ...
:: next_line_is_templatized
:: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
:: disable the echo
@echo off
:: this is part of the name of the file - not used
set _Action=run
:: the name of the Product next_line_is_templatized
set _ProductName=morphus
:: the version of the current Product next_line_is_templatized
set _ProductVersion=1.2.3
:: could be dev , test , dev , prod next_line_is_templatized
set _ProductType=dev
:: who owns this Product / environment next_line_is_templatized
set _ProductOwner=ysg
:: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )
set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%
:: go the run dir
cd %~dp0
:: do 4 times going up
for /L %%i in (1,1,5) do pushd ..
:: The BaseDir is 4 dirs up than the run dir
set _ProductBaseDir=%CD%
:: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
:: remove the trailing \
IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
:: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
:: debug pause
:: The version directory of the Product
set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%
:: the dir under which all the perl scripts are placed
set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl
:: The Perl script performing all the tasks
set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl
:: where the log events are stored
set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log
:: define a favorite editor
set _MyEditor=textpad
ECHO Check the variables
set _
:: debug PAUSE
:: truncate the run log
echo date is %date% time is %time% > %_RunLog%
:: uncomment this to debug all the vars
:: debug set >> %_RunLog%
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: now open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: this is the call without debugging
:: old
echo CFPoint1 OK The run cmd script %0 is executed >> %_RunLog%
echo CFPoint2 OK compile the exe file STDOUT and STDERR to a single _RunLog file >> %_RunLog%
cd %_ProductVersionPerlDir%
pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1
:: open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: uncomment this line to wait for 5 seconds
:: ping localhost -n 5
:: uncomment this line to see what is happening
:: PAUSE
::
:::::::
:: Purpose:
:: To compile every *.pl file into *.exe file under a folder
:::::::
:: Requirements :
:: perl , pp , win gnu utils tee
:: perl -MCPAN -e "install PAR::Packer"
:: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
:::::::
:: VersionHistory
:: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
:::::::
:: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
The >
is a child selector. So if your HTML looks like this:
<h1 class="hc-reform">
title
<p>stuff here</p>
</h1>
... then that's your ticket.
But if your HTML looks like this:
<h1 class="hc-reform">
title
</h1>
<p>stuff here</p>
Then you want the adjacent selector:
h1.hc-reform + p{
clear:both;
}
Use:
import os
print os.sep
to see how separator looks on a current OS.
In your code you can use:
import os
path = os.path.join('folder_name', 'file_name')
What did work for me (inspired from aax' thanks) :
Paste this into /Library/LaunchDaemons/com.apple.launchd.limit.plist then reboot :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>eicar</string>
<key>ProgramArguments</key>
<array>
<string>/bin/launchctl</string>
<string>limit</string>
<string>maxfiles</string>
<string>16384</string>
<string>16384</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>ServiceIPC</key>
<false/>
</dict>
</plist>
If you need it step by step :
?+v
). This will force the limit to 16384 files per process and 16384 files totalesc
then :wq
I hope this helped you.
Use Invoke-RestMethod
to consume REST-APIs. Save the JSON to a string and use that as the body, ex:
$JSON = @'
{"@type":"login",
"username":"[email protected]",
"password":"yyy"
}
'@
$response = Invoke-RestMethod -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"
If you use Powershell 3, I know there have been some issues with Invoke-RestMethod
, but you should be able to use Invoke-WebRequest
as a replacement:
$response = Invoke-WebRequest -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"
If you don't want to write your own JSON every time, you can use a hashtable and use PowerShell to convert it to JSON before posting it. Ex.
$JSON = @{
"@type" = "login"
"username" = "[email protected]"
"password" = "yyy"
} | ConvertTo-Json
Found this on github...
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas
leftclickben answer worked for me, but I wanted a path from a given node back up the tree to the root, and these seemed to be going the other way, down the tree. So, I had to flip some of the fields around and renamed for clarity, and this works for me, in case this is what anyone else wants too--
item | parent
-------------
1 | null
2 | 1
3 | 1
4 | 2
5 | 4
6 | 3
and
select t.item_id as item, @pv:=t.parent as parent
from (select * from item_tree order by item_id desc) t
join
(select @pv:=6)tmp
where t.item_id=@pv;
gives:
item | parent
-------------
6 | 3
3 | 1
1 | null
I think, it should be like this:
class foo():
input = get_input(__qualname__)
git config user.name only changes the name I commit. I still cannot push. This is how I solved it, and I think is an easy way to me.
Generate a SSH key under the user name you want to push on the computer you will use https://help.github.com/articles/connecting-to-github-with-ssh/
Add this key to the github user account that you want to push to https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/
Choose to Clone with SSH
You can push in as this user to that repo now.
select * from table where
(dtColumn between #3/1/2009# and #3/31/2009#) and
(hour(dtColumn) between 6 and 22) and
(weekday(dtColumn, 1) between 2 and 4)
Simplest of all solutions:
filtered_df = df[df['var2'].isnull()]
This filters and gives you rows which has only NaN
values in 'var2'
column.
SELECT DISTINCT dbo.Table.Email,dbo.Table.FirstName dbo.Table.LastName, dbo.Table.DateOfBirth (etc) FROM dbo.Table.Contacts WHERE Email = 'name@email';
Give boon a try:
https://github.com/RichardHightower/boon
It is wicked fast:
https://github.com/RichardHightower/json-parsers-benchmark
Don't take my word for it... check out the gatling benchmark.
https://github.com/gatling/json-parsers-benchmark
(Up to 4x is some cases, and out of the 100s of test. It also has a index overlay mode that is even faster. It is young but already has some users.)
It can parse JSON to Maps and Lists faster than any other lib can parse to a JSON DOM and that is without Index Overlay mode. With Boon Index Overlay mode, it is even faster.
It also has a very fast JSON lax mode and a PLIST parser mode. :) (and has a super low memory, direct from bytes mode with UTF-8 encoding on the fly).
It also has the fastest JSON to JavaBean mode too.
It is new, but if speed and simple API is what you are looking for, I don't think there is a faster or more minimalist API.
it is recommended not to use str
int
list
etc.. as variable names, even though python will allow it.
this is because it might create such accidents when trying to access reserved keywords that are named the same
The solution from CSS-Tricks no longer works in jQuery 2.2.0. It will throw a selector error:
JavaScript runtime error: Syntax error, unrecognized expression: a[href*=#]:not([href=#])
I fixed it by changing the selector. The full snippet is this:
$(function() {
$("a[href*='#']:not([href='#'])").click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
The solution is to run an NTP client , just run the command as below
#ntpdate 172.16.12.100
172.16.12.100 is the ntp server
So because pod update SomePod
touches everything in the latest versions of cocoapods, I found a workaround.
Follow the next steps:
Remove SomePod
from the Podfile
Run pod install
pods will now remove SomePod
from our project and from the Podfile.lock
file.
Put back SomePod
into the Podfile
Run pod install
again
This time the latest version of our pod will be installed and saved in the Podfile.lock
.
... or if you want / need to keep your option 'value' as it was, just add a new attribute:
<select id="my_selection">
<option value="x" href="/link/to/somewhere">value 1</option>
<option value="y" href="/link/to/somewhere/else">value 2</option>
</select>
<script>
document.getElementById('my_selection').onchange = function() {
window.location.href = this.children[this.selectedIndex].getAttribute('href');
}
</script>
Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.
If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.
The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.
So the ultimate difference is:
Update for 2019, if you want to create a folder with path bucket_name/folder1/folder2 you can use this code:
from boto3 import client, resource
class S3Helper:
def __init__(self):
self.client = client("s3")
self.s3 = resource('s3')
def create_folder(self, path):
path_arr = path.rstrip("/").split("/")
if len(path_arr) == 1:
return self.client.create_bucket(Bucket=path_arr[0])
parent = path_arr[0]
bucket = self.s3.Bucket(parent)
status = bucket.put_object(Key="/".join(path_arr[1:]) + "/")
return status
s3 = S3Helper()
s3.create_folder("bucket_name/folder1/folder2)
AppDomain.UnhandledException Event
This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.
public App()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
}
If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.
For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.
gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT HON env variable.
This means the Python env. variable should point to the executable python file, in my case:
SET PYTHON=C:\work\_env\Python27\python.exe
Did you try redirecting inside the logout function itself? For example, say your logout function is as follows
$scope.logout = function()
{
$scope.userSession = undefined;
window.location = "http://www.yoursite.com/#"
}
Then you can just have
<a ng-click="logout()">Sign out</a>
For the comment on the answer by vogash, I understand that you want something like a time counter, thats because you can have more than 24 hours. For this you can do the following:
select to_char(trunc(xxx/3600)) || to_char(to_date(mod(xxx, 86400),'sssss'),':mi:ss') as time
from dual;
xxx
are your number of seconds.
The first part accumulate the hours and the second part calculates the remaining minutes and seconds. For example, having 150023 seconds
it will give you 41:40:23
.
But if you always want have hh24:mi:ss even if you have more than 86000 seconds
(1 day) you can do:
select to_char(to_date(mod(xxx, 86400),'sssss'),'hh24:mi:ss') as time
from dual;
xxx
are your number of seconds.
For example, having 86402 seconds
it will reset the time to 00:00:02
.
You can create folder using the following Java code:
File dir = new File("nameoffolder");
dir.mkdir();
By executing above you will have folder 'nameoffolder' in current folder.
This will aslo solve your problem if your image in gallery are not showing instead they might showing a 404 type bitmap in midle. please add a the tags that are in my code with your image because there must some meta data in order to show image in gallery.
String resultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)+
getString(R.string.directory) + System.currentTimeMillis() + ".jpg";
new File(resultPath).getParentFile().mkdir();
try {
OutputStream fileOutputStream = new FileOutputStream(resultPath);
savedBitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
savedBitmap.recycle();
File file = new File(resultPath);
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Photo");
values.put(MediaStore.Images.Media.DESCRIPTION, "Edited");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis ());
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Images.ImageColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
values.put("_data", resultPath);
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
return resultPath;
Also , with Anonymous types ( I prefer not to do this) -- this is just another approach.
void Main()
{
var x = new
{
items = new[]
{
new
{
name = "command", index = "X", optional = "0"
},
new
{
name = "command", index = "X", optional = "0"
}
}
};
JavaScriptSerializer js = new JavaScriptSerializer(); //system.web.extension assembly....
Console.WriteLine(js.Serialize(x));
}
result :
{"items":[{"name":"command","index":"X","optional":"0"},{"name":"command","index":"X","optional":"0"}]}
For jQuery with twitter bootstrap
Check caps locked for the following characters:
uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';', '*', '''
lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ',', '+', '#'
/* check for CAPS LOCK on all password fields */
$("input[type='password']").keypress(function(e) {
var kc = e.which; // get keycode
var isUpperCase = ((kc >= 65 && kc <= 90) || (kc >= 33 && kc <= 34) || (kc >= 36 && kc <= 39) || (kc >= 40 && kc <= 42) || kc == 47 || (kc >= 58 && kc <= 59) || kc == 61 || kc == 63 || kc == 167 || kc == 196 || kc == 214 || kc == 220) ? true : false; // uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';'
var isLowerCase = ((kc >= 97 && kc <= 122) || (kc >= 48 && kc <= 57) || kc == 35 || (kc >= 43 && kc <= 44) || kc == 46 || kc == 228 || kc == 223 || kc == 246 || kc == 252) ? true : false; // lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ','
// event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
var isShift = (e.shiftKey) ? e.shiftKey : ((kc == 16) ? true : false); // shift is pressed
// uppercase w/out shift or lowercase with shift == caps lock
if ((isUpperCase && !isShift) || (isLowerCase && isShift)) {
$(this).next('.form-control-feedback').show().parent().addClass('has-warning has-feedback').next(".capsWarn").show();
} else {
$(this).next('.form-control-feedback').hide().parent().removeClass('has-warning has-feedback').next(".capsWarn").hide();
}
}).after('<span class="glyphicon glyphicon-warning-sign form-control-feedback" style="display:none;"></span>').parent().after("<span class='capsWarn text-danger' style='display:none;'>Is your CAPSLOCK on?</span>");
Ideally, I would use a construct like this instead:
for (std::vector<your_type>::const_iterator i = things.begin(); i != things.end(); ++i)
{
// if you ever need the distance, you may call std::distance
// it won't cause any overhead because the compiler will likely optimize the call
size_t distance = std::distance(things.begin(), i);
}
This a has the neat advantage that your code suddenly becomes container agnostic.
And regarding your problem, if some library you use requires you to use int
where an unsigned int
would better fit, their API is messy. Anyway, if you are sure that those int
are always positive, you may just do:
int int_distance = static_cast<int>(distance);
Which will specify clearly your intent to the compiler: it won't bug you with warnings anymore.
I try all of above code but any code is not working for my website.then i try this code and This code is running perfect for my website. You can use the following Rule in htaccess :
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
//Redirect http to https
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
//Redirect non-www to www
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
</IfModule>
Change example.com with your domain name and sorry for my poor english.
function bookmark(title, url) {
if (window.sidebar) {
// Firefox
window.sidebar.addPanel(title, url, '');
}
else if (window.opera && window.print)
{
// Opera
var elem = document.createElement('a');
elem.setAttribute('href', url);
elem.setAttribute('title', title);
elem.setAttribute('rel', 'sidebar');
elem.click(); //this.title=document.title;
}
else if (document.all)
{
// ie
window.external.AddFavorite(url, title);
}
}
I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!
I am a bit late, but another way is to use list comprehension and the any
function, that takes an iterable and returns True
whenever one element is True
:
# Checking if string 'Mary' exists in the lists of the dictionary values
print any(any('Mary' in s for s in subList) for subList in myDict.values())
If you wanna count the number of element that have "Mary" in them, you can use sum()
:
# Number of sublists containing 'Mary'
print sum(any('Mary' in s for s in subList) for subList in myDict.values())
# Number of strings containing 'Mary'
print sum(sum('Mary' in s for s in subList) for subList in myDict.values())
From these methods, we can easily make functions to check which are the keys or values matching.
To get the keys containing 'Mary':
def matchingKeys(dictionary, searchString):
return [key for key,val in dictionary.items() if any(searchString in s for s in val)]
To get the sublists:
def matchingValues(dictionary, searchString):
return [val for val in dictionary.values() if any(searchString in s for s in val)]
To get the strings:
def matchingValues(dictionary, searchString):
return [s for s i for val in dictionary.values() if any(searchString in s for s in val)]
To get both:
def matchingElements(dictionary, searchString):
return {key:val for key,val in dictionary.items() if any(searchString in s for s in val)}
And if you want to get only the strings containing "Mary", you can do a double list comprehension :
def matchingStrings(dictionary, searchString):
return [s for val in dictionary.values() for s in val if searchString in s]
If you really need to hide the value that the "real" iterator returns (for example because you want to use your key-iterator with standard algorithms, so that they operate on the keys instead of the pairs), then take a look at Boost's transform_iterator.
[Tip: when looking at Boost documentation for a new class, read the "examples" at the end first. You then have a sporting chance of figuring out what on earth the rest of it is talking about :-)]
I had a similar problem with IndentationError in PyCharm.
I could not find any tabs in my code, but once I deleted code AFTER the line with the IndentationError, all was well.
I suspect that you had a tab in the following line:
sex = sex if not sex == 2 else random.randint(0,1)
/*I am working with turbo c++ compiler so namespace std is not used by me.Also i am familiar with turbo.*/
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<fstream.h> //required while dealing with files
void main ()
{
clrscr();
ofstream fout; //object created **fout**
fout.open("your desired file name + extension");
fout<<"contents to be written inside the file"<<endl;
fout.close();
getch();
}
After running the program the file will be created inside the bin folder in your compiler folder itself.
If you using JavaScript to test your Regex, try \\.
instead of \.
.
It acts on the same way because JS remove first backslash.
Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL
1) Enter MySQL
mysql -u your_user -p
2) Let's see the list of locked tables
mysql> show open tables where in_use>0;
3) Let's see the list of the current processes, one of them is locking your table(s)
mysql> show processlist;
4) Let's kill one of these processes
mysql> kill put_process_id_here;
At the risk of irritating you;
You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.
Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.
What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.
It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.
In short, it's just unnecessarily conflating the matter when there is no need to.
Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit()
than ini_set()
.
Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)
The Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all transactions in progress for the process. Consequently this exception can be thrown when there are many transactions in progress even when most of the individual transactions are of moderate size.
refer this link
I know this is not possible for alert(), so I guess it is not possible for confirm either. Reason is security: it is not allowed for you to change it so you wouldn't present yourself as some system process or something.
NIO copy with a buffer is the fastest according to my test. See the working code below from a test project of mine at https://github.com/mhisoft/fastcopy
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
public class test {
private static final int BUFFER = 4096*16;
static final DecimalFormat df = new DecimalFormat("#,###.##");
public static void nioBufferCopy(final File source, final File target ) {
FileChannel in = null;
FileChannel out = null;
double size=0;
long overallT1 = System.currentTimeMillis();
try {
in = new FileInputStream(source).getChannel();
out = new FileOutputStream(target).getChannel();
size = in.size();
double size2InKB = size / 1024 ;
ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER);
while (in.read(buffer) != -1) {
buffer.flip();
while(buffer.hasRemaining()){
out.write(buffer);
}
buffer.clear();
}
long overallT2 = System.currentTimeMillis();
System.out.println(String.format("Copied %s KB in %s millisecs", df.format(size2InKB), (overallT2 - overallT1)));
}
catch (IOException e) {
e.printStackTrace();
}
finally {
close(in);
close(out);
}
}
private static void close(Closeable closable) {
if (closable != null) {
try {
closable.close();
} catch (IOException e) {
if (FastCopy.debug)
e.printStackTrace();
}
}
}
}
According to the documentation.
If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.
You can check what all devices are used by tensorflow by -
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
Also as suggested in this answer
import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.
If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.
pip install tensorflow-gpu
I have used a destructor (for debug purposes only) to see if an object was being purged from memory in the scope of a WPF application. I was unsure if garbage collection was truly purging the object from memory, and this was a good way to verify.
SQL Server, nicely formatted table for all tables in KB/MB:
SELECT
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
t.Name
I found this code on https://electrictoolbox.com/javascript-get-all-cookies/, which worked for me better than the other solutions:
function get_cookies_array() {
var cookies = { };
if (document.cookie && document.cookie != '') {
var split = document.cookie.split(';');
for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
name_value[0] = name_value[0].replace(/^ /, '');
cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
}
}
return cookies;
}
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
My solution:
#ifdef WIN32
#include <Windows.h>
#include <tchar.h>
#else
#include <unistd.h>
#endif
void GetMachineName(char machineName[150])
{
char Name[150];
int i=0;
#ifdef WIN32
TCHAR infoBuf[150];
DWORD bufCharCount = 150;
memset(Name, 0, 150);
if( GetComputerName( infoBuf, &bufCharCount ) )
{
for(i=0; i<150; i++)
{
Name[i] = infoBuf[i];
}
}
else
{
strcpy(Name, "Unknown_Host_Name");
}
#else
memset(Name, 0, 150);
gethostname(Name, 150);
#endif
strncpy(machineName,Name, 150);
}
Thanks @Clint for the great answer:
Just wanted to highlight how easy it was to solve this using the Expando Object:
var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
foreach (var property in properties) {
dynamicObject.Add(property.Key,property.Value);
}
No, TRUNCATE
is all or nothing. You can do a DELETE FROM <table> WHERE <conditions>
but this loses the speed advantages of TRUNCATE
.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in dirs:
print os.path.join(root, name)
Walk is a good built-in for what you are doing
Here is the example macro to convert the Excel worksheet to XML file.
#'vba code to convert excel to xml
Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.
Maybe this is unrelated but a similar error appears when you upgrade postgres
to a major version using brew
; using brew info postgresql
found out this that helped:
To migrate existing data from a previous major version of PostgreSQL run:
brew postgresql-upgrade-database
You can factor out your common logic to a private method, for example called Initialize
that gets called from both constructors.
Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.
Example:
public Point2D(double x, double y)
{
// Contracts
Initialize(x, y);
}
public Point2D(Point2D point)
{
if (point == null)
throw new ArgumentNullException("point");
// Contracts
Initialize(point.X, point.Y);
}
private void Initialize(double x, double y)
{
X = x;
Y = y;
}
As @Devart says, the total length of your index is too long.
The short answer is that you shouldn't be indexing such long VARCHAR columns anyway, because the index will be very bulky and inefficient.
The best practice is to use prefix indexes so you're only indexing a left substring of the data. Most of your data will be a lot shorter than 255 characters anyway.
You can declare a prefix length per column as you define the index. For example:
...
KEY `index` (`parent_menu_id`,`menu_link`(50),`plugin`(50),`alias`(50))
...
But what's the best prefix length for a given column? Here's a method to find out:
SELECT
ROUND(SUM(LENGTH(`menu_link`)<10)*100/COUNT(`menu_link`),2) AS pct_length_10,
ROUND(SUM(LENGTH(`menu_link`)<20)*100/COUNT(`menu_link`),2) AS pct_length_20,
ROUND(SUM(LENGTH(`menu_link`)<50)*100/COUNT(`menu_link`),2) AS pct_length_50,
ROUND(SUM(LENGTH(`menu_link`)<100)*100/COUNT(`menu_link`),2) AS pct_length_100
FROM `pds_core_menu_items`;
It tells you the proportion of rows that have no more than a given string length in the menu_link
column. You might see output like this:
+---------------+---------------+---------------+----------------+
| pct_length_10 | pct_length_20 | pct_length_50 | pct_length_100 |
+---------------+---------------+---------------+----------------+
| 21.78 | 80.20 | 100.00 | 100.00 |
+---------------+---------------+---------------+----------------+
This tells you that 80% of your strings are less than 20 characters, and all of your strings are less than 50 characters. So there's no need to index more than a prefix length of 50, and certainly no need to index the full length of 255 characters.
PS: The INT(1)
and INT(32)
data types indicates another misunderstanding about MySQL. The numeric argument has no effect related to storage or the range of values allowed for the column. INT
is always 4 bytes, and it always allows values from -2147483648 to 2147483647. The numeric argument is about padding values during display, which has no effect unless you use the ZEROFILL
option.
To those still having problems, I solved it this way:
List<Item> newItems = databaseHandler.getItems();
ListArrayAdapter.clear();
ListArrayAdapter.addAll(newItems);
ListArrayAdapter.notifyDataSetChanged();
databaseHandler.close();
I first cleared the data from the adapter, then added the new collection of items, and only then set notifyDataSetChanged();
This was not clear for me at first, so I wanted to point this out. Take note that without calling notifyDataSetChanged()
the view won't be updated.
You can open the SDK standalone by going to installation directory, just right click on the SDK Manager.exe and click on run as Administrator. i hope it will help.
First of all jar
creates a jar, and does not run it. Try java -jar
instead.
Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2
) and as file (com/mycomp/myproj/dir2/MainClass2.class
)?
Edit:
It seems as if java -jar
requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ...
instead. -cp
sets the jar on the classpath and enables java to look up the main class there.