Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
Try this : Using this you can select data from last 30 days
SELECT
*
FROM
product
WHERE
purchase_date > DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
Swift 3 version code:
let urlString = "file:///Users/Documents/Book/Note.txt"
let pathURL = URL(string: urlString)!
print("the url = " + pathURL.path)
Since none of these answers deal with the cause I encountered, for this problem, I will add my answer here as well.
In my case, it was a copy pasting code problem. We had a TestProjectA
where there are specific type of tests that we want to pull out to its own test project - TestProjectB
. The problem now was that, while tests in TestProjectA
continue to show up just fine, the tests in the new TestProjectB
aren't showing up in VS Test Explorer - unless you specifically build TestProjectB
or manually right click on a test there and run it.
The cause was that in copy pasting the code over, some namespaces didn't get updated:
TestMethodA()
in TestClassA
in namespace TestProjectA.ModuleA
with filepath \TestProjectA\TestClassA.cs
TestMethodA()
in TestClassB
in namespace TestProjectA.ModuleA
with filepath \TestProjectB\TestClassB.cs
So visual Studio prints out a message in Output window that the TestId for these two are the same, and proceeds to show TestProjectA
and not TestProjectB
in Test Explorer due to the TestId clashing between the two projects. Correcting the namespace to TestProjectB.ModuleB
for \TestProjectB\TestClassB.cs
fixed the issue.
It looks like you want to define Truck as a Class
with properties NumberOfAxles, AxleWeights & AxleSpacings.
This can be defined in a CLASS MODULE (here named clsTrucks)
Option Explicit
Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double
Public Property Get truckID() As String
truckID = tID
End Property
Public Property Let truckID(value As String)
tID = value
End Property
Public Property Get truckNumberOfAxles() As Double
truckNumberOfAxles = tNumberOfAxles
End Property
Public Property Let truckNumberOfAxles(value As Double)
tNumberOfAxles = value
End Property
Public Property Get truckAxleSpacings() As Double
truckAxleSpacings = tAxleSpacings
End Property
Public Property Let truckAxleSpacings(value As Double)
tAxleSpacings = value
End Property
then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.
Option Explicit
Public TruckCollection As New Collection
Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long
'Add 5 trucks
For i = 1 To 5
Set tempTruck = New clsTrucks
'Random data
tempTruck.truckID = "Truck" & i
tempTruck.truckAxleSpacings = 13.5 + i
tempTruck.truckNumberOfAxles = 20.5 + i
'tempTruck.truckID is the collection key
TruckCollection.Add tempTruck, tempTruck.truckID
Next i
'retrieve 5 trucks
For i = 1 To 5
'retrieve by collection index
Debug.Print TruckCollection(i).truckAxleSpacings
'retrieve by key
Debug.Print TruckCollection("Truck" & i).truckAxleSpacings
Next i
End Sub
There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.
I just had this and it was because I had a <configuration>
element nested inside of a <configuration>
element.
If you are using pip 19.0.3
and python 3.7.4
. Then go for pip list
command in your virtualenv. It will show all the installed packages with respective versions.
We can use Carbon
$time = '09:15 PM';
$s=Carbon::parse($time);
echo $military_time =$s->format('G:i');
I'm not sure this is so surprising. Most people who code in PHP are not well versed in what PHP is actually doing at the bare metal. I'll state a few things, which will be true most of the time:
If you're not modifying the variable, by-value is faster in PHP. This is because it's reference counted anyway and by-value gives it less to do. It knows the second you modify that ZVAL (PHP's internal data structure for most types), it will have to break it off in a straightforward way (copy it and forget about the other ZVAL). But you never modify it, so it doesn't matter. References make that more complicated with more bookkeeping it has to do to know what to do when you modify the variable. So if you're read-only, paradoxically it's better not the point that out with the &. I know, it's counter intuitive, but it's also true.
Foreach isn't slow. And for simple iteration, the condition it's testing against — "am I at the end of this array" — is done using native code, not PHP opcodes. Even if it's APC cached opcodes, it's still slower than a bunch of native operations done at the bare metal.
Using a for loop "for ($i=0; $i < count($x); $i++) is slow because of the count(), and the lack of PHP's ability (or really any interpreted language) to evaluate at parse time whether anything modifies the array. This prevents it from evaluating the count once.
But even once you fix it with "$c=count($x); for ($i=0; $i<$c; $i++) the $i<$c is a bunch of Zend opcodes at best, as is the $i++. In the course of 100000 iterations, this can matter. Foreach knows at the native level what to do. No PHP opcodes needed to test the "am I at the end of this array" condition.
What about the old school "while(list(" stuff? Well, using each(), current(), etc. are all going to involve at least 1 function call, which isn't slow, but not free. Yes, those are PHP opcodes again! So while + list + each has its costs as well.
For these reasons foreach is understandably the best option for simple iteration.
And don't forget, it's also the easiest to read, so it's win-win.
This will safely remove only if token is at end of string.
StringUtils.removeEnd(string, ".xml");
Apache StringUtils functions are null-, empty-, and no match- safe
None of the 13 existing answers worked for me. However, I could resolve the issue by first removing all modules:
File
> Project Structure...
,Modules
tab,then removing all remaining Maven modules from Maven
tool window:
Remove projects
,and then adding them again in Project
tool window:
pom.xml
,Add as Maven project
,now unignoring any ignored modules from Maven
tool window:
Unignore
,and finally rebuilding using Build
> Rebuild project
. This assumes that a mvn clean install
already happened.
// Some more complex constant variable/pointer declaration.
// Observing cases when we get error and warning would help
// understanding it better.
int main(void)
{
char ca1[10]= "aaaa"; // char array 1
char ca2[10]= "bbbb"; // char array 2
char *pca1= ca1;
char *pca2= ca2;
char const *ccs= pca1;
char * const csc= pca2;
ccs[1]='m'; // Bad - error: assignment of read-only location ‘*(ccs + 1u)’
ccs= csc; // Good
csc[1]='n'; // Good
csc= ccs; // Bad - error: assignment of read-only variable ‘csc’
char const **ccss= &ccs; // Good
char const **ccss1= &csc; // Bad - warning: initialization from incompatible pointer type
char * const *cscs= &csc; // Good
char * const *cscs1= &ccs; // Bad - warning: initialization from incompatible pointer type
char ** const cssc= &pca1; // Good
char ** const cssc1= &ccs; // Bad - warning: initialization from incompatible pointer type
char ** const cssc2= &csc; // Bad - warning: initialization discards ‘const’
// qualifier from pointer target type
*ccss[1]= 'x'; // Bad - error: assignment of read-only location ‘**(ccss + 8u)’
*ccss= ccs; // Good
*ccss= csc; // Good
ccss= ccss1; // Good
ccss= cscs; // Bad - warning: assignment from incompatible pointer type
*cscs[1]= 'y'; // Good
*cscs= ccs; // Bad - error: assignment of read-only location ‘*cscs’
*cscs= csc; // Bad - error: assignment of read-only location ‘*cscs’
cscs= cscs1; // Good
cscs= cssc; // Good
*cssc[1]= 'z'; // Good
*cssc= ccs; // Bad - warning: assignment discards ‘const’
// qualifier from pointer target type
*cssc= csc; // Good
*cssc= pca2; // Good
cssc= ccss; // Bad - error: assignment of read-only variable ‘cssc’
cssc= cscs; // Bad - error: assignment of read-only variable ‘cssc’
cssc= cssc1; // Bad - error: assignment of read-only variable ‘cssc’
}
Following is the working solution to read the entire file in chunks and its efficient solution to read the large files using a scanner class.
try {
FileInputStream fiStream = new FileInputStream(inputFile_name);
Scanner sc = null;
try {
sc = new Scanner(fiStream);
while (sc.hasNextLine()) {
String line = sc.nextLine();
byte[] buf = line.getBytes();
}
} finally {
if (fiStream != null) {
fiStream.close();
}
if (sc != null) {
sc.close();
}
}
}catch (Exception e){
Log.e(TAG, "Exception: " + e.toString());
}
The static
keyword means that something (a field, method or nested class) is related to the type rather than any particular instance of the type. So for example, one calls Math.sin(...)
without any instance of the Math
class, and indeed you can't create an instance of the Math
class.
For more information, see the relevant bit of Oracle's Java Tutorial.
Sidenote
Java unfortunately allows you to access static members as if they were instance members, e.g.
// Bad code!
Thread.currentThread().sleep(5000);
someOtherThread.sleep(5000);
That makes it look as if sleep
is an instance method, but it's actually a static method - it always makes the current thread sleep. It's better practice to make this clear in the calling code:
// Clearer
Thread.sleep(5000);
Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.
Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.
As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:
Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.
Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:
meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)
Formula is from Chris Broadfoot's comment.
Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
What you're looking for are the scales for each zoom level. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
You forgot to add the global operator. Use this:
var s = "04.07.2012";_x000D_
alert(s.replace(new RegExp("[0-9]","g"), "X"));
_x000D_
I know this is a very old question and the problem is marked as fixed. However, if someone with a case like mine where the table have trigger for data logging on update events, this will cause problem. Both the columns will get the update and log will make useless entries. The way I did
IF (CONDITION) IS TRUE
BEGIN
UPDATE table SET columnx = 25
END
ELSE
BEGIN
UPDATE table SET columny = 25
END
Now this have another benefit that it does not have unnecessary writes on the table like the above solutions.
I googled and found this question, but the answer I am really looking for fulfils two criteria:
Since I couldn't find exactly what I want here, I have cobbled the answer from various answers and sharing it here.
Few things to note:
id
with type as int
as primary keycreate a stored procedure like this:
DELIMITER //
CREATE PROCEDURE reset_autoincrement(IN tablename varchar(200))
BEGIN
SET @get_next_inc = CONCAT('SELECT @next_inc := max(id) + 1 FROM ',tablename,';');
PREPARE stmt FROM @get_next_inc;
EXECUTE stmt;
SELECT @next_inc AS result;
DEALLOCATE PREPARE stmt;
set @alter_statement = concat('ALTER TABLE ', tablename, ' AUTO_INCREMENT = ', @next_inc, ';');
PREPARE stmt FROM @alter_statement;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
Then run it.
Before run, it looks like this when you look under Stored Procedures in your database.
When I run, I simply select the stored procedure and press Run Selection
Note: the delimiters part are crucial. Hence if you copy and paste from the top selected answers in this question, they tend not to work for this reason.
After I run, I should see the stored procedure
If you need to change the stored procedure, you need to delete the stored procedure, then select to run again.
This time you can simply use normal MySQL queries.
call reset_autoincrement('products');
Originally from my own SQL queries notes in https://simkimsia.com/library/sql-queries/#mysql-reset-autoinc and adapted for StackOverflow
If you are using Python selenium
bindings, nowadays, there is an extension to selenium
- selenium-requests
:
Extends Selenium WebDriver classes to include the request function from the Requests library, while doing all the needed cookie and request headers handling.
Example:
from seleniumrequests import Firefox
webdriver = Firefox()
response = webdriver.request('POST', 'url here', data={"param1": "value1"})
print(response)
Here's a generic multidimensional sort, allowing for reversing and/or mapping on each level.
Written in Typescript. For Javascript, check out this JSFiddle
type itemMap = (n: any) => any;
interface SortConfig<T> {
key: keyof T;
reverse?: boolean;
map?: itemMap;
}
export function byObjectValues<T extends object>(keys: ((keyof T) | SortConfig<T>)[]): (a: T, b: T) => 0 | 1 | -1 {
return function(a: T, b: T) {
const firstKey: keyof T | SortConfig<T> = keys[0];
const isSimple = typeof firstKey === 'string';
const key: keyof T = isSimple ? (firstKey as keyof T) : (firstKey as SortConfig<T>).key;
const reverse: boolean = isSimple ? false : !!(firstKey as SortConfig<T>).reverse;
const map: itemMap | null = isSimple ? null : (firstKey as SortConfig<T>).map || null;
const valA = map ? map(a[key]) : a[key];
const valB = map ? map(b[key]) : b[key];
if (valA === valB) {
if (keys.length === 1) {
return 0;
}
return byObjectValues<T>(keys.slice(1))(a, b);
}
if (reverse) {
return valA > valB ? -1 : 1;
}
return valA > valB ? 1 : -1;
};
}
Sorting a people array by last name, then first name:
interface Person {
firstName: string;
lastName: string;
}
people.sort(byObjectValues<Person>(['lastName','firstName']));
Sort language codes by their name, not their language code (see map
), then by descending version (see reverse
).
interface Language {
code: string;
version: number;
}
// languageCodeToName(code) is defined elsewhere in code
languageCodes.sort(byObjectValues<Language>([
{
key: 'code',
map(code:string) => languageCodeToName(code),
},
{
key: 'version',
reverse: true,
}
]));
This is exactly what I was looking for after finding that RedirectToAction()
would not pass complex class objects.
As an example, I want to call the IndexComparison
method in the LifeCycleEffectsResults
controller and pass it a complex class object named model.
Here is the code that failed:
return RedirectToAction("IndexComparison", "LifeCycleEffectsResults", model);
Worth noting is that Strings, integers, etc were surviving the trip to this controller method, but generic list objects were suffering from what was reminiscent of C memory leaks.
As recommended above, here's the code I replaced it with:
var controller = DependencyResolver.Current.GetService<LifeCycleEffectsResultsController>();
var result = controller.IndexComparison(model);
return result;
All is working as intended now. Thank you for leading the way.
Delete every things (jar, pom.xml, etc) under your local ~/.m2/repository/phonegap/1.1.0/
directory if you are using a linux OS.
I solved this by subclassing UILabel
and overriding drawTextInRect:
like this:
- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = {0, 5, 0, 5};
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
Swift 3.1:
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
Swift 4.2.1:
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
super.drawText(in: rect.inset(by: insets))
}
As you might have gathered, this is an adaptation of tc.'s answer. It has two advantages over that one:
sizeToFit
messageCheck field type in table just save time stamp value in datatype like bigint
etc.
Not datetime
type
I use this:
template <typename T>
bool fromHex(const std::string& hexValue, T& result)
{
std::stringstream ss;
ss << std::hex << hexValue;
ss >> result;
return !ss.fail();
}
You can use the function "=IF(ISERROR(A1);0;A1)" this will show zero if the cell A1 contains an errore or the real value if it doesn't.
The following works:
(
echo "From: ${from}";
echo "To: ${to}";
echo "Subject: ${subject}";
echo "Content-Type: text/html";
echo "MIME-Version: 1.0";
echo "";
echo "${message}";
) | sendmail -t
For troubleshooting msmtp, which is compatible with sendmail
, see:
public static void main(String args[]) throws ParseException {
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date dt1 = format1.parse("20/10/2013");
Calendar c = Calendar.getInstance();
c.setTime(dt1);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
long diff = Calendar.getInstance().getTime().getTime() ;
System.out.println(dayOfWeek);
switch (dayOfWeek) {
case 6:
System.out.println(days[dayOfWeek - 1]);
break;
case 5:
System.out.println(days[dayOfWeek - 1]);
break;
case 4:
System.out.println(days[dayOfWeek - 1]);
break;
case 3:
System.out.println(days[dayOfWeek - 1]);
break;
case 2:
System.out.println(days[dayOfWeek - 1]);
break;
case 1:
System.out.println(days[dayOfWeek - 1]);
diff = diff -(dt1.getTime()- 3 );
long valuebefore = dt1.getTime();
long valueafetr = dt1.getTime()-2;
System.out.println("DATE IS befor subtraction :"+valuebefore);
System.out.println("DATE IS after subtraction :"+valueafetr);
long x= dt1.getTime()-(2 * 24 * 3600 * 1000);
System.out.println("Deducted date to find firday is - 2 days form Sunday :"+new Date((dt1.getTime()-(2*24*3600*1000))));
System.out.println("DIffrence from now on is :"+diff);
if(diff > 0) {
diff = diff / (1000 * 60 * 60 * 24);
System.out.println("Diff"+diff);
System.out.println("Date is Expired!"+(dt1.getTime() -(long)2));
}
break;
}
}
Yes it works fine and is commonly used:
$ echo "hello world" | mail -s "a subject" [email protected]
You could convert it to a string instead of printing the list directly:
print(", ".join(LIST))
If the elements in the list aren't strings, you can convert them to string using either repr
(if you want quotes around strings) or str
(if you don't), like so:
LIST = [1, "foo", 3.5, { "hello": "bye" }]
print( ", ".join( repr(e) for e in LIST ) )
Which gives the output:
1, 'foo', 3.5, {'hello': 'bye'}
If you don't have the Runnable references, on the first callback, get the obj of the message, and use removeCallbacksAndMessages() to remove all related callbacks.
I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy
and JoinColumn
were not working).
I think you were trying to do a bi-directional relationships.
First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post
side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:
(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
private List<Post> posts;
}
public class Post {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
private User user;
}
By doing so, the table for Post
will have a column user_id
which store the relationship. Hibernate is getting the relationship by the user
in Post
(Instead of posts
in User
. You will notice the difference if you have Post
's user
but missing User
's posts
).
You have mentioned mappedBy
and JoinColumn
is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.
Edit:
Just a bit extra information on the use of mappedBy
as it is usually confusing at first. In mappedBy
, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.
"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:
Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.
This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.
Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.
This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:
Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false
I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.
_return.desc = (boost::format("fail to detect. cv_result = %d") % st_result).str();
While you are switching, switch to PDO instead of mysqli, It helps you write database agnositc code and have better features for prepared statements.
Bindparam for PDO: http://se.php.net/manual/en/pdostatement.bindparam.php
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = :value1 && field2 = :value2");
$sth->bindParam(':value1', 'foo');
$sth->bindParam(':value2', 'bar');
$sth->execute();
or:
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = ? && field2 = ?");
$sth->bindParam(1, 'foo');
$sth->bindParam(2, 'bar');
$sth->execute();
or execute with the parameters as an array:
$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = :value1 && field2 = :value2");
$sth->execute(array(':value1' => 'foo' , ':value2' => 'bar'));
It will be easier for you if you would like your application to be able to run on different databases in the future.
I also think you should invest some time in using some of the classes from Zend Framwework whilst working with PDO. Check out their Zend_Db and more specifically [Zend_Db_Factory][2]. You do not have to use all of the framework or convert your application to the MVC pattern, but using the framework and reading up on it is time well spent.
CREATE TABLE some_table (
field1 int(11) NOT NULL AUTO_INCREMENT,
field2 varchar(10) NOT NULL,
field3 varchar(10) NOT NULL,
PRIMARY KEY (`field1`)
);
INSERT INTO `some_table` (field1, field2, field3) VALUES
(1, 'text one', 'foo'),
(2, 'text two', 'bar'),
(3, 'text three', 'data'),
(4, 'text four', 'magic');
This query is a bit strange but it does not need another query to initialize the variable; and it can be embedded in a more complex query. It returns all the 'field2's separated by a semicolon.
SELECT result
FROM (SELECT @result := '',
(SELECT result
FROM (SELECT @result := CONCAT_WS(';', @result, field2) AS result,
LENGTH(@result) AS blength
FROM some_table
ORDER BY blength DESC
LIMIT 1) AS sub1) AS result) AS sub2;
I have tried all the methods above but none of them could fix the same issue on my laptop. Finally instead of pushing the branch to origin in git bash, I trun to use TortoiseGit's push option to do the pushing, then a window pops-up to ask me to add the new host key to cache, after clicking the yes button, everything goes fine now.
Hope it helps to you all.
Like this:
int counts[26];
memset(counts, 0, sizeof(counts));
char *p = string;
while (*p) {
counts[tolower(*p++) - 'a']++;
}
This code assumes that the string is null-terminated, and that it contains only characters a
through z
or A
through Z
, inclusive.
To understand how this works, recall that after conversion tolower
each letter has a code between a
and z
, and that the codes are consecutive. As the result, tolower(*p) - 'a'
evaluates to a number from 0
to 25
, inclusive, representing the letter's sequential number in the alphabet.
This code combines ++
and *p
to shorten the program.
1 Close Android Studio (AS)
2 Delete the folder in C:\Users.gradle\wrapper\dists\gradle-2.1-all
3 Run AS as admin
4 Sync your project files
In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction()
but instead wrap your code in DB::beginTransaction
and DB::commit
/DB::rollback()
:
DB::beginTransaction();
try {
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit();
// all good
} catch (\Exception $e) {
DB::rollback();
// something went wrong
}
See the transaction docs.
I believe the link below will always give you the latest version of the 64-bit JRE http://javadl.sun.com/webapps/download/AutoDL?BundleId=43883
None of the above solutions worked for me. The following however works like a charm:-
override fun setUserVisibleHint(isVisibleToUser: Boolean)
You should use a callback parameter:
function Typer(callback)
{
var srcText = 'EXAMPLE ';
var i = 0;
var result = srcText[i];
var interval = setInterval(function() {
if(i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
},
100);
return true;
}
function playBGM () {
alert("Play BGM function");
$('#bgm').get(0).play();
}
Typer(function () {
playBGM();
});
// or one-liner: Typer(playBGM);
So, you pass a function as parameter (callback
) that will be called in that if
before return
.
Also, this is a good article about callbacks.
function Typer(callback)_x000D_
{_x000D_
var srcText = 'EXAMPLE ';_x000D_
var i = 0;_x000D_
var result = srcText[i];_x000D_
var interval = setInterval(function() {_x000D_
if(i == srcText.length - 1) {_x000D_
clearInterval(interval);_x000D_
callback();_x000D_
return;_x000D_
}_x000D_
i++;_x000D_
result += srcText[i].replace("\n", "<br />");_x000D_
$("#message").html(result);_x000D_
},_x000D_
100);_x000D_
return true;_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
function playBGM () {_x000D_
alert("Play BGM function");_x000D_
$('#bgm').get(0).play();_x000D_
}_x000D_
_x000D_
Typer(function () {_x000D_
playBGM();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
</div>_x000D_
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">_x000D_
</audio>
_x000D_
Left Click on chart. «PivotTable Field List» will appear on right. On the right down quarter of PivotTable Field List (S Values), you see the names of the legends. Left Click on the legend name. Left Click on the «Value field settings». At the top there is «Source Name». You can’t change it. Below there is «Custom Name». Change the Custom Name as you wish. Now the legend name on the chart has the new name you gave.
The comma operator evaluates all its operands and yields the value of the last one. So basically whichever condition you write first, it will be disregarded, and the second one will be significant only.
for (i = 0; j >= 0, i <= 5; i++)
is thus equivalent with
for (i = 0; i <= 5; i++)
which may or may not be what the author of the code intended, depending on his intents - I hope this is not production code, because if the programmer having written this wanted to express an AND relation between the conditions, then this is incorrect and the &&
operator should have been used instead.
Use this in Your Activity
btnsub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("pincode", txtpincode.getText().toString());
request.addProperty("bg", bloodgroup.getSelectedItem().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject) envelope.getResponse();
Log.e("result data", "data" + result);
SoapObject root = (SoapObject) result.getProperty(0);
// SoapObject s_deals = (SoapObject) root.getProperty(0);
// SoapObject s_deals_1 = (SoapObject) s_deals.getProperty(0);
//
System.out.println("********Count : " + root.getPropertyCount());
value = new ArrayList<Detailinfo>();
for (int i = 0; i < root.getPropertyCount(); i++) {
SoapObject s_deals = (SoapObject) root.getProperty(i);
Detailinfo info = new Detailinfo();
info.setFirstName(s_deals.getProperty("Firstname").toString());
info.setLastName(s_deals.getProperty("Lastname").toString());
info.setDOB(s_deals.getProperty("DOB").toString());
info.setGender(s_deals.getProperty("Gender").toString());
info.setAddress(s_deals.getProperty("Address").toString());
info.setCity(s_deals.getProperty("City").toString());
info.setState(s_deals.getProperty("State").toString());
info.setPinecode(s_deals.getProperty("Pinecode").toString());
info.setMobile(s_deals.getProperty("Mobile").toString());
info.setEmail(s_deals.getProperty("Email").toString());
info.setBloodgroup(s_deals.getProperty("Bloodgroup").toString());
info.setAdddate(s_deals.getProperty("Adddate").toString());
info.setWaight(s_deals.getProperty("waight").toString());
value.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), ComposeMail.class);
//intent.putParcelableArrayListExtra("valuesList", value);
startActivity(intent);
}
}).start();
}
});
I had this error when trying to SSH into my Raspberry pi from my MBP via bash terminal. My RPI was connected to the network via wifi/wlan0 and this IP had been changed upon restart by my routers DHCP.
Check IP being used to login via SSH is correct. Re-check IP of device being SSH'd into (in my case the RPI), which can be checked using hostname -I
Confirm/amend SSH login credentials on "guest" device (in my case the MBP) and it worked fine in my attempt.
Hope this would help:
-> And that serial number is UDID
Or is ||
And is &&
Update for changed question:
You need to specify what you are comparing against in each logical section of the if statement.
if (title == "User greeting" || title == "User name")
{
// do stuff
}
The procedures outlined here do not work for Android 7 (Nougat) [and possibly Android 6, but I'm unable to verify]. You can't pull the .apk files directly under Nougat (unless in root mode, but that requires a rooted phone). But, you can copy the .apk to an alternate path (say /sdcard/Download) on the phone using adb shell, then you can do an adb pull from the alternate path.
You can use reflection to find all the get
methods in your DAO objects and call the equivalent set
method in the DTO. This will only work if all such methods exist. It should be easy to find example code for this.
Since I do not prefer to rely on external libraries and/or other programs, I have extended your solution so that it works. The actual change here is using the GetFromClipboard function instead of Paste which is mainly used to paste a range of cells. Of course, the downside is that the user must not change focus or intervene during the whole process.
Dim pathPDF As String, textPDF As String
Dim openPDF As Object
Dim objPDF As MsForms.DataObject
pathPDF = "C:\some\path\data.pdf"
Set openPDF = CreateObject("Shell.Application")
openPDF.Open (pathPDF)
'TIME TO WAIT BEFORE/AFTER COPY AND PASTE SENDKEYS
Application.Wait Now + TimeValue("00:00:2")
SendKeys "^a"
Application.Wait Now + TimeValue("00:00:2")
SendKeys "^c"
Application.Wait Now + TimeValue("00:00:1")
AppActivate ActiveWorkbook.Windows(1).Caption
objPDF.GetFromClipboard
textPDF = objPDF.GetText(1)
MsgBox textPDF
If you're interested see my project in github.
scrollBottom
is not a method in jQuery.
UPDATED DEMO - http://jsfiddle.net/xEFq5/10/
Try this:
$("#upClick").on("click" ,function(){
scrolled=scrolled-300;
$(".cover").animate({
scrollTop: scrolled
});
});
You can use timezone.now()
for created and auto_now
for modified:
from django.utils import timezone
class User(models.Model):
created = models.DateTimeField(default=timezone.now())
modified = models.DateTimeField(auto_now=True)
If you are using a custom primary key instead of the default auto- increment int
, auto_now_add
will lead to a bug.
Here is the code of Django's default DateTimeField.pre_save withauto_now
and auto_now_add
:
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = timezone.now()
setattr(model_instance, self.attname, value)
return value
else:
return super(DateTimeField, self).pre_save(model_instance, add)
I am not sure what the parameter add
is. I hope it will some thing like:
add = True if getattr(model_instance, 'id') else False
The new record will not have attr
id
, sogetattr(model_instance, 'id')
will return False will lead to not setting any value in the field.
There are different eclipse plugins available to manage Tomcat server and create war file.
For example you can use tomcatPlugin. It permits to start/stop and build the war simply. You can read this tutorial.
I would recommend using an ArrayList
, which handles dynamic sizing, whereas an array will require a defined size up front, which you may not know. You can always turn the list back into an array.
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
You can you the distinct keyword in you criteria builder like this.
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Orders> query = builder.createQuery(Orders.class);
Root<Orders> root = query.from(Orders.class);
query.distinct(true).multiselect(root.get("cust_email").as(String.class));
And create the field constructor in your model class.
I think that you should make the reference to your config file
26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
you can try to start your redis server like
./redis-server /path/to/redis-stable/redis.conf
This single command line is easy to remember:
npx kill-port 3000
For a more powerful tool with search:
npx fkill-cli
PS: They use third party javascript packages. npx
comes built in with Node.js.
If you want to check the python version in a particular cond environment you can also use conda list python
Give a style inside the td element or in your scss file, like this:
vertical-align:
middle;
You can extend the RecursiveFilterIterator class like this:
class ExtensionFilter extends RecursiveFilterIterator
{
/**
* Hold the extensions pass to the class constructor
*/
protected $extensions;
/**
* ExtensionFilter constructor.
*
* @param RecursiveIterator $iterator
* @param string|array $extensions Extension to filter as an array ['php'] or
* as string with commas in between 'php, exe, ini'
*/
public function __construct(RecursiveIterator $iterator, $extensions)
{
parent::__construct($iterator);
$this->extensions = is_array($extensions) ? $extensions : array_map('trim', explode(',', $extensions));
}
public function accept()
{
if ($this->hasChildren()) {
return true;
}
return $this->current()->isFile() &&
in_array(strtolower($this->current()->getExtension()), $this->extensions);
}
public function getChildren()
{
return new self($this->getInnerIterator()->getChildren(), $this->extensions);
}
Now you can instantiate RecursiveDirectoryIterator with path as an argument like this:
$iterator = new RecursiveDirectoryIterator('\path\to\dir');
$iterator = new ExtensionFilter($iterator, 'xml, php, ini');
foreach($iterator as $file)
{
echo $file . '<br />';
}
This will list files under the current folder only.
To get the files in subdirectories also,
pass the $iterator ( ExtensionFIlter Iterator) to RecursiveIteratorIterator as argument:
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
Now run the foreach loop on this iterator. You will get the files with specified extension
Note:-- Also make sure to run the ExtensionFilter before RecursiveIteratorIterator, otherwise you will get all the files
It is not the asker's problem in this instance but the first troubleshooting step for a generic "AttributeError: __exit__" should be making sure the brackets are there, e.g.
with SomeContextManager() as foo:
#works because a new object is referenced...
not
with SomeContextManager as foo:
#AttributeError because the class is referenced
Catches me out from time to time and I end up here -__-
Doing type('')
is effectively equivalent to str
and types.StringType
so type('') == str == types.StringType
will evaluate to "True
"
Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode)
or assert isinstance(obj, basestring)
, the latter of which was suggested in the comments by 007Brendan and is probably preferred.
isinstance()
is useful if you want to ask whether an object is an instance of a class, e.g:
class MyClass: pass
print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception
But for basic types, e.g. str
, unicode
, int
, float
, long
etc asking type(var) == TYPE
will work OK.
Add the following to Body
tag,
<body onload="document.forms['member_signup'].submit()">
and give name
attribute to your Form
.
<form method="POST" action="" name="member_signup">
For NodeJS v12 and above, --experimental-json-modules
would do the trick, without any help from babel.
https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_experimental_json_modules
But it is imported in commonjs form, so import { a, b } from 'c.json'
is not yet supported.
But you can do:
import c from 'c.json';
const { a, b } = c;
The way that Magento themes handle actual url's is as such (in view partials - phtml files):
echo $this->getSkinUrl('images/logo.png');
If you need the actual base path on disk to the image directory use:
echo Mage::getBaseDir('skin');
Some more base directory types are available in this great blog post:
With PHP 5.4, you can turn Matthew's answer into a one-liner:
$date = sprintf('%d-%d-01', $year, date_parse('may')['month']);
Try doing this:
adb kill-server && adb start-server
(that restarts adb) Also you can try to edit an adb config file .android/adb_usb.ini
and add a line 04e8
after the header. Restart adb required for changes to take effect.
For googler, I wrote a simple Stateless Widget containing 3 method mentioned in this SO. Hope this make it easier to understand.
import 'package:flutter/material.dart';
class ListAndFP extends StatelessWidget {
final List<String> items = ['apple', 'banana', 'orange', 'lemon'];
// for in (require dart 2.2.2 SDK or later)
Widget method1() {
return Column(
children: <Widget>[
Text('You can put other Widgets here'),
for (var item in items) Text(item),
],
);
}
// map() + toList() + Spread Property
Widget method2() {
return Column(
children: <Widget>[
Text('You can put other Widgets here'),
...items.map((item) => Text(item)).toList(),
],
);
}
// map() + toList()
Widget method3() {
return Column(
// Text('You CANNOT put other Widgets here'),
children: items.map((item) => Text(item)).toList(),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: method1(),
);
}
}
I believe commenting out display_errors in php.ini won't work because the default is On. You must set it to 'Off' instead.
Don't forget to restart Apache to apply configuration changes.
Also note that while you can set display_errors at runtime, changing it here does not affect FATAL errors.
As noted by others, ideally during development you should run with error_reporting at the highest level possible and display_errors enabled. While annoying when you first start out, these errors, warnings, notices and strict coding advice all add up and enable you to becoem a better coder.
Log.v("blah", "blah blah");
You need to add the android Log view in eclipse to see them. There are also other methods depending on the severity of the message (error, verbose, warning, etc..).
If you are not working with others (or are happy to cause them significant annoyance), then it is possible to remove commits from bitbucket branches.
git reset HEAD^ # remove the last commit from the branch history
git push origin :branch_name # delete the branch from bitbucket
git push origin branch_name # push the branch back up again, without the last commit
In git generally, the master branch is not special - it's just a convention. However, bitbucket and github and similar sites usually require there to be a main branch (presumably because it's easier than writing more code to handle the event that a repository has no branches - not sure). So you need to create a new branch, and make that the main branch:
# on master:
git checkout -b master_temp
git reset HEAD^ # undo the bad commit on master_temp
git push origin master_temp # push the new master to Bitbucket
On Bitbucket, go to the repository settings, and change the "Main branch" to master_temp
(on Github, change the "Default branch").
git push origin :master # delete the original master branch from Bitbucket
git checkout master
git reset master_temp # reset master to master_temp (removing the bad commit)
git push origin master # re-upload master to bitbucket
Now go to Bitbucket, and you should see the history that you want. You can now go to the settings page and change the Main branch back to master
.
This process will also work with any other history changes (e.g. git filter-branch
). You just have to make sure to reset to appropriate commits, before the new history split off from the old.
edit: apparently you don't need to go to all this hassle on github, as you can force-push a reset branch.
Next time anyone tries to pull from your repository, (if they've already pulled the bad commit), the pull will fail. They will manually have to reset to a commit before the changed history, and then pull again.
git reset HEAD^
git pull
If they have pulled the bad commit, and committed on top of it, then they will have to reset, and then git cherry-pick
the good commits that they want to create, effectively re-creating the whole branch without the bad commit.
If they never pulled the bad commit, then this whole process won't affect them, and they can pull as normal.
You can also use sqlcmd
mode for this (enable this on the "Query" menu in Management Studio).
:setvar dbname "TEST"
CREATE DATABASE $(dbname)
GO
ALTER DATABASE $(dbname) SET COMPATIBILITY_LEVEL = 90
GO
ALTER DATABASE $(dbname) SET RECOVERY SIMPLE
GO
EDIT:
Check this MSDN article to set parameters via the SQLCMD tool.
I think what the questioner is after is converting the string representation of a hexadecimal value to a byte array representing that hexadecimal value.
The apache commons-codec has a class for that, Hex.
String s = "9B7D2C34A366BF890C730641E6CECF6F";
byte[] bytes = Hex.decodeHex(s.toCharArray());
You should be doing this
String input = "hello world, this is a line of text";
int i = input.indexOf(' ');
String word = input.substring(0, i);
String rest = input.substring(i);
The above is the fastest way of doing this task.
For portable code, the macros in inttypes.h may be used. They expand to the correct ones for the platform.
E.g. for 64 bit integer, the macro PRId64
can be used.
int64_t n = 7;
printf("n is %" PRId64 "\n", n);
I like Ctrl+K, Ctrl+D, which indents the whole document.
The simple approach of just averaging them has weird edge cases with angles when they wrap from 359' back to 0'.
A much earlier question on SO asked about finding the average of a set of compass angles.
An expansion of the approach recommended there for spherical coordinates would be:
If you like to use Jackson Databind (which Spring
uses by default for its HttpMessageConverters
), then you may use the ObjectMapper.readTree(InputStream) API. For example,
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(myInputStream);
-- Option 1: php-cgi --
Use 'php-cgi' in place of 'php' to run your script. This is the simplest way as you won't need to specially modify your php code to work with it:
php-cgi -f /my/script/file.php a=1 b=2 c=3
-- Option 2: if you have a web server --
If the php file is on a web server you can use 'wget' on the command line:
wget 'http://localhost/my/script/file.php?a=1&b=2&c=3'
OR:
wget -q -O - "http://localhost/my/script/file.php?a=1&b=2&c=3"
-- Accessing the variables in php --
In both option 1 & 2 you access these parameters like this:
$a = $_GET["a"];
$b = $_GET["b"];
$c = $_GET["c"];
You are entering a null value to nextInt, it will fail if you give a null value...
i have added a null check to the piece of code
Try this code:
import java.util.Scanner;
class MyClass
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int eid,sid;
String ename;
System.out.println("Enter Employeeid:");
eid=(scanner.nextInt());
System.out.println("Enter EmployeeName:");
ename=(scanner.next());
System.out.println("Enter SupervisiorId:");
if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
sid=scanner.nextInt();
}//null check
}
}
string[] strArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if(Array.contains(strArray , value))
{
// Do something if the value is available in Array.
}
Are you thinking about something like this?
$('ul li').each(function(i)
{
$(this).attr('rel'); // This is your rel value
});
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");
t.appendChild(y);
_x000D_
<p id="p">This is some text</p>
_x000D_
I don't know why but (for now) httpclient can be compiled only as a jar into the libs directory in your project. HttpCore works fine when it is included from mvn like that:
dependencies {
compile 'org.apache.httpcomponents:httpcore:4.4.3'
}
I had the case where my app would deploy to my iPhone but not my watch. Deploying to the watch would give the "A valid provisioning profile for this executable was not found." error. This is with XCode Version 11.2.1 and using the free developer account.
Here is what I did to get it deployed to my watch:
1) I deleted my provisioning profile in XCode. I did this by going to Window -> Devices And Simulators. Then right Click on the iPhone name and choose "Show Provisioning Profiles". From there I could delete the file
2) In The Devices and Simulators screen I also deleted my app from the "Installed Apps" section.
3) Did a "clean build folder" (Product -> Clean Build Folder)
4) In the "Build Settings" -> "Signing section" I made sure each target (iPhone, Tests and Watch) had the same settings (development team, code signing style, provisioning profile was set to automatic etc).
5) Ensured the ~/Library/MobileDevice/Provisioning Profiles directory was empty.
6) Unplugged phone from computer
7) Rebooted computer, phone and watch
8) Plugged phone back into computer, and went through the "trust this machine" prompts on phone and watch.
9) Ran app. It worked!
Now you can download an extension directly in the "Resources" section, there's a "Download extension" link, I hope this information is still useful.
You can try this:
<script>
function checkAllCheckBox(value)
{
if($('#select_all_').is(':checked')){
$(".check_").attr ( "checked" ,"checked" );
}
else
{
$(".check_").removeAttr('checked');
}
}
</script>
<input type="checkbox" name="chkbox" id="select_all_" value="1" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
Simple Get Request using HttpClient Class
using System.Net.Http;
class Program
{
static void Main(string[] args)
{
HttpClient httpClient = new HttpClient();
var result = httpClient.GetAsync("https://www.google.com").Result;
}
}
You can try these codes
claimantAuxillaryRecord.TPOCDate2 = Convert.ToDateTime(tpoc2[0]).ToString("yyyyMMdd");
Or
claimantAuxillaryRecord.TPOCDate2 = Convert.ToDateTime(tpoc2[0]).ToString("yyyyMMdd hh:mm:ss");
Regarding increasing the max stack size, on 32 bit and 64 bit machines V8's memory allocation defaults are, respectively, 700 MB and 1400 MB. In newer versions of V8, memory limits on 64 bit systems are no longer set by V8, theoretically indicating no limit. However, the OS (Operating System) on which Node is running can always limit the amount of memory V8 can take, so the true limit of any given process cannot be generally stated.
Though V8 makes available the --max_old_space_size
option, which allows control over the amount of memory available to a process, accepting a value in MB. Should you need to increase memory allocation, simply pass this option the desired value when spawning a Node process.
It is often an excellent strategy to reduce the available memory allocation for a given Node instance, especially when running many instances. As with stack limits, consider whether massive memory needs are better delegated to a dedicated storage layer, such as an in-memory database or similar.
You can try:
string s1 = Regex.Replace(s, "[^A-Za-z0-9 -]", "");
Where s
is your string.
if ( $( "#myDiv" ).length ) {
// if ( "#myDiv" ) is exist this will perform
$( "#myDiv" ).show();
}
Another shorthand way:
$( "#myDiv" ).length && $( "#myDiv" ).show();
So there are some commands which you can use for cleaning
1. mvn clean cache
2. mvn clean install
3. mvn clean install -Pclean-database
also deleting repository folder from .m2 can help.
I recommend adding the following line after the export to PDF:
ThisWorkbook.Sheets("Sheet1").Select
(where eg. Sheet1
is the single sheet you want to be active afterwards)
Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)
None of the answers mentioned that the ToString()
method can be applied to integer expressions
Debug.Assert((1000*1000).ToString()=="1000000");
even to integer literals
Debug.Assert(256.ToString("X")=="100");
Although integer literals like this are often considered to be bad coding style (magic numbers) there may be cases where this feature is useful...
1) You can use standard java utility xjc - ([your java home dir]\bin\xjc.exe). But you need to create .bat (or .sh) script for using it.
e.g. generate.bat:
[your java home dir]\bin\xjc.exe %1 %2 %3
e.g. test-scheme.xsd:
<?xml version="1.0"?>
<xs:schema version="1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://myprojects.net/xsd/TestScheme"
xmlns="http://myprojects.net/xsd/TestScheme">
<xs:element name="employee" type="PersonInfoType"/>
<xs:complexType name="PersonInfoType">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Run .bat file with parameters: generate.bat test-scheme.xsd -d [your src dir]
For more info use this documentation - http://docs.oracle.com/javaee/5/tutorial/doc/bnazg.html
and this - http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html
2) JAXB (xjc utility) is installed together with JDK6 by default.
I added a directory to svn, then I accidentally deleted the .svn folder within.
I used
svn delete --keep-local folderName
to fix my problem.
If your page really relies on the fact that people won't be able to see that menu, you should know that modern browsers (for example Firefox) let the user decide if he really wants to disable it or not. So you have no guarantee at all that the menu would be really disabled.
Another option in SQL Server is to do all of your dynamic querying into table variable in a stored proc, then use a cursor to query and process that. As to the dreaded cursor debate :), I have seen studies that show that in some situations, a cursor can actually be faster if properly set up. I use them myself when the required query is too complex, or just not humanly (for me ;) ) possible.
$cookie_name = "my cookie";
$cookie_value = "my value";
$cookie_new_value = "my new value";
// Create a cookie,
setcookie($cookie_name, $cookie_value , time() + (86400 * 30), "/"); //86400 = 24 hours in seconds
// Get value in a cookie,
$cookie_value = $_COOKIE[$cookie_name];
// Update a cookie,
setcookie($cookie_name, $cookie_new_value , time() + (86400 * 30), "/");
// Delete a cookie,
setcookie($cookie_name, '' , time() - 3600, "/"); // time() - 3600 means, set the cookie expiration date to the past hour.
code:
// Create Directory if not exist then Copy a file.
public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {
Path FROM = Paths.get(origin);
Path TO = Paths.get(destination);
File directory = new File(String.valueOf(destDir));
if (!directory.exists()) {
directory.mkdir();
}
//overwrite the destination file if it exists, and copy
// the file attributes, including the rwx permissions
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(FROM, TO, options);
}
For only one line, you need
...
<View android:id="@+id/primerdivisor"
android:layout_height="2dp"
android:layout_width="fill_parent"
android:background="#ffffff" />
...
Using modern --inspect with node the console.log is captured and relayed to the browser.
node --inspect myApp.js
or to capture early logging --inspect-brk can be used to stop the program on the first line of the first module...
node --inspect-brk myApp.js
1> You can add image from layout itself:
<ImageView
android:id="@+id/iv_your_image"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:background="@mipmap/your_image"
android:padding="2dp" />
OR
2> Programmatically in java class:
ImageView ivYouImage= (ImageView)findViewById(R.id.iv_your_image);
ivYouImage.setImageResource(R.mipmap.ic_changeImage);
OR for fragments:
View rowView= inflater.inflate(R.layout.your_layout, null, true);
ImageView ivYouImage= (ImageView) rowView.findViewById(R.id.iv_your_image);
ivYouImage.setImageResource(R.mipmap.ic_changeImage);
JSONP stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue.
jsonCallback(
{
"sites":
[
{
"siteName": "JQUERY4U",
"domainName": "http://www.jquery4u.com",
"description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets."
},
{
"siteName": "BLOGOOLA",
"domainName": "http://www.blogoola.com",
"description": "Expose your blog to millions and increase your audience."
},
{
"siteName": "PHPSCRIPTS4U",
"domainName": "http://www.phpscripts4u.com",
"description": "The Blog of Enthusiastic PHP Scripters"
}
]
});
(function($) {
var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.sites);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
Now we can request the JSON via AJAX using JSONP and the callback function we created around the JSON content. The output should be the JSON as an object which we can then use the data for whatever we want without restrictions.
Check this library, it's completable with booth bootstrap 3 and bootstrap 4
<form>
<div class="form-group">
<input class="form-control" data-validator="required|min:4|max:10">
</div>
</form>
$(document).on('blur', '[data-validator]', function () {
new Validator($(this));
});
@peterSO has correct answer. I am adding more examples here:
package main
import (
"fmt"
strings "strings"
)
func main() {
test := "\t pdftk 2.0.2 \n"
result := strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
test = "\n\r pdftk 2.0.2 \n\r"
result = strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
test = "\n\r\n\r pdftk 2.0.2 \n\r\n\r"
result = strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
test = "\r pdftk 2.0.2 \r"
result = strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
}
You can find this in Go lang playground too.
I had a similar issue to this. I solved it by making all the projects within my solution target the same .NET Framework 4 Client Profile and then rebuilding the entire solution.
No one mentioned this, but in conjunction to the other responses, you can also get the apk file from your bin directory to your phone or tablet by putting it on a web site and just downloading it.
Your device will complain about installing it after you download it. Your device will advise you or a risk of installing programs from unknown sources and give you the option to bypass the advice.
Your question is very specific. You don't have to pull it from your emulator, just grab the apk file from the bin folder in your project and place it on your real device.
Most people are giving you valuable information for the next step (signing and publishing your apk), you are not required to do that step to get it on your real device.
Downloading it to your real device is a simple method.
If upper and lower bound of Int32
matters:
public bool IsInt32(double value)
{
return value >= int.MinValue && value <= int.MaxValue && value == (int)value;
}
SELECT CONVERT(DATE,DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0)) AS FirstDayOfPrevMonth
SELECT CONVERT(DATE,DATEADD(MS, -3, DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) , 0))) AS LastDayOfPrevMonth
Why is 21 the default port for FTP? Or 80 the default for HTTP? It is a convention.
The second argument Title does not mean Title of the page - It is more of a definition/information for the state of that page
But we can still change the title using onpopstate event, and passing the title name not from the second argument, but as an attribute from the first parameter passed as object
Reference: http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/
On OSX use fn instead of shift.
First you need to turn on virtualization on your machine. To do that, restart your machine. Press F2. Goto BIOS. Make Virtualization Enabled. Press F10. Start windows. Now, goto Extras folder of Android installation folder and find intel-haxm-android.exe. Run it. Start Android Studio. Now, it should allow you to run your program using emulator.
You should check for the type of the item in the localStorage
if(localStorage.token !== null) {
// this will only work if the token is set in the localStorage
}
if(typeof localStorage.token !== 'undefined') {
// do something with token
}
if(typeof localStorage.token === 'undefined') {
// token doesn't exist in the localStorage, maybe set it?
}
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
In some situations you can hide the shadow by another container. Eg, if there is a DIV above and below the DIV with the shadow, you can use position: relative; z-index: 1;
on the surrounding DIVs.
If I've understood your question correctly, then you are looking for the mouseup
event, rather than the click
event:
$("#message_link").mouseup(function() {
//Do stuff here
});
The mouseup
event fires when the mouse button is released, and does not take into account whether the mouse button was pressed on that element, whereas click
takes into account both mousedown
and mouseup
.
However, click
should work fine, because it won't actually fire until the mouse button is released.
If you are fortunate enough to be running Python 3.4+, you can use pathlib
:
>>> from pathlib import Path
>>> dirname = '/home/reports'
>>> filename = 'daily'
>>> suffix = '.pdf'
>>> Path(dirname, filename).with_suffix(suffix)
PosixPath('/home/reports/daily.pdf')
Change the .find
to .filter
...
Here's a function I wrote that takes Molly's code and some other code I've found on the internet to make slightly fancier grouped boxplots:
import numpy as np
import matplotlib.pyplot as plt
def custom_legend(colors, labels, linestyles=None):
""" Creates a list of matplotlib Patch objects that can be passed to the legend(...) function to create a custom
legend.
:param colors: A list of colors, one for each entry in the legend. You can also include a linestyle, for example: 'k--'
:param labels: A list of labels, one for each entry in the legend.
"""
if linestyles is not None:
assert len(linestyles) == len(colors), "Length of linestyles must match length of colors."
h = list()
for k,(c,l) in enumerate(zip(colors, labels)):
clr = c
ls = 'solid'
if linestyles is not None:
ls = linestyles[k]
patch = patches.Patch(color=clr, label=l, linestyle=ls)
h.append(patch)
return h
def grouped_boxplot(data, group_names=None, subgroup_names=None, ax=None, subgroup_colors=None,
box_width=0.6, box_spacing=1.0):
""" Draws a grouped boxplot. The data should be organized in a hierarchy, where there are multiple
subgroups for each main group.
:param data: A dictionary of length equal to the number of the groups. The key should be the
group name, the value should be a list of arrays. The length of the list should be
equal to the number of subgroups.
:param group_names: (Optional) The group names, should be the same as data.keys(), but can be ordered.
:param subgroup_names: (Optional) Names of the subgroups.
:param subgroup_colors: A list specifying the plot color for each subgroup.
:param ax: (Optional) The axis to plot on.
"""
if group_names is None:
group_names = data.keys()
if ax is None:
ax = plt.gca()
plt.sca(ax)
nsubgroups = np.array([len(v) for v in data.values()])
assert len(np.unique(nsubgroups)) == 1, "Number of subgroups for each property differ!"
nsubgroups = nsubgroups[0]
if subgroup_colors is None:
subgroup_colors = list()
for k in range(nsubgroups):
subgroup_colors.append(np.random.rand(3))
else:
assert len(subgroup_colors) == nsubgroups, "subgroup_colors length must match number of subgroups (%d)" % nsubgroups
def _decorate_box(_bp, _d):
plt.setp(_bp['boxes'], lw=0, color='k')
plt.setp(_bp['whiskers'], lw=3.0, color='k')
# fill in each box with a color
assert len(_bp['boxes']) == nsubgroups
for _k,_box in enumerate(_bp['boxes']):
_boxX = list()
_boxY = list()
for _j in range(5):
_boxX.append(_box.get_xdata()[_j])
_boxY.append(_box.get_ydata()[_j])
_boxCoords = zip(_boxX, _boxY)
_boxPolygon = plt.Polygon(_boxCoords, facecolor=subgroup_colors[_k])
ax.add_patch(_boxPolygon)
# draw a black line for the median
for _k,_med in enumerate(_bp['medians']):
_medianX = list()
_medianY = list()
for _j in range(2):
_medianX.append(_med.get_xdata()[_j])
_medianY.append(_med.get_ydata()[_j])
plt.plot(_medianX, _medianY, 'k', linewidth=3.0)
# draw a black asterisk for the mean
plt.plot([np.mean(_med.get_xdata())], [np.mean(_d[_k])], color='w', marker='*',
markeredgecolor='k', markersize=12)
cpos = 1
label_pos = list()
for k in group_names:
d = data[k]
nsubgroups = len(d)
pos = np.arange(nsubgroups) + cpos
label_pos.append(pos.mean())
bp = plt.boxplot(d, positions=pos, widths=box_width)
_decorate_box(bp, d)
cpos += nsubgroups + box_spacing
plt.xlim(0, cpos-1)
plt.xticks(label_pos, group_names)
if subgroup_names is not None:
leg = custom_legend(subgroup_colors, subgroup_names)
plt.legend(handles=leg)
You can use the function(s) like this:
data = { 'A':[np.random.randn(100), np.random.randn(100) + 5],
'B':[np.random.randn(100)+1, np.random.randn(100) + 9],
'C':[np.random.randn(100)-3, np.random.randn(100) -5]
}
grouped_boxplot(data, group_names=['A', 'B', 'C'], subgroup_names=['Apples', 'Oranges'], subgroup_colors=['#D02D2E', '#D67700'])
plt.show()
If you are programming in PHP, it is useful to split lines by \n
and then trim()
each line (provided you don't care about whitespace) to give you a "clean" line regardless.
foreach($line in explode("\n", $data))
{
$line = trim($line);
...
}
Assuming that you have a program running in the foreground, press ctrl-Z, then:
[1]+ Stopped myprogram
$ disown -h %1
$ bg 1
[1]+ myprogram &
$ logout
If there is only one job, then you don't need to specify the job number. Just use disown -h
and bg
.
You press ctrl-Z. The system suspends the running program, displays a job number and a "Stopped" message and returns you to a bash prompt.
You type the disown -h %1
command (here, I've used a 1
, but you'd use the job number that was displayed in the Stopped
message) which marks the job so it ignores the SIGHUP
signal (it will not be stopped by logging out).
Next, type the bg
command using the same job number; this resumes the running of the program in the background and a message is displayed confirming that.
You can now log out and it will continue running..
If you are using CSRF enter 'before'=>'csrf'
In your case
Route::get('auth/login', ['before'=>'csrf','uses' => 'Auth\AuthController@getLogin', 'as' => 'login']);
For more details view Laravel 5 Documentation Security Protecting Routes
We can try by using latest jQuery library. I got the same issue. I used jQuery-1.4.2.min before and getting the error. After that I used version 1.9.1 and it works. Thanks
You can use following extentions
public static class JsonExtensions
{
public static T ToObject<T>(this string jsonText)
{
return JsonConvert.DeserializeObject<T>(jsonText);
}
public static string ToJson<T>(this T obj)
{
return JsonConvert.SerializeObject(obj);
}
}
DateTime.Today
as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1)
;
There are sufficient options available in DateTime to get the formatting like ToShortDateString
depending on your culture and you have no need to concatenate them individually.
Also you can have a desirable format in the .ToString()
version of the DateTime
instance
If the file is large, you may not want to load it entirely into memory at once. This approach avoids that. (Of course, making a dict out of it could still take up some RAM, but it's guaranteed to be smaller than the original file.)
my_dict = {}
for i, line in enumerate(file):
if (i - 8) % 7:
continue
k, v = line.split("\t")[:3:2]
my_dict[k] = v
Edit: Not sure where I got extend
from before. I meant update
In jQuery just use an attribute selector like
$('input[name="locationthemes"]:checked');
to select all checked inputs with name "locationthemes"
console.log($('input[name="locationthemes"]:checked').serialize());
//or
$('input[name="locationthemes"]:checked').each(function() {
console.log(this.value);
});
In VanillaJS
[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {
console.log(cb.value);
});
In ES6/spread operator
[...document.querySelectorAll('input[name="locationthemes"]:checked')]
.forEach((cb) => console.log(cb.value));
In general, that depends on your shell, but if you use bash, zsh, ksh or sh (as provided by dash), the following should work:
if ! type "$foobar_command_name" > /dev/null; then
# install foobar here
fi
For a real installation script, you'd probably want to be sure that type
doesn't return successfully in the case when there is an alias foobar
. In bash you could do something like this:
if ! foobar_loc="$(type -p "$foobar_command_name")" || [[ -z $foobar_loc ]]; then
# install foobar here
fi
we can use createNativeQuery("Here Nagitive SQL Query ");
for Example :
Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();
I have noticed some of the other answers here use a bare clone and then mirror push to the new repository, however this does not work for me and when I open the new repository after that, the files look mixed up and not as I expect.
Here is a solution that definitely works for copying the files, although it does not preserve the original repository's revision history.
git clone
the repository onto your local machine.cd
into the project directory and then run rm -rf .git
to remove all the old git metadata including commit history, etc.git init
.git add . ; git commit -am "Initial commit"
- Of course you can call this commit what you want.git remote add origin https://github.com/user/repo-name
(replace the url with the url to your new repository)git push origin master
.In my case the error came out of nowhere, but didn't let me push to the remote branch.
git fetch origin
And that solved it.
I agree this may not solve the issue for everyone, but before trying a more complex approach give it a shot at this one, nothing to loose.
If you want to fetch particular element/node or tag in loop for e.g.
<p class="weekday" data-today="monday">Monday</p>
<p class="weekday" data-today="tuesday">Tuesday</p>
<p class="weekday" data-today="wednesday">Wednesday</p>
<p class="weekday" data-today="thursday">Thursday</p>
So, from above code loop is executed and we want particular field to select for that we have to use jQuery selection that can select only expecting element from above loop so, code will be
$('.weekdays:eq(n)');
e.g.
$('.weekdays:eq(0)');
as well as by other method
$('.weekday').find('p').first('.weekdays').next()/last()/prev();
but first method is more efficient when HTML <tag>
has unique class name.
NOTE:Second method is use when their is no class name in target element or node.
for more follow https://api.jquery.com/eq/
find out what you have assigned to 'list' by displaying it
>>> print(list)
if it has content, you have to clean it with
>>> del list
now display 'list' again and expect this
<class 'list'>
Once you see this, you can proceed with your copy.
none of the above answers worked for me. This one did:
=QUERY(Copy!A1:AP, "select AP, E, F, AO where AP="&E1&" ",1)
I provide a functional+recursive approach. See comments to understand how it works:
const input1 = ['a', 'aa', 'aaa']_x000D_
const input2 = ['asdf', 'qwer', 'zxcv']_x000D_
const input3 = ['asdfasdf fdasdf a sd f', ' asdfsdf', 'asdfasdfds', 'asdfsdf', 'asdfsdaf']_x000D_
const input4 = ['ddd', 'dddddddd', 'dddd', 'ddddd', 'ddd', 'dd', 'd', 'd', 'dddddddddddd']_x000D_
_x000D_
// Outputs which words has the greater length_x000D_
// greatestWord :: String -> String -> String_x000D_
const greatestWord = x => y => _x000D_
x.length > y.length ? x : y_x000D_
_x000D_
// Recursively outputs the first longest word in a series_x000D_
// longestRec :: String -> [String] -> String_x000D_
const longestRec = longestWord => ([ nextWord, ...words ]) =>_x000D_
// ^^^^^^^^^^^^_x000D_
// Destructuring lets us get the next word, and remaining ones!_x000D_
nextWord // <-- If next word is undefined, then it won't recurse._x000D_
? longestRec (greatestWord (nextWord) (longestWord)) (words) _x000D_
: longestWord_x000D_
_x000D_
_x000D_
// Outputs the first longest word in a series_x000D_
// longest :: [String] -> String_x000D_
const longest = longestRec ('')_x000D_
_x000D_
const output1 = longest (input1)_x000D_
const output2 = longest (input2) _x000D_
const output3 = longest (input3)_x000D_
const output4 = longest (input4)_x000D_
_x000D_
console.log ('output1: ', output1)_x000D_
console.log ('output2: ', output2)_x000D_
console.log ('output3: ', output3)_x000D_
console.log ('output4: ', output4)
_x000D_
You can do this using Escape Sequence.
\"
So you will have to write something like this :
String name = "\"john\"";
You can learn about Escape Sequences from here.
Saying it's the difference between "local and global" isn't entirely accurate.
It might be better to think of it as the difference between "local and nearest". The nearest can surely be global, but that won't always be the case.
/* global scope */
var local = true;
var global = true;
function outer() {
/* local scope */
var local = true;
var global = false;
/* nearest scope = outer */
local = !global;
function inner() {
/* nearest scope = outer */
local = false;
global = false;
/* nearest scope = undefined */
/* defaults to defining a global */
public = global;
}
}
I'm providing an answer to this question, because I do not see any native, recursive implementations here that resolve the problem of DOM
elements.
The problem there is that <element>
has parent
and child
attributes, that link to other elements with parent
and child
values, which point back to the original <element>
, causing either an infinite recursive or cyclic redundancy.
If your object is something safe and simple like
{
'123':456
}
...then any other answer here will probably work.
But if you have...
{
'123':<reactJSComponent>,
'456':document.createElement('div'),
}
...then you need something like this:
// cloneVariable() : Clone variable, return null for elements or components.
var cloneVariable = function (args) {
const variable = args.variable;
if(variable === null) {
return null;
}
if(typeof(variable) === 'object') {
if(variable instanceof HTMLElement || variable.nodeType > 0) {
return null;
}
if(Array.isArray(variable)) {
var arrayclone = [];
variable.forEach((element) => {
arrayclone.push(cloneVariable({'variable':element}));
});
return arrayclone;
}
var objectclone = {};
Object.keys(variable).forEach((field) => {
objectclone[field] = cloneVariable({'variable':variable[field]});
});
return objectclone;
}
return variable;
}
Instead of using Bitmap
, you can also do this through a trivial InputStream
. Well, I am not sure, but I think it's a bit efficient.
InputStream inputStream = new FileInputStream(fileName); // You can get an inputStream using any I/O API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
If this isn't a good solution for any reason, please let me know. It worked fine for me.
What I did is to hide the Sidebar and then make appear the navbar with breakpoints
@media screen and (max-width: 771px) {
#fixed-sidebar {
display: none;
}
#navbar-superior {
display: block !important;
}
}
Monolithic kernel has all kernel services along with kernel core part, thus are heavy and has negative impact on speed and performance. On the other hand micro kernel is lightweight causing increase in performance and speed.
I answered same question at wordpress site.
For the difference between monolithic, microkernel and exokernel in tabular form, you can visit here
You should just use Spread operator:
var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);_x000D_
_x000D_
var newArr = [...myMap].map(value => value[1] + 1);_x000D_
console.log(newArr); //[2, 3, 4]_x000D_
_x000D_
var newArr2 = [for(value of myMap) value = value[1] + 1];_x000D_
console.log(newArr2); //[2, 3, 4]
_x000D_
This might work for you:
printf "{new\nto\nlinux}" | paste -sd' '
{new to linux}
or:
printf "{new\nto\nlinux}" | tr '\n' ' '
{new to linux}
or:
printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}
Seriously this took my much valuable time but not found solution. Basically if you are taking data from sql then you are converting then you can follow these steps.
rows = cursor.fetchall()---- only tried on single column
dataset=[]
for x in rows:
dataset.append(float(x[0]))
Swift 4.2
extension URL {
func checkFileExist() -> Bool {
let path = self.path
if (FileManager.default.fileExists(atPath: path)) {
print("FILE AVAILABLE")
return true
}else {
print("FILE NOT AVAILABLE")
return false;
}
}
}
Using: -
if fileUrl.checkFileExist()
{
// Do Something
}
myFunction(
contextParamers : {
param1: any,
param2: string
param3: string
}){
contextParamers.param1 = contextParamers.param1+ 'canChange';
//contextParamers.param4 = "CannotChange";
var contextParamers2 : any = contextParamers;// lost the typescript on the new object of type any
contextParamers2.param4 = 'canChange';
return contextParamers2;
}
Simplified form:
Last week data:
SELECT id FROM tbl
WHERE
WEEK (date) = WEEK( current_date ) - 1 AND YEAR( date) = YEAR( current_date );
2 weeks ago data:
SELECT id FROM tbl
WHERE
WEEK (date) = WEEK( current_date ) - 2 AND YEAR( date) = YEAR( current_date );
SQL Fiddle
This is what the difference i found. Please let me know if any .
Or the real lazy mans way, just make use of what is there already and flip it:
public class InverseBooleanToVisibilityConverter : IValueConverter
{
private BooleanToVisibilityConverter _converter = new BooleanToVisibilityConverter();
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var result = _converter.Convert(value, targetType, parameter, culture) as Visibility?;
return result == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var result = _converter.ConvertBack(value, targetType, parameter, culture) as bool?;
return result == true ? false : true;
}
}
db.query(
TABLE_NAME,
new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
TABLE_ROW_ID + "=" + rowID,
null, null, null, null, null
);
TABLE_ROW_ID + "=" + rowID
, here =
is the where
clause. To select all values you will have to give all column names:
or you can use a raw query like this
db.rawQuery("SELECT * FROM permissions_table WHERE name = 'Comics' ", null);
and here is a good tutorial for database.
The argument is of length zero takes places when you get an output as an integer of length 0 and not a NULL output.i.e., integer(0).
You can further verify my point by finding the class of your output-
>class(output)
"integer"
pip install configparser
sudo cp /usr/lib/python3.6/configparser.py /usr/lib/python3.6/ConfigParser.py
Then try to install the MYSQL-python again. That Worked for me
as per @Jon Skeet 's comment, you should use a XmlReader only if your file is very big. Here's how to use it. Assuming you have a Book class
public class Book {
public string Title {get; set;}
public string Author {get; set;}
}
you can read the XML file line by line with a small memory footprint, like this:
public static class XmlHelper {
public static IEnumerable<Book> StreamBooks(string uri) {
using (XmlReader reader = XmlReader.Create(uri)) {
string title = null;
string author = null;
reader.MoveToContent();
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element
&& reader.Name == "Book") {
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Title") {
title = reader.ReadString();
break;
}
}
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Author") {
author =reader.ReadString();
break;
}
}
yield return new Book() {Title = title, Author = author};
}
}
}
}
Example of usage:
string uri = @"c:\test.xml"; // your big XML file
foreach (var book in XmlHelper.StreamBooks(uri)) {
Console.WriteLine("Title, Author: {0}, {1}", book.Title, book.Author);
}
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
I second Hightechrider: there is a specialized Url class already built for you.
I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.
I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.
sudo apt-get install openjfx
jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).
I don't if anybody else has a better option...
<% if (Model.VariableName == "" || Model.VariableName== null) { %>
<%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], "",
new{stlye=" "})%>
<% } else{ %>
<%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"],
Model.VariableName, new{stlye=" "})%>
<% }>
for converting dd/mm/yyyy
to mm/dd/yyyy
=DATE(RIGHT(a1,4),MID(a1,4,2),LEFT(a1,2))
Here is an extension method that overloads the AppendText
method with a color parameter:
public static class RichTextBoxExtensions
{
public static void AppendText(this RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
}
And this is how you would use it:
var userid = "USER0001";
var message = "Access denied";
var box = new RichTextBox
{
Dock = DockStyle.Fill,
Font = new Font("Courier New", 10)
};
box.AppendText("[" + DateTime.Now.ToShortTimeString() + "]", Color.Red);
box.AppendText(" ");
box.AppendText(userid, Color.Green);
box.AppendText(": ");
box.AppendText(message, Color.Blue);
box.AppendText(Environment.NewLine);
new Form {Controls = {box}}.ShowDialog();
Note that you may notice some flickering if you're outputting a lot of messages. See this C# Corner article for ideas on how to reduce RichTextBox flicker.
you can disable or set date and time for log setting.
System > Configuration > Advanced > System > Log Cleaning
Python's eager in its evaluation, so eval(input(...))
(Python 3) will evaluate the user's input as soon as it hits the eval
, regardless of what you do with the data afterwards. Therefore, this is not safe, especially when you eval
user input.
Use ast.literal_eval
.
As an example, entering this at the prompt could be very bad for you:
__import__('os').system('rm -rf /a-path-you-really-care-about')
I have had the same problem with a simple Activity carrying only one fragment (which would get replaced sometimes). I then realized I use onSaveInstanceState only in the fragment (and onCreateView to check for savedInstanceState), not in the activity.
On device turn the activity containing the fragments gets restarted and onCreated is called. There I did attach the required fragment (which is correct on the first start).
On the device turn Android first re-created the fragment that was visible and then called onCreate of the containing activity where my fragment was attached, thus replacing the original visible one.
To avoid that I simply changed my activity to check for savedInstanceState:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
/**making sure you are not attaching the fragments again as they have
been
*already added
**/
return;
}
else{
// following code to attach fragment initially
}
}
I did not even Overwrite onSaveInstanceState of the activity.
Removing .git hidden folder worked for me.
You should form the command with the contents of the textboxes:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text +
"," + textbox3.Text+ ")";
This, of course, provided that you manage to open the connection correctly.
It would be helpful to know what is happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.
You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code).
Thank you. I use passing in an object as a parameter. My Android code is below
String oPerson= null;
if (CheckAddress("5556", oPerson))
{
Toast.makeText(this,
"It's Match! " + oPerson,
Toast.LENGTH_LONG).show();
}
private boolean CheckAddress(String iAddress, String oPerson)
{
Cursor cAddress = mDbHelper.getAllContacts();
String address = "";
if (cAddress.getCount() > 0) {
cAddress.moveToFirst();
while (cAddress.isAfterLast() == false) {
address = cAddress.getString(2).toString();
oPerson = cAddress.getString(1).toString();
if(iAddress.indexOf(address) != -1)
{
Toast.makeText(this,
"Person : " + oPerson,
Toast.LENGTH_LONG).show();
System.out.println(oPerson);
cAddress.close();
return true;
}
else cAddress.moveToNext();
}
}
cAddress.close();
return false;
}
The result is
Person : John
It's Match! null
Actually, "It's Match! John"
Please check my mistake.
sizeWithFont constrainedToSize:lineBreakMode:
is the method to use. An example of how to use it is below:
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
I've found the updated answer from this video, the accepted answer didn't work for me.
First clone the latest repo from git (if haven't) using
git clone <HTTPs link of the project>
(or using SSH) then go to the desire branch using
git checkout <branch name>
.
Use the command
git log
to check the latest commits. Copy the shal of the particular commit. Then use the command
git fetch origin <Copy paste the shal here>
After pressing enter key. Now use the command
git checkout FETCH_HEAD
Now the particular commit will be available to your local. Change anything and push the code using git push origin <branch name>
. That's all.
Check the video for reference.
My 2 cents addition to the answers here are:
With reference to Field or Property access (away from performance considerations) both are legitimately accessed by means of getters and setters, thus, my model logic can set/get them in the same manner. The difference comes to play when the persistence runtime provider (Hibernate, EclipseLink or else) needs to persist/set some record in Table A which has a foreign key referring to some column in Table B. In case of a Property access type, the persistence runtime system uses my coded setter method to assign the cell in Table B column a new value. In case of a Field access type, the persistence runtime system sets the cell in Table B column directly. This difference is not of importance in the context of a uni-directional relationship, yet it is a MUST to use my own coded setter method (Property access type) for a bi-directional relationship provided the setter method is well designed to account for consistency. Consistency is a critical issue for bi-directional relationships refer to this link for a simple example for a well-designed setter.
With reference to Equals/hashCode: It is impossible to use the Eclipse auto-generated Equals/hashCode methods for entities participating in a bi-directional relationship, otherwise they will have a circular reference resulting in a stackoverflow Exception. Once you try a bidirectional relationship (say OneToOne) and auto-generate Equals() or hashCode() or even toString() you will get caught in this stackoverflow exception.
In my case I am using a variation of the solution proposed by @seanwright:
https://github.com/NetanelBasal/ngx-take-until-destroy
It's a file used in the ngx-rocket / starter-kit project. You can access it here until-destroyed.ts
The component would look like so
/**
* RxJS operator that unsubscribe from observables on destory.
* Code forked from https://github.com/NetanelBasal/ngx-take-until-destroy
*
* IMPORTANT: Add the `untilDestroyed` operator as the last one to
* prevent leaks with intermediate observables in the
* operator chain.
*
* @param instance The parent Angular component or object instance.
* @param destroyMethodName The method to hook on (default: 'ngOnDestroy').
*/
import { untilDestroyed } from '../../core/until-destroyed';
@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent implements OnInit, OnDestroy {
ngOnInit() {
interval(1000)
.pipe(untilDestroyed(this))
.subscribe(val => console.log(val));
// ...
}
// This method must be present, even if empty.
ngOnDestroy() {
// To protect you, an error will be thrown if it doesn't exist.
}
}
Trying to do things as smooth as possible - I here suggest modifying GuyWhoLikesPowershell's suggestion slightly.
I replaced the if and until with one while - and I check for "Stopped", since I don't want to start if status is "starting" or " Stopping".
$Service = 'ServiceName'
while ((Get-Service $Service).Status -eq 'Stopped')
{
Start-Service $Service -ErrorAction SilentlyContinue
Start-Sleep 10
}
Return "$($Service) has STARTED"
I have created a filter. The filter can be used in any page.
Vue.filter('toCurrency', function (value) {
if (typeof value !== "number") {
return value;
}
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0
});
return formatter.format(value);
});
Then I can use this filter like this:
<td class="text-right">
{{ invoice.fees | toCurrency }}
</td>
I used these related answers to help with the implementation of the filter:
onCreate(Bundle savedInstanceState) gets called and savedInstanceState will be non-null if your Activity and it was terminated in a scenario(visual view) described above. Your app can then grab (catch) the data from savedInstanceState and regenerate your Activity
Developers and administrators running Bash may find these convenience functions helpful:
jar_jdk_version() {
[[ -n "$1" && -x "`command -v javap`" ]] && javap -classpath "$1" -verbose $(jar -tf "$1" | grep '.class' | head -n1 | sed -e 's/\.class$//') | grep 'major version' | sed -e 's/[^0-9]\{1,\}//'
}
print_jar_jdk_version() {
local version
version=$(jar_jdk_version "$1")
case $version in 49) version=1.5;; 50) version=1.6;; 51) version=1.7;; 52) version=1.8;; esac
[[ -n "$version" ]] && echo "`basename "$1"` contains classes compiled with JDK version $version."
}
You can paste them in for one-time usage or add them to ~/.bash_aliases
or ~/.bashrc
. The results look something like:
$ jar_jdk_version poi-ooxml-3.5-FINAL.jar
49
and
$ print_jar_jdk_version poi-ooxml-3.5-FINAL.jar
poi-ooxml-3.5-FINAL.jar contains classes compiled with JDK version 1.5.
EDIT
As jackrabbit points out, you can't 100% rely on the manifest to tell you anything useful. If it was, then you could pull it out in your favorite UNIX shell with unzip
:
$ unzip -pa poi-ooxml-3.5-FINAL.jar META-INF/MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 11.3-b02 (Sun Microsystems Inc.)
Built-By: yegor
Specification-Title: Apache POI
Specification-Version: 3.5-FINAL-20090928
Specification-Vendor: Apache
Implementation-Title: Apache POI
Implementation-Version: 3.5-FINAL-20090928
Implementation-Vendor: Apache
This .jar doesn't have anything useful in the manifest about the contained classes.
You may run:
git log <SHA1>..HEAD --ancestry-path --merges
From comment of last commit in the output you may find original branch name
Example:
c---e---g--- feature
/ \
-a---b---d---f---h---j--- master
git log e..master --ancestry-path --merges
commit h
Merge: g f
Author: Eugen Konkov <>
Date: Sat Oct 1 00:54:18 2016 +0300
Merge branch 'feature' into master
Yes, MD5 is somewhat less CPU-intensive. On my Intel x86 (Core2 Quad Q6600, 2.4 GHz, using one core), I get this in 32-bit mode:
MD5 411
SHA-1 218
SHA-256 118
SHA-512 46
and this in 64-bit mode:
MD5 407
SHA-1 312
SHA-256 148
SHA-512 189
Figures are in megabytes per second, for a "long" message (this is what you get for messages longer than 8 kB). This is with sphlib, a library of hash function implementations in C (and Java). All implementations are from the same author (me) and were made with comparable efforts at optimizations; thus the speed differences can be considered as really intrinsic to the functions.
As a point of comparison, consider that a recent hard disk will run at about 100 MB/s, and anything over USB will top below 60 MB/s. Even though SHA-256 appears "slow" here, it is fast enough for most purposes.
Note that OpenSSL includes a 32-bit implementation of SHA-512 which is quite faster than my code (but not as fast as the 64-bit SHA-512), because the OpenSSL implementation is in assembly and uses SSE2 registers, something which cannot be done in plain C. SHA-512 is the only function among those four which benefits from a SSE2 implementation.
Edit: on this page (archive), one can find a report on the speed of many hash functions (click on the "Telechargez maintenant" link). The report is in French, but it is mostly full of tables and numbers, and numbers are international. The implemented hash functions do not include the SHA-3 candidates (except SHABAL) but I am working on it.
Issue is resolved by:
Bundle bundle = new Bundle();
bundle.putSerializable("data", bigdata);
...
CacheHelper.saveState(bundle,"DATA");
Intent intent = new Intent(mActivity, AActivity.class);
startActivity(intent, bb);// do not put data to intent.
In Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = CacheHelper.getInstance().loadState(Constants.DATA);
if (bundle != null){
Intent intent = getIntent();
intent.putExtras(bundle);
}
getIntent().getExtra(..);
....
}
@Override
protected void onDestroy() {
super.onDestroy();
CacheHelper.clearState("DATA");
}
public class CacheHelper {
public static void saveState(Bundle savedInstanceState, String name) {
Bundle saved = (Bundle) savedInstanceState.clone();
save(name, saved);
}
public Bundle loadState(String name) {
Object object = load(name);
if (object != null) {
Bundle bundle = (Bundle) object;
return bundle;
}
return null;
}
private static void save(String fileName, Bundle object) {
try {
String path = StorageUtils.getFullPath(fileName);
File file = new File(path);
if (file.exists()) {
file.delete();
}
FileOutputStream fos = new FileOutputStream(path, false);
Parcel p = Parcel.obtain(); //creating empty parcel object
object.writeToParcel(p, 0); //saving bundle as parcel
//parcel.writeBundle(bundle);
fos.write(p.marshall()); //writing parcel to file
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static Bundle load(String fileName) {
try {
String path = StorageUtils.getFullPath(fileName);
FileInputStream fis = new FileInputStream(path);
byte[] array = new byte[(int) fis.getChannel().size()];
fis.read(array, 0, array.length);
Parcel parcel = Parcel.obtain(); //creating empty parcel object
parcel.unmarshall(array, 0, array.length);
parcel.setDataPosition(0);
Bundle out = parcel.readBundle();
out.putAll(out);
fis.close();
parcel.recycle();
return out;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void clearState(Activity ac) {
String name = ac.getClass().getName();
String path = StorageUtils.getFullPath(name);
File file = new File(path);
if (file.exists()) {
file.delete();
}
}
}
Have you considered letting the user of your application select their own color scheme? Without fail you won't be able to please all of your users with your selection but you can allow them to find what pleases them.
Enabled
property to false
or
this.dataGridView1.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.BackColor;
this.dataGridView1.DefaultCellStyle.SelectionForeColor = this.dataGridView1.DefaultCellStyle.ForeColor;
You forgot to define the default value for left
so it doesn't know how to animate.
.test {
left: 0;
transition:left 1s linear;
}
See here: http://jsfiddle.net/shomz/yFy5n/5/
You can parse the output of ifconfig
logging.basicConfig()
can take a keyword argument handlers
since Python 3.3, which simplifies logging setup a lot, especially when setting up multiple handlers with the same formatter:
handlers
– If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function.
The whole setup can therefore be done with a single call like this:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler()
]
)
(Or with import sys
+ StreamHandler(sys.stdout)
per original question's requirements – the default for StreamHandler is to write to stderr. Look at LogRecord attributes if you want to customize the log format and add things like filename/line, thread info etc.)
The setup above needs to be done only once near the beginning of the script. You can use the logging from all other places in the codebase later like this:
logging.info('Useful message')
logging.error('Something bad happened')
...
Note: If it doesn't work, someone else has probably already initialized the logging system differently. Comments suggest doing logging.root.handlers = []
before the call to basicConfig()
.
There wasn't any luck here with the other answers, but I managed to work it out with this nice one-liner:
((GuidAttribute)(AppDomain.CurrentDomain.DomainManager.EntryAssembly).GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value
Passing by reference in the above case is just an alias
for the actual object.
You'll be referring to the actual object just with a different name.
There are many advantages which references
offer compared to pointer references
.
You can also combine es6 and stateless functions to get a much cleaner result:
import Dashboard from './Dashboard';
import Comments from './Comments';
let dashboardWrapper = () => <Dashboard {...props} />,
commentsWrapper = () => <Comments {...props} />,
index = () => <div>
<header>Some header</header>
<RouteHandler />
{this.props.children}
</div>;
routes = {
component: index,
path: '/',
childRoutes: [
{
path: 'comments',
component: dashboardWrapper
}, {
path: 'dashboard',
component: commentsWrapper
}
]
}
You can't wrap that text as it's unbroken without any spaces. You need a JavaScript or server side solution which splits the string after a few characters.
EDIT
You need to add this property in CSS.
word-wrap: break-word;
You should use NSIntegers if you need to compare them against constant values such as NSNotFound or NSIntegerMax, as these values will differ on 32-bit and 64-bit systems, so index values, counts and the like: use NSInteger or NSUInteger.
It doesn't hurt to use NSInteger in most circumstances, excepting that it takes up twice as much memory. The memory impact is very small, but if you have a huge amount of numbers floating around at any one time, it might make a difference to use ints.
If you DO use NSInteger or NSUInteger, you will want to cast them into long integers or unsigned long integers when using format strings, as new Xcode feature returns a warning if you try and log out an NSInteger as if it had a known length. You should similarly be careful when sending them to variables or arguments that are typed as ints, since you may lose some precision in the process.
On the whole, if you're not expecting to have hundreds of thousands of them in memory at once, it's easier to use NSInteger than constantly worry about the difference between the two.
Array's include?
method accepts any object, not just a string. This should work:
@suggested_horses = []
@suggested_horses << Horse.first(:offset => rand(Horse.count))
while @suggested_horses.length < 8
horse = Horse.first(:offset => rand(Horse.count))
@suggested_horses << horse unless @suggested_horses.include?(horse)
end
You can use pyuic4
command on shell:
pyuic4 input.ui -o output.py
its work for me SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.format(new Date));
String to Uri
Uri myUri = Uri.parse("https://www.google.com");
Uri to String
Uri uri;
String stringUri = uri.toString();
The problem is the way you are using it in code. Just try the below code
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
ImageBrush myBrush = new ImageBrush();
myBrush.ImageSource =
new BitmapImage(new Uri("pack://application:,,,/icon.jpg", UriKind.Absolute));
this.Background = myBrush;
}
}
You can find more details regarding this in
http://msdn.microsoft.com/en-us/library/aa970069.aspx
<RatingBar
style="?android:attr/ratingBarStyleIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
There are 2 major differences.
Technical, there are 3 major differences:
First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.
Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.
Third, VS Community's ability to create Virtual Environments has been severely cut.
On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.
For all other things, there are tools that do the same job faster, better and cheaper.
If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.
Licensing:
A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.
The above does not consitute legal advise.
See also:
https://softwareengineering.stackexchange.com/questions/262916/understanding-visual-studio-community-edition-license
You can do it using mysqldump tool in command-line:
mysqldump your_database_name > script.sql
This creates a file with database create statements together with insert statements.
More info about options for mysql dump: https://dev.mysql.com/doc/refman/5.7/en/mysqldump-sql-format.html