ORA-12154: TNS:could not resolve the connect identifier specified?
In case the TNS is not defined you can also try this one:
If you are using C#.net 2010
or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:
static string constr = @"Data Source=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
User Id=system ;Password=yourpasswrd";
After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified
then first you have to do restart your system and run your project.
And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:
Oracle Data Provider for .NET 2.0
Oracle Providers for ASP.NET
Oracle Developer Tools for Visual Studio
Oracle Instant Client
And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......
@Magnus answer, only then for Swift (2.0)
let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromTop
self.navigationController!.view.layer.addAnimation(transition, forKey: nil)
let writeView : WriteViewController = self.storyboard?.instantiateViewControllerWithIdentifier("WriteView") as! WriteViewController
self.navigationController?.pushViewController(writeView, animated: false)
Some sidenotes:
You can do this as well with Segue, just implement this in prepareForSegue
or shouldPerformSegueWithIdentifier
. However, this will keep the default animation in it as well. To fix this you have to go to the storyboard, click the Segue, and uncheck the box 'Animates'. But this will limit your app for IOS 9.0 and above (atleast when I did it in Xcode 7).
When doing in a segue, the last two lines should be replaced with:
self.navigationController?.popViewControllerAnimated(false)
Even though I set false, it kind of ignores it.
Another alternative altogether is to use the printf function.
printf -v str 'hello'
Moreover, this construct, combined with the use of single quotes where appropriate, helps to avoid the multi-escape problems of subshells and other forms of interpolative quoting.
There is no "isContentViewSet" method. You may put some dummy requestWindowFeature call into try/catch block before setContentView like this:
try { requestWindowFeature(Window.FEATURE_CONTEXT_MENU); setContentView(...) } catch (AndroidRuntimeException e) { // do smth or nothing }
If content view was already set, requestWindowFeature will throw an exception.
dynamically build list of objects
var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
listOfObjects.push(singleObj);
});
here's a working example http://jsfiddle.net/b9f6Q/2/ see console for output
Preferably use std::iota
like this:
std::vector<int> v(100) ; // vector with 100 ints.
std::iota (std::begin(v), std::end(v), 0); // Fill with 0, 1, ..., 99.
That said, if you don't have any c++11
support (still a real problem where I work), use std::generate
like this:
struct IncGenerator {
int current_;
IncGenerator (int start) : current_(start) {}
int operator() () { return current_++; }
};
// ...
std::vector<int> v(100) ; // vector with 100 ints.
IncGenerator g (0);
std::generate( v.begin(), v.end(), g); // Fill with the result of calling g() repeatedly.
byte * matToBytes(Mat image)
{
int size = image.total() * image.elemSize();
byte * bytes = new byte[size]; //delete[] later
std::memcpy(bytes,image.data,size * sizeof(byte));
}
For people checking the existence to drop View
use this
From SQL Server 2016 CTP3
you can use new DIE statements instead of big IF
wrappers
syntax
DROP VIEW [ IF EXISTS ] [ schema_name . ] view_name [ ...,n ] [ ; ]
Query :
DROP VIEW IF EXISTS view_name
More info here
The question is tagged WPF but the answers so far are specific WinForms and Win32.
To do this in WPF, simply construct a KeyEventArgs and call RaiseEvent on the target. For example, to send an Insert key KeyDown event to the currently focused element:
var key = Key.Insert; // Key to send
var target = Keyboard.FocusedElement; // Target element
var routedEvent = Keyboard.KeyDownEvent; // Event to send
target.RaiseEvent(
new KeyEventArgs(
Keyboard.PrimaryDevice,
PresentationSource.FromVisual(target),
0,
key)
{ RoutedEvent=routedEvent }
);
This solution doesn't rely on native calls or Windows internals and should be much more reliable than the others. It also allows you to simulate a keypress on a specific element.
Note that this code is only applicable to PreviewKeyDown, KeyDown, PreviewKeyUp, and KeyUp events. If you want to send TextInput events you'll do this instead:
var text = "Hello";
var target = Keyboard.FocusedElement;
var routedEvent = TextCompositionManager.TextInputEvent;
target.RaiseEvent(
new TextCompositionEventArgs(
InputManager.Current.PrimaryKeyboardDevice,
new TextComposition(InputManager.Current, target, text))
{ RoutedEvent = routedEvent }
);
Also note that:
Controls expect to receive Preview events, for example PreviewKeyDown should precede KeyDown
Using target.RaiseEvent(...) sends the event directly to the target without meta-processing such as accelerators, text composition and IME. This is normally what you want. On the other hand, if you really do what to simulate actual keyboard keys for some reason, you would use InputManager.ProcessInput() instead.
I was importing also some projects from VS2010 to VS 2012. I had the same errors. The errors disappeared when I set back Properties > Config. Properties > General > Platform Toolset to v100 (VS2010). That might not be the correct approach, however.
Starting with:
houses <- read.table(text="Semi 1
Single 2
Row 3
Single 2
Apartment 4
Apartment 4
Row 3",col.names=c("HouseType","HouseTypeNo"))
... you can use
as.numeric(factor(houses$HouseType))
... to give a unique number for each house type. You can see the result here:
> houses2 <- data.frame(houses,as.numeric(factor(houses$HouseType)))
> houses2
HouseType HouseTypeNo as.numeric.factor.houses.HouseType..
1 Semi 1 3
2 Single 2 4
3 Row 3 2
4 Single 2 4
5 Apartment 4 1
6 Apartment 4 1
7 Row 3 2
... so you end up with different numbers on the rows (because the factors are ordered alphabetically) but the same pattern.
(EDIT: the remaining text in this answer is actually redundant. It occurred to me to check and it turned out that read.table()
had already made houses$HouseType into a factor when it was read into the dataframe in the first place).
However, you may well be better just to convert HouseType to a factor, which would give you all the same benefits as HouseTypeNo, but would be easier to interpret because the house types are named rather than numbered, e.g.:
> houses3 <- houses
> houses3$HouseType <- factor(houses3$HouseType)
> houses3
HouseType HouseTypeNo
1 Semi 1
2 Single 2
3 Row 3
4 Single 2
5 Apartment 4
6 Apartment 4
7 Row 3
> levels(houses3$HouseType)
[1] "Apartment" "Row" "Semi" "Single"
This code will check foreground
and background
in any condition:
Java Code:
private static boolean isApplicationForeground(Context context) {
KeyguardManager keyguardManager =
(KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (keyguardManager.isKeyguardLocked()) {
return false;
}
int myPid = Process.myPid();
ActivityManager activityManager =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> list;
if ((list = activityManager.getRunningAppProcesses()) != null) {
for (ActivityManager.RunningAppProcessInfo aList : list) {
ActivityManager.RunningAppProcessInfo info;
if ((info = aList).pid == myPid) {
return info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
}
}
}
return false;
}
Kotlin Code:
private fun isApplicationForeground(context: Context): Boolean {
val keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
if (keyguardManager.isKeyguardLocked) {
return false
}
val myPid = Process.myPid()
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
var list: List<ActivityManager.RunningAppProcessInfo>
if (activityManager.runningAppProcesses.also { list = it } != null) {
for (aList in list) {
var info: ActivityManager.RunningAppProcessInfo
if (aList.also { info = it }.pid == myPid) {
return info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
}
}
return false
}
What was EXTREMLY HELPFUL to me on this way are the source codes for Capture2Text project. http://sourceforge.net/projects/capture2text/files/Capture2Text/.
BTW: Kudos to it's author for sharing such a painstaking algorithm.
Pay special attention to the file Capture2Text\SourceCode\leptonica_util\leptonica_util.c - that's the essence of image preprocession for this utility.
If you will run the binaries, you can check the image transformation before/after the process in Capture2Text\Output\ folder.
P.S. mentioned solution uses Tesseract for OCR and Leptonica for preprocessing.
The best way to do this is here i found after searching for one issue after other in the LogCat
MediaPlayer mp;
mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.reset();
mp.release();
mp=null;
}
});
mp.start();
Not releasing the Media player gives you this error in LogCat:
Android: MediaPlayer finalized without being released
Not resetting the Media player gives you this error in LogCat:
Android: mediaplayer went away with unhandled events
So play safe and simple code to use media player.
To play more than one sounds in same Activity/Fragment simply change the resID while creating new Media player like
mp = MediaPlayer.create(context, R.raw.sound_two);
and play it !
Have fun!
From the HTTP 1.1 specification:
no-store:
The purpose of the no-store directive is to prevent the inadvertent release or retention of sensitive information (for example, on backup tapes). The no-store directive applies to the entire message, and MAY be sent either in a response or in a request. If sent in a request, a cache MUST NOT store any part of either this request or any response to it. If sent in a response, a cache MUST NOT store any part of either this response or the request that elicited it. This directive applies to both non- shared and shared caches. "MUST NOT store" in this context means that the cache MUST NOT intentionally store the information in non-volatile storage, and MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible after forwarding it. Even when this directive is associated with a response, users might explicitly store such a response outside of the caching system (e.g., with a "Save As" dialog). History buffers MAY store such responses as part of their normal operation. The purpose of this directive is to meet the stated requirements of certain users and service authors who are concerned about accidental releases of information via unanticipated accesses to cache data structures. While the use of this directive might improve privacy in some cases, we caution that it is NOT in any way a reliable or sufficient mechanism for ensuring privacy. In particular, malicious or compromised caches might not recognize or obey this directive, and communications networks might be vulnerable to eavesdropping.
I also tried this style for ionic hybrid app background. this is also having style for background blur effect.
.bg-image {
position: absolute;
background: url(../img/bglogin.jpg) no-repeat;
height: 100%;
width: 100%;
background-size: cover;
bottom: 0px;
margin: 0 auto;
background-position: 50%;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
If you just want the bitmap, This too works
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();
sample uri : content://media/external/images/media/12345
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
No.
You want to use: .indexOf("foo")
and then check the index. If it's >= 0, it contains that string.
You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:
str.substring(0, str.indexOf(":"));
Where 'str' represents the variable with your string inside.
Click here for JSFiddle Example
Javascript
var input_string = document.getElementById('my-input').innerText;
var output_element = document.getElementById('my-output');
var left_text = input_string.substring(0, input_string.indexOf(":"));
output_element.innerText = left_text;
Html
<p>
<h5>Input:</h5>
<strong id="my-input">Left Text:Right Text</strong>
<h5>Output:</h5>
<strong id="my-output">XXX</strong>
</p>
CSS
body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
width:90%;
padding: 0.5em 1em;
background-color: cyan;
}
#my-output { background-color: gold; }
You need to change the directory permission so that web server process can change the directory.
To change ownership of the directory, use chown
:
chown -R user-id:group-id /path/to/the/directory
To see which user own the web server process (change httpd
accordingly):
ps aux | grep httpd | grep -v grep
OR
ps -efl | grep httpd | grep -v grep
There are multiple ways of doing this, since state update is a async operation, so to update the state object, we need to use updater function with setState
.
1- Simplest one:
First create a copy of jasper
then do the changes in that:
this.setState(prevState => {
let jasper = Object.assign({}, prevState.jasper); // creating copy of state variable jasper
jasper.name = 'someothername'; // update the name property, assign a new value
return { jasper }; // return new object jasper object
})
Instead of using Object.assign
we can also write it like this:
let jasper = { ...prevState.jasper };
2- Using spread syntax:
this.setState(prevState => ({
jasper: { // object that we want to update
...prevState.jasper, // keep all other key-value pairs
name: 'something' // update the value of specific key
}
}))
Note: Object.assign
and Spread Operator
creates only shallow copy, so if you have defined nested object or array of objects, you need a different approach.
Assume you have defined state as:
this.state = {
food: {
sandwich: {
capsicum: true,
crackers: true,
mayonnaise: true
},
pizza: {
jalapeno: true,
extraCheese: false
}
}
}
To update extraCheese of pizza object:
this.setState(prevState => ({
food: {
...prevState.food, // copy all other key-value pairs of food object
pizza: { // specific object of food object
...prevState.food.pizza, // copy all pizza key-value pairs
extraCheese: true // update value of specific key
}
}
}))
Lets assume you have a todo app, and you are managing the data in this form:
this.state = {
todoItems: [
{
name: 'Learn React Basics',
status: 'pending'
}, {
name: 'Check Codebase',
status: 'pending'
}
]
}
To update the status of any todo object, run a map on the array and check for some unique value of each object, in case of condition=true
, return the new object with updated value, else same object.
let key = 2;
this.setState(prevState => ({
todoItems: prevState.todoItems.map(
el => el.key === key? { ...el, status: 'done' }: el
)
}))
Suggestion: If object doesn't have a unique value, then use array index.
This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.
The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.
Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:
The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null
. In other words, leaving the anchor null ensures the tip points where it is supposed to point.
However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.
By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.
var pinShadow = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
null,
null,
/* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
new google.maps.Point(40, 110),
new google.maps.Size(120, 110));
to give this:
for (var i in conf) {
val = conf[i];
console.log(val.path);
}
If for some reason you can't get your hands on any of the Python modules that other users mentioned, I suggest the following solution for Python 2.7:
import subprocess
def makePretty(filepath):
cmd = "xmllint --format " + filepath
prettyXML = subprocess.check_output(cmd, shell = True)
with open(filepath, "w") as outfile:
outfile.write(prettyXML)
As far as I know, this solution will work on Unix-based systems that have the xmllint
package installed.
Extract the information from the database for the checkbox fields. Next change the above example line to:
(this code assumes that you've retrieved the information for the user into an associative array called dbvalue
and the DB field names match those on the HTML form)
<input type="checkbox" name="tag_1" id="tag_1" value="yes" <?php echo ($dbvalue['tag_1']==1 ? 'checked' : '');?>>
If you're looking for the code to do everything for you, you've come to the wrong place.
What's wrong with just simply using a single, simple UPDATE
statement??
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.
The feature that I'm missing a lot from postman in Firefox extensions is WebView
(preview when API returns HTML).
Now I'm settled with Fiddler (Inspectors > WebView)
You'll need to learn how to use sed http://unixhelp.ed.ac.uk/CGI/man-cgi?sed
And also to use for so you can loop through your file entries http://www.cyberciti.biz/faq/bash-for-loop/
Your command will look something like this, I don't have a term beside me so I can't check
for i in `dir` do mv $i `echo $i | sed '/orig/new/g'`
May be you can just use the split method to eliminate the '/myapp' for example:
string[] uris=request.getRequestURI().split("/");
string uri="/"+uri[1]+"/"+uris[2];
To delete all the records except te last N you may use the query reported below.
It's a single query but with many statements so it's actually not a single query the way it was intended in the original question.
Also you need a variable and a built-in (in the query) prepared statement due to a bug in MySQL.
Hope it may be useful anyway...
nnn are the rows to keep and theTable is the table you're working on.
I'm assuming you have an autoincrementing record named id
SELECT @ROWS_TO_DELETE := COUNT(*) - nnn FROM `theTable`;
SELECT @ROWS_TO_DELETE := IF(@ROWS_TO_DELETE<0,0,@ROWS_TO_DELETE);
PREPARE STMT FROM "DELETE FROM `theTable` ORDER BY `id` ASC LIMIT ?";
EXECUTE STMT USING @ROWS_TO_DELETE;
The good thing about this approach is performance: I've tested the query on a local DB with about 13,000 record, keeping the last 1,000. It runs in 0.08 seconds.
The script from the accepted answer...
DELETE FROM `table`
WHERE id NOT IN (
SELECT id
FROM (
SELECT id
FROM `table`
ORDER BY id DESC
LIMIT 42 -- keep this many records
) foo
);
Takes 0.55 seconds. About 7 times more.
Test environment: mySQL 5.5.25 on a late 2011 i7 MacBookPro with SSD
Although TripleDESCryptoServiceProvider is a safe and good method but it's too slow. If you want to refer to MSDN you will get that advise you to use AES rather TripleDES. Please check below link: http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider.aspx you will see this attention in the remark section:
Note A newer symmetric encryption algorithm, Advanced Encryption Standard (AES), is available. Consider using the AesCryptoServiceProvider class instead of the TripleDESCryptoServiceProvider class. Use TripleDESCryptoServiceProvider only for compatibility with legacy applications and data.
Good luck
If you want to make it shorter, you could write :
import matplolib.pyplot as plt
for i in range(4):
plt.subplot(2,2,i+1).set_title('Subplot n°{}' .format(i+1))
plt.show()
It makes it maybe less clear but you don't need more lines or variables
I know this has been answered with a very high-quality answer. But, in short, you cant have spaces.
#!/bin/bash
STR = "Hello World"
echo $STR
Didn't work because of the spaces around the equal sign. If you were to run...
#!/bin/bash
STR="Hello World"
echo $STR
It would work
The next()
method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:
Moves the cursor down one row from its current position.
This method return true if there's another row or false otherwise.
Update the bind-address = 0.0.0.0
in the /etc/mysql/mysql.conf.d/mysqld.cnf
and from the mysql command line allow the root
user to connect from any Ip.
Below was the only commands worked for mysql-8.0 as other were failing with error syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'abcd'' at line 1
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
UPDATE mysql.user SET host='%' WHERE user='root';
Restart the mysql client
sudo service mysql restart
The user Klaro suggested to restore the old visibility classes, which is a good idea. Unfortunately, their solution did not work in my project.
I think that it is a better idea to restore the old mixin of bootstrap, because it is covering all breakpoints which can be individually defined by the user.
Here is the code:
// Restore Bootstrap 3 "hidden" utility classes.
@each $bp in map-keys($grid-breakpoints) {
.hidden-#{$bp}-up {
@include media-breakpoint-up($bp) {
display: none !important;
}
}
.hidden-#{$bp}-down {
@include media-breakpoint-down($bp) {
display: none !important;
}
}
.hidden-#{$bp}-only{
@include media-breakpoint-only($bp){
display:none !important;
}
}
}
In my case, I have inserted this part in a _custom.scss
file which is included at this point in the bootstrap.scss
:
/*!
* Bootstrap v4.0.0-beta (https://getbootstrap.com)
* Copyright 2011-2017 The Bootstrap Authors
* Copyright 2011-2017 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
@import "functions";
@import "variables";
@import "mixins";
@import "custom"; // <-- my custom file for overwriting default vars and adding the snippet from above
@import "print";
@import "reboot";
[..]
Collections by themselves do not have a predefined order, therefore you must convert them to
a java.util.List
. Then you can use one form of java.util.Collections.sort
Collection< T > collection = ...;
List< T > list = new ArrayList< T >( collection );
Collections.sort( list );
// or
Collections.sort( list, new Comparator< T >( ){...} );
// list now is sorted
For swift 4.2 to change UIImage color as you want (solid color)
extension UIImage {
func imageWithColor(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
color.setFill()
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(origin: .zero, size: CGSize(width: self.size.width, height: self.size.height))
context?.clip(to: rect, mask: self.cgImage!)
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
How to use
self.imgVw.image = UIImage(named: "testImage")?.imageWithColor(UIColor.red)
This feature already exists in Ubuntu and Debian, in the command-not-found
package.
First, I strongly suggest to use a Library or Framework to do your Javascript. But just for something very very simple, or for the fun to learn, it is ok. (you can use jquery, underscore, knockoutjs, angular)
Second, it is not advised to bind directly to onclick, my first suggestion goes in that way too.
That's said What you need is to modify the src of a img in your page.
In the place where you want your image displayed, you should insert a img tag like this:
Next, you need to modify the onclick to update the src attribute. The easiest way I can think of is like his
onclick=""document.getElementById('image-placeholder').src = 'http://webpage.com/images/' + document.getElementById('imagename').value + '.png"
Then again, it is not the best way to do it, but it is a start. I recommend you to try jQuery and see how can you accomplish the same whitout using onclick (tip... check the section on jquery about events)
I did a simple fiddle as a example of your poblem using some google logos... type 4 o 3 in the box and you'll two images of different size. (sorry.. I have no time to search for better images as example)
<style type="text/css">
table {
border:1px solid black;
}
</style>
Lombok Issue #78 references this page https://www.donneo.de/2015/09/16/lomboks-builder-annotation-and-inheritance/ with this lovely explanation:
@AllArgsConstructor public class Parent { private String a; } public class Child extends Parent { private String b; @Builder public Child(String a, String b){ super(a); this.b = b; } }
As a result you can then use the generated builder like this:
Child.builder().a("testA").b("testB").build();
The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.
I also found this works nicely with Spring Data JPA.
By definition "A Set is a collection of values, where each value may occur only once." So, if your array has repeated values then only one value among the repeated values will be added to your Set.
var arr = [1, 2, 3];
var set = new Set(arr);
console.log(set); // {1,2,3}
var arr = [1, 2, 1];
var set = new Set(arr);
console.log(set); // {1,2}
So, do not convert to set if you have repeated values in your array.
Firstly, I highly recommend you do your CSS styling in an external CSS file, rather than doing it inline. It's much easier to maintain and can be more reusable using classes.
Working off Alex's answer (& Garret's clearfix) of "adding an element at the end with clear: both", you can do it like so:
<div id='outerdiv' style='border: 1px solid black; background-color: black;'>
<div style='width: 300px; border: red 1px dashed; float: left;'>
<p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
</div>
<div style='width: 300px; border: red 1px dashed; float: right;'>
<p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
</div>
<div style='clear:both;'></div>
</div>
This works (but as you can see inline CSS isn't so pretty).
It means you don't have privileges to create the trigger with root@localhost user..
try removing definer from the trigger command:
CREATE DEFINER = root
@localhost
FUNCTION fnc_calcWalkedDistance
I got this error message from using an oracle database in a docker despite the fact i had publish port to host option "-p 1521:1521". I was using jdbc url that was using ip address 127.0.0.1, i changed it to the host machine real ip address and everything worked then.
Worked this out, turns out that android.R.color.black is not the same as Color.BLACK. Changed the code to:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);
and it all works fine now!!
Or in pure WPF use PointToScreen.
Sample helper method:
// Gets the absolute mouse position, relative to screen
Point GetMousePos() => _window.PointToScreen(Mouse.GetPosition(_window));
pushing a value (not necessarily stored in a register) means writing it to the stack.
popping means restoring whatever is on top of the stack into a register. Those are basic instructions:
push 0xdeadbeef ; push a value to the stack
pop eax ; eax is now 0xdeadbeef
; swap contents of registers
push eax
mov eax, ebx
pop ebx
Missing ;
after var_dump($row)
I solved this problem by making sure that the value of JAVA_HOME was the folder location in English
C:\Program Files\Java\jdk1.8.0_31
rather than the folder location that one can see/explorer browse in my Windows7 - Portuguese installation
C:\Programas\Java\jdk1.8.0_31
sudo apt-get install python-dev # for python2.x installs
sudo apt-get install python3-dev # for python3.x installs
It will install any missing headers. It solved my issue
First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.
The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "
Source and example of polyfill here:
http://www.programmerinterview.com/index.php/html5/html5-polyfill/
On MacOS, can try:
brew tap let-us-go/zkcli
brew install zkcli
zkcli ls /brokers/ids
zkcli get /brokers/ids/1
I usually do this to switch back and forth between forms.
Firstly, in Program file I keep ApplicationContext and add a helper SwitchMainForm method.
static class Program
{
public static ApplicationContext AppContext { get; set; }
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Save app context
Program.AppContext = new ApplicationContext(new LoginForm());
Application.Run(AppContext);
}
//helper method to switch forms
public static void SwitchMainForm(Form newForm)
{
var oldMainForm = AppContext.MainForm;
AppContext.MainForm = newForm;
oldMainForm?.Close();
newForm.Show();
}
}
Then anywhere in the code now I call SwitchMainForm method to switch easily to the new form.
// switch to some other form
var otherForm = new MyForm();
Program.SwitchMainForm(otherForm);
extension String {
// MARK: - sub String
func substringToIndex(index:Int) -> String {
return self.substringToIndex(advance(self.startIndex, index))
}
func substringFromIndex(index:Int) -> String {
return self.substringFromIndex(advance(self.startIndex, index))
}
func substringWithRange(range:Range<Int>) -> String {
let start = advance(self.startIndex, range.startIndex)
let end = advance(self.startIndex, range.endIndex)
return self.substringWithRange(start..<end)
}
subscript(index:Int) -> Character{
return self[advance(self.startIndex, index)]
}
subscript(range:Range<Int>) -> String {
let start = advance(self.startIndex, range.startIndex)
let end = advance(self.startIndex, range.endIndex)
return self[start..<end]
}
// MARK: - replace
func replaceCharactersInRange(range:Range<Int>, withString: String!) -> String {
var result:NSMutableString = NSMutableString(string: self)
result.replaceCharactersInRange(NSRange(range), withString: withString)
return result
}
}
You need to add the below mentioned code in the manifest file. Search for the activity in which you want to add the back arrow functionality. If you find the one then fine or create the activity
<activity android:name=".SearchActivity">
</activity>
Then add the following three lines of code in between.
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.raqib.instadate.MainActivity" />
And don't forget to add this piece of code in onCreate(); method of your particular activity in which you need back arrow.
Toolbar toolbar = (Toolbar) findViewById(R.id.searchToolbar);
setSupportActionBar(toolbar);
try{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}catch(NullPointerException e){
Log.e("SearchActivity Toolbar", "You have got a NULL POINTER EXCEPTION");
}
This is how i solved the problem. Thanks.
I didn't realise from your original question that you were opening a file on the local machine, I thought you were sending a file from the web server to the client.
Based on your screenshot, try formatting your link like so:
<a href="file:///C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">Klik hier</a>
(without knowing the contents of each of your recordset variables I can't give you the exact ASP code)
Note: The snippet would only work if the iframe is with the same origin.
Other answers proposed the load
event, but it fires after the new page in the iframe is loaded. You might need to be notified immediately after the URL changes, not after the new page is loaded.
Here's a plain JavaScript solution:
function iframeURLChange(iframe, callback) {_x000D_
var unloadHandler = function () {_x000D_
// Timeout needed because the URL changes immediately after_x000D_
// the `unload` event is dispatched._x000D_
setTimeout(function () {_x000D_
callback(iframe.contentWindow.location.href);_x000D_
}, 0);_x000D_
};_x000D_
_x000D_
function attachUnload() {_x000D_
// Remove the unloadHandler in case it was already attached._x000D_
// Otherwise, the change will be dispatched twice._x000D_
iframe.contentWindow.removeEventListener("unload", unloadHandler);_x000D_
iframe.contentWindow.addEventListener("unload", unloadHandler);_x000D_
}_x000D_
_x000D_
iframe.addEventListener("load", attachUnload);_x000D_
attachUnload();_x000D_
}_x000D_
_x000D_
iframeURLChange(document.getElementById("mainframe"), function (newURL) {_x000D_
console.log("URL changed:", newURL);_x000D_
});
_x000D_
<iframe id="mainframe" src=""></iframe>
_x000D_
This will successfully track the src
attribute changes, as well as any URL changes made from within the iframe itself.
Tested in all modern browsers.
I made a gist with this code as well. You can check my other answer too. It goes a bit in-depth into how this works.
It appears your issue was created by an old Docker bug, where the socket file was not recreated after Docker crashed. If this is the issue, then renaming the socket file should allow it to be re-created:
$ sudo service docker stop
$ sudo mv /var/lib/docker /var/lib/docker.bak
$ sudo service docker start
Since this bug is fixed, most people getting the error Couldn't connect to Docker daemon
are probably getting it because they are not in the docker
group and don't have permissions to read that file. Running with sudo docker ...
will fix that, but isn't a great solution.
Docker can be run as a non-root user (without sudo
) that has the proper group permissions. The Linux post-install docs has the details. The short version:
$ sudo groupadd docker
$ sudo usermod -aG docker $USER
# Log out and log back in again to apply the groups
$ groups # docker should be in the list of groups for your user
$ docker run hello-world # Works without sudo
This allows users in the docker
group to run docker
and docker-compose
commands without sudo
. Docker itself runs a root, allowing some attacks, so you still need to be careful with what containers you run. See Docker Security Documentation for more details.
If you are using vscode and you are on Windows i would recommend you to click the option at the bottom-right of the window and set it to LF from CRLF. Because we should not turn off the configuration just for sake of removing errors on Windows
If you don't see LF / CLRF, then right click the status bar and select Editor End of Line.
SELECT MIN(Date) AS Date FROM tbl_Employee /*To get First date Of Employee*/
Test if the object implements either java.util.Collection
or java.util.Map
. (Map
has to be tested separately because it isn't a sub-interface of Collection
.)
you can use the following command in SQL Developer or SQLPLUS in command prompt to find out the Oracle server version number.
select * from v$version;
in my case it gave me the below mentioned info.
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
PL/SQL Release 11.2.0.1.0 - Production
"CORE 11.2.0.1.0 Production"
TNS for 64-bit Windows: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
No, it is not possible. What type should the dereferenced value have?
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(new File(keyStoreFile)),
keyStorePassword.toCharArray());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
.build(),
NoopHostnameVerifier.INSTANCE);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
socketFactory).build();
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
MyRecord record = restTemplate.getForObject(uri, MyRecord.class);
LOG.debug(record.toString());
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
To get the whole HTML raw data (with <head>
and <body>
):
NSString *html = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];
If you are using npm you can use the shelljs package
To install: npm install [-g] shelljs
var shell = require('shelljs');
shell.ls('*.js').forEach(function (file) {
// do something
});
See more: https://www.npmjs.com/package/shelljs
(In reply to Antony Hatchkins)
This is the current, literally official way to set Chrome policies: https://support.google.com/chrome/a/answer/187202?hl=en
The Windows and Linux templates, as well as common policy documentation for all operating systems, can be found here: https://dl.google.com/dl/edgedl/chrome/policy/policy_templates.zip (Zip file of Google Chrome templates and documentation)
Instructions for Windows (with my additions):
Open the ADM or ADMX template you downloaded:
- Extract "chrome.adm" in the language of your choice from the "policy_templates.zip" downloaded earlier (e.g. "policy_templates.zip\windows\adm\en-US\chrome.adm").
- Navigate to Start > Run: gpedit.msc.
- Navigate to Local Computer Policy > Computer / User Configuration > Administrative Templates.
- Right-click Administrative Templates, and select Add/Remove Templates.
- Add the "chrome.adm" template via the dialog.
- Once complete, Classic Administrative Templates (ADM) / Google / Google Chrome folder will appear under Administrative Templates.
- No matter whether you add the template under Computer Configuration or User Configuration, the settings will appear in both places, so you can configure Chrome at a machine or a user level.
Once you're done with this, continue from step 5 of Antony Hatchkins' answer. After you have added the extension ID(s), you can check that the policy is working in Chrome by opening chrome://policy
(search for ExtensionInstallWhitelist).
It happen if there are two more ContextLoaderListener
exist in your project.
For ex: in my case 2 ContextLoaderListener
was exist using
So, remove any one ContextLoaderListener
from your project and run your application.
You can use Array.filter function to filter out elements of an array based on the return value of a callback function. The callback function runs for every element of the original array.
The logic for the callback function here is that if the indexOf
value for current item is same as the index, it means the element has been encountered first time, so it can be considered unique. If not, it means the element has been encountered already, so should be discarded now.
var arr = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"];_x000D_
_x000D_
var filteredArray = arr.filter(function(item, pos){_x000D_
return arr.indexOf(item)== pos; _x000D_
});_x000D_
_x000D_
console.log( filteredArray );
_x000D_
Caveat: As pointed out by rob in the comments, this method should be avoided with very large arrays as it runs in O(N^2)
.
UPDATE (16 Nov 2017)
If you can rely on ES6 features, then you can use Set object and Spread operator to create a unique array from a given array, as already specified in @Travis Heeter's answer below:
var uniqueArray = [...new Set(array)]
There is no way to do this with slf4j
.
I imagine that the reason that this functionality is missing is that it is next to impossible to construct a Level
type for slf4j
that can be efficiently mapped to the Level
(or equivalent) type used in all of the possible logging implementations behind the facade. Alternatively, the designers decided that your use-case is too unusual to justify the overheads of supporting it.
Concerning @ripper234's use-case (unit testing), I think the pragmatic solution is modify the unit test(s) to hard-wire knowledge of what logging system is behind the slf4j facade ... when running the unit tests.
This is my solution:
# your test class
class TestingClass(unittest.TestCase):
# This will only run once for all the tests within this class
@classmethod
def setUpClass(cls) -> None:
if len(sys.argv) > 1:
cls.email = sys.argv[1]
def testEmails(self):
assertEqual(self.email, "[email protected]")
if __name__ == "__main__":
unittest.main()
you could have a runner.py
file with something like this:
# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests
with the above code, you should be to run your tests with runner.py [email protected]
Along with Bootstrap 3 I used this code. The second set of rules just undo what bootstrap does for focus/active buttons:
button::-moz-focus-inner {
border: 0; /*removes dotted lines around buttons*/
}
.btn.active.focus, .btn.active:focus, .btn.focus, .btn.focus:active, .btn:active:focus, .btn:focus{
outline:0;
}
NOTE that your custom css file should come after Bootstrap css file in your html code to override it.
just found
grep $'\r'
It's using $'\r'
for c-style escape in Bash.
in this article
You can loop through all non-indexed properties of an object like this:
var s = new MyObject();
foreach (var p in s.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any())) {
Console.WriteLine(p.GetValue(s, null));
}
Since GetProperties()
returns indexers as well as simple properties, you need an additional filter before calling GetValue
to know that it is safe to pass null
as the second parameter.
You may need to modify the filter further in order to weed out write-only and otherwise inaccessible properties.
The Maven Wrapper is an excellent choice for projects that need a specific version of Maven (or for users that don't want to install Maven at all). Instead of installing many versions of it in the operating system, we can just use the project-specific wrapper script.
mvnw: it's an executable Unix shell script used in place of a fully installed Maven
mvnw.cmd: it's for Windows environment
Use Cases
The wrapper should work with different operating systems such as:
After that, we can run our goals like this for the Unix system:
./mvnw clean install
And the following command for Batch:
./mvnw.cmd clean install
If we don't have the specified Maven in the wrapper properties, it'll be downloaded and installed in the folder $USER_HOME/.m2/wrapper/dists
of the system.
Maven Wrapper plugin
Maven Wrapper plugin to make auto installation in a simple Spring Boot project.
First, we need to go in the main folder of the project and run this command:
mvn -N io.takari:maven:wrapper
We can also specify the version of Maven:
mvn -N io.takari:maven:wrapper -Dmaven=3.5.2
The option -N means –non-recursive so that the wrapper will only be applied to the main project of the current directory, not in any submodules.
Source 1 (further reading): https://www.baeldung.com/maven-wrapper
Strace stands out as a tool for investigating production systems where you can't afford to run these programs under a debugger. In particular, we have used strace in the following two situations:
For an example of analyzing using strace see my answer to this question.
You should use setTimestamp instead, if you hardcode it:
$start_date = new DateTime();
$start_date->setTimestamp(1372622987);
in your case
$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);
For me the combination of the following three was the solution:
1. control panel > turn windows features on or offf > Hyper-V : deselect
2. admin cmd > bcdedit > hypervisorlaunchtype:Auto disabling: bcdedit /set hypervisorlaunchtype off
3. gpedit.msc > 'Computer configuration > Administrative Template > System > Device Guard' > Turn On Virtualization Based Security : Change from 'Not configured' to 'Disabled'
REBOOT
note: after the reboot the VirtualBox worked, but Docker Desktop's VirtualBox started complaining about missing Hyper-V !
It seems that this might have been the root of all my evil... Extra info: https://forums.docker.com/t/running-docker-and-virtualbox-on-the-same-machine/23578/13
The formatting can be done like this (I assumed you meant HH:MM instead of HH:SS, but it's easy to change):
Time.now.strftime("%d/%m/%Y %H:%M")
#=> "14/09/2011 14:09"
Updated for the shifting:
d = DateTime.now
d.strftime("%d/%m/%Y %H:%M")
#=> "11/06/2017 18:11"
d.next_month.strftime("%d/%m/%Y %H:%M")
#=> "11/07/2017 18:11"
You need to require 'date'
for this btw.
Granted you have administrative Windows privileges on the server, another option would be to start SQL Server in Single User Mode, using the Startup parameter "-m". Doing this, you can login using SQLCMD, create a new user and give it sysadmin privileges. Finally, you have to disable Single User Mode, login to SSMS using your new user, and go to Segurity/Logins and change "sa" user password.
You can check this post: http://v-consult.be/2011/05/26/recover-sa-password-microsoft-sql-server-2008-r2/
As per CodeTrawler's answer, the solution is to enter the following into an explorer window:
%systemroot%\Microsoft.NET\Framework
Then search for:
Mscorlib.dll
...and right-click / go to the version tab for each result.
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
Check out Boost.Units: link text
It provides zero-overhead Dimensional analysis through operator overloading. How much clearer can this get?
quantity<force> F = 2.0*newton;
quantity<length> dx = 2.0*meter;
quantity<energy> E = F * dx;
std::cout << "Energy = " << E << endl;
would actually output "Energy = 4 J" which is correct.
Instead of using a sheet name, in case you don't know or can't open the excel file to check in ubuntu (in my case, Python 3.6.7, ubuntu 18.04), I use the parameter index_col (index_col=0 for the first sheet)
import pandas as pd
file_name = 'some_data_file.xlsx'
df = pd.read_excel(file_name, index_col=0)
print(df.head()) # print the first 5 rows
I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.
Check out the Angular seed project. Within the app.js you'll find an example for the route provider. To use params simply append them like this:
$routeProvider.when('/view1/:param1/:param2', {
templateUrl: 'partials/partial1.html',
controller: 'MyCtrl1'
});
Then in your controller inject $routeParams:
.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
var param1 = $routeParams.param1;
var param2 = $routeParams.param2;
...
}]);
With this approach you can use params with a url such as: "http://www.example.com/view1/param1/param2"
As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below
git ls-files -z | xargs -0 rm
git checkout -- .
or one line
git ls-files -z | xargs -0 rm ; git checkout -- .
I use it all the time and haven't found any down sides yet!
For some further explanation, the -z
appends a null character onto the end of each entry output by ls-files
, and the -0
tells xargs
to delimit the output it was receiving by those null characters.
SELECT column FROM table
ORDER BY RAND()
LIMIT 10
Not the efficient solution but works
With :before
and :after
you specify which content should be inserted before (or after) the content inside of that element. input
elements have no content.
E.g. if you write <input type="text">Test</input>
(which is wrong) the browser will correct this and put the text after the input element.
The only thing you could do is to wrap every input element in a span or div and apply the CSS on these.
See the examples in the specification:
For example, the following document fragment and style sheet:
<h2> Header </h2> h2 { display: run-in; } <p> Text </p> p:before { display: block; content: 'Some'; }
...would render in exactly the same way as the following document fragment and style sheet:
<h2> Header </h2> h2 { display: run-in; } <p><span>Some</span> Text </p> span { display: block }
This is the same reason why it does not work for <br>
, <img>
, etc. (<textarea>
seems to be special).
"set -e
" is probably the easiest way to do this. Just put that before any commands in your program.
Same problem. List contained numbers of type numpy.int64 which throws a TypeError
. Quick workaround for me was to
mylist = eval(str(mylist_of_integers))
json.dumps({'mylist': mylist})
which converts list
to str()
and eval()
function evaluates the String like a Python expression and returns the result as a list of integers
in my case.
This is what I've used for my latest app.
# redirect the main page to landing
##RedirectMatch 302 ^/$ /landing
# remove php ext from url
# https://stackoverflow.com/questions/4026021/remove-php-extension-with-htaccess
RewriteEngine on
# File exists but has a trailing slash
# https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)/+$ /$1 [R=302,L,QSA]
# ok. It will still find the file but relative assets won't load
# e.g. page: /landing/ -> assets/js/main.js/main
# that's we have the rules above.
RewriteCond %{REQUEST_FILENAME} !\.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*?)/?$ $1.php
The ID will work with @
sign in front also, but we have to add one parameter after that. that is null
look like:
@Html.ActionLink("Label Name", "Name_Of_Page_To_Redirect", "Controller", new {@id="Id_Value"}, null)
Triple quoted comments are an interesting subtopic of this question. PEP 257 specifies triple quotes for doc strings. I did a quick check using Google Code Search and found that triple double quotes in Python are about 10x as popular as triple single quotes -- 1.3M vs 131K occurrences in the code Google indexes. So in the multi line case your code is probably going to be more familiar to people if it uses triple double quotes.
I have encountered this problem and i solved mentioned problem by adding -DprofileIdEnabled=true
parameter while running mvn cli command.
Please run your mvn cli command as : mvn clean install -Pdev1 -DprofileIdEnabled=true
.
In addition to this solution, you don't need to remove activeByDefault settings in your POM mentioned as previouses answer.
I hope this answer solve your problem.
It appears to be a known issue.
http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html
http://bugs.mysql.com/bug.php?id=16757
Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example
SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)
can be re-written as
SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID
or
SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)
can be
SELECT FOO.* FROM FOO
LEFT OUTER JOIN FOO2
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL
if you trying with version symfony
please try with
symfony 2 +
cmd>php app/console --version
symfony 3+
cmd>php bin/console --version
for example
D:project>php bin/console --version
Symfony 3.2.8 (kernel: app, env: dev, debug: true)
Safer.
$galleries = array(1,2,5);
array_walk($galleries , 'intval');
$ids = implode(',', $galleries);
$sql = "SELECT * FROM galleries WHERE id IN ($ids)";
I tested Github Flavored Markdown for a while and can summarize with four rules:
-
For example, if your section is named this:
## 1.1 Hello World
Create a link to it this way:
[Link](#11-hello-world)
Although it's not possible in general to do what's been asked, it's still often useful to have a count of how many items were iterated over after having iterated over them. For that, you can use jaraco.itertools.Counter or similar. Here's an example using Python 3 and rwt to load the package.
$ rwt -q jaraco.itertools -- -q
>>> import jaraco.itertools
>>> items = jaraco.itertools.Counter(range(100))
>>> _ = list(counted)
>>> items.count
100
>>> import random
>>> def gen(n):
... for i in range(n):
... if random.randint(0, 1) == 0:
... yield i
...
>>> items = jaraco.itertools.Counter(gen(100))
>>> _ = list(counted)
>>> items.count
48
In Swift 3.0
func deleteAllRecords() {
//delete all data
let context = appDelegate.persistentContainer.viewContext
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "YourClassName")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try context.execute(deleteRequest)
try context.save()
} catch {
print ("There was an error")
}
}
I have copied all library files from installer media databases/stage/ext/lib to $ORACLE_HOME/lib and it resolved the issue.
pass the output to str() function and it will remove the convert the unicode output. also by printing the output it will remove the u'' tags from it.
It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. This allows you to do something like:
switch (today.compareTo(questionDate)) {
case -1: System.out.println("today is sooner than questionDate"); break;
case 0: System.out.println("today and questionDate are equal"); break;
case 1: System.out.println("today is later than questionDate"); break;
default: System.out.println("Invalid results from date comparison"); break;
}
It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful.
I used the Google Apps Script method indexOf()
and its results were wrong. So I wrote the small function Myindexof()
, instead of indexOf
:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');
e= StringVar()
def fileDialog():
filename = filedialog.askopenfilename(initialdir = "/",title = "Select A
File",filetype = (("jpeg","*.jpg"),("png","*.png"),("All Files","*.*")))
e.set(filename)
la = Entry(self,textvariable = e,width = 30).place(x=230,y=330)
butt=Button(self,text="Browse",width=7,command=fileDialog).place(x=430,y=328)
Try it this way in a simple manner it will work
$userset = User::where('name',$data['name'])->first();
if(!$userset) echo "no user found";
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
Use this style
<div class="form-control"
style="height:100px;
width:55%;
overflow:hidden;
cursor:pointer">
</div>
Open Terminal and put below command.
Install:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Uninstall:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
Once install complete after entering brew commands:
brew install wget
brew install node
brew install watchman
...
...
No. But can you give an example what you have in mind? What condition do you want to check?
Maybe Sass or Compass are interesting for you.
Quote from Sass:
Sass makes CSS fun again. Sass is CSS, plus nested rules, variables, mixins, and more, all in a concise, readable syntax.
If you're using Python3.5+, you could use jsons
. It will convert your object (and all its attributes recursively) to a dict.
import jsons
a_dict = jsons.dump(your_object)
Or if you wanted a string:
a_str = jsons.dumps(your_object)
Or if your class implemented jsons.JsonSerializable
:
a_dict = your_object.json
find
is the common tool for this kind of task :
find ./my_dir -mtime +10 -type f -delete
EXPLANATIONS
./my_dir
your directory (replace with your own)-mtime +10
older than 10 days-type f
only files-delete
no surprise. Remove it to test your find
filter before executing the whole commandAnd take care that ./my_dir
exists to avoid bad surprises !
this should work
.navbar-nav {
position: absolute;
left: 50%;
transform: translatex(-50%);
}
Not being a developer I found a solution in running multiple ps commands in one line. E.g:
powershell "& 'c:\path with spaces\to\executable.exe' -arguments ; second command ; etc
By placing a " (double quote) before the & (ampersand) it executes the executable. In none of the examples I have found this was mentioned. Without the double quotes the ps prompt opens and waits for input.
As of vim 7.3, you can use set colorcolumn=80
(set cc=80
for short).
Since earlier versions do not support this, my .vimrc
uses instead:
if exists('+colorcolumn')
set colorcolumn=80
else
au BufWinEnter * let w:m2=matchadd('ErrorMsg', '\%>80v.\+', -1)
endif
See also the online documentation on the colorcolumn
option.
If I'm reading your question right, you want to run a script in the post build actions part of the build.
I myself use PostBuildScript Plugin for running git clean -fxd
after the build has archived artifacts and published test results. My Jenkins slaves have SSD disks, so I do not have the room keep generated files in the workspace.
A condensed code block is as follows:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// things to do on the main thread
}
});
This does not involve passing down the Activity reference or the Application reference.
Kotlin Equivalent:
Handler(Looper.getMainLooper()).post(Runnable {
// things to do on the main thread
})
That's shorter.
function IsArrows (e) {
return (e.keyCode >= 37 && e.keyCode <= 40);
}
Decorators are very powerful in Python since it allows programmers to pass function as argument and can also define function inside another function.
def decorator(func):
def insideFunction():
print("This is inside function before execution")
func()
return insideFunction
def func():
print("I am argument function")
func_obj = decorator(func)
func_obj()
Below is the Jquery way of populating a drop down list whose id is "FolderListDropDown"
$.getJSON("/Admin/GetFolderList/", function(result) {
for (var i = 0; i < result.length; i++) {
var elem = $("<option></option>");
elem.attr("value", result[i].ImageFolderID);
elem.text(result[i].Name);
elem.appendTo($("select#FolderListDropDown"));
}
});
I started off using the community wiki answer, but realised that it wasn't detecting alt-tab events in Chrome. This is because it uses the first available event source, and in this case it's the page visibility API, which in Chrome seems to not track alt-tabbing.
I decided to modify the script a bit to keep track of all possible events for page focus changes. Here's a function you can drop in:
function onVisibilityChange(callback) {
var visible = true;
if (!callback) {
throw new Error('no callback given');
}
function focused() {
if (!visible) {
callback(visible = true);
}
}
function unfocused() {
if (visible) {
callback(visible = false);
}
}
// Standards:
if ('hidden' in document) {
document.addEventListener('visibilitychange',
function() {(document.hidden ? unfocused : focused)()});
}
if ('mozHidden' in document) {
document.addEventListener('mozvisibilitychange',
function() {(document.mozHidden ? unfocused : focused)()});
}
if ('webkitHidden' in document) {
document.addEventListener('webkitvisibilitychange',
function() {(document.webkitHidden ? unfocused : focused)()});
}
if ('msHidden' in document) {
document.addEventListener('msvisibilitychange',
function() {(document.msHidden ? unfocused : focused)()});
}
// IE 9 and lower:
if ('onfocusin' in document) {
document.onfocusin = focused;
document.onfocusout = unfocused;
}
// All others:
window.onpageshow = window.onfocus = focused;
window.onpagehide = window.onblur = unfocused;
};
Use it like this:
onVisibilityChange(function(visible) {
console.log('the page is now', visible ? 'focused' : 'unfocused');
});
This version listens for all the different visibility events and fires a callback if any of them causes a change. The focused
and unfocused
handlers make sure that the callback isn't called multiple times if multiple APIs catch the same visibility change.
please check below code it will help you
DrawerActivity.userListview
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int pos = position;
Intent intent = new Intent(getContext(),
UserDetail.class);
intent.putExtra("model", list.get(position));
context.startActivity(intent);
}
});
return convertView;
}
@Override
public android.widget.Filter getFilter() {
return new android.widget.Filter() {
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
ArrayList<UserListModel> updatelist = (ArrayList<UserListModel>) results.values;
UserListCustomAdaptor newadaptor = new UserListCustomAdaptor(
getContext(), getCount(), updatelist);
if (results.equals(constraint)) {
updatelist.add(modelobj);
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
list = new ArrayList<UserListModel>();
if (constraint != null && DrawerActivity.userlist != null) {
constraint = constraint.toString().toLowerCase();
int length = DrawerActivity.userlist.size();
int i = 0;
while (i < length) {
UserListModel modelobj = DrawerActivity.userlist.get(i);
String data = modelobj.getFirstName() + " "
+ modelobj.getLastName();
if (data.toLowerCase().contains(constraint.toString())) {
list.add(modelobj);
}
i++;
}
filterResults.values = list;
filterResults.count = list.size();
}
return filterResults;
}
};
}
@Override
public int getCount() {
return list.size();
}
@Override
public UserListModel getItem(int position) {
return list.get(position);
}
First you have to define attribute in form2(child) you will update this attribute in form2 and also from form1(parent) :
public string Response { get; set; }
private void OkButton_Click(object sender, EventArgs e)
{
Response = "ok";
}
private void CancelButton_Click(object sender, EventArgs e)
{
Response = "Cancel";
}
Calling of form2(child) from form1(parent):
using (Form2 formObject= new Form2() )
{
formObject.ShowDialog();
string result = formObject.Response;
//to update response of form2 after saving in result
formObject.Response="";
// do what ever with result...
MessageBox.Show("Response from form2: "+result);
}
Or you can try this
dict = {
'somekey': 'somevalue'
};
val = dict['anotherkey'] || 'anotherval';
You have a wrong idea of what fgets returns. Take a look at this: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/
It returns null when it finds an EOF character. Try running the program above and pressing CTRL+D (or whatever combination is your EOF character), and the loop will exit succesfully.
How do you want to detect the end of the input? Newline? Dot (you said sentence xD)?
from sklearn.metrics import mean_squared_error
rmse = mean_squared_error(y_actual, y_predicted, squared=False)
or
import math
from sklearn.metrics import mean_squared_error
rmse = math.sqrt(mean_squared_error(y_actual, y_predicted))
I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.
HEAD: the current commit your repo is on. Most of the time HEAD
points to the latest commit in your current branch, but that doesn't have to be the case. HEAD
really just means "what is my repo currently pointing at".
In the event that the commit HEAD
refers to is not the tip of any branch, this is called a "detached head".
master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.
origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.
HEAD
is an official notion in git. HEAD
always has a well-defined meaning. master
and origin
are common names usually used in git, but they don't have to be.
It is simple. Use trim-redux package and write like this in componentDidMount
or other place and kill it in componentWillUnmount
.
componentDidMount() {
this.tm = setTimeout(function() {
setStore({ age: 20 });
}, 3000);
}
componentWillUnmount() {
clearTimeout(this.tm);
}
You can use these classes
input-lg
input
and
input-sm
for input fields and replace input with btn for buttons.
Check this documentation http://getbootstrap.com/getting-started/#migration
This will change only height of the element, to reduce the width you have to use grid system classes like col-xs-* col-md-* col-lg-*
.
Example col-md-3
. See doc here http://getbootstrap.com/css/#grid
You could also use wp_list_categories();
wp_list_categories( array('taxonomy' => 'product_cat', 'title_li' => '') );
Just came to know about this when I was searching for a solution to a similar problem. SQL has a new keyword called CONTAINS you can use that. For more details see http://msdn.microsoft.com/en-us/library/ms187787.aspx
Try following with heavy files
library(data.table)
URL <- "http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x <- fread(URL)
Installing the Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019 worked for me with a similar problem, and helped with another (slightly different) driver issue.
The self answer given by MagngooSasa did the trick, but for anyone else trying to understand the answer, here are a few bit more details:
When developing Cordova apps with Visual Studio, I tried to import a remote JavaScript file [located here http://Guess.What.com/MyScript.js], but I have the error mentioned in the title.
Here is the meta tag before, in the index.html file of the project:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
Here is the corrected meta tag, to allow importing a remote script:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;**script-src 'self' http://onlineerp.solution.quebec 'unsafe-inline' 'unsafe-eval';** ">
And no more error!
You'll have to do 2 things to make a Bootstrap label (or anything really) adjust sizes based on screen size:
.label { font-size: 75% }
. So any extra selector on your CSS rule will make it more specific.Here's an example CSS listing to accomplish what you are asking, using the default 4 sizes in Bootstrap:
@media (max-width: 767) {
/* your custom css class on a parent will increase specificity */
/* so this rule will override Bootstrap's font size setting */
.autosized .label { font-size: 14px; }
}
@media (min-width: 768px) and (max-width: 991px) {
.autosized .label { font-size: 16px; }
}
@media (min-width: 992px) and (max-width: 1199px) {
.autosized .label { font-size: 18px; }
}
@media (min-width: 1200px) {
.autosized .label { font-size: 20px; }
}
Here is how it could be used in the HTML:
<!-- any ancestor could be set to autosized -->
<div class="autosized">
...
...
<span class="label label-primary">Label 1</span>
</div>
You need to add a vertical-align
property to your two child div's.
If .small
is always shorter, you need only apply the property to .small
.
However, if either could be tallest then you should apply the property to both .small
and .big
.
.container{
border: 1px black solid;
width: 320px;
height: 120px;
}
.small{
display: inline-block;
width: 40%;
height: 30%;
border: 1px black solid;
background: aliceblue;
vertical-align: top;
}
.big {
display: inline-block;
border: 1px black solid;
width: 40%;
height: 50%;
background: beige;
vertical-align: top;
}
Vertical align affects inline or table-cell box's, and there are a large nubmer of different values for this property. Please see https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align for more details.
HTTP Error 500.30 – ANCM In-Process Start Failure” is moreover a generic error. To know more information about the error
Go to Azure Portal > your App Service > under development tools open console. We can run the application through this console and thus visualize the real error that is causing our application not to load.
For that put, the name of our project followed by “.exe” and press the enter key.
Most of the answers, here do clearing the DOS prompt screen, with clearing commands, which is not the question. Other answers here, were printing blank lines to show a clearing effect of the screen.
The simplest answer of this question is
It is not possible to clear python IDLE shell without some external module integration. If you really want to get a blank pure fresh shell just close the previous shell and run it again
I got this problem on freeBSD. It seems lapack packages are missing, I solved it installing them (as root) with:
pkg install lapack
pkg install atlas-devel #not sure this is needed, but just in case
I imagine it could work on other system too using the appropriate package installer (e.g. apt-get)
My interpretation is: I think of YouTube it has a comment-section, and inside the comment-section there are multiple articles (in this case comments).
So a section is like a div-container that holds articles.
For AF_UNIX you can use call unlink (path); after close() socket in "server" app
If your blog outputs an RSS feed you can use Facebook's "RSS Graffiti" application to post that feed to your wall in Facebook. There are other RSS Facebook apps as well; just search "Facebook for RSS apps"...
Following worked for me:
CSS
.round {
border-radius: 50%;
overflow: hidden;
width: 30px;
height: 30px;
background: no-repeat 50%;
object-fit: cover;
}
.round img {
display: block;
height: 100%;
width: 100%;
}
HTML
<div class="round">
<img src="test.png" />
</div>
The Picup app is a way to take pictures from an HTML5 page and upload them to your server. It requires some extra programming on the server, but apart from PhoneGap, I have not found another way.
Swift 4 version of Leo Natan answer is
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 28)
If you wanted to set a custom font you could use
if let font = UIFont(name: "font-name", size: 12) {
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = font
}
Just a tip for this, you don't need the BEGIN and END if it only contains a single statement.
ie:
IF(@Trans_type = 'subscr_signup')
set @tmpType = 'premium'
ELSE iF(@Trans_type = 'subscr_cancel')
set @tmpType = 'basic'
You will find in binary the maximum value of an Int32 is 1111111111111111111111111111111 but in ten based you will find it is 2147483647 or 2^31-1 or Int32.MaxValue
it depends what sort of t-test you want to do (one sided or two sided dependent or independent) but it should be as simple as:
from scipy.stats import ttest_ind
cat1 = my_data[my_data['Category']=='cat1']
cat2 = my_data[my_data['Category']=='cat2']
ttest_ind(cat1['values'], cat2['values'])
>>> (1.4927289925706944, 0.16970867501294376)
it returns a tuple with the t-statistic & the p-value
see here for other t-tests http://docs.scipy.org/doc/scipy/reference/stats.html
Intent intent=new Intent(String) is defined for parameter task, whereas you are passing parameter componentname into this, use instead:
Intent i = new Intent(Settings.this, com.scytec.datamobile.vd.gui.android.AppPreferenceActivity.class);
startActivity(i);
In this statement replace ActivityName by Name of Class of Activity, this code resides in.
For swift
var dateString:String = "2014-05-20";
var dateFmt = NSDateFormatter()
// the format you want
dateFmt.dateFormat = "yyyy-MM-dd"
var date1:NSDate = dateFmt.dateFromString(dateString)!;
My preferred is:
This will have some overhead, but technically it does answer your question
echo abc `#put your comment here` \ def `#another chance for a comment` \ xyz etc
And for pipelines specifically, there is a cleaner solution with no overhead
echo abc | # normal comment OK here tr a-z A-Z | # another normal comment OK here sort | # the pipelines are automatically continued uniq # final comment
You can use this jquery select change event for get selected option value
$(document).ready(function () { _x000D_
$('body').on('change','#select', function() {_x000D_
$('#show_selected').val(this.value);_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<title>Learn Jquery value Method</title>_x000D_
<head> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
</head> _x000D_
<body> _x000D_
<select id="select">_x000D_
<option value="">Select One</option>_x000D_
<option value="PHP">PHP</option>_x000D_
<option value="jAVA">JAVA</option>_x000D_
<option value="Jquery">jQuery</option>_x000D_
<option value="Python">Python</option>_x000D_
<option value="Mysql">Mysql</option>_x000D_
</select>_x000D_
<br><br> _x000D_
<input type="text" id="show_selected">_x000D_
</body> _x000D_
</html>
_x000D_
if you are sure, that you want to delete the entire dir tree, and are no more interested in contents of dir, then crawling for entire dir tree is stupidness... just call native OS command from python to do that. It will be faster, efficient and less memory consuming.
RMDIR c:\blah /s /q
or *nix
rm -rf /home/whatever
In python, the code will look like..
import sys
import os
mswindows = (sys.platform == "win32")
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
if not mswindows:
return commands.getstatusoutput(cmd)
pipe = os.popen(cmd + ' 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None: sts = 0
if text[-1:] == '\n': text = text[:-1]
return sts, text
def deleteDir(path):
"""deletes the path entirely"""
if mswindows:
cmd = "RMDIR "+ path +" /s /q"
else:
cmd = "rm -rf "+path
result = getstatusoutput(cmd)
if(result[0]!=0):
raise RuntimeError(result[1])
Well in case you have changed everything in the indentation part as told and checked for the typo errors but still get an error then you should do this simple which worked for me and it seems this is overlooked by almost everyone
even if you have correct spacing after the assets: you still might be doinbg this one thing wrong
keep the indentation in this order
flutter: <2_spaces>assets: <no_space>- assets/images/image.png
thus it should look like this
flutter:
assets:
- assets/images/image.png
When using the .html()
method, a htmlString
must be the parameter. (source) Put your string inside a HTML tag and it should work or use .text()
as suggested by farzad.
Example:
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>
<script type="text/javascript">
$("div.demo-container").html( "<p>All new content. <em>You bet!</em></p>" );
</script>
select *
from stores
where name like 'a%' or
name like 'b%'
order by name
I'm using UBUNTU and I got this same error. I restarted the set up using sudo and did a custom install. This solved my problem!
--More Specific--
re-installed using # sudo ./studio.sh
then I made sure to click "Custom Install"
then I made sure all packages were selected.
And I got this message Android virtual device Nexus_5_API_22_x86 was successfully created
This happens if you forgot to change your build settings to Simulator
. Unless you want to build to a device, in which case you should see the other answers.
Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.
Based on gkemp answer, On Windows, I found the keystore file path, password, key alias and key password in an earlier log report before I updated Android Studio.
From windows file explorer c:/Users/your pc name/.AndroidStudio1.4 (your android studio version)\system\log\idea.log.1 (or any old log number)
Then I searched for “android.injected.signing.store” and found this from an earlier date:
-Pandroid.injected.signing.store.file= path to your keystore
-Pandroid.injected.signing.store.password=yourstorepassword
-Pandroid.injected.signing.key.alias=yourkeyalias
-Pandroid.injected.signing.key.password=yourkeypassword
There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.
Nick's answer shows how you can do something similar that handles arbitrary types using interface{}
. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{}
type)
My other answer shows how you can do something similar that avoids creating a type using anonymous structs.
These techniques have some properties of tuples, but no, they are not tuples.
"Stubbing-out a function means you'll write only enough to show that the function was called, leaving the details for later when you have more time."
From: SAMS Teach yourself C++, Jesse Liberty and Bradley Jones
"Once upon a time there were three little pigs".Split(" ") | ForEach {
"$_ is a token"
}
The key is $_
, which stands for the current variable in the pipeline.
About the code you found online:
%
is an alias for ForEach-Object
. Anything enclosed inside the brackets is run once for each object it receives. In this case, it's only running once, because you're sending it a single string.
$_.Split(" ")
is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach
.
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
Another useful thing to do with numpy.histogram
is to plot the output as the x and y coordinates on a linegraph. For example:
arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()
This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.
You can find what you need on infochimps.org.
They have a list of 350,000 simple (ie non-compound) words available for free download.
Word List - 350,000+ Simple English Words
Regarding other languages, you might want to poke around on Wiktionary. Here is a link to all the database backups - the information isnt organized so likely but if they have a language, you can download the data in SQL format.
Although this question is long-since answered, I used an alternative approach that people might find simpler than any of these solutions (even Keith Stein's excellent answer). So I'm posting it in case it might help anyone.
You can achieve rounded corners on a button without having to write any XAML (other than a Style, once) and without having to replace the template or set/change any other properties. Just use an EventSetter in your style for the button's "Loaded" event and change it in code-behind.
(And if your style lives in a separate Resource Dictionary XAML file, then you can put the event code in a code-behind file for your resource dictionary.)
I do it like this:
Xaml Style:
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
<EventSetter Event="Loaded" Handler="ButtonLoaded"/>
</Style>
Code-Behind:
public partial class ButtonStyles
{
private void ButtonLoaded(object sender, RoutedEventArgs e)
{
if (!(sender is Button b))
return;
// Find the first top-level border we can.
Border border = default;
for (var i = 0; null == border && i < VisualTreeHelper.GetChildrenCount(b); ++i)
border = VisualTreeHelper.GetChild(b, i) as Border;
// If we found it, set its corner radius how we want.
if (border != null)
border.CornerRadius = new CornerRadius(3);
}
}
If you had to add the code-behind file to an existing resource dictionary xaml file, you can even have the code-behind file automatically appear underneath that XAML file in the Visual Studio Solution if you want. In a .NET Core project, just give it appropriate corresponding name (e.g if the resource Dictionary is "MyDictionary.xaml", name the code-behind file "MyDictionary.xaml.cs"). In a .NET Framework project, you need to edit the .csproj file in XML mode
In your example propertyInfo.GetValue(this, null)
should work. Consider altering GetNamesAndTypesAndValues()
as follows:
public void GetNamesAndTypesAndValues()
{
foreach (PropertyInfo propertyInfo in allClassProperties)
{
Console.WriteLine("{0} [type = {1}] [value = {2}]",
propertyInfo.Name,
propertyInfo.PropertyType,
propertyInfo.GetValue(this, null));
}
}
Please check this out below sample code for semaphore implementation(Lock and unlock).
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include<string.h>
#include<malloc.h>
#include <sys/sem.h>
int main()
{
int key,share_id,num;
char *data;
int semid;
struct sembuf sb={0,-1,0};
key=ftok(".",'a');
if(key == -1 ) {
printf("\n\n Initialization Falied of shared memory \n\n");
return 1;
}
share_id=shmget(key,1024,IPC_CREAT|0744);
if(share_id == -1 ) {
printf("\n\n Error captured while share memory allocation\n\n");
return 1;
}
data=(char *)shmat(share_id,(void *)0,0);
strcpy(data,"Testing string\n");
if(!fork()) { //Child Porcess
sb.sem_op=-1; //Lock
semop(share_id,(struct sembuf *)&sb,1);
strncat(data,"feeding form child\n",20);
sb.sem_op=1;//Unlock
semop(share_id,(struct sembuf *)&sb,1);
_Exit(0);
} else { //Parent Process
sb.sem_op=-1; //Lock
semop(share_id,(struct sembuf *)&sb,1);
strncat(data,"feeding form parent\n",20);
sb.sem_op=1;//Unlock
semop(share_id,(struct sembuf *)&sb,1);
}
return 0;
}
Update:
This answer was for a much older release of Ui-Router. For the more recent releases (0.2.5+), please use the helper directive ui-sref-active
. Details here.
Original Answer:
Include the $state service in your controller. You can assign this service to a property on your scope.
An example:
$scope.$state = $state;
Then to get the current state in your templates:
$state.current.name
To check if a state is current active:
$state.includes('stateName');
This method returns true if the state is included, even if it's part of a nested state. If you were at a nested state, user.details
, and you checked for $state.includes('user')
, it'd return true.
In your class example, you'd do something like this:
ng-class="{active: $state.includes('stateName')}"
i know this is an old post but there is an option to sent the elemd id with the function call:
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
function f1(objButton)
{
if (objButton.innerHTML=="EXPAND") objButton.innerHTML = "MINIMIZE";
else objButton.innerHTML = "EXPAND";
}
personaly, i'm using exceptions to handle validation. it requires following steps:
the trick here, is to bind only to objects which derive from DependencyObject. simple implementation of INotifyPropertyChanged wouldn't work - there is a bug in the framework, which prevents you from accessing error collection.
I can think of two things:
First, try loading the image with:
string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));
Maybe the problem is with WinForm's image resizing, if the image is stretched set Stretch on the image control to "Uniform" or "UnfirofmToFill".
Second option is that maybe the image is not aligned to the pixel grid, you can read about it on my blog at http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx
What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000
. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:
$ nc -l 4000
...and change socket address to localhost:4000
, it will work and try to read something from nc
-created server.
ServerSocket
and listen on it:ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();
The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
Starting Python 3.8
, the math
module directly provides the dist
function, which returns the euclidean distance between two points (given as tuples or lists of coordinates):
from math import dist
dist((1, 2, 6), (-2, 3, 2)) # 5.0990195135927845
And if you're working with lists:
dist([1, 2, 6], [-2, 3, 2]) # 5.0990195135927845
number=5.55
decimal=(number-int(number))
decimal_1=round(decimal,2)
print(decimal)
print(decimal_1)
output: 0.55
in these cases you can try ssh if https is stuck.
Also you can try increasing the buffer size to an astronomical figure so that you dont have to worry about the buffer size any more git config http.postBuffer 100000000
os.environ
behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get
and set
operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.
Python 3
For python 3, dictionaries use the in keyword instead of has_key
>>> import os
>>> 'HOME' in os.environ # Check an existing env. variable
True
...
Python 2
>>> import os
>>> os.environ.has_key('HOME') # Check an existing env. variable
True
>>> os.environ.has_key('FOO') # Check for a non existing variable
False
>>> os.environ['FOO'] = '1' # Set a new env. variable (String value)
>>> os.environ.has_key('FOO')
True
>>> os.environ.get('FOO') # Retrieve the value
'1'
There is one important thing to note about using os.environ
:
Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ
again will not reflect the latest values.
Excerpt from the docs:
This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.
os.environ.data
which stores all the environment variables, is a dict object, which contains all the environment values:
>>> type(os.environ.data) # changed to _data since v3.2 (refer comment below)
<type 'dict'>
As the key is needed, the accepted solution doesn't work.
This:
end($array);
return array(key($array) => array_pop($array));
will return exactly as the example in the question.
In the Solution Explorer, right-click any ASPX page and select "Browse With" and select IE as the default.
Note... the same steps can be used to add Google Chrome as a browser option and to optionally set it as the default browser.
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
The usage of yield is similar to the keyword return, except that it will return a generator. And the generator object will only traverse once.
yield has two benefits:
There is another clear explanation maybe help you.
Should be
~/([^/]*)$~
Means: Match a /
and then everything, that is not a /
([^/]*
) until the end ($
, "end"-anchor).
I use the ~
as delimiter, because now I don't need to escape the forward-slash /
.
Just to point out the generic way to iterate over any map:
private <K, V> void iterateOverMap(Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
}
}
On PostgreSQL you can use:
SELECT * FROM table_name WHERE (boolean_column IS NULL OR NOT boolean_column)
its happen when you try to delete the same object and then again update the same object use this after delete
session.clear();
To avoid any ambiguity, use the utilities methods from SwingUtilities :
SwingUtilities.isLeftMouseButton(MouseEvent anEvent)
SwingUtilities.isRightMouseButton(MouseEvent anEvent)
SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)
Really liked the answer with the reduce() function. Here's another way to sort the string using accumulate().
from itertools import accumulate
s = 'mississippi'
print(tuple(accumulate(sorted(s)))[-1])
sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's']
tuple(accumulate(sorted(s)) -> ('i', 'ii', 'iii', 'iiii', 'iiiim', 'iiiimp', 'iiiimpp', 'iiiimpps', 'iiiimppss', 'iiiimppsss', 'iiiimppssss')
We are selecting the last index (-1) of the tuple
I have used the below as a background for the layout:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="1dp"
android:dashWidth="10px"
android:dashGap="10px"
android:color="android:@color/black"
/>
</shape>
You might be better off to use memory-mapped files handling here.. The memory mapped file support will be around in .NET 4 (I think...I heard that through someone else talking about it), hence this wrapper which uses p/invokes to do the same job..
Edit: See here on the MSDN for how it works, here's the blog entry indicating how it is done in the upcoming .NET 4 when it comes out as release. The link I have given earlier on is a wrapper around the pinvoke to achieve this. You can map the entire file into memory, and view it like a sliding window when scrolling through the file.
100% working
Do some little trick using attribute. In your form add an attribute like data-flag in your form, assign "0" as false.
<form id="from1" data-flag="0">
//your inputs
</form>
In your javascript:
document.querySelector('#from1').onsubmit = function(e){
$flag = $(this).attr('data-flag');
if($flag==0){
e.preventDefault(); //to prevent submitting
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm){
swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");
//update the data-flag to 1 (as true), to submit
$('#from1').attr('data-flag', '1');
$('#from1').submit();
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
}
return true;
});
I was getting the same error after granting remote access until I made this:
From /etc/mysql/my.cnf
In newer versions of mysql the location of the file is
/etc/mysql/mysql.conf.d/mysqld.cnf
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address = 127.0.0.1
(comment this line: bind-address = 127.0.0.1
)
Then run service mysql restart
.
Go to File->Settings->Version Control->Subversion enter the path for your SVN executable in the General tab under Subversion configuration directory. Also, you can download a latest SVN client such as VisualSVN and point the path to the executable as mentioned above. That will most likely solve your problem.
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
Michael Kropats solution in VB.net
Private Function RandomString(ByVal length As Integer, Optional ByVal allowedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") As String
If length < 0 Then Throw New ArgumentOutOfRangeException("length", "length cannot be less than zero.")
If String.IsNullOrEmpty(allowedChars) Then Throw New ArgumentException("allowedChars may not be empty.")
Dim byteSize As Integer = 256
Dim hash As HashSet(Of Char) = New HashSet(Of Char)(allowedChars)
'Dim hash As HashSet(Of String) = New HashSet(Of String)(allowedChars)
Dim allowedCharSet() = hash.ToArray
If byteSize < allowedCharSet.Length Then Throw New ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize))
' Guid.NewGuid and System.Random are not particularly random. By using a
' cryptographically-secure random number generator, the caller is always
' protected, regardless of use.
Dim rng = New System.Security.Cryptography.RNGCryptoServiceProvider()
Dim result = New System.Text.StringBuilder()
Dim buf = New Byte(128) {}
While result.Length < length
rng.GetBytes(buf)
Dim i
For i = 0 To buf.Length - 1 Step +1
If result.Length >= length Then Exit For
' Divide the byte into allowedCharSet-sized groups. If the
' random value falls into the last group and the last group is
' too small to choose from the entire allowedCharSet, ignore
' the value in order to avoid biasing the result.
Dim outOfRangeStart = byteSize - (byteSize Mod allowedCharSet.Length)
If outOfRangeStart <= buf(i) Then
Continue For
End If
result.Append(allowedCharSet(buf(i) Mod allowedCharSet.Length))
Next
End While
Return result.ToString()
End Function
If you would like to setup the search facility inside your Fragment
, just add these few lines:
Step 1 - Add the search field to you toolbar
:
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="Search"/>
Step 2 - Add the logic to your onCreateOptionsMenu()
import android.support.v7.widget.SearchView; // not the default !
@Override
public boolean onCreateOptionsMenu( Menu menu) {
getMenuInflater().inflate( R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
searchView = (SearchView) myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// Toast like print
UserFeedback.show( "SearchOnQueryTextSubmit: " + query);
if( ! searchView.isIconified()) {
searchView.setIconified(true);
}
myActionMenuItem.collapseActionView();
return false;
}
@Override
public boolean onQueryTextChange(String s) {
// UserFeedback.show( "SearchOnQueryTextChanged: " + s);
return false;
}
});
return true;
}