The code you are talking about sounds like ServiceLoader
, which was introduced in Java 6 to support a feature that has been defined since Java 1.3 or earlier. For performance reasons, this is the recommended approach to find interface implementations at runtime; if you need support for this in an older version of Java, I hope that you'll find my implementation helpful.
There are a couple of implementations of this in earlier versions of Java, but in the Sun packages, not in the core API (I think there are some classes internal to ImageIO that do this). As the code is simple, I'd recommend providing your own implementation rather than relying on non-standard Sun code which is subject to change.
The methods viewWillLayoutSubviews
and viewDidLayoutSubviews
aren't mentioned in the diagrams, but these are called between viewWillAppear
and viewDidAppear
. They can be called multiple times.
You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye
var groupByReference = (from m in context.Measurements
.GroupBy(m => m.Reference)
.Take(numOfEntries).AsEnumerable()
.Select(g => new {Creation = g.FirstOrDefault().CreationTime,
Avg = g.Average(m => m.CreationTime.Ticks),
Items = g })
.OrderBy(x => x.Creation)
.ThenBy(x => x.Avg)
.ToList() select m);
Your sql query would look similar (depending on your input) this
SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
SELECT [t0].[Reference]
FROM [Measurements] AS [t0]
GROUP BY [t0].[Reference]
) AS [t1]
GO
-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO
-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
We can achieve this using flex-box very easily.
If we have three elements like Header, MiddleContainer and Footer. And we want to give some fixed height to Header and Footer. then we can write like this:
For React/RN(defaults are 'display' as flex and 'flexDirection' as column), in web css we'll have to specify the body container or container containing these as display: 'flex', flex-direction: 'column' like below:
container-containing-these-elements: {
display: flex,
flex-direction: column
}
header: {
height: 40,
},
middle-container: {
flex: 1, // this will take the rest of the space available.
},
footer: {
height: 100,
}
Steps to do it on PgAdmin:
From your project directory, run
react-native start
It outputs the following:
$ react-native start
+----------------------------------------------------------------------------+
¦ Running packager on port 8081. ¦
¦ ¦
¦ Keep this packager running while developing on any JS projects. Feel ¦
¦ free to close this tab and run your own packager instance if you ¦
¦ prefer. ¦
¦ ¦
¦ https://github.com/facebook/react-native ¦
¦ ¦
+----------------------------------------------------------------------------+
Looking for JS files in
/home/user/AwesomeProject
React packager ready.
[11:30:10 PM] <START> Building Dependency Graph
[11:30:10 PM] <START> Crawling File System
[11:30:16 PM] <END> Crawling File System (5869ms)
[11:30:16 PM] <START> Building in-memory fs for JavaScript
[11:30:17 PM] <END> Building in-memory fs for JavaScript (852ms)
[11:30:17 PM] <START> Building in-memory fs for Assets
[11:30:17 PM] <END> Building in-memory fs for Assets (838ms)
[11:30:17 PM] <START> Building Haste Map
[11:30:18 PM] <START> Building (deprecated) Asset Map
[11:30:18 PM] <END> Building (deprecated) Asset Map (220ms)
[11:30:18 PM] <END> Building Haste Map (759ms)
[11:30:18 PM] <END> Building Dependency Graph (8319ms)
I found that DataGridViewTextBox
values and some JSON objects don't equal Null but instead are "{}"
values. Comparing them to Null doesn't work but using these do the trick:
if (cell.Value is System.DBNull)
if (cell.Value == System.DBNull.Value)
A good excerpt I found concerning the difference between Null and DBNull:
Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.
You can learn more about the DBNull class here.
I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I've watched online from my firefox cache:
#!/bin/bash
# flvcache script
CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache
OUTPUTDIR=~/Videos/flvs
MINFILESIZE=2M
for f in `find $CACHE -size +$MINFILESIZE`
do
a=$(file $f | cut -f2 -d ' ')
o=$(basename $f)
if [ "$a" = "Macromedia" ]
then
cp "$f" "$OUTPUTDIR/$o"
fi
done
nautilus "$OUTPUTDIR"&
It uses similar ideas to those presented here, hope this is helpful to someone.
A little bit info about this keyword
Let's log this
keyword to the console in global scope without any more code but
console.log(this)
In Client/Browser this
keyword is a global object which is window
console.log(this === window) // true
and
In Server/Node/Javascript runtime this
keyword is also a global object which is module.exports
console.log(this === module.exports) // true
console.log(this === exports) // true
Keep in mind exports
is just a reference to module.exports
It has to do with the Normal Form for the SQL language. IF
statements can, by definition, only take a single SQL statement. However, there is a special kind of SQL statement which can contain multiple SQL statements, the BEGIN-END
block.
If you omit the BEGIN-END
block, your SQL will run fine, but it will only execute the first statement as part of the IF
.
Basically, this:
IF @Term = 3
INSERT INTO @Classes
SELECT
XXXXXX
FROM XXXX blah blah blah
is equivalent to the same thing with the BEGIN-END
block, because you are only executing a single statement. However, for the same reason that not including the curly-braces on an IF
statement in a C-like language is a bad idea, it is always preferable to use BEGIN
and END
.
In the click event "this" is the a tag that was clicked
jQuery('.class1 a').click( function() {
var divToSlide = $(this).parent().find(".class2");
if (divToSlide.is(":hidden")) {
divToSlide.slideDown("slow");
} else {
divToSlide.slideUp();
}
});
There's multiple ways to get to the div though you could also use .siblings, .next etc
Here is another option for a specific case. :)
If you want to test for a member on an object and want to know if it has been set to something other than:
then you can use:
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
I just found an elegant way:
Convert.ChangeType("2020-12-31", typeof(DateTime));
Convert.ChangeType("2020/12/31", typeof(DateTime));
Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));
Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
Convert.ChangeType("11/?????/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));
Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"
PHP 5.3 (an I think older versions too) seems to have problem with same name in different cases. So I had this problem when a had the class Login and the interface it implements LogIn. After I renamed LogIn to Log_In the problem got solved.
Unfortunately none of these solutions provided really solve the problem because at the end of the day the APIs are seriously lacking when it comes to providing the pertinent information. You can make a few guesses however using currentUserNotificationSettings
(iOS8+) just isn't sufficient in its current form to really answer the question. Although a lot of the solutions here seem to suggest that either that or isRegisteredForRemoteNotifications
is more of a definitive answer it really is not.
Consider this:
with isRegisteredForRemoteNotifications
documentation states:
Returns YES if the application is currently registered for remote notifications, taking into account any systemwide settings...
However if you throw a simply NSLog
into your app delegate to observe the behavior it is clear this does not behave the way we are anticipating it will work. It actually pertains directly to remote notifications having been activated for this app/device. Once activated for the first time this will always return YES
. Even turning them off in settings (notifications) will still result in this returning YES
this is because, as of iOS8, an app may register for remote notifications and even send to a device without the user having notifications enabled, they just may not do Alerts, Badges and Sound without the user turning that on. Silent notifications are a good example of something you may continue to do even with notifications turned off.
As far as currentUserNotificationSettings
it indicates one of four things:
Alerts are on Badges are on Sound is on None are on.
This gives you absolutely no indication whatsoever about the other factors or the Notification switch itself.
A user may in fact turn off badges, sound and alerts but still have show on lockscreen or in notification center. This user should still be receiving push notifications and be able to see them both on the lock screen and in the notification center. They have the notification switch on. BUT currentUserNotificationSettings
will return: UIUserNotificationTypeNone
in that case. This is not truly indicative of the users actual settings.
A few guesses one can make:
isRegisteredForRemoteNotifications
is NO
then you can assume that this device has never successfully registered for remote notifications.application:didRegisterUserNotificationSettings:
is made containing user notification settings at this time since this is the first time a user has been registered the settings should indicate what the user selected in terms of the permission request. If the settings equate to anything other than: UIUserNotificationTypeNone
then push permission was granted, otherwise it was declined. The reason for this is that from the moment you begin the remote registration process the user only has the ability to accept or decline, with the initial settings of an acceptance being the settings you setup during the registration process.As pointed out (and hopefully unsurprisingly), using if+else
is indeed the idiomatic way to do conditionals in Go.
In addition to the full blown var+if+else
block of code, though, this spelling is also used often:
index := val
if val <= 0 {
index = -val
}
and if you have a block of code that is repetitive enough, such as the equivalent of int value = a <= b ? a : b
, you can create a function to hold it:
func min(a, b int) int {
if a <= b {
return a
}
return b
}
...
value := min(a, b)
The compiler will inline such simple functions, so it's fast, more clear, and shorter.
During my current projects, I'm often passing rear parts of a path to a function and therefore use the Path
module. To get the n-th part in reverse order, I'm using:
from typing import Union
from pathlib import Path
def get_single_subpath_part(base_dir: Union[Path, str], n:int) -> str:
if n ==0:
return Path(base_dir).name
for _ in range(n):
base_dir = Path(base_dir).parent
return getattr(base_dir, "name")
path= "/folderA/folderB/folderC/folderD/"
# for getting the last part:
print(get_single_subpath_part(path, 0))
# yields "folderD"
# for the second last
print(get_single_subpath_part(path, 1))
#yields "folderC"
Furthermore, to pass the n-th part in reverse order of a path containing the remaining path, I use:
from typing import Union
from pathlib import Path
def get_n_last_subparts_path(base_dir: Union[Path, str], n:int) -> Path:
return Path(*Path(base_dir).parts[-n-1:])
path= "/folderA/folderB/folderC/folderD/"
# for getting the last part:
print(get_n_last_subparts_path(path, 0))
# yields a `Path` object of "folderD"
# for second last and last part together
print(get_n_last_subparts_path(path, 1))
# yields a `Path` object of "folderc/folderD"
Note that this function returns a Path
object which can easily be converted to a string (e.g. str(path)
)
I want to comment but don't have enough reputation.
The user-adding executable script shown above has to be modified with --authenticationDatabase admin and NEWDATABASENAME.
mongo --authenticationDatabase admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED NEWDATABASENAME --eval "db.createUser({user: 'NEWUSERNAME', pwd: 'PASSWORD', roles: [{role: 'readWrite', db: 'NEWDATABASENAME'}]});"
The pipe character |
has a special meaning in regular expressions. a|b
means "match either a
or b
". If you want to match a literal |
character, you need to escape it:
... | Select-String -Pattern 'H\|159' -NotMatch | ...
Change CI index.php file to:
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
if (defined('ENVIRONMENT')){
switch (ENVIRONMENT){
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
IF PHP errors are off, but any MySQL errors are still going to show, turn these off in the /config/database.php file. Set the db_debug option to false:
$db['default']['db_debug'] = FALSE;
Also, you can use active_group as development and production to match the environment https://www.codeigniter.com/user_guide/database/configuration.html
$active_group = 'development';
$db['development']['hostname'] = 'localhost';
$db['development']['username'] = '---';
$db['development']['password'] = '---';
$db['development']['database'] = '---';
$db['development']['dbdriver'] = 'mysql';
$db['development']['dbprefix'] = '';
$db['development']['pconnect'] = TRUE;
$db['development']['db_debug'] = TRUE;
$db['development']['cache_on'] = FALSE;
$db['development']['cachedir'] = '';
$db['development']['char_set'] = 'utf8';
$db['development']['dbcollat'] = 'utf8_general_ci';
$db['development']['swap_pre'] = '';
$db['development']['autoinit'] = TRUE;
$db['development']['stricton'] = FALSE;
$db['production']['hostname'] = 'localhost';
$db['production']['username'] = '---';
$db['production']['password'] = '---';
$db['production']['database'] = '---';
$db['production']['dbdriver'] = 'mysql';
$db['production']['dbprefix'] = '';
$db['production']['pconnect'] = TRUE;
$db['production']['db_debug'] = FALSE;
$db['production']['cache_on'] = FALSE;
$db['production']['cachedir'] = '';
$db['production']['char_set'] = 'utf8';
$db['production']['dbcollat'] = 'utf8_general_ci';
$db['production']['swap_pre'] = '';
$db['production']['autoinit'] = TRUE;
$db['production']['stricton'] = FALSE;
There's a new method to do this in ES6/2015 using findIndex and array spread operator:
const index = data.findIndex(obj => obj.id === id);
const newData = [
...data.slice(0, index),
...data.slice(index + 1)
]
You can turn it into a function for later reuse like this:
function remove(array, key, value) {
const index = array.findIndex(obj => obj[key] === value);
return index >= 0 ? [
...array.slice(0, index),
...array.slice(index + 1)
] : array;
}
This way you can to remove items by different keys using one method (and if there's no object that meets the criteria, you get original array returned):
const newData = remove(data, "id", "88");
const newData2 = remove(data, "name", "You are awesome!");
Or you can put it on your Array.prototype:
Array.prototype.remove = function (key, value) {
const index = this.findIndex(obj => obj[key] === value);
return index >= 0 ? [
...this.slice(0, index),
...this.slice(index + 1)
] : this;
};
And use it this way:
const newData = data.remove("id", "88");
const newData2 = data.remove("name", "You are awesome!");
Here is a variation of ben blank's answer, if you don't like tuples.
This saves you a few characters.
var keys = [];
for (var key in sortme) {
keys.push(key);
}
keys.sort(function(k0, k1) {
var a = sortme[k0];
var b = sortme[k1];
return a < b ? -1 : (a > b ? 1 : 0);
});
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = sortme[key];
// Do something with key and value.
}
Here I am writing full query which will clear your all doubts
SELECT BillingDate,
COUNT(*) AS BillingQty,
SUM(BillingTotal) AS BillingSum
FROM Billings
WHERE BillingDate BETWEEN '2002-05-01' AND '2002-05-31'
GROUP BY BillingDate
HAVING COUNT(*) > 1
AND SUM(BillingTotal) > 100
ORDER BY BillingDate DESC
Open Android Studio then go to gradle.properties file and change the last line to
org.gradle.jvmargs=-Xmx1024m.
And then press try again
I've fixed the typescript version. For javascript, just remove type definitions.
_getFormDataKey(key0: any, key1: any): string {
return !key0 ? key1 : `${key0}[${key1}]`;
}
_convertModelToFormData(model: any, key: string, frmData?: FormData): FormData {
let formData = frmData || new FormData();
if (!model) return formData;
if (model instanceof Date) {
formData.append(key, model.toISOString());
} else if (model instanceof Array) {
model.forEach((element: any, i: number) => {
this._convertModelToFormData(element, this._getFormDataKey(key, i), formData);
});
} else if (typeof model === 'object' && !(model instanceof File)) {
for (let propertyName in model) {
if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
this._convertModelToFormData(model[propertyName], this._getFormDataKey(key, propertyName), formData);
}
} else {
formData.append(key, model);
}
return formData;
}
Some of the other answers would have poor performance on very large arrays, because methods like removeObject:
and removeObjectsInArray:
involve doing a linear search of the receiver, which is a waste because you already know where the object is. Also, any call to removeObjectAtIndex:
will have to copy values from the index to the end of the array up by one slot at a time.
More efficient would be the following:
NSMutableArray *array = ...
NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];
for (id object in array) {
if (! shouldRemove(object)) {
[itemsToKeep addObject:object];
}
}
[array setArray:itemsToKeep];
Because we set the capacity of itemsToKeep
, we don't waste any time copying values during a resize. We don't modify the array in place, so we are free to use Fast Enumeration. Using setArray:
to replace the contents of array
with itemsToKeep
will be efficient. Depending on your code, you could even replace the last line with:
[array release];
array = [itemsToKeep retain];
So there isn't even a need to copy values, only swap a pointer.
Also check out the open financial exchange (ofx) http://www.ofx.net/
This is what apps like quicken, ms money etc use.
As an alternative to $dollarsign
notation, use a within
block:
breast <- within(breast, {
class <- as.numeric(as.character(class))
})
Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class)
will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.
1st solution (fastest) :
yourDateTime.Year % 100
2nd solution (more elegant in my opinion) :
yourDateTime.ToString("yy")
You will need to put a quote at the beginning of your first text and the end of your last.
public class CustomEditText extends androidx.appcompat.widget.AppCompatEditText {
private Drawable drawableRight;
private Drawable drawableLeft;
private Drawable drawableTop;
private Drawable drawableBottom;
int actionX, actionY;
private DrawableClickListener clickListener;
public CustomEditText (Context context, AttributeSet attrs) {
super(context, attrs);
// this Contructure required when you are using this view in xml
}
public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
public void setCompoundDrawables(Drawable left, Drawable top,
Drawable right, Drawable bottom) {
if (left != null) {
drawableLeft = left;
}
if (right != null) {
drawableRight = right;
}
if (top != null) {
drawableTop = top;
}
if (bottom != null) {
drawableBottom = bottom;
}
super.setCompoundDrawables(left, top, right, bottom);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Rect bounds;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
actionX = (int) event.getX();
actionY = (int) event.getY();
if (drawableBottom != null
&& drawableBottom.getBounds().contains(actionX, actionY)) {
clickListener.onClick(DrawablePosition.BOTTOM);
return super.onTouchEvent(event);
}
if (drawableTop != null
&& drawableTop.getBounds().contains(actionX, actionY)) {
clickListener.onClick(DrawablePosition.TOP);
return super.onTouchEvent(event);
}
// this works for left since container shares 0,0 origin with bounds
if (drawableLeft != null) {
bounds = null;
bounds = drawableLeft.getBounds();
int x, y;
int extraTapArea = (int) (13 * getResources().getDisplayMetrics().density + 0.5);
x = actionX;
y = actionY;
if (!bounds.contains(actionX, actionY)) {
/** Gives the +20 area for tapping. */
x = (int) (actionX - extraTapArea);
y = (int) (actionY - extraTapArea);
if (x <= 0)
x = actionX;
if (y <= 0)
y = actionY;
/** Creates square from the smallest value */
if (x < y) {
y = x;
}
}
if (bounds.contains(x, y) && clickListener != null) {
clickListener
.onClick(DrawableClickListener.DrawablePosition.LEFT);
event.setAction(MotionEvent.ACTION_CANCEL);
return false;
}
}
if (drawableRight != null) {
bounds = null;
bounds = drawableRight.getBounds();
int x, y;
int extraTapArea = 13;
/**
* IF USER CLICKS JUST OUT SIDE THE RECTANGLE OF THE DRAWABLE
* THAN ADD X AND SUBTRACT THE Y WITH SOME VALUE SO THAT AFTER
* CALCULATING X AND Y CO-ORDINATE LIES INTO THE DRAWBABLE
* BOUND. - this process help to increase the tappable area of
* the rectangle.
*/
x = (int) (actionX + extraTapArea);
y = (int) (actionY - extraTapArea);
/**Since this is right drawable subtract the value of x from the width
* of view. so that width - tappedarea will result in x co-ordinate in drawable bound.
*/
x = getWidth() - x;
/*x can be negative if user taps at x co-ordinate just near the width.
* e.g views width = 300 and user taps 290. Then as per previous calculation
* 290 + 13 = 303. So subtract X from getWidth() will result in negative value.
* So to avoid this add the value previous added when x goes negative.
*/
if(x <= 0){
x += extraTapArea;
}
/* If result after calculating for extra tappable area is negative.
* assign the original value so that after subtracting
* extratapping area value doesn't go into negative value.
*/
if (y <= 0)
y = actionY;
/**If drawble bounds contains the x and y points then move ahead.*/
if (bounds.contains(x, y) && clickListener != null) {
clickListener
.onClick(DrawableClickListener.DrawablePosition.RIGHT);
event.setAction(MotionEvent.ACTION_CANCEL);
return false;
}
return super.onTouchEvent(event);
}
}
return super.onTouchEvent(event);
}
@Override
protected void finalize() throws Throwable {
drawableRight = null;
drawableBottom = null;
drawableLeft = null;
drawableTop = null;
super.finalize();
}
public void setDrawableClickListener(DrawableClickListener listener) {
this.clickListener = listener;
}
}
Also Create an Interface with
public interface DrawableClickListener {
public static enum DrawablePosition { TOP, BOTTOM, LEFT, RIGHT };
public void onClick(DrawablePosition target);
}
Still if u need any help, comment
Also set the drawableClickListener on the view in activity file.
editText.setDrawableClickListener(new DrawableClickListener() {
public void onClick(DrawablePosition target) {
switch (target) {
case LEFT:
//Do something here
break;
default:
break;
}
}
});
Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:
$('#myButton').on('click', function(event) {
event.preventDefault(); // To prevent following the link (optional)
...
});
You can also use inline javascript in the onclick attribute:
<a ... onclick="myFunc();">..</a>
The solution is to use display: table-cell
to bring those elements inline instead of using display: inline-block
or float: left
.
div#container {_x000D_
padding: 20px;_x000D_
background: #F1F1F1_x000D_
}_x000D_
.content {_x000D_
width: 150px;_x000D_
background: #ddd;_x000D_
padding: 10px;_x000D_
display: table-cell;_x000D_
vertical-align: top;_x000D_
}_x000D_
.text {_x000D_
font-family: 12px Tahoma, Geneva, sans-serif;_x000D_
color: #555;_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="content">_x000D_
<h1>Title 1</h1>_x000D_
_x000D_
<div class="text">Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text._x000D_
<br>Sample Text. Sample Text. Sample Text._x000D_
<br>Sample Text._x000D_
<br>_x000D_
</div>_x000D_
</div>_x000D_
<div class="content">_x000D_
<h1>Title 2</h1>_x000D_
_x000D_
<div class="text">Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text. Sample Text.</div>_x000D_
</div>_x000D_
</div>
_x000D_
Think of (char *) as string.begin(). The essential difference is that (char *) is an iterator and std::string is a container. If you stick to basic strings a (char *) will give you what std::string::iterator does. You could use (char *) when you want the benefit of an iterator and also compatibility with C, but that's the exception and not the rule. As always, be careful of iterator invalidation. When people say (char *) isn't safe this is what they mean. It's as safe as any other C++ iterator.
Changing the ng-src
value is actually very simple. Like this:
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>
Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/
define margin and padding for the element is facing the problem:
#element_id {margin: 0; padding: 0}
and see if problem exists. IE renders the page with to more unwanted inheritance. you should stop it from doing so.
You can also use substring replacement to test for the presence of a substring. Here I remove quotes to create PATH_NQ, then I remove "c:\mydir" from the PATH_NQ and compare it to the original to see if anything changed:
set PATH_NQ=%PATH:"=%
if not "%PATH_NQ%"=="%PATH_NQ:c:\mydir=%" goto already_in_path
set PATH=%PATH%;c:\mydir
:already_in_path
Based on saikirans solution, I have written this, which helped me. On the .m file:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(selectedRowIndex && indexPath.row == selectedRowIndex.row) {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
selectedRowIndex = nil;
}
else { self.selectedRowIndex = [indexPath retain]; }
[tableView beginUpdates];
[tableView endUpdates];
}
And on the header file:
@property (retain, nonatomic) NSIndexPath* selectedRowIndex;
I am not very experienced either, so double check for memory leaks etc.
I tried this in Ubuntu 18.04 and is the only solution that worked for me:
ALTER USER my_user@'%' IDENTIFIED WITH mysql_native_password BY 'password';
Use:
Question question = Question.Role;
int value = question.GetHashCode();
It will result in value == 2
.
This is only true if the enum fits inside an int
.
SIMPLE..
First check with the closing tag of project. It should be placed after all the dependency tags are closed.This way I solved my error. --Sush happy coding :)
setTimeout('Redirect()', 1000);
function Redirect()
{
window.location="https://stackoverflow.com";
}
//document.write("You will be Redirect to a new page in 1000 -> 1 Seconds, 2000 -> 2 Seconds");
You can use jquery load for that.
<script type="text/javascript">
$(document).ready(function(e) {
$('#header').load('name.html',function(){alert('loaded')});
});
</script>
Don't forget to include jquery library befor above code.
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt)
{
if(jTextField1.getText().length()>=5)
{
jTextField1.setText(jTextField1.getText().substring(0, 4));
}
}
I have taken a jtextfield whose name is jTextField1, the code is in its key pressed event. I Have tested it and it works. And I am using the NetBeans IDE.
Suppose an autofac setting like the following:
public class AutofacContractResolver : DefaultContractResolver
{
private readonly IContainer _container;
public AutofacContractResolver(IContainer container)
{
_container = container;
}
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
JsonObjectContract contract = base.CreateObjectContract(objectType);
// use Autofac to create types that have been registered with it
if (_container.IsRegistered(objectType))
{
contract.DefaultCreator = () => _container.Resolve(objectType);
}
return contract;
}
}
Then, suppose your class is like this:
public class TaskController
{
private readonly ITaskRepository _repository;
private readonly ILogger _logger;
public TaskController(ITaskRepository repository, ILogger logger)
{
_repository = repository;
_logger = logger;
}
public ITaskRepository Repository
{
get { return _repository; }
}
public ILogger Logger
{
get { return _logger; }
}
}
Therefore, the usage of the resolver in deserialization could be like:
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<TaskRepository>().As<ITaskRepository>();
builder.RegisterType<TaskController>();
builder.Register(c => new LogService(new DateTime(2000, 12, 12))).As<ILogger>();
IContainer container = builder.Build();
AutofacContractResolver contractResolver = new AutofacContractResolver(container);
string json = @"{
'Logger': {
'Level':'Debug'
}
}";
// ITaskRespository and ILogger constructor parameters are injected by Autofac
TaskController controller = JsonConvert.DeserializeObject<TaskController>(json, new JsonSerializerSettings
{
ContractResolver = contractResolver
});
Console.WriteLine(controller.Repository.GetType().Name);
You can see more details in http://www.newtonsoft.com/json/help/html/DeserializeWithDependencyInjection.htm
Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.
Adding this to your WebSecurityConfiguration class should do the trick.
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
}
If you are looking for a number that is bigger than all others:
Method 1:
float('inf')
Method 2:
import sys
max = sys.maxsize
If you are looking for a number that is smaller than all others:
Method 1:
float('-inf')
Method 2:
import sys
min = -sys.maxsize - 1
Method 1 works in both Python2 and Python3. Method 2 works in Python3. I have not tried Method 2 in Python2.
You can deserialize this really easily. The data's structure in C# is just List<string[]>
so you could just do;
List<string[]> data = JsonConvert.DeserializeObject<List<string[]>>(jsonString);
The above code is assuming you're using json.NET.
EDIT: Note the json is technically an array of string arrays. I prefer to use List<string[]>
for my own declaration because it's imo more intuitive. It won't cause any problems for json.NET, if you want it to be an array of string arrays then you need to change the type to (I think) string[][]
but there are some funny little gotcha's with jagged and 2D arrays in C# that I don't really know about so I just don't bother dealing with it here.
if you want php you can count the array and just make an if statement like
if((int)count($_FILES['i_dont_know_whats_coming_next'] > 2)
echo "error message";
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
You can use this working script:
/**
* @param {range} countRange Range to be evaluated
* @param {range} colorRef Cell with background color to be searched for in countRange
* @return {number}
* @customfunction
*/
function countColoredCells(countRange,colorRef) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var formula = activeRange.getFormula();
var rangeA1Notation = formula.match(/\((.*)\,/).pop();
var range = activeSheet.getRange(rangeA1Notation);
var bg = range.getBackgrounds();
var values = range.getValues();
var colorCellA1Notation = formula.match(/\,(.*)\)/).pop();
var colorCell = activeSheet.getRange(colorCellA1Notation);
var color = colorCell.getBackground();
var count = 0;
for(var i=0;i<bg.length;i++)
for(var j=0;j<bg[0].length;j++)
if( bg[i][j] == color )
count=count+1;
return count;
};
Then call this function in your google sheets:
=countColoredCells(D5:D123,Z11)
There is an easy way to get many informations using Workbench:
Right-click the schema name and click "Schema inspector".
In the resulting window you have a number of tabs. The first tab "Info" shows a rough estimate of the database size in MB.
The second tab, "Tables", shows Data length and other details for each table.
Write the queue job information in long format to text file
qstat -f > queue.txt
Grep job names
grep 'Job_Name' queue.txt
I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.
<form name="paymentitrform" id="paymentitrform" class="payment"
method="post"
action="abc.php">
<input name="email" value="" placeholder="email" />
<input type="hidden" name="planamount" id="planamount" value="0">
<input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
name="planform">
</form>
You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button
function form_submit() {
document.getElementById("paymentitrform").submit();
}
The options discussed above won't work because they are not part of the CSS
specification (it is jQuery
extension). Having spent 2-3 days digging around for information, I found that the only way to select the Text of the selected option from the drop down is:
{ $("select", id:"Some_ID").find("option[selected='selected']")}
Refer to additional notes below:
Because :selected is a jQuery
extension and not part of the CSS
specification, queries using :selected cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :selected to select elements, first select the elements using a pure CSS
selector, then use .filter(":selected")
. (copied from: http://api.jquery.com/selected-selector/)
Try this:
String[] columnDetail = column.split("\t", -1);
Read the Javadoc on String.split(java.lang.String, int) for an explanation about the limit parameter of split function:
split
public String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
The string "boo:and:foo", for example, yields the following results with these parameters:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
When the last few fields (I guest that's your situation) are missing, you will get the column like this:
field1\tfield2\tfield3\t\t
If no limit is set to split(), the limit is 0, which will lead to that "trailing empty strings will be discarded". So you can just get just 3 fields, {"field1", "field2", "field3"}.
When limit is set to -1, a non-positive value, trailing empty strings will not be discarded. So you can get 5 fields with the last two being empty string, {"field1", "field2", "field3", "", ""}.
Application.Sum often does not work well in my experience (or at least the VBA developer environment does not like it for whatever reason).
The function that works best for me is Excel.WorksheetFunction.Sum()
Example:
Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.
Report.Cells(11, 1).Value = Excel.WorksheetFunction.Sum(Report.Range("A1:A10")) 'Add the function result.
The other method which you were looking for I think is to place the function directly into the cell. This can be done by inputting the function string into the cell value. Here is an example that provides the same result as above, except the cell value is given the function and not the result of the function:
Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.
Report.Cells(11, 1).Value = "=Sum(A1:A10)" 'Add the function.
You can use substr
for example:
new Date().getFullYear().toString().substr(-2)
Not to steal your answer and adapt it for points or anything, but here is another factorization:
select d.name,
sum(m0.size*8.0/1024) data_file_size_mb,
sum(m1.size*8.0/1024) log_file_size_mb
from sys.databases d
inner join sys.master_files m0 on m0.database_id = d.database_id
inner join sys.master_files m1 on m1.database_id = d.database_id
where m0.type = 0 and m1.type = 1
group by d.name, d.database_id
order by d.database_id
in a simple word: An abstract data type is a collection of data and operations that work on that data. The operations both describe the data to the rest of the program and allow the rest of the program to change the data. The word “data” in “abstract data type” is used loosely. An ADT might be a graphics window with all the operations that affect it, a file and file operations, an insurance-rates table and the operations on it, or something else.
from code complete 2 book
Just finished understanding Peek and Keep and had same confusion initially. The confusion arises becauses TempData behaves differently under different condition. You can watch this video which explains the Keep and Peek with demonstration https://www.facebook.com/video.php?v=689393794478113
Tempdata helps to preserve values for a single request and CAN ALSO preserve values for the next request depending on 4 conditions”.
If we understand these 4 points you would see more clarity.Below is a diagram with all 4 conditions, read the third and fourth point which talks about Peek and Keep.
Condition 1 (Not read):- If you set a “TempData” inside your action and if you do not read it in your view then “TempData” will be persisted for the next request.
Condition 2 ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request.
string str = TempData["MyData"];
Even if you are displaying it’s a normal read like the code below.
@TempData["MyData"];
Condition 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted.
@TempData["MyData"];
TempData.Keep("MyData");
Condition 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request.
string str = TempData.Peek("Td").ToString();
Reference :- http://www.codeproject.com/Articles/818493/MVC-Tempdata-Peek-and-Keep-confusion
Go to the page from where you want to access the App_code class, and then add the namespace of the app_code class. You need to provide a using
statement, as follows:
using WebApplication3.App_Code;
After that, you will need to go to the app_code class property and set the 'Build Action' to 'Compile'.
If you're using Eclipse Collections (formerly GS Collections), you can use the makeString()
method.
List<String> list = Arrays.asList("Bill", "Bob", "Steve");
String string = ListAdapter.adapt(list).makeString(" and ");
Assert.assertEquals("Bill and Bob and Steve", string);
If you can convert your List
to an Eclipse Collections type, then you can get rid of the adapter.
MutableList<String> list = Lists.mutable.with("Bill", "Bob", "Steve");
String string = list.makeString(" and ");
If you just want a comma separated string, you can use the version of makeString()
that takes no parameters.
Assert.assertEquals(
"Bill, Bob, Steve",
Lists.mutable.with("Bill", "Bob", "Steve").makeString());
Note: I am a committer for Eclipse Collections.
Use SELECT ... INTO
:
SELECT *
INTO ABC_1
FROM ABC;
This will create a new table ABC_1
that has the same column structure as ABC
and contains the same data. Constraints (e.g. keys, default values), however, are -not- copied.
You can run this query multiple times with a different table name each time.
If you don't need to copy the data, only to create a new empty table with the same column structure, add a WHERE
clause with a falsy expression:
SELECT *
INTO ABC_1
FROM ABC
WHERE 1 <> 1;
There is no difference in terms of functionality. In fact, both do this:
return this.Add(new SqlParameter(parameterName, value));
The reason they deprecated the old one in favor of AddWithValue
is to add additional clarity, as well as because the second parameter is object
, which makes it not immediately obvious to some people which overload of Add
was being called, and they resulted in wildly different behavior.
Take a look at this example:
SqlCommand command = new SqlCommand();
command.Parameters.Add("@name", 0);
At first glance, it looks like it is calling the Add(string name, object value)
overload, but it isn't. It's calling the Add(string name, SqlDbType type)
overload! This is because 0 is implicitly convertible to enum types. So these two lines:
command.Parameters.Add("@name", 0);
and
command.Parameters.Add("@name", 1);
Actually result in two different methods being called. 1
is not convertible to an enum implicitly, so it chooses the object
overload. With 0
, it chooses the enum overload.
You can find the most up to date answer for the value in your project just execute the
mvn3 help:effective-pom
command and find the <build> ... <directory>
tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.
Forking creates an entirely new repository from existing repository (simply doing git clone on gitHub/bitbucket)
Forks are best used: when the intent of the ‘split’ is to create a logically independent project, which may never reunite with its parent.
Branch strategy creates a new branch over the existing/working repository
Branches are best used: when they are created as temporary places to work through a feature, with the intent to merge the branch with the origin.
More Specific :- In open source projects it is the owner of the repository who decides who can push to the repository. However, the idea of open source is that everybody can contribute to the project.
This problem is solved by forks: any time a developer wants to change something in an open source project, they don’t clone the official repository directly. Instead, they fork it to create a copy. When the work is finished, they make a pull request so that the owner of the repository can review the changes and decide whether to merge them to his project.
At its core forking is similar to feature branching, but instead of creating branches a fork of the repository is made, and instead of doing a merge request you create a pull request.
The below links provide the difference in a well-explained manner :
https://blog.gitprime.com/the-definitive-guide-to-forks-and-branches-in-git/
I had the problem a few weeks ago with a few discrete features which were formatted as 'object'. This solution seemed to work.
for col in discrete:
df[col] = pd.to_numeric(df[col], errors='coerce').astype(pd.Int64Dtype())
The correct syntax is
set def off;
insert into tablename values( 'J&J');
I like to remove missing values from a list like this:
list_no_nan = [x for x in list_with_nan if pd.notnull(x)]
You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com
This problem has nothing to do with the linker, so modifying it's setting won't affect the outcome. You're getting this because I assume you're trying to target x86 but for one reason or another wxcode_msw28d_freechart.lib is being built as an x64 file.
Try looking at wxcode_msw28d_freechart.lib and whatever source code it derives from. Your problem is happening there. See if there are some special build steps that are using the wrong set of tools (x64 instead of x86).
Polished version + case ignoring support:
public static int[] AllIndexesOf(string str, string substr, bool ignoreCase = false)
{
if (string.IsNullOrWhiteSpace(str) ||
string.IsNullOrWhiteSpace(substr))
{
throw new ArgumentException("String or substring is not specified.");
}
var indexes = new List<int>();
int index = 0;
while ((index = str.IndexOf(substr, index, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) != -1)
{
indexes.Add(index++);
}
return indexes.ToArray();
}
There are two ways to use this variable:
passing it as a command line argument just like Job mentioned:
cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..
assigning value to it in CMakeLists.txt
:
SET(CMAKE_INSTALL_PREFIX < install_path >)
But do remember to place it BEFORE PROJECT(< project_name>)
command, otherwise it will not work!
Since you return to the client just String
and its content type == 'text/plain'
, there is no any chance for default converters to determine how to convert String
response to the FFSampleResponseHttp
object.
The simple way to fix it:
expected-response-type
from <int-http:outbound-gateway>
replyChannel1
<json-to-object-transformer>
Otherwise you should write your own HttpMessageConverter
to convert the String to the appropriate object.
To make it work with MappingJackson2HttpMessageConverter
(one of default converters) and your expected-response-type
, you should send your reply with content type = 'application/json'
.
If there is a need, just add <header-enricher>
after your <service-activator>
and before sending a reply to the <int-http:inbound-gateway>
.
So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.
UPDATE
OK. Since you changed your server to return FfSampleResponseHttp
object as HTTP response, not String, just add contentType = 'application/json'
header before sending the response for the HTTP and MappingJackson2HttpMessageConverter
will do the stuff for you - your object will be converted to JSON and with correct contentType
header.
From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp"
and MappingJackson2HttpMessageConverter
should do the stuff for you again.
Of course you should remove <json-to-object-transformer>
from you message flow after <int-http:outbound-gateway>
.
I had some trouble similar to this,
<repository>
<id>java.net</id>
<url>https://maven-repository.dev.java.net/nonav/repository</url>
<layout>legacy</layout>
</repository>
<repository>
<id>java.net2</id>
<url>https://maven2-repository.dev.java.net/nonav/repository</url>
</repository>
Setting the updatePolicy to "never" did not work. Removing these repo was the way I solved it. ps: I was following this tutorial about web services (btw, probably the best tutorial for ws for java)
df[df['ID'].duplicated() == True]
This worked for me
If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:
function formSubmit(house_number)
{
document.forms[0].house_number.value = house_number;
document.forms[0].submit();
}
Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:
<form action="house.php" method="POST">
<input type="hidden" name="house_number" value="-1">
<?php
foreach ($houses as $id => name)
{
echo "<a href=\"javascript:formSubmit($id);\">$name</a>\n";
}
?>
</form>
That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavasScript submits the form.
Adding nan to list, and the below works for me:
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456',np.nan]
any([i for i in [x for x in some_list if str(x) != 'nan'] if "abc" in i])
#header {
top:0;
width:100%;
position:fixed;
background-color:#FFF;
}
#content {
position:static;
margin-top:100px;
}
I'll take a stab at it:
/^[a-z](?:_?[a-z0-9]+)*$/i
Explained:
/
^ # match beginning of string
[a-z] # match a letter for the first char
(?: # start non-capture group
_? # match 0 or 1 '_'
[a-z0-9]+ # match a letter or number, 1 or more times
)* # end non-capture group, match whole group 0 or more times
$ # match end of string
/i # case insensitive flag
The non-capture group takes care of a) not allowing two _
's (it forces at least one letter or number per group) and b) only allowing the last char to be a letter or number.
Some test strings:
"a": match
"_": fail
"zz": match
"a0": match
"A_": fail
"a0_b": match
"a__b": fail
"a_1_c": match
function getProductionGroupItems($itemId){
$this->db->select("*");
$this->db->where("id",$itemId);
$this->db->or_where("parent_item_id",$itemId);
/*********** order by *********** */
$this->db->order_by("id", "asc");
$q=$this->db->get("recipe_products");
if($q->num_rows()>0){
foreach($q->result() as $row){
$data[]=$row;
}
return $data;
}
return false;
}
Install zip
sudo apt-get install zip
Zip your folder:
zip -r {filename.zip} {foldername}
Windows does not come with a command-line zip program, despite Windows Explorer natively supporting Zip files since the Plus! pack for Windows 98.
I recommend the open-source 7-Zip utility which includes a command-line executable and supports many different archive file types, especially its own *.7z
format which offers superior compression ratios to traditional (PKZIP) *.zip
files:
Download 7-Zip from the 7-Zip home page
Add the path to 7z.exe
to your PATH
environment variable. See this QA:
How to set the path and environment variables in Windows
Open a new command-prompt window and use this command to create a PKZIP *.zip
file:
7z a -tzip {yourfile.zip} {yourfolder}
If you have the Java JDK installed then you can use the jar
utility to create Zip files, as *.jar
files are essentially just renamed *.zip
(PKZIP) files:
jar -cfM {yourfile.zip} {yourfolder}
Explanation: * -c compress * -f specify filename * -M do not include a MANIFEST file
ColumnNames
is a property of type List<String>
so when you are setting up you need to pass a List<String>
in the Returns
call as an argument (or a func which return a List<String>
)
But with this line you are trying to return just a string
input.SetupGet(x => x.ColumnNames).Returns(temp[0]);
which is causing the exception.
Change it to return whole list:
input.SetupGet(x => x.ColumnNames).Returns(temp);
You can use json_encode()
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Later just use json_decode() to decode the string from your DB. Anything else is useless, JSON keeps the array relationship intact for later usage!
Hi the problem is in FileDownloader class
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.
Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)
Attaching the working code with screenshots.
MainActivity.java
package com.example.downloadread;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
private class DownloadFile extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
}
FileDownloader.java
package com.example.downloadread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadread"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.downloadread.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="download"
android:onClick="download" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="38dp"
android:text="view"
android:onClick="view" />
</RelativeLayout>
replace your image tag with
<img src="http://localhost:6054/wp-content/themes/BLANK-Theme/images/material/images.jpg" alt="the-buzz-img3" style="width:640px;height:360px" />
use style attribute and make sure there is no css class for image which set image height and width
try using javascript for this! Seems like its the best and easiest way to do this. You'll get inbuilt funcn to execute a html code only after HTML page loads completely.
or else you may use state based programming where an event occurs at a particular state of the browser..
Well ya you can do that in this way.
<input type="text" name="address" id="address">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
<input type="button" onclick="showAddress(address.value)" value="ShowMap"/>
Java Script
function showAddress(address){
alert("This is address :"+address)
}
That is one example for the same. and that will run.
It appears that semicolons should not be used in conjunction with cursor operations: OPEN
, FETCH
, CLOSE
and DEALLOCATE
. I just wasted a couple of hours with this. I had a close look at the BOL and noticed that [;] is not shown in the syntax for these cursor statements!!
So I had:
OPEN mycursor;
and this gave me error 16916.
But:
OPEN mycursor
worked.
Just want to add my two cents on this old post:
In my opinion, almost all of relational database engines include a commit transaction execution automatically after execute a DDL command even when you have autocommit=false, So you don't need to start a transaction to avoid a potential truncated object creation because It is completely unnecessary.
I follow Wordpress's example on this one. I go and define a root path, normally the document root, and then go define a bunch of other path's along with that (one for each of my class dirs. IE: database, users, html, etc). Often I will define the root path manually instead of relying on a server variable.
Example
if($_SERVER['SERVERNAME'] == "localhost") { define("ABS_PATH", "/path/to/upper/most/directory"); // Manual } else { define("ABS_PATH, dirname(__FILE__)); // This defines the path as the directory of the containing file, normally a config.php } // define other paths... include(ABS_PATH."/mystuff.php");
git config --system core.longpaths true
Note: if step 2 does not work or gives any error, you can also try running this command:
git config --global core.longpaths true
Read more about git config
here.
Use .unshift()
to add to the beginning of an array.
TheArray.unshift(TheNewObject);
See MDN for doc on unshift()
and here for doc on other array methods.
FYI, just like there's .push()
and .pop()
for the end of the array, there's .shift()
and .unshift()
for the beginning of the array.
To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:
In child add:
public Action UpdateProgress; // In place of event handler declaration
// declare an Action delegate
.
.
.
private LoadData() {
this.UpdateProgress(); // call to Action delegate - MyMethod in
// parent
}
In parent add:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod; // assigns MyMethod to child delegate
Good practice to work with SQL Server.
Create below stored procedure and set short key,
CREATE PROCEDURE [dbo].[Searchinall]
(@strFind AS VARCHAR(MAX))
AS
BEGIN
SET NOCOUNT ON;
--TO FIND STRING IN ALL PROCEDURES
BEGIN
SELECT OBJECT_NAME(OBJECT_ID) SP_Name
,OBJECT_DEFINITION(OBJECT_ID) SP_Definition
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+@strFind+'%'
END
--TO FIND STRING IN ALL VIEWS
BEGIN
SELECT OBJECT_NAME(OBJECT_ID) View_Name
,OBJECT_DEFINITION(OBJECT_ID) View_Definition
FROM sys.views
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+@strFind+'%'
END
--TO FIND STRING IN ALL FUNCTION
BEGIN
SELECT ROUTINE_NAME Function_Name
,ROUTINE_DEFINITION Function_definition
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%'+@strFind+'%'
AND ROUTINE_TYPE = 'FUNCTION'
ORDER BY
ROUTINE_NAME
END
--TO FIND STRING IN ALL TABLES OF DATABASE.
BEGIN
SELECT t.name AS Table_Name
,c.name AS COLUMN_NAME
FROM sys.tables AS t
INNER JOIN sys.columns c
ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%'+@strFind+'%'
ORDER BY
Table_Name
END
END
Now - Set short key as below,
So next time whenever you want to find a particular text in any of the four objects like Store procedure
, Views
, Functions
and Tables
. You just need to write that keyword and press shortcut key.
For example: I want to search 'PaymentTable' then write 'PaymentTable' and make sure you select or highlight the written keyword in query editor and press shortcut key ctrl+4
- it will provide you full result.
Using iJordan's answer as inspiration, why not simply create a Category on UINavigationController to use throughout your app instead of copying/pasting this animation code all over the place?
UINavigationController+Animation.h
@interface UINavigationController (Animation)
- (void) pushViewControllerWithFlip:(UIViewController*) controller;
- (void) popViewControllerWithFlip;
@end
UINavigationController+Animation.m
@implementation UINavigationController (Animation)
- (void) pushViewControllerWithFlip:(UIViewController *) controller
{
[UIView animateWithDuration:0.50
animations:^{
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[self pushViewController:controller animated:NO];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:NO];
}];
}
- (void) popViewControllerWithFlip
{
[UIView animateWithDuration:0.5
animations:^{
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:NO];
}];
[self popViewControllerAnimated:NO];
}
@end
Then simply import the UINavigationController+Animation.h file and call it normally:
[self.navigationController pushViewControllerWithFlip:[[NewViewController alloc] init]];
[self.navigationController popViewControllerWithFlip];
I have used the following procedure.
Android Studio 3.4.1
View>Tool Windows>Device File Explorer
I just add
apt-get install php5-mysqlnd
This will ask to overwrite mysql.so from "php5-mysql".
This work for me.
Actually, I think that the answer given in the question you mentioned is just wrong (UPDATE - 20101106: someone fixed it, this answer refers to the version preceding the edit) and this explains, at least partially, why you run into troubles.
It generates two jar files in logmanager/target: logmanager-0.1.0.jar, and logmanager-0.1.0-jar-with-dependencies.jar.
The first one is the JAR of the logmanager module generated during the package
phase by jar:jar
(because the module has a packaging of type jar
). The second one is the assembly generated by assembly:assembly
and should contain the classes from the current module and its dependencies (if you used the descriptor jar-with-dependencies
).
I get an error when I double-click on the first jar:
Could not find the main class: com.gorkwobble.logmanager.LogManager. Program will exit.
If you applied the suggested configuration of the link posted as reference, you configured the jar plugin to produce an executable artifact, something like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.gorkwobble.logmanager.LogManager</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
So logmanager-0.1.0.jar
is indeed executable but 1. this is not what you want (because it doesn't have all dependencies) and 2. it doesn't contain com.gorkwobble.logmanager.LogManager
(this is what the error is saying, check the content of the jar).
A slightly different error when I double-click the jar-with-dependencies.jar:
Failed to load Main-Class manifest attribute from: C:\EclipseProjects\logmanager\target\logmanager-0.1.0-jar-with-dependencies.jar
Again, if you configured the assembly plugin as suggested, you have something like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
With this setup, logmanager-0.1.0-jar-with-dependencies.jar
contains the classes from the current module and its dependencies but, according to the error, its META-INF/MANIFEST.MF
doesn't contain a Main-Class
entry (its likely not the same MANIFEST.MF as in logmanager-0.1.0.jar). The jar is actually not executable, which again is not what you want.
So, my suggestion would be to remove the configuration
element from the maven-jar-plugin and to configure the maven-assembly-plugin like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<!-- nothing here -->
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-4</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>org.sample.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
Of course, replace org.sample.App
with the class you want to have executed. Little bonus, I've bound assembly:single
to the package
phase so you don't have to run assembly:assembly
anymore. Just run mvn install
and the assembly will be produced during the standard build.
So, please update your pom.xml with the configuration given above and run mvn clean install
. Then, cd into the target
directory and try again:
java -jar logmanager-0.1.0-jar-with-dependencies.jar
If you get an error, please update your question with it and post the content of the META-INF/MANIFEST.MF
file and the relevant part of your pom.xml
(the plugins configuration parts). Also please post the result of:
java -cp logmanager-0.1.0-jar-with-dependencies.jar com.gorkwobble.logmanager.LogManager
to demonstrate it's working fine on the command line (regardless of what eclipse is saying).
EDIT: For Java 6, you need to configure the maven-compiler-plugin. Add this to your pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
It looks like you have a typo on your array, it should read:
int my_array[3][3] = {...
You don't have the _
or the {
.
Also my_array[3][3]
is an invalid location. Since computers begin counting at 0
, you are accessing position 4
. (Arrays are weird like that).
If you want just the last element:
printf("%d\n", my_array[2][2]);
If you want the entire array:
for(int i = 0; i < my_array.length; i++) {
for(int j = 0; j < my_array[i].length; j++)
printf("%d ", my_array[i][j]);
printf("\n");
}
As it was mentioned above CasperJS is the best tool to fill and send forms. Simplest possible example of how to fill & submit form using fill() function:
casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
this.fill('form#loginForm', {
'login': 'admin',
'password': '12345678'
}, true);
this.evaluate(function(){
//trigger click event on submit button
document.querySelector('input[type="submit"]').click();
});
});
for single line comment add # at starting of a line
for multiple line comments add ' (single quote) from where you want to start & add ' (again single quote) at the point where you want to end the comment line.
/*$mpdf = new mPDF('', // mode - default ''
'', // format - A4, for example, default ''
0, // font size - default 0
'', // default font family
15, // margin_left
15, // margin right
16, // margin top
16, // margin bottom
9, // margin header
9, // margin footer
'L'); // L - landscape, P - portrait*/
I'm not sure it's good way to check it. What about case when user uses button "clear data" from settings? SharedPreferences will be cleared and you catch "first run" again. And it's a problem. I guess it's better idea to use InstallReferrerReceiver.
from traceback import format_exc
try:
fault = 10/0
except ZeroDivision:
print(format_exc())
Another possibility is to use the format_exc() method from the traceback module.
Try doing like this: array1.compare(array2)=true
Array.prototype.compare = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].compare(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
// get image from upload-image page
public function postUplodeImage(Request $request)
{
$this->validate($request, [
// check validtion for image or file
'uplode_image_file' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
// rename image name or file name
$getimageName = time().'.'.$request->uplode_image_file->getClientOriginalExtension();
$request->uplode_image_file->move(public_path('images'), $getimageName);
return back()
->with('success','images Has been You uploaded successfully.')
->with('image',$getimageName);
}
initialize the Start property in the constructor
Start = DateTime.Now;
This worked for me when I was trying to add few new fields to the ASP .Net Identity Framework's Users table (AspNetUsers) using Code First. I updated the Class - ApplicationUser in IdentityModels.cs and I added a field lastLogin of type DateTime.
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
CreatedOn = DateTime.Now;
LastPassUpdate = DateTime.Now;
LastLogin = DateTime.Now;
}
public String FirstName { get; set; }
public String MiddleName { get; set; }
public String LastName { get; set; }
public String EmailId { get; set; }
public String ContactNo { get; set; }
public String HintQuestion { get; set; }
public String HintAnswer { get; set; }
public Boolean IsUserActive { get; set; }
//Auditing Fields
public DateTime CreatedOn { get; set; }
public DateTime LastPassUpdate { get; set; }
public DateTime LastLogin { get; set; }
}
If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".
First, checkout temp branch and start standard merge
git checkout -b temp
git merge origin/master
You will have to resolve conflicts, but only once and only real ones. Then stage all files and finish merge.
git commit -m "Merge branch 'origin/master' into 'temp'"
Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.
git checkout alpha
git rebase origin/master -X theirs
Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.
git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)
And delete temporary branch
git branch -D temp
That's all. We did a rebase via hidden merge.
Also I wrote a script, so that can be done in a dialog manner, you can find it here.
After going through all the answers I thought i will add two simple options
If you already accessed the record using FirstOrDefault() with tracking enabled (without using .AsNoTracking() function as it will disable tracking) and updated some fields then you can simply call context.SaveChanges()
In other case either you have entity posted to server using HtppPost or you disabled tracking for some reason then you should call context.Update(entityName) before context.SaveChanges()
1st option will only update the fields you changed but 2nd option will update all the fields in the database even though none of the field values were actually updated :)
Hope this will work for you!
You can use library(qpcR)
for combining two matrix with unequal size.
resultant_matrix <- qpcR:::cbind.na(matrix1, matrix2)
NOTE:- The resultant matrix will be of size of matrix2.
Implement a function that, given a linked list that may be circular, swaps the first two elements, the third with the fourth, etc...
edit
The iOS Instagram app has now registered for regular http links to open in the Instagram app and this deeplink methodology is no longer necessary.
old
Swift 4 short-code parsing solution
private static func instagramDeepLinkFromHTTPLink(_ link: String) -> String? {
guard let shortcode = link.components(separatedBy: "/").last else { return nil }
// algorithm from https://stackoverflow.com/a/37246231/337934
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
var mediaId: Int = 0
for (_, char) in shortcode.enumerated() {
guard let index = alphabet.index(of: char) else { continue }
mediaId = (mediaId * 64) + index.encodedOffset
}
return "instagram://media?id=\(mediaId)"
}
ok to hide back arrow use
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
then find hamburger icon in web ->hamburger
and finally, set this drawable in your project with action bar method:
getSupportActionBar().setLogo(R.drawable.hamburger_icon);
This way worked for me:
adding the path that you like:
export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add
checking: you can run 'export' cmd and check the output or you can check it using this cmd:
python -c "import sys; print(sys.path)"
function unzip {
param (
[string]$archiveFilePath,
[string]$destinationPath
)
if ($archiveFilePath -notlike '?:\*') {
$archiveFilePath = [System.IO.Path]::Combine($PWD, $archiveFilePath)
}
if ($destinationPath -notlike '?:\*') {
$destinationPath = [System.IO.Path]::Combine($PWD, $destinationPath)
}
Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archiveFile = [System.IO.File]::Open($archiveFilePath, [System.IO.FileMode]::Open)
$archive = [System.IO.Compression.ZipArchive]::new($archiveFile)
if (Test-Path $destinationPath) {
foreach ($item in $archive.Entries) {
$destinationItemPath = [System.IO.Path]::Combine($destinationPath, $item.FullName)
if ($destinationItemPath -like '*/') {
New-Item $destinationItemPath -Force -ItemType Directory > $null
} else {
New-Item $destinationItemPath -Force -ItemType File > $null
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($item, $destinationItemPath, $true)
}
}
} else {
[System.IO.Compression.ZipFileExtensions]::ExtractToDirectory($archive, $destinationPath)
}
}
Using:
unzip 'Applications\Site.zip' 'C:\inetpub\wwwroot\Site'
You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.
To perform a request with a cookie attached just do the following:
var requestify = require('requestify');
requestify.post('http://google.com', {}, {
cookies: {
sessionCookie: 'session-cookie-data'
}
});
None of the answers worked for me. The simplest way would be to add <td>
s in between with width = 5px
and background='white'
or whatever the background color of the page is.
Again this will fail in case you have a list of <th>
s representing table headers.
session_start(); //php part
$_SESSION['student']=array();
$student_name=$_POST['student_name']; //student_name form field name
$student_city=$_POST['city_id']; //city_id form field name
array_push($_SESSION['student'],$student_name,$student_city);
//print_r($_SESSION['student']);
<table class="table"> //html part
<tr>
<th>Name</th>
<th>City</th>
</tr>
<tr>
<?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
echo '<td>'.$_SESSION['student'][$i].'</td>';
} ?>
</tr>
</table>
Here is a generalized simple command argument interface you can paste to the top of all your scripts.
#!/bin/bash
declare -A flags
declare -A booleans
args=()
while [ "$1" ];
do
arg=$1
if [ "${1:0:1}" == "-" ]
then
shift
rev=$(echo "$arg" | rev)
if [ -z "$1" ] || [ "${1:0:1}" == "-" ] || [ "${rev:0:1}" == ":" ]
then
bool=$(echo ${arg:1} | sed s/://g)
booleans[$bool]=true
echo \"$bool\" is boolean
else
value=$1
flags[${arg:1}]=$value
shift
echo \"$arg\" is flag with value \"$value\"
fi
else
args+=("$arg")
shift
echo \"$arg\" is an arg
fi
done
echo -e "\n"
echo booleans: ${booleans[@]}
echo flags: ${flags[@]}
echo args: ${args[@]}
echo -e "\nBoolean types:\n\tPrecedes Flag(pf): ${booleans[pf]}\n\tFinal Arg(f): ${booleans[f]}\n\tColon Terminated(Ct): ${booleans[Ct]}\n\tNot Mentioned(nm): ${boolean[nm]}"
echo -e "\nFlag: myFlag => ${flags["myFlag"]}"
echo -e "\nArgs: one: ${args[0]}, two: ${args[1]}, three: ${args[2]}"
By running the command:
bashScript.sh firstArg -pf -myFlag "my flag value" secondArg -Ct: thirdArg -f
The output will be this:
"firstArg" is an arg
"pf" is boolean
"-myFlag" is flag with value "my flag value"
"secondArg" is an arg
"Ct" is boolean
"thirdArg" is an arg
"f" is boolean
booleans: true true true
flags: my flag value
args: firstArg secondArg thirdArg
Boolean types:
Precedes Flag(pf): true
Final Arg(f): true
Colon Terminated(Ct): true
Not Mentioned(nm):
Flag: myFlag => my flag value
Args: one => firstArg, two => secondArg, three => thirdArg
Basically, the arguments are divided up into flags booleans and generic arguments. By doing it this way a user can put the flags and booleans anywhere as long as he/she keeps the generic arguments (if there are any) in the specified order.
Allowing me and now you to never deal with bash argument parsing again!
You can view an updated script here
This has been enormously useful over the last year. It can now simulate scope by prefixing the variables with a scope parameter.
Just call the script like
replace() (
source $FUTIL_REL_DIR/commandParser.sh -scope ${FUNCNAME[0]} "$@"
echo ${replaceFlags[f]}
echo ${replaceBooleans[b]}
)
Doesn't look like I implemented argument scope, not sure why I guess I haven't needed it yet.
you can define the variable global , but when using this variable must to write in script block .
def foo="foo"
pipeline {
agent none
stages {
stage("first") {
script{
sh "echo ${foo}"
}
}
}
}
For native code it's probably best to use Dependency Walker. It also possible to use dumpbin command line utility that comes with Visual Studio.
package main
import "encoding/json"
func main() {
in := []byte(`{ "votes": { "option_A": "3" } }`)
var raw map[string]interface{}
if err := json.Unmarshal(in, &raw); err != nil {
panic(err)
}
raw["count"] = 1
out, err := json.Marshal(raw)
if err != nil {
panic(err)
}
println(string(out))
}
What I found useful and I found on one link above is this FQL query where you ask for likes, total, share and click count of one link by looking at the link_stat table
https://graph.facebook.com/fql?q=SELECT%20like_count,%20total_count,%20share_count,%20click_count,%20comment_count%20FROM%20link_stat%20WHERE%20url%20=%20%22http://google.com%22
That will output something like this:
{
data: [
{
like_count: 3440162,
total_count: 13226503,
share_count: 7732740,
click_count: 265614,
comment_count: 2053601
}
]
}
From this version, you can use native Node.js function from util library.
const fs = require('fs')
const { promisify } = require('util')
const readFileAsync = promisify(fs.readFile)
const writeFileAsync = promisify(fs.writeFile)
const run = async () => {
const res = await readFileAsync('./data.json')
console.log(res)
}
run()
const fs = require('fs')
const readFile = (path, opts = 'utf8') =>
new Promise((resolve, reject) => {
fs.readFile(path, opts, (err, data) => {
if (err) reject(err)
else resolve(data)
})
})
const writeFile = (path, data, opts = 'utf8') =>
new Promise((resolve, reject) => {
fs.writeFile(path, data, opts, (err) => {
if (err) reject(err)
else resolve()
})
})
module.exports = {
readFile,
writeFile
}
...
// in some file, with imported functions above
// in async block
const run = async () => {
const res = await readFile('./data.json')
console.log(res)
}
run()
Always use try..catch
for await blocks, if you don't want to rethrow exception upper.
Download Microsoft Drivers for PHP for SQL Server. Extract the files and use one of:
File Thread Safe VC Bulid
php_sqlsrv_53_nts_vc6.dll No VC6
php_sqlsrv_53_nts_vc9.dll No VC9
php_sqlsrv_53_ts_vc6.dll Yes VC6
php_sqlsrv_53_ts_vc9.dll Yes VC9
You can see the Thread Safety status in phpinfo().
Add the correct file to your ext directory and the following line to your php.ini:
extension=php_sqlsrv_53_*_vc*.dll
Use the filename of the file you used.
As Gordon already posted this is the new Extension from Microsoft and uses the sqlsrv_* API instead of mssql_*
Update:
On Linux you do not have the requisite drivers and neither the SQLSERV Extension.
Look at Connect to MS SQL Server from PHP on Linux? for a discussion on this.
In short you need to install FreeTDS and YES you need to use mssql_* functions on linux. see update 2
To simplify things in the long run I would recommend creating a wrapper class with requisite functions which use the appropriate API (sqlsrv_* or mssql_*) based on which extension is loaded.
Update 2: You do not need to use mssql_* functions on linux. You can connect to an ms sql server using PDO + ODBC + FreeTDS. On windows, the best performing method to connect is via PDO + ODBC + SQL Native Client since the PDO + SQLSRV driver can be incredibly slow.
To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent
and background-image: none
) without explicitly specifying any value such as transparent
or none
, you can do so by writing:
background: initial;
From a quick search, Oracle appears to use double quotes ("
, eg "table"
) and apparently requires the correct case—whereas, for anyone interested, MySQL defaults to using backticks (`) except when set to use double quotes for compatibility.
You could always use CSS to simply adjust the width and the height of those elements that you want to do a colspan
and rowspan
and then simply omit displaying the overlapped DIVs. For example:
<div class = 'td colspan3 rowspan5'> Some data </div>
<style>
.td
{
display: table-cell;
}
.colspan3
{
width: 300px; /*3 times the standard cell width of 100px - colspan3 */
}
.rowspan5
{
height: 500px; /* 5 times the standard height of a cell - rowspan5 */
}
</style>
I had the same problem with eclipse on windows 10.
I installed it like recommende over the windows command window (cmd) with:
C:\Users\NAMEOFUSER\AppData\Local\Programs\Python\beautifulsoup4-4.8.2\setup.py install
BeautifulSoup was install like this in my python directory:
C:\Users\NAMEOFUSE\AppData\Local\Programs\Python\Python38\Lib\site-packages\beautifulsoup4-4.8.2-py3.8.egg
After manually coping the bs4 and EGG-INFO folders into the site-packages folder everything started to work, also the example:
from bs4 import BeautifulSoup
html = """
<html>
<body>
<p> Ich bin ein Absatz!</p>
</body>
</html>
"""
print(html)
soup = BeautifulSoup(html, 'html.parser')
print(soup.find_all("p"))
OK this does fix it I tried it today Sept 5-2012 but you have to be sure to check out the demo
The solution by niftylettuce in issue 2130 seems to fix modals in all mobile platforms...
9/1/12 UPDATE: The fix has been updated here: twitter bootstrap jquery plugins
here is the link to the Demo It works great heres the code I used
title_dialog.modal();
title_dialog.modalResponsiveFix({})
title_dialog.touchScroll();
If you are using Python3 the following module will help you: https://github.com/mahmoudadel2/pysed
wget https://raw.githubusercontent.com/mahmoudadel2/pysed/master/pysed.py
Place the module file into your Python3 modules path, then:
import pysed
pysed.replace(<Old string>, <Replacement String>, <Text File>)
pysed.rmlinematch(<Unwanted string>, <Text File>)
pysed.rmlinenumber(<Unwanted Line Number>, <Text File>)
The accepted answer doesn't create a name-only attribute anymore (as of September 2017).
You should use JQuery prop() method to create name-only attributes.
$(body).prop('data-body', true)
I find the easiest way to illustrate it is to look at some code. This getting started page on the NUnit site is a good introduction to the what and the how
http://www.nunit.org/index.php?p=quickStart&r=2.5
Is everything testable? Generally if it calculates something then yes. UI code is a whole other problem to deal with though, as simulating users clicking on buttons is tricky.
What should you test? I tend to write tests around the things I know are going to be tricky. Complicated state transitions, business critical calculations, that sort of thing. Generally I'm not too worried about testing basic input/output stuff, although the purists will doubtless say I'm wrong on that front and everything should be tested. Like so many other things, there is no right answer!
I had to run
php-config --configure-options --enable-soap
as root and restart apache.
That worked! Now my phpinfo() call shows the SOAP section.
The cin.clear()
clears the error flag on cin
(so that future I/O operations will work correctly), and then cin.ignore(10000, '\n')
skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.
You have two ways to fix this. The preferred way is to use:
string answer;
(instead of char
). The other possible way to fix it is:
if (answer == 'y') ...
(note single quotes instead of double, representing a char
constant).
new File(absolutePath).getName();
Prerequisite: Your website is currently on http://localhost:8081/
with a tool like live-server
Within the same network, you can access your machine with your current ip address or hostname. You can find the ip address running ipconfig | grep IPv4
or the hostname by sending a ping -a
to that ip.
http://192.128.1.18:80/
http://hostname:80/
Note: For best results, use port 80, connect on a private network, and check your firewall settings.
Opt 1 - You can use ngrok to provide port forwarding over ngrok's public facing ports
Download ngrok and run the following command:
$ ./ngrok http 8081
Opt 2 - You can use localhost.run to create a ssh tunnel with the following command:
ssh -R 80:localhost:8081 kylemit@ssh.localhost.run
To connect your browser dev tools with a connected device, follow the instructions at Get Started with Remote Debugging Android Devices
Open Dev Tools > More Tools > Remote Debugging (try here if Device Not Detected)
Find your site and Click Inspect which will open up a new inspector window
Spring @Bean annotation indicates that a method produces a bean to be managed by the Spring container.
More reference: https://www.concretepage.com/spring-5/spring-bean-annotation
This can also happen when you mix -fno-rtti
and -frtti
code. Then you need to ensure that any class, which type_info
is accessed in the -frtti
code, have their key method compiled with -frtti
. Such access can happen when you create an object of the class, use dynamic_cast
etc.
[source]
Have you tried using the stream_context_set_option()
method ?
$context = stream_context_create();
$result = stream_context_set_option($context, 'ssl', 'local_cert', '/etc/ssl/certs/cacert.pem');
$fp = fsockopen($host, $port, $errno, $errstr, 20, $context);
In addition, try file_get_contents()
for the pem file, to make sure you have permissions to access it, and make sure the host name matches the certificate.
There are two ways:
The best way is to remove the <p>
altogether. It is acting according to specification when it adds space.
Alternately, use CSS to style the <p>
. Something like:
ul li p {
padding: 0;
margin: 0;
display: inline;
}
My Problem:
docker run <IMAGE_NAME>
docker ps -a
I could see two containers. docker run <IMAGE_NAME>
command, new image was getting createdSolution: To work on the same container you created in the first place run follow these steps
docker ps
to get container of your containerdocker container start <CONTAINER_ID>
to start existing containerdocker exec -it <CONTAINER_ID> /bin/bash
In my case, @
caused some sort of encoding problem, I still prefer my old way:
curl -d "$(cat /path/to/file)" https://example.com
Much easier with numpy:
>>> arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> arr
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> arr.T
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
>>> theArray = np.array([['a','b','c'],['d','e','f'],['g','h','i']])
>>> theArray
array([['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']],
dtype='|S1')
>>> theArray.T
array([['a', 'd', 'g'],
['b', 'e', 'h'],
['c', 'f', 'i']],
dtype='|S1')
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
In my case I have solved this annoying warning by simply adding the <!DOCTYPE xml>
after the <?xml ... >
tag.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
Whenever you try to show a Link
on a page thats outside the BrowserRouter
you will get that error.
This error message is essentially saying that any component that is not a child of our <Router>
cannot contain any React Router related components.
You need to migrate your component hierarchy to how you see it in the first answer above. For anyone else reviewing this post who may need to look at more examples.
Let's say you have a Header.js
component that looks like this:
import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => {
return (
<div className="ui secondary pointing menu">
<Link to="/" className="item">
Streamy
</Link>
<div className="right menu">
<Link to="/" className="item">
All Streams
</Link>
</div>
</div>
);
};
export default Header;
And your App.js
file looks like this:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';
const App = () => {
return (
<div className="ui container">
<Header />
<BrowserRouter>
<div>
<Route path="/" exact component={StreamList} />
<Route path="/streams/new" exact component={StreamCreate} />
<Route path="/streams/edit" exact component={StreamEdit} />
<Route path="/streams/delete" exact component={StreamDelete} />
<Route path="/streams/show" exact component={StreamShow} />
</div>
</BrowserRouter>
</div>
);
};
export default App;
Notice that the Header.js
component is making use of the Link
tag from react-router-dom
but the componet was placed outside the <BrowserRouter>
, this will lead to the same error as the one experience by the OP. In this case, you can make the correction in one move:
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';
const App = () => {
return (
<div className="ui container">
<BrowserRouter>
<div>
<Header />
<Route path="/" exact component={StreamList} />
<Route path="/streams/new" exact component={StreamCreate} />
<Route path="/streams/edit" exact component={StreamEdit} />
<Route path="/streams/delete" exact component={StreamDelete} />
<Route path="/streams/show" exact component={StreamShow} />
</div>
</BrowserRouter>
</div>
);
};
export default App;
Please review carefully and ensure you have the <Header />
or whatever your component may be inside of not only the <BrowserRouter>
but also inside of the <div>
, otherwise you will also get the error that a Router may only have one child which is referring to the <div>
which is the child of <BrowserRouter>
. Everything else such as Route
and components must go within it in the hierarchy.
So now the <Header />
is a child of the <BrowserRouter>
within the <div>
tags and it can successfully make use of the Link
element.
try xctool, it is a replacement for Apple's xcodebuild that makes it easier to build and test iOS and Mac products. It's especially helpful for continuous integration. It has a few extra features:
No.3 is extremely useful. I don't if anyone can read the console output of xcodebuild, I can't, usually it gave me one line with 5000+ characters. Even harder to read than a thesis paper.
Joining the party late, but just as a complement, I ran into some problems with Seaborn not so long ago, because CoLab installed a version with !pip that wasn't updated. In my specific case, I couldn't use Scatterplot, for example. The answer to this is below:
To install the module, all you need is:
!pip install seaborn
To upgrade it to the most updated version:
!pip install --upgrade seaborn
If you want to install a specific version
!pip install seaborn==0.9.0
I believe all the rules common to pip apply normally, so that pretty much should work.
I use this function to indent my output (for example to print a tree structure). The indent
is the number of spaces before the string.
void print_with_indent(int indent, char * string)
{
printf("%*s%s", indent, "", string);
}
I f you want just the first element try this: b = (a-set()).pop()
JSP implicit objects likes session
, request
etc. are not available inside JSP declaration <%! %>
tags.
You could use it directly in your expression as
<td>Username: </td>
<td><input type="text" value="<%= session.getAttribute("username") %>" /></td>
On other note, using scriptlets in JSP has been long deprecated. Use of EL (expression language) and JSTL tags is highly recommended. For example, here you could use EL as
<td>Username: </td>
<td><input type="text" value="${username}" /></td>
The best part is that scope resolution is done automatically. So, here username could come from page, or request, or session, or application scopes in that order. If for a particular instance you need to override this because of a name collision you can explicitly specify the scope as
<td><input type="text" value="${requestScope.username}" /></td> or,
<td><input type="text" value="${sessionScope.username}" /></td> or,
<td><input type="text" value="${applicationScope.username}" /></td>
If you aren't doing some kind of numeric comparison of the length property, it's better not to use it in the if statement, just do:
if(theHref){
// do stuff
}else{
// do other stuff
}
An empty (or undefined, as it is in this case) string will evaluate to false (just like a length of zero would.)
$("#file-upload").change(function () {
var validExtensions = ["jpg","pdf","jpeg","gif","png"]
var file = $(this).val().split('.').pop();
if (validExtensions.indexOf(file) == -1) {
alert("Only formats are allowed : "+validExtensions.join(', '));
}
});
I think that this is equivalent to asking if ToList does a deep or shallow copy. As ToList has no way to clone MyObject, it must do a shallow copy, so the created list contains the same references as the original one, so the code returns 5.
How about creating another component(for object that needs to go into the array) and pass the following as props?
<SubObjectForm setData={this.setSubObjectData} objectIndex={index}/>
Here {index} can be passed in based on position where this SubObjectForm is used.
and setSubObjectData can be something like this.
setSubObjectData: function(index, data){
var arrayFromParentObject= <retrieve from props or state>;
var objectInArray= arrayFromParentObject.array[index];
arrayFromParentObject.array[index] = Object.assign(objectInArray, data);
}
In SubObjectForm, this.props.setData can be called on data change as given below.
<input type="text" name="name" onChange={(e) => this.props.setData(this.props.objectIndex,{name: e.target.value})}/>
Here is a method that does not require editing the code and works regardless of the number of characters.
String text =
java.text.MessageFormat.format(
"You're about to delete {0} rows.".replaceAll("'", "''"), 5);
Box and Cox (1964) suggested a family of transformations designed to reduce nonnormality of the errors in a linear model. In turns out that in doing this, it often reduces non-linearity as well.
Here is a nice summary of the original work and all the work that's been done since: http://www.ime.usp.br/~abe/lista/pdfm9cJKUmFZp.pdf
You will notice, however, that the log-likelihood function governing the selection of the lambda power transform is dependent on the residual sum of squares of an underlying model (no LaTeX on SO -- see the reference), so no transformation can be applied without a model.
A typical application is as follows:
library(MASS)
# generate some data
set.seed(1)
n <- 100
x <- runif(n, 1, 5)
y <- x^3 + rnorm(n)
# run a linear model
m <- lm(y ~ x)
# run the box-cox transformation
bc <- boxcox(y ~ x)
(lambda <- bc$x[which.max(bc$y)])
[1] 0.4242424
powerTransform <- function(y, lambda1, lambda2 = NULL, method = "boxcox") {
boxcoxTrans <- function(x, lam1, lam2 = NULL) {
# if we set lambda2 to zero, it becomes the one parameter transformation
lam2 <- ifelse(is.null(lam2), 0, lam2)
if (lam1 == 0L) {
log(y + lam2)
} else {
(((y + lam2)^lam1) - 1) / lam1
}
}
switch(method
, boxcox = boxcoxTrans(y, lambda1, lambda2)
, tukey = y^lambda1
)
}
# re-run with transformation
mnew <- lm(powerTransform(y, lambda) ~ x)
# QQ-plot
op <- par(pty = "s", mfrow = c(1, 2))
qqnorm(m$residuals); qqline(m$residuals)
qqnorm(mnew$residuals); qqline(mnew$residuals)
par(op)
As you can see this is no magic bullet -- only some data can be effectively transformed (usually a lambda less than -2 or greater than 2 is a sign you should not be using the method). As with any statistical method, use with caution before implementing.
To use the two parameter Box-Cox transformation, use the geoR
package to find the lambdas:
library("geoR")
bc2 <- boxcoxfit(x, y, lambda2 = TRUE)
lambda1 <- bc2$lambda[1]
lambda2 <- bc2$lambda[2]
EDITS: Conflation of Tukey and Box-Cox implementation as pointed out by @Yui-Shiuan fixed.
You need to create custom background like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item>
<shape>
<gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear"/>
<stroke android:width="1dp" android:color="#504a4b"/>
<corners android:radius="5dp"/>
<padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp"/>
</shape>
</item>
<item>
<bitmap android:gravity="bottom|right" android:src="@drawable/drop_down"/> // you can place your dropdown image
</item>
</layer-list>
</item>
</selector>
Then create style for spinner like this:
<style name="spinner_style">
<item name="android:background">@drawable/YOURCUSTOMBACKGROUND</item>
<item name="android:layout_marginLeft">5dp</item>
<item name="android:layout_marginRight">5dp</item>
<item name="android:layout_marginBottom">5dp</item>
</style>
after that apply this style to your spinner
As the error clearly states, OffenceBox.Text()
is not a function and therefore doesn't make sense.
def reverse_lines(filename):
y=open(filename).readlines()
return y[::-1]
The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.
I think ADTC's solution is better, but mine's also works.
Here is the other solution I found
select p.name
from person p
where instr(p.name,chr(8211)) > 0; --contains the character chr(8211)
--at least 1 time
Thank you.
try this:
.button input, .button a {
//css here
}
That will apply the style to all a tags nested inside of <p class="button"></p>
I tested your code and works properly. I've added a small demo with another way to print all the data in the map:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
for (String key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey().toString();
Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
When you export a class module and open the file in Notepad, you'll notice, near the top, a bunch of hidden attributes (the VBE doesn't display them, and doesn't expose functionality to tweak most of them either). One of them is VB_PredeclaredId
:
Attribute VB_PredeclaredId = False
Set it to True
, save, and re-import the module into your VBA project.
Classes with a PredeclaredId
have a "global instance" that you get for free - exactly like UserForm
modules (export a user form, you'll see its predeclaredId attribute is set to true).
A lot of people just happily use the predeclared instance to store state. That's wrong - it's like storing instance state in a static class!
Instead, you leverage that default instance to implement your factory method:
[Employee
class]
'@PredeclaredId
Option Explicit
Private Type TEmployee
Name As String
Age As Integer
End Type
Private this As TEmployee
Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As Employee
With New Employee
.Name = emplName
.Age = emplAge
Set Create = .Self 'returns the newly created instance
End With
End Function
Public Property Get Self() As Employee
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Age() As String
Age = this.Age
End Property
Public Property Let Age(ByVal value As String)
this.Age = value
End Property
With that, you can do this:
Dim empl As Employee
Set empl = Employee.Create("Johnny", 69)
Employee.Create
is working off the default instance, i.e. it's considered a member of the type, and invoked from the default instance only.
Problem is, this is also perfectly legal:
Dim emplFactory As New Employee
Dim empl As Employee
Set empl = emplFactory.Create("Johnny", 69)
And that sucks, because now you have a confusing API. You could use '@Description
annotations / VB_Description
attributes to document usage, but without Rubberduck there's nothing in the editor that shows you that information at the call sites.
Besides, the Property Let
members are accessible, so your Employee
instance is mutable:
empl.Name = "Jane" ' Johnny no more!
The trick is to make your class implement an interface that only exposes what needs to be exposed:
[IEmployee
class]
Option Explicit
Public Property Get Name() As String : End Property
Public Property Get Age() As Integer : End Property
And now you make Employee
implement IEmployee
- the final class might look like this:
[Employee
class]
'@PredeclaredId
Option Explicit
Implements IEmployee
Private Type TEmployee
Name As String
Age As Integer
End Type
Private this As TEmployee
Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As IEmployee
With New Employee
.Name = emplName
.Age = emplAge
Set Create = .Self 'returns the newly created instance
End With
End Function
Public Property Get Self() As IEmployee
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Age() As String
Age = this.Age
End Property
Public Property Let Age(ByVal value As String)
this.Age = value
End Property
Private Property Get IEmployee_Name() As String
IEmployee_Name = Name
End Property
Private Property Get IEmployee_Age() As Integer
IEmployee_Age = Age
End Property
Notice the Create
method now returns the interface, and the interface doesn't expose the Property Let
members? Now calling code can look like this:
Dim empl As IEmployee
Set empl = Employee.Create("Immutable", 42)
And since the client code is written against the interface, the only members empl
exposes are the members defined by the IEmployee
interface, which means it doesn't see the Create
method, nor the Self
getter, nor any of the Property Let
mutators: so instead of working with the "concrete" Employee
class, the rest of the code can work with the "abstract" IEmployee
interface, and enjoy an immutable, polymorphic object.
You can use prop() for this, as Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop()
method provides a way to explicitly retrieve property values, while .attr()
retrieves attributes.
var prop=false;
if(value == 1) {
prop=true;
}
$('#checkbox').prop('checked',prop);
or simply,
$('#checkbox').prop('checked',(value == 1));
Snippet
$(document).ready(function() {_x000D_
var chkbox = $('.customcheckbox');_x000D_
$(".customvalue").keyup(function() {_x000D_
chkbox.prop('checked', this.value==1);_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h4>This is a domo to show check box is checked_x000D_
if you enter value 1 else check box will be unchecked </h4>_x000D_
Enter a value:_x000D_
<input type="text" value="" class="customvalue">_x000D_
<br>checkbox output :_x000D_
<input type="checkbox" class="customcheckbox">
_x000D_
I'm showing that a combination of lines.pop(0)
l.remove()
and del l
does the trick.
from matplotlib import pyplot
import numpy, weakref
a = numpy.arange(int(1e3))
fig = pyplot.Figure()
ax = fig.add_subplot(1, 1, 1)
lines = ax.plot(a)
l = lines.pop(0)
wl = weakref.ref(l) # create a weak reference to see if references still exist
# to this object
print wl # not dead
l.remove()
print wl # not dead
del l
print wl # dead (remove either of the steps above and this is still live)
I checked your large dataset and the release of the memory is confirmed on the system monitor as well.
Of course the simpler way (when not trouble-shooting) would be to pop it from the list and call remove
on the line object without creating a hard reference to it:
lines.pop(0).remove()
What you’re looking for is the CSS Sticky Footer.
* {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
#wrap {_x000D_
min-height: 100%;_x000D_
}_x000D_
_x000D_
#main {_x000D_
overflow: auto;_x000D_
padding-bottom: 180px;_x000D_
/* must be same height as the footer */_x000D_
}_x000D_
_x000D_
#footer {_x000D_
position: relative;_x000D_
margin-top: -180px;_x000D_
/* negative value of footer height */_x000D_
height: 180px;_x000D_
clear: both;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Opera Fix thanks to Maleika (Kohoutec) */_x000D_
_x000D_
body:before {_x000D_
content: "";_x000D_
height: 100%;_x000D_
float: left;_x000D_
width: 0;_x000D_
margin-top: -32767px;_x000D_
/* thank you Erik J - negate effect of float*/_x000D_
}
_x000D_
<div id="wrap">_x000D_
<div id="main"></div>_x000D_
</div>_x000D_
_x000D_
<div id="footer"></div>
_x000D_
You can use this as well:
String uri = "tel:" + posted_by.replaceAll("[^0-9|\\+]", "");
What's the problem with using for
loop inside, just like outside?
for (int j = i + 1; j < list.size(); ++j) {
...
}
In general, since Java 5, I used iterators only once or twice.
According to your question...
How to pass parameters to Thread.ThreadStart() method in C#?
...and the error you encountered, you would have to correct your code from
Thread thread = new Thread(new ThreadStart(download(filename));
to
Thread thread = new Thread(new ThreadStart(download));
thread.Start(filename);
However, the question is more complex as it seems at first.
The Thread
class currently (4.7.2) provides several constructors and a Start
method with overloads.
These relevant constructors for this question are:
public Thread(ThreadStart start);
and
public Thread(ParameterizedThreadStart start);
which either take a ThreadStart
delegate or a ParameterizedThreadStart
delegate.
The corresponding delegates look like this:
public delegate void ThreadStart();
public delegate void ParameterizedThreadStart(object obj);
So as can be seen, the correct constructor to use seems to be the one taking a ParameterizedThreadStart
delegate so that some method conform to the specified signature of the delegate can be started by the thread.
A simple example for instanciating the Thread
class would be
Thread thread = new Thread(new ParameterizedThreadStart(Work));
or just
Thread thread = new Thread(Work);
The signature of the corresponding method (called Work
in this example) looks like this:
private void Work(object data)
{
...
}
What is left is to start the thread. This is done by using either
public void Start();
or
public void Start(object parameter);
While Start()
would start the thread and pass null
as data to the method, Start(...)
can be used to pass anything into the Work
method of the thread.
There is however one big problem with this approach:
Everything passed into the Work
method is cast into an object. That means within the Work
method it has to be cast to the original type again like in the following example:
public static void Main(string[] args)
{
Thread thread = new Thread(Work);
thread.Start("I've got some text");
Console.ReadLine();
}
private static void Work(object data)
{
string message = (string)data; // Wow, this is ugly
Console.WriteLine($"I, the thread write: {message}");
}
Casting is something you typically do not want to do.
What if someone passes something else which is not a string? As this seems not possible at first (because It is my method, I know what I do or The method is private, how should someone ever be able to pass anything to it?) you may possibly end up with exactly that case for various reasons. As some cases may not be a problem, others are. In such cases you will probably end up with an InvalidCastException
which you probably will not notice because it simply terminates the thread.
As a solution you would expect to get a generic ParameterizedThreadStart
delegate like ParameterizedThreadStart<T>
where T
would be the type of data you want to pass into the Work
method. Unfortunately something like this does not exist (yet?).
There is however a suggested solution to this issue. It involves creating a class which contains both, the data to be passed to the thread as well as the method that represents the worker method like this:
public class ThreadWithState
{
private string message;
public ThreadWithState(string message)
{
this.message = message;
}
public void Work()
{
Console.WriteLine($"I, the thread write: {this.message}");
}
}
With this approach you would start the thread like this:
ThreadWithState tws = new ThreadWithState("I've got some text");
Thread thread = new Thread(tws.Work);
thread.Start();
So in this way you simply avoid casting around and have a typesafe way of providing data to a thread ;-)
You mentioned mobile-first sites... For a responsive design, it's certainly possible to override small-screen styles with large-screen styles. But you might not need to.
Try this:
.thisClass {
/* Rules for all window sizes. */
}
@media all and (max-width: 480px) {
.thisClass {
/* Rules for only small browser windows. */
}
}
@media all and (min-width: 481px) and (max-width: 960px) {
.thisClass {
/* Rules for only medium browser windows. */
}
}
@media all and (min-width: 961px) {
.thisClass {
/* Rules for only large browser windows. */
}
}
Those media queries don't overlap, so their rules don't override each other. This makes it easier to maintain each set of styles separately.
After
apply plugin: 'com.android.application'
You should add this:
repositories {
mavenCentral()
maven {
url "https://repository-achartengine.forge.cloudbees.com/snapshot/"
}
}
@Benjamin explained the reason.
If you have a maven with authentication you can use:
repositories {
mavenCentral()
maven {
credentials {
username xxx
password xxx
}
url 'http://mymaven/xxxx/repositories/releases/'
}
}
It is important the order.
You can add properties dynamically using some of the options below:
In you example:
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
You can define a property with a dynamic value in the next two ways:
data.key = value;
or
data['key'] = value;
Even more..if your key is also dynamic you can define using the Object class with:
Object.defineProperty(data, key, withValue(value));
where data is your object, key is the variable to store the key name and value is the variable to store the value.
I hope this helps!
document.getElementById("serverTime").innerHTML = ...;
Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.
If you're on GNU Make, use the :=
assignment instead of =
. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.
FILES := $(shell ...) # expand now; FILES is now the result of $(shell ...)
FILES = $(shell ...) # expand later: FILES holds the syntax $(shell ...)
If you use the =
assignment, it means that every single occurrence of $(FILES)
will be expanding the $(shell ...)
syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.
simply do the select
:
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))
That didn't really work in my case - i.e. in order to overwrite hosts file you have to follow it's directions, ie:
./emulator -avd myEmulatorName -partition-size 280
and then in other term window (pushing new hosts file /tmp/hosts):
./adb remount
./adb push /tmp/hosts /system/etc
Yes, encryption add some load to your cpu, but if your cpu is not ancient that should not affect as much as you say.
If you enable compression for SSH, SCP is actually faster than FTP despite the SSH encryption (if I remember, twice as fast as FTP for the files I tried). I haven't actually used SFTP, but I believe it uses SCP for the actual file transfer. So please try this and let us know :-)
To extract number :
var arrNumber = new Array();
$('input[type=number]').each(function(){
arrNumber.push($(this).val());
})
To extract text:
var arrText= new Array();
$('input[type=text]').each(function(){
arrText.push($(this).val());
})
.map
implementationvar arrText= $('input[type=text]').map(function(){
return this.value;
}).get();
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
What you want is called a pivot, and it's not directly supported in MySQL, check this answer out for the options you've got:
on mac when anything else seems to work - select with mouse, right click choose copy. uff
You can edit Rprofile
in the base
library (in 'C:/Program Files/R.Files/library/base/R'
by default) to include code to be run on startup. Append
######## User code ########
.libPaths('C:/my/dir')
to Rprofile
using any text editor (like Notepad) to cause R to add 'C:/my/dir'
to the list of libraries it knows about.
(Notepad can't save to Program Files, so save your edited Rprofile somewhere else and then copy it in using Windows Explorer.)
When you are only dealing with a single table anyway, the biggest practical difference I have found is that DataSet has a "HasChanges" method but DataTable does not. Both have a "GetChanges" however, so you can use that and test for null.
You do this in 3 different ways:
Before you do an INSERT
, always issue a BEGIN;
statement. This will turn off autocommits. You will need to do a COMMIT;
once you want your data to be persisted in the database.
Use autocommit=0;
every time you instantiate a database connection.
For a global setting, add a autocommit=0
variable in your my.cnf
configuration file in MySQL.
Why don't you simply hide, append, then show, like this:
<div id="parent1" style=" width: 300px; height: 300px; background-color: yellow;">
<div id="child" style=" width: 100px; height: 100px; background-color: red;"></div>
</div>
<div id="parent2" style=" width: 300px; height: 300px; background-color: green;">
</div>
<input id="mybutton" type="button" value="move">
<script>
$("#mybutton").click(function(){
$('#child').hide(1000, function(){
$('#parent2').append($('#child'));
$('#child').show(1000);
});
});
</script>
You can use the diff
command for that:
diff -bur folder1/ folder2/
This will output a recursive diff that ignore spaces, with a unified context:
I have come across articles that state that SELECT COUNT(*) FROM TABLE_NAME will be slow when the table has lots of rows and lots of columns.
That depends on the database. Some speed up counts, for instance by keeping track of whether rows are live or dead in the index, allowing for an index only scan to extract the number of rows. Others do not, and consequently require visiting the whole table and counting live rows one by one. Either will be slow for a huge table.
Note that you can generally extract a good estimate by using query optimization tools, table statistics, etc. In the case of PostgreSQL, for instance, you could parse the output of explain count(*) from yourtable
and get a reasonably good estimate of the number of rows. Which brings me to your second question.
I have a table that might contain even billions of rows [it has approximately 15 columns]. Is there a better way to get the EXACT count of the number of rows of a table?
Seriously? :-) You really mean the exact count from a table with billions of rows? Are you really sure? :-)
If you really do, you could keep a trace of the total using triggers, but mind concurrency and deadlocks if you do.