This was a problem with the user having deny privileges as well; in my haste to grant permissions I basically gave the user everything. And deny was killing it. So as soon as I removed those permissions it worked.
If you know which dict
in the list has the key you're looking for, then you already have the solution (as presented by Matt and Ignacio). However, if you don't know which dict has this key, then you could do this:
def getValueOf(k, L):
for d in L:
if k in d:
return d[k]
The main purpose of toString is to generate a String representation of an object, means the return value is always a String. In most cases this simply is the object's class and package name, but on some cases like StringBuilder you will got actually a String-text.
In C#, a method can return only one value. If you would like to return more than one value, you can use the out keyword. The out modifier returns as return-by-reference. The simplest answer is that the keyword “out” is used to get the value from the method.
In C#, when you pass a value type such as int, float, double etc. as an argument to the method parameter, it is passed by value. Therefore, if you modify the parameter value, it does not affect argument in the method call. But if you mark the parameter with “ref” keyword, it will reflect in the actual variable.
When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1
SELECT * FROM a WHERE a.group_id IN
(SELECT group_id FROM b WHERE b.user_id!=$_SESSION{'[user_id']} AND b.group_id = a.group_id)
WHERE a.keyword LIKE '%".$keyword."%';
If your objective is to import a theme into your Wordpress then you can manually copy paste your theme into your wp-content->themes folder and extract it of course. I just encountered this and couldn't locate the php.ini file for WAMP.
As a jQuery user I would use the Metadata plugin. The HTML looks clean, it validates, and you can embed anything that can be described using JSON notation.
-- Reverse the date format
-- this false:
select * from test where date = '28/10/2015'
-- this true:
select * from test where date = '2015/10/28'
You must define the class before creating an instance of the class. Move the invocation of Something
to the end of the script.
You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:
echo rawurlencode('http://www.google.com/index.html?id=asd asd');
yields
http%3A%2F%2Fwww.google.com%2Findex.html%3Fid%3Dasd%20asd
while
echo urlencode('http://www.google.com/index.html?id=asd asd');
yields
http%3A%2F%2Fwww.google.com%2Findex.html%3Fid%3Dasd+asd
The difference being the asd%20asd
vs asd+asd
urlencode differs from RFC 1738 by encoding spaces as +
instead of %20
1)your id should have sys dba access 2)
select sum(a.value) total_cur, avg(a.value) avg_cur, max(a.value) max_cur,
s.username, s.machine
from v$sesstat a, v$statname b, v$session s
where a.statistic# = b.statistic# and s.sid=a.sid
and b.name = 'opened cursors current'
group by s.username, s.machine
order by 1 desc;
Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.
Yes you can, for example:
[textField setKeyboardType:UIKeyboardTypeNumberPad];
You can use Oracle Data Dictionary to get information about oracle objects.
You can get list of tables in different ways:
select *
from dba_tables
or for example:
select *
from dba_objects
where object_type = 'TABLE'
Then you can get table columns using table name:
select *
from dba_tab_columns
Then you can get list of dependencies (triggers, views and etc.):
select *
from dba_dependencies
where referenced_type='TABLE' and referenced_name=:t_name
Then you can get text source of this objects:
select * from dba_source
And you can use USER
or ALL
views instead of DBA
if you want.
You would think this common problem would be taken care of by Hibernate. But its not! There are a few "hacks" to get it right.
The one I use is to store the Date as a Long in the database. So I am always working with milliseconds after 1/1/70. I then have getters and setters on my Class that return/accept only Dates. So the API remains the same. The down side is that I have longs in the database. SO with SQL I can pretty much only do <,>,= comparisons -- not fancy date operators.
Another approach is to user a custom mapping type as described here: http://www.hibernate.org/100.html
I think the correct way to deal with this is to use a Calendar instead of a Date though. With the Calendar you can set the TimeZone before persisting.
NOTE: Silly stackoverflow won't let me comment, so here is a response to david a.
If you create this object in Chicago:
new Date(0);
Hibernate persists it as "12/31/1969 18:00:00". Dates should be devoid of timezone, so I'm not sure why the adjustment would be made.
ES6 String Template
Here is a simple way if you don't need IE/EDGE support
$(`input[id=${x}]`).hide();
or
$(`input[id=${$(this).attr("name")}]`).hide();
This is a es6 feature called template string
(function($) {_x000D_
$("input[type=button]").click(function() {_x000D_
var x = $(this).attr("name");_x000D_
$(`input[id=${x}]`).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" name="bx" value="1" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" name="by" value="2" />_x000D_
_x000D_
_x000D_
String Concatenation
If you need IE/EDGE support use
$("#" + $(this).attr("name")).hide();
(function($) {_x000D_
$("input[type=button]").click(function() {_x000D_
$("#" + $(this).attr("name")).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" name="bx" value="1" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" name="by" value="2" />_x000D_
_x000D_
_x000D_
Selector in DOM as data attribute
This is my preferred way as it makes you code really DRY
// HTML
<input type="text" id="bx" />
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick"/>
//JS
$($(this).data("input-sel")).hide();
(function($) {_x000D_
$(".js-hide-onclick").click(function() {_x000D_
$($(this).data("input-sel")).toggle(); //use hide instead of toggle_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="bx" />_x000D_
<input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick" />_x000D_
<input type="text" id="by" />_x000D_
<input type="button" data-input-sel="#by" value="2" class="js-hide-onclick" />_x000D_
_x000D_
_x000D_
This doesn't work. only one value is ever pre-selected even though both options are available in the list only the first is shown
('#searchproject').select2('val', ['New Co-location','Expansion']);
You almost have it, you just left out 0 and forgot the quantifier.
word.matches("^[0-9,;]+$")
In .dropdown
content put the .keep-open
class on any label like so:
$('.dropdown').on('click', function (e) {
var target = $(e.target);
var dropdown = target.closest('.dropdown');
if (target.hasClass('keep-open')) {
$(dropdown).addClass('keep-open');
} else {
$(dropdown).removeClass('keep-open');
}
});
$(document).on('hide.bs.dropdown', function (e) {
var target = $(e.target);
if ($(target).is('.keep-open')) {
return false
}
});
The previous cases avoided the events related to the container objects, now the container inherits the class keep-open and check before being closed.
In windows 2008 Server.
i removed ";" in front of extension=php_mbstring.dll in php.ini file and it worked... i followed below link...
not really sure what you're doing exactly via the context of your code but...
why make the listOfTopicAuthors
variable at all?
List<String> list = Arrays.asList((....).toArray( new String[0] ) );
the "...." represents however your set came into play, whether it's new or came from another location.
I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.
You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.
You can also use the statement debugger;
in your JavaScript code the set a breakpoint.
The difference is second parameter. Their second parameters, while both numbers, are expecting two different things:
When using substring the second parameter is the first index not to include:
var s = "string";
s.substring(1, 3); // would return 'tr'
var s = "another example";
s.substring(3, 7); // would return 'ther'
When using substr the second parameter is the number of characters to include in the substring:
var s = "string";
s.substr(1, 3); // would return 'tri'
var s = "another example";
s.substr(3, 7); // would return 'ther ex'
You can use a checkbox
to simulate onClick with CSS:
input[type=checkbox]:checked + p {
display: none;
}
QApplication is derived from QCoreApplication and thereby inherits quit()
which is a public slot of QCoreApplication
, so there is no difference between QApplication::quit()
and QCoreApplication::quit()
.
As we can read in the documentation of QCoreApplication::quit()
it "tells the application to exit with return code 0 (success).". If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call QCoreApplication::exit()
because you can provide a non-zero returnCode which, by convention, indicates an error.
It is important to note that "if the event loop is not running, this function (QCoreApplication::exit()) does nothing", so in that case you should call exit(EXIT_FAILURE)
.
It is clear by now, that they are not the same. The way to code that is
var var1, var2, var3
var1 = var2 = var3 = 1
And, what about let assigment? Exactly the same as var, don't let the let assigment confuse you because of block scope.
let var1 = var2 = 1 // here var2 belong to the global scope
We could do the following:
let v1, v2, v3
v1 = v2 = v3 = 2
Note: btw, I do not recommend use multiple assignments, not even multiple declarations in the same line.
__call__()
method when creating a class instanceIf you've done Python programming for more than a few months you'll eventually stumble upon code that looks like this:
# define a class
class SomeClass(object):
# ...
# some definition here ...
# ...
# create an instance of it
instance = SomeClass()
# then call the object as if it's a function
result = instance('foo', 'bar')
The latter is possible when you implement the __call__()
magic method on the class.
class SomeClass(object):
# ...
# some definition here ...
# ...
def __call__(self, foo, bar):
return bar + foo
The __call__()
method is invoked when an instance of a class is used as a callable. But as we've seen from previous answers a class itself is an instance of a metaclass, so when we use the class as a callable (i.e. when we create an instance of it) we're actually calling its metaclass' __call__()
method. At this point most Python programmers are a bit confused because they've been told that when creating an instance like this instance = SomeClass()
you're calling its __init__()
method. Some who've dug a bit deeper know that before __init__()
there's __new__()
. Well, today another layer of truth is being revealed, before __new__()
there's the metaclass' __call__()
.
Let's study the method call chain from specifically the perspective of creating an instance of a class.
This is a metaclass that logs exactly the moment before an instance is created and the moment it's about to return it.
class Meta_1(type):
def __call__(cls):
print "Meta_1.__call__() before creating an instance of ", cls
instance = super(Meta_1, cls).__call__()
print "Meta_1.__call__() about to return instance."
return instance
This is a class that uses that metaclass
class Class_1(object):
__metaclass__ = Meta_1
def __new__(cls):
print "Class_1.__new__() before creating an instance."
instance = super(Class_1, cls).__new__(cls)
print "Class_1.__new__() about to return instance."
return instance
def __init__(self):
print "entering Class_1.__init__() for instance initialization."
super(Class_1,self).__init__()
print "exiting Class_1.__init__()."
And now let's create an instance of Class_1
instance = Class_1()
# Meta_1.__call__() before creating an instance of <class '__main__.Class_1'>.
# Class_1.__new__() before creating an instance.
# Class_1.__new__() about to return instance.
# entering Class_1.__init__() for instance initialization.
# exiting Class_1.__init__().
# Meta_1.__call__() about to return instance.
Observe that the code above doesn't actually do anything more than logging the tasks. Each method delegates the actual work to its parent's implementation, thus keeping the default behavior. Since type
is Meta_1
's parent class (type
being the default parent metaclass) and considering the ordering sequence of the output above, we now have a clue as to what would be the pseudo implementation of type.__call__()
:
class type:
def __call__(cls, *args, **kwarg):
# ... maybe a few things done to cls here
# then we call __new__() on the class to create an instance
instance = cls.__new__(cls, *args, **kwargs)
# ... maybe a few things done to the instance here
# then we initialize the instance with its __init__() method
instance.__init__(*args, **kwargs)
# ... maybe a few more things done to instance here
# then we return it
return instance
We can see that the metaclass' __call__()
method is the one that's called first. It then delegates creation of the instance to the class's __new__()
method and initialization to the instance's __init__()
. It's also the one that ultimately returns the instance.
From the above it stems that the metaclass' __call__()
is also given the opportunity to decide whether or not a call to Class_1.__new__()
or Class_1.__init__()
will eventually be made. Over the course of its execution it could actually return an object that hasn't been touched by either of these methods. Take for example this approach to the singleton pattern:
class Meta_2(type):
singletons = {}
def __call__(cls, *args, **kwargs):
if cls in Meta_2.singletons:
# we return the only instance and skip a call to __new__()
# and __init__()
print ("{} singleton returning from Meta_2.__call__(), "
"skipping creation of new instance.".format(cls))
return Meta_2.singletons[cls]
# else if the singleton isn't present we proceed as usual
print "Meta_2.__call__() before creating an instance."
instance = super(Meta_2, cls).__call__(*args, **kwargs)
Meta_2.singletons[cls] = instance
print "Meta_2.__call__() returning new instance."
return instance
class Class_2(object):
__metaclass__ = Meta_2
def __new__(cls, *args, **kwargs):
print "Class_2.__new__() before creating instance."
instance = super(Class_2, cls).__new__(cls)
print "Class_2.__new__() returning instance."
return instance
def __init__(self, *args, **kwargs):
print "entering Class_2.__init__() for initialization."
super(Class_2, self).__init__()
print "exiting Class_2.__init__()."
Let's observe what happens when repeatedly trying to create an object of type Class_2
a = Class_2()
# Meta_2.__call__() before creating an instance.
# Class_2.__new__() before creating instance.
# Class_2.__new__() returning instance.
# entering Class_2.__init__() for initialization.
# exiting Class_2.__init__().
# Meta_2.__call__() returning new instance.
b = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.
c = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.
a is b is c # True
I'm assuming this is for a game or for a fast-responding type of application hence the use of KEYDOWN than KEYPRESS.
Edit: Dang! I stand corrected (thank you Crescent Fresh and David): JQuery (or even rather the underlying DOM hosts) do not expose the detail of the WM_KEYDOWN and of other events. Rather they pre-digest this data and, in the case of keyDown even in JQuery, we get:
Note that these properties are the UniCode values.
Note, I wasn't able to find an authorititative reference to that in JQuery docs, but many reputable examples on the net refer to these two properties.
The following code, adapted from some java (not javascript) of mine, is therefore totally wrong...
The following will give you the "interesting" parts of the keycode:
value = e.KeyCode;
repeatCount = value & 0xFF;
scanCode = (value >> 16) & 0xFF; // note we take the "extended bit" deal w/ it later.
wasDown = ((value & 0x4000) != 0); // indicate key was readily down (auto-repeat)
if (scanCode > 127)
// deal with extended
else
// "regular" character
All string functions as lower
, upper
, strip
are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable
, it will fail.
x = 'hello'
x[0] = 'i' #'str' object does not support item assignment
There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them
Have you tried to remove "pytrace=True" ?
pytest.fail(exc, pytrace=True) # before
pytest.fail(exc) # after
Have you tried to run with '--fulltrace' ?
<div class="headerdivider"></div>
and
.headerdivider {
border-left: 1px solid #38546d;
background: #16222c;
width: 1px;
height: 80px;
position: absolute;
right: 250px;
top: 10px;
}
Step 1:
Install node module: npm install csvtojson --save
Step 2:
var Converter = require("csvtojson").Converter;
var converter = new Converter({});
converter.fromFile("./path-to-your-file.csv",function(err,result){
if(err){
console.log("Error");
console.log(err);
}
var data = result;
//to check json
console.log(data);
});
I struggled with this problem many times.
The solution I am currently using is weather the webapp(or the folder where you kept the views like jsp) is under deployment assembly.
To do so Right click on the project > Build Path > Configure Build path > Deployment Assembly > Add(right hand side) > Folder > (add your jsp
folder. In default case it is src/main/webapp
)
You could also get this error after you did everything correct but on the JSP you put the anchor tag the old fashion(I am adding this incase if it help anybody else with the same issue).
I had the following syntax on the jsp. <a href="/mappedpath">TakeMeToTheController</a>
and I kept seeing the error mentioned in the question. However changing the tag into the one shown below solved the issue.
<a href=" <spring:url value="/mappedpath" /> ">TakeMeToTheController</a>
I like the INFORMATION_SCHEMA technique, but another I've used is: exec sp_pkeys 'table'
Simply try converting it to an int and then bailing out if it doesn't work.
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
If it's still of interest, here is an answer to a similar question: Convert HTTP Proxy to HTTPS Proxy in Twisted
To answer the second part of the question:
If yes, what kind of proxy server allows this?
Out of the box, most proxy servers will be configured to allow HTTPS connections only to port 443, so https URIs with custom ports wouldn't work. This is generally configurable, depending on the proxy server. Squid and TinyProxy support this, for example.
The simple solution that worked for me as below, wrap the table with a div and change the line-height
, this line-height is taken as a ratio.
<div class="col-md-6" style="line-height: 0.5">_x000D_
<table class="table table-striped" >_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Parameter</th>_x000D_
<th>Recorded Value</th>_x000D_
<th>Individual Score</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Respiratory Rate</td>_x000D_
<td>Doe</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Respiratory Effort</td>_x000D_
<td>Moe</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Oxygon Saturation</td>_x000D_
<td>Dooley</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>
_x000D_
Try changing the value as it fits for you.
Here is another method: using SQL Server Management Studio, in Object Explorer, go to your database and select Tables
Then open the Object Explorer Details (either by pressing F7 or going to View->Object Explorer Details). In the object explorer details page, right click on the column header and enable the columns that you would like to see in the page. You can sort the data by any column too.
Return a tuple:
func getTime() -> (Int, Int, Int) {
...
return ( hour, minute, second)
}
Then it's invoked as:
let (hour, minute, second) = getTime()
or:
let time = getTime()
println("hour: \(time.0)")
numpy.ndarray
can contain any type of element, e.g. int
, float
, string
etc. Check the type an do a conversion if neccessary.
If you want to literally use the method code from A
and B
you can make your C
class contain an instance of each. If you code against interfaces for A
and B
then your clients don't need to know you're giving them a C
rather than an A
or a B
.
interface IA { void SomeMethodOnA(); }
interface IB { void SomeMethodOnB(); }
class A : IA { void SomeMethodOnA() { /* do something */ } }
class B : IB { void SomeMethodOnB() { /* do something */ } }
class C : IA, IB
{
private IA a = new A();
private IB b = new B();
void SomeMethodOnA() { a.SomeMethodOnA(); }
void SomeMethodOnB() { b.SomeMethodOnB(); }
}
I faced the same problem while installing Eclipse for c/c++ applications .I downloaded Mingw GCC ,put its bin folder in your path ,used it in toolchains while making new C++ project in Eclipse and build which solved my problem. Referred to this video
In sonar.properties file in conf folder I had hardcoaded ip of my machine where sobarqube was installed in property sonar.web.host=10.9 235.22 I commented this and it started working for me.
I needed this to check if the view controller is the current viewed controller, I did it via checking if there's any presented view controller or pushed through the navigator, I'm posting it in case anyone needed such a solution:
if presentedViewController != nil || navigationController?.topViewController != self {
//Viewcontroller isn't viewed
}else{
// Now your viewcontroller is being viewed
}
Quite late to this party, today I had the same problem.
The right answer on macOs I think is use jenv
brew install jenv openjdk@11
jenv add /usr/local/opt/openjdk@11
And then add into Intellij IDEA as new SDK the following path:
~/.jenv/versions/11/libexec/openjdk.jdk/Contents/Home/
I can give you an ok solution and you can go with it, but before I do I'm going to try to explain why Document is not a DependencyProperty
to begin with.
During the lifetime of a RichTextBox
control, the Document
property generally doesn't change. The RichTextBox
is initialized with a FlowDocument
. That document is displayed, can be edited and mangled in many ways, but the underlying value of the Document
property remains that one instance of the FlowDocument
. Therefore, there is really no reason it should be a DependencyProperty
, ie, Bindable. If you have multiple locations that reference this FlowDocument
, you only need the reference once. Since it is the same instance everywhere, the changes will be accessible to everyone.
I don't think FlowDocument
supports document change notifications, though I am not sure.
That being said, here's a solution. Before you start, since RichTextBox
doesn't implement INotifyPropertyChanged
and Document is not a DependencyProperty
, we have no notifications when the RichTextBox
's Document property changes, so the binding can only be OneWay.
Create a class that will provide the FlowDocument
. Binding requires the existence of a DependencyProperty
, so this class inherits from DependencyObject
.
class HasDocument : DependencyObject
{
public static readonly DependencyProperty DocumentProperty =
DependencyProperty.Register("Document",
typeof(FlowDocument),
typeof(HasDocument),
new PropertyMetadata(new PropertyChangedCallback(DocumentChanged)));
private static void DocumentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine("Document has changed");
}
public FlowDocument Document
{
get { return GetValue(DocumentProperty) as FlowDocument; }
set { SetValue(DocumentProperty, value); }
}
}
Create a Window
with a rich text box in XAML.
<Window x:Class="samples.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Flow Document Binding" Height="300" Width="300"
>
<Grid>
<RichTextBox Name="richTextBox" />
</Grid>
</Window>
Give the Window
a field of type HasDocument
.
HasDocument hasDocument;
Window constructor should create the binding.
hasDocument = new HasDocument();
InitializeComponent();
Binding b = new Binding("Document");
b.Source = richTextBox;
b.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(hasDocument, HasDocument.DocumentProperty, b);
If you want to be able to declare the binding in XAML, you would have to make your HasDocument
class derive from FrameworkElement
so that it can be inserted into the logical tree.
Now, if you were to change the Document
property on HasDocument
, the rich text box's Document
will also change.
FlowDocument d = new FlowDocument();
Paragraph g = new Paragraph();
Run a = new Run();
a.Text = "I showed this using a binding";
g.Inlines.Add(a);
d.Blocks.Add(g);
hasDocument.Document = d;
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
You can concatenate strings using strcat
. If you plan on concatenating numbers as strings, you must first use num2str
to convert the numbers to strings.
Also, strings can't be stored in a vector or matrix, so f
must be defined as a cell array, and must be indexed using {
and }
(instead of normal round brackets).
f = cell(N, 1);
for i=1:N
f{i} = strcat('f', num2str(i));
end
You can't detect the codepage
This is clearly false. Every web browser has some kind of universal charset detector to deal with pages which have no indication whatsoever of an encoding. Firefox has one. You can download the code and see how it does it. See some documentation here. Basically, it is a heuristic, but one that works really well.
Given a reasonable amount of text, it is even possible to detect the language.
Here's another one I just found using Google:
I always use this:
// Lock form
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
This way you can always resize the form from Designer without changing code.
If you're referring to the concept of accessors, then the simple goal is to hide the underlying storage from arbitrary manipulation. The most extreme mechanism for this is
function Foo(someValue) {
this.getValue = function() { return someValue; }
return this;
}
var myFoo = new Foo(5);
/* We can read someValue through getValue(), but there is no mechanism
* to modify it -- hurrah, we have achieved encapsulation!
*/
myFoo.getValue();
If you're referring to the actual JS getter/setter feature, eg. defineGetter
/defineSetter
, or { get Foo() { /* code */ } }
, then it's worth noting that in most modern engines subsequent usage of those properties will be much much slower than it would otherwise be. eg. compare performance of
var a = { getValue: function(){ return 5; }; }
for (var i = 0; i < 100000; i++)
a.getValue();
vs.
var a = { get value(){ return 5; }; }
for (var i = 0; i < 100000; i++)
a.value;
Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:
myDate : Date;
Handling bytes and unsigned integers with BigInteger:
byte[] b = ... // your integer in big-endian
BigInteger ui = new BigInteger(b) // let BigInteger do the work
int i = ui.intValue() // unsigned value assigned to i
Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.
An example:
"c:\program files\my app\app.exe"
If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:
escapedString = """c:\program files\my app\app.exe"""
How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.
It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.
If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):
"c:\program files\my app\app.exe" "c:\documents and settings\steve"
I would enter this:
escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""
I've helped my sysadmins with some VBScripts that have had even more quotes.
It's not pretty, but that's how it works.
This worked for me:
mysql -u root -p
mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
You might need sudo for the first step:
sudo mysql -u root -p
here you are adding the foreign key for your "Child" table
ALTER TABLE child
ADD FOREIGN KEY (P_Id)
REFERENCES parent(P_Id)
ON DELETE CASCADE
ON UPDATE CASCADE;
After that if you make a DELETE query on "Parent" table like this
DELETE FROM parent WHERE .....
since the child has a reference to parent with DELETE CASCADE, the "Child" rows also will be deleted! along with the "parent".
It depends upon the context. Some possible contexts in HTML:
See OWASP's Cross Site Scripting Prevention Cheat Sheet, especially the "Why Can't I Just HTML Entity Encode Untrusted Data?" and "XSS Prevention Rules" sections. However, it's best to read the whole document.
If you are using XDebug simply use
var_dump($variable);
This will dump the variable like print_r
does - but nicely formatted and in a <pre>
.
(If you don't use XDebug then var_dump
will be as badly formated as print_r
without <pre>
.)
I had to embed my $location.path()
statement like this because my digest was still running:
function routeMe(data) {
var waitForRender = function () {
if ($http.pendingRequests.length > 0) {
$timeout(waitForRender);
} else {
$location.path(data);
}
};
$timeout(waitForRender);
}
Check your .bash_profile
, .zshrc
, or .profile
file. You most likely had a problem during the installation.
You should have the following at the end of one of those files.
[[ -s $HOME/.nvm/nvm.sh ]] && . $HOME/.nvm/nvm.sh # This loads NVM
The . $HOME/.nvm/nvm.sh
is the same as source $HOME/.nvm/nvm.sh
See: Sourcing a File
You can also check to see if you have a .nvm
folder.
ls -a | grep .nvm
If you're missing that folder then the installation failed to run the git command. This could be due to being behind a proxy. Try running the following instead.
git clone http://github.com/creationix/nvm.git .nvm
Visibility : Hidden Vs Collapsed
Consider following code which only shows three Labels
and has second Label
visibility
as Collapsed
:
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Center">
<StackPanel.Resources>
<Style TargetType="Label">
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="0"/>
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="1" />
</Style>
</StackPanel.Resources>
<Label Width="50" Content="First"/>
<Label Width="50" Content="Second" Visibility="Collapsed"/>
<Label Width="50" Content="Third"/>
</StackPanel>
Output Collapsed:
Now change the second Label
visibility
to Hiddden
.
<Label Width="50" Content="Second" Visibility="Hidden"/>
Output Hidden:
As simple as that.
Follow these step your problem will be solved
1- Download .htaccess file from here https://www.dropbox.com/s/tupcu1ctkb8pmmd/.htaccess?dl=0
2- Change the CodeIgnitor directory name on Line #5. like my directory name is abc (add your name)
3- Save .htaccess file on main directory (abc) of your codeignitor folder
4- Change uri_protocol from AUTO to PATH_INFO in Config.php file
Note: First of all you have to enable mod_rewrite from httpd.conf of apachi by removing the comments
As the error says your router link should match the existing routes configured
It should be just routerLink="/about
"
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
In the meantime urllib2 seems to verify server certificates by default. The warning, that was shown in the past disappeared for 2.7.9 and I currently ran into this problem in a test environment with a self signed certificate (and Python 2.7.9).
My evil workaround (don't do this in production!):
import urllib2
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
urllib2.urlopen("https://your-test-server.local", context=ctx)
According to docs calling SSLContext constructor directly should work, too. I haven't tried that.
Just append :after
to your #alertlist li:hover
selector the same way you do with your #alertlist li.selected
selector:
#alertlist li.selected:after, #alertlist li:hover:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}
You have to loop through the entire array, there's no changing that. You can however, do it a little easier
for (Dog dog : list) {
if (dog.getId() == id) {
return dog; //gotcha!
}
}
return null; // dog not found.
or without the new for loop
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId() == id) {
return list.get(i);
}
}
In Ubuntu with php7.3:
sudo apt install php7.3-soap
sudo service apache2 restart
http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
refer the above link for more details on Cross domain resource sharing.
you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.
sample below:
ajax call:
$(document).ready(function () {
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "<your middle man service url here>/GetQuote?callback=?",
data: { symbol: 'ctsh' },
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
});
service (asmx) which will return jsonp:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetQuote(String symbol,string callback)
{
WebProxy myProxy = new WebProxy("<proxy url here>", true);
myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
SQ.Proxy = myProxy;
String result = SQ.GetQuote(symbol);
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(result));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
Here's another option:
import time
from time import gmtime, strftime
d = time.strptime("16 Jun 2010", "%d %b %Y")
print(strftime(d, '%U'))
which prints 24
.
See: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
For windows8
right click my pc properties
then click environment variables
user variable or System variables >> new >> put variable name and path : like this C:\Program Files\nodejs
Then ok
now open cmd and type npm it will work
Check the version of your Compiler.
n= raw_input("Enter your Input: ")
n= input("Enter your Input: ")
You forgot the second set of quotes, which makes the accepted answer incorrect:
$('td[name="tcol1"]')
I think Internal and External Linkage in C++ gives a clear and concise explanation:
A translation unit refers to an implementation (.c/.cpp) file and all header (.h/.hpp) files it includes. If an object or function inside such a translation unit has internal linkage, then that specific symbol is only visible to the linker within that translation unit. If an object or function has external linkage, the linker can also see it when processing other translation units. The static keyword, when used in the global namespace, forces a symbol to have internal linkage. The extern keyword results in a symbol having external linkage.
The compiler defaults the linkage of symbols such that:
Non-const global variables have external linkage by default
Const global variables have internal linkage by default
Functions have external linkage by default
Create a directive and put a watch on it.
app.directive("myApp", function(){
link:function(scope){
function:getTotal(){
..do your maths here
}
scope.$watch('one', getTotals());
scope.$watch('two', getTotals());
}
})
You are using some sort of revision control, right? Then it should be quite simple to restore to the commit before you added the gem, or revert the one where you added it if you have several revisions after that you wish to keep.
As everybody else has already said you need to edit /etc/ssh/sshd_config
and change PasswordAuthentication no
to PasswordAuthentication yes
I ran into this problem setting up a Vagrant box - so therefore it makes sense to script this and do it automatically in a shell provisioner:
sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config;
sudo systemctl restart sshd;
Open the start menu and type cmd
into the search box
Hold Ctrl + Shift
and press Enter
This runs the Command Prompt in Administrator mode.
Now type regsvr32 MyComobject.dll
Don't define the height as a percent, just set the top=0
and bottom=0
, like this:
#div {
top: 0; bottom: 0;
position: absolute;
width: 100%;
}
You need to name the entity that holds the association to User. For example,
... INNER JOIN ug.user u ...
That's the "path" the error message is complaining about -- path from UserGroup to User entity.
Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.
when using jQuery $.ajax()
the response will have the responseJSON
property if the response was JSON, this could be checked like this:
if (xhr.hasOwnProperty('responseJSON')) {}
Although you should have no problem running a 2005 instance of the database engine beside a 2008 instance, The tools are installed into a shared directory, so you can't have two versions of the tools installed. Fortunately, the 2008 tools are backwards-compatible. As we speak, I'm using SSMS 2008 and Profiler 2008 to manage my 2005 Express instances. Works great.
Before installing the 2008 tools, you need to remove any and all "shared" components from 2005. Try going to your Add/Remove programs control panel, find Microsoft SQL Server 2005, and click "Change." Then choose "Workstation Components" and remove everything there (this will not remove your database engine).
I believe the 2008 installer also has an option to upgrade shared components only. You might try that. Good luck!
tools:replace="android:supportsRtl,android:allowBackup,icon,label">
In MVC 3 I had to add:
using System.ComponentModel.DataAnnotations;
among usings when adding properties:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Especially if you are adding these properties in .edmx file like me. I found that by default .edmx files don't have this using so adding only propeties is not enough.
How about:
Random generator = new Random();
int i = 10 - generator.nextInt(10);
I was getting this error when using Laravel and eloquent, trying to make a foreign key link would cause a 1452. The problem was lack of data in the linked table.
Please see here for an example: http://mstd.eu/index.php/2016/12/02/laravel-eloquent-integrity-constraint-violation-1452-foreign-key-constraint/
The error pretty much explains what the problem is: you are trying to include a file that is not there.
Try to use the full path to the file, using realpath()
, and use dirname(__FILE__)
to get your current directory:
require_once(realpath(dirname(__FILE__) . '/../includes/dbconn.inc'));
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
I also have a site that has numerous urls with urlencoded characters. I am finding that many web APIs (including Google webmaster tools and several Drupal modules) trip over urlencoded characters. Many APIs automatically decode urls at some point in their process and then use the result as a URL or HTML. When I find one of these problems, I usually double encode the results (which turns %2f into %252f) for that API. However, this will break other APIs which are not expecting double encoding, so this is not a universal solution.
Personally I am getting rid of as many special characters in my URLs as possible.
Also, I am using id numbers in my URLs which do not depend on urldecoding:
example.com/blog/my-amazing-blog%2fstory/yesterday
becomes:
example.com/blog/12354/my-amazing-blog%2fstory/yesterday
in this case, my code only uses 12354 to look for the article, and the rest of the URL gets ignored by my system (but is still used for SEO.) Also, this number should appear BEFORE the unused URL components. that way, the url will still work, even if the %2f gets decoded incorrectly.
Also, be sure to use canonical tags to ensure that url mistakes don't translate into duplicate content.
Add this to your NodeJS Server below imports:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Like this:
>>> text = 'a,b,c'
>>> text = text.split(',')
>>> text
[ 'a', 'b', 'c' ]
Alternatively, you can use eval()
if you trust the string to be safe:
>>> text = 'a,b,c'
>>> text = eval('[' + text + ']')
Using the MONTH and YEAR functions as suggested in most of the responses has the disadvantage that SQL Server will not be able to use any index there may be on your date column. This can kill performance on a large table.
I would be inclined to pass a DATETIME value (e.g. @StartDate) to the stored procedure which represents the first day of the month you are interested in.
You can then use
SELECT ... FROM ...
WHERE DateColumn >= @StartDate
AND DateColumn < DATEADD(month, 1, @StartDate)
If you must pass the month and year as separate parameters to the stored procedure, you can generate a DATETIME representing the first day of the month using CAST and CONVERT then proceed as above. If you do this I would recommend writing a function that generates a DATETIME from integer year, month, day values, e.g. the following from a SQL Server blog.
create function Date(@Year int, @Month int, @Day int)
returns datetime
as
begin
return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
end
go
The query then becomes:
SELECT ... FROM ...
WHERE DateColumn >= Date(@Year,@Month,1)
AND DateColumn < DATEADD(month, 1, Date(@Year,@Month,1))
You can't do it with just CSS, but you can do it with Javascript, and (optionally) jQuery.
If you want to do it without jQuery:
<script>
window.onload = function() {
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
alert('ho ho ho');
}
}
}
</script>
And to do it without jQuery, and only on a specific class (ex: hohoho
):
<script>
window.onload = function() {
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if(/\bhohoho\b/).match(anchor.className)) {
anchor.onclick = function() {
alert('ho ho ho');
}
}
}
}
</script>
If you are okay with using jQuery, then you can do this for all anchors:
<script>
$(document).ready(function() {
$('a').click(function() {
alert('ho ho ho');
});
});
</script>
And this jQuery snippet to only apply it to anchors with a specific class:
<script>
$(document).ready(function() {
$('a.hohoho').click(function() {
alert('ho ho ho');
});
});
</script>
angular.module('app').directive('conversation', function() {
return {
restrict: 'E',
link: function ($scope, $elm, $attr) {
$scope.$watch("some_prop", function (newValue, oldValue) {
var typeId = $attr.type-id;
// Your logic.
});
}
};
}
Technically, you don't need a framework. If you're making a really really simple site (think of the web back in 1992), you can just do it all with hard-coded HTML and some CSS.
And if you want to make a modern webapp, you don't actually need to use a framework for that, either.
You can instead choose to write all of the logic you need yourself, every time. You can write your own data-persistence/storage layer, or - if you're too busy - just write custom SQL for every single database access. You can write your own authentication and session handling layers. And your own template rending logic. And your own exception-handling logic. And your own security functions. And your own unit test framework to make sure it all works fine. And your own... [goes on for quite a long time]
Then again, if you do use a framework, you'll be able to benefit from the good, usually peer-reviewed and very well tested work of dozens if not hundreds of other developers, who may well be better than you. You'll get to build what you want rapidly, without having to spend time building or worrying too much about the infrastructure items listed above.
You can get more done in less time, and know that the framework code you're using or extending is very likely to be done better than you doing it all yourself.
And the cost of this? Investing some time learning the framework. But - as virtually every web dev out there will attest - it's definitely worth the time spent learning to get massive (really, massive) benefits from using whatever framework you choose.
Added IF/ELSEIF statements to the code from Dave and AmalMurali for handling strings without spaces
if ((strpos($string, ' ') !== false) && (strlen($string) > 200)) {
$WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), ' '));
}
elseif (strlen($string) > 200) {
$WidgetText = substr($string, 0, 200);
}
It's easier than it is thought:
my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation
You can use a single group for seconds/minutes. The following expression may suit your needs:
([0-9]+)\s*(seconds|minutes)
For those looking for an SCSS mixin instead, including woff2:
@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
@font-face {
font-family: $family;
@if $svg == '' {
// with OTF without SVG and EOT
src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
} @else {
// traditional src inclusions
src: url('#{$path}#{$type}.eot');
src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
}
font-weight: $weight;
font-style: $style;
}
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);
$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
font-family: Inter;
font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
font-family: AmaticSC;
font-weight: 700; // default font is loaded
}
The $type
parameter is useful for stacking related families with different weights.
The @if
is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.
If you get a can't resolve error, remember to double check your fonts directory ($dir
).
Unblock multi-line comment
Ctrl+5
Multi-line comment
Ctrl+4
NOTE: For my version of Spyder (3.1.4) if I highlighted the entire multi-line comment and used Ctrl+5 the block remained commented out. Only after highlighting a small portion of the multi-line comment did Ctrl+5 work.
You don't have to do anything special, it should just be working.
When I have a fresh rails app with this controller:
class FooController < ApplicationController
def index
raise "error"
end
end
and go to http://127.0.0.1:3000/foo/
I am seeing the exception with a stack trace.
You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.
See config/initializers/backtrace_silencers.rb
in your Rails project
Now in one-liner flavor:
console.log(['a', 'b', 'c', 'd', 'e', 'f', 'g'].filter(x => !~['b', 'c', 'g'].indexOf(x)))
_x000D_
Might not work on old browsers.
You can use this
moment().format("DD/MM/YYYY");
However, this returns a date string in the specified format for today, not a moment date object. Doing the following will make it a moment date object in the format you want.
var someDateString = moment().format("DD/MM/YYYY");
var someDate = moment(someDateString, "DD/MM/YYYY");
supportActionBar?.title = "Hola tio"
supportActionBar?.subtitle = "Vamos colega!"
Finally I got some answer,
::test::GTEST_FLAG(list_tests) = true;
//From your program, not w.r.t console.
If you would like to use --gtest_filter =*;
/* =*, =xyz*... etc*/
// You need to use them in Console.
So, my requirement is to use them from the program not from the console.
Updated:-
Finally I got the answer for updating the same in from the program.
::testing::GTEST_FLAG(filter) = "*Counter*:*IsPrime*:*ListenersTest.DoesNotLeak*";//":-:*Counter*";
InitGoogleTest(&argc, argv);
RUN_ALL_TEST();
So, Thanks for all the answers.
You people are great.
In swift 4.2 I used following code to show and hide code using NSNotification
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardheight = keyboardSize.height
print(keyboardheight)
}
}
If you want the correlations between all pairs of columns, you could do something like this:
import pandas as pd
import numpy as np
def get_corrs(df):
col_correlations = df.corr()
col_correlations.loc[:, :] = np.tril(col_correlations, k=-1)
cor_pairs = col_correlations.stack()
return cor_pairs.to_dict()
my_corrs = get_corrs(df)
# and the following line to retrieve the single correlation
print(my_corrs[('Citable docs per Capita','Energy Supply per Capita')])
Some people say that operator overloading in Java would lead to obsfuscation. Have those people ever stopped to look at some Java code doing some basic maths like increasing a financial value by a percentage using BigDecimal ? .... the verbosity of such an exercise becomes its own demonstration of obsfuscation. Ironically, adding operator overloading to Java would allow us to create our own Currency class which would make such mathematical code elegant and simple (less obsfuscated).
You're trying to do &(2), &(4)
which won't work
#romtest {
.detailed {
th {
&:nth-child(2) {//your styles here}
&:nth-child(4) {//your styles here}
&:nth-child(6) {//your styles here}
}
}
}
EDIT:
As mentioned in a comment, My answer doesn't account for characters that need to be escaped like a ;
. You should use the accepted answer Darin made if your file name could contain a semi-colon.
Add a Response.AddHeader to set the file name
Response.AddHeader("Content-Disposition", "attachment; filename=*FILE_NAME*");
Just change FILE_NAME to the name of the file.
To read the user input and store it in a variable, for later use, you can use SQL*Plus command ACCEPT
.
Accept <your variable> <variable type if needed [number|char|date]> prompt 'message'
example
accept x number prompt 'Please enter something: '
And then you can use the x
variable in a PL/SQL block as follows:
declare
a number;
begin
a := &x;
end;
/
Working with a string example:
accept x char prompt 'Please enter something: '
declare
a varchar2(10);
begin
a := '&x'; -- for a substitution variable of char data type
end; -- to be treated as a character string it needs
/ -- to be enclosed with single quotation marks
For older versions of jQuery
jQuery().jquery (or)
jQuery().fn.jquery
For newer versions of jQuery
$().jquery (or)
$().fn.jquery
If you (like me) need to remove all the leading zeros from each "word" in a string, you can modify @polygenelubricants' answer to the following:
String s = "003 d0g 00ss 00 0 00";
s.replaceAll("\\b0+(?!\\b)", "");
which results in:
3 d0g ss 0 0 0
Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx
Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\
In the folder path F:\Temp\
, create an Excel 2007 spreadsheet file named States_1.xlsx
with two worksheets.
Sheet 1
of States_1.xlsx contained the following data
Sheet 2
of States_1.xlsx contained the following data
In the folder path F:\Temp\
, create another Excel 2007 spreadsheet file named States_2.xlsx
with two worksheets.
Sheet 1
of States_2.xlsx contained the following data
Sheet 2
of States_2.xlsx contained the following data
Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.
CREATE TABLE [dbo].[Destination](
[Id] [int] IDENTITY(1,1) NOT NULL,
[State] [nvarchar](255) NULL,
[Country] [nvarchar](255) NULL,
[FilePath] [nvarchar](255) NULL,
[SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO
The table is currently empty.
Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx
. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx
of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$
to avoid design time error.
In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.
Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider
under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx
Click on the All
section on the left side and set the property Extended Properties to Excel 12.0
to denote the version of Excel. Here in this case 12.0 denotes Excel 2007
. Click on the Test Connection to make sure that the connection succeeds.
Create an Excel connection manager named Excel as shown below.
Create an OLE DB Connection SQL Server named SQLServer
. So, we should have three connections on the package as shown below.
We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.
On the connection ExcelSchema, configure the expression ServerName
to use the variable FilePath
. Click on the ellipsis button to configure the expression.
Similarly on the connection Excel, configure the expression ServerName
to use the variable FilePath
. Click on the ellipsis button to configure the expression.
On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container
named Loop files will loop through the files. The second Foreach Loop container
will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL
Configure the first Foreach loop container named Loop files as shown below:
Configure the first Foreach loop container named Loop sheets as shown below:
Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:
Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.
Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.
Configure the OLE DB destination to insert the data into the SQL table.
Below screenshot shows successful execution of the package.
Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.
Hope that helps.
Having tested, the solutions posted above by various, including chaos, to hide elements do now work in the latest versions of Firefox (66.0.4), Chrome (74.0.3729.169) and Edge (42.17134.1.0)
$("#edit-field-service-sub-cat-value option[value=" + title + "]").hide();
$("#edit-field-service-sub-cat-value option[value=" + title + "]").show();
For IE, this does not work, however you can disable the option
$("#edit-field-service-sub-cat-value option[value=" + title + "]").attr("disabled", "disabled");
$("#edit-field-service-sub-cat-value option[value=" + title + "]").removeAttr("disabled");
and then force the selection of a different value.
$("#edit-field-service-sub-cat-value").val("0");
Note, for a disabled option, the val of the drop down will now be null, not the value of the selected option if it is disabled.
strikes = [number_map[int(x)] for x in input_str.split()]
Use square brackets to explore dictionaries.
All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.
return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);
You can use Apache Commmons Beanutils. The API is
org.apache.commons.beanutils.PropertyUtilsBean.copyProperties(Object dest, Object orig)
.
It copies property values from the "origin" bean to the "destination" bean for all cases where the property names are the same.
Now I am going to off topic. Using DTO is mostly considered an anti-pattern in EJB3. If your DTO and your domain objects are very alike, there is really no need to duplicate codes. DTO still has merits, especially for saving network bandwidth when remote access is involved. I do not have details about your application architecture, but if the layers you talked about are logical layers and does not cross network, I do not see the need for DTO.
The quoting rules are painful. I think you want:
SELECT nextval('foo."SQ_ID"');
to prevent case-folding of SQ_ID
.
Just as an alternative to the '[ -d ]' and '[ -h ]' options, you can make use of stat
to obtain the file type and parse it.
#! /bin/bash
MY_DIR=$1
NODE_TYPE=$(stat -c '%F' ${MY_DIR} 2>/dev/null)
case "${NODE_TYPE}" in
"directory") echo $MY_DIR;;
"symbolic link") echo $(readlink $MY_DIR);;
"") echo "$MY_DIR does not exist";;
*) echo "$NODE_TYPE is unsupported";;
esac
exit 0
Test data:
$ mkdir tmp
$ ln -s tmp derp
$ touch a.txt
$ ./dir.sh tmp
tmp
$ ./dir.sh derp
tmp
$ ./dir.sh a.txt
regular file is unsupported
$ ./dir.sh god
god does not exist
My way on Windows 8
Add a directory with ssh-keygen to the system PATH variable, usually C:\Program Files (x86)\Git\bin
Open CMD, go to C:\Users\Me\
Generate SSH key ssh-keygen -t rsa
Enter file in which to save the key (//.ssh/id_rsa): .ssh/id_rsa (change a default incorrect path to .ssh/somegoodname_rsa)
Add the key to Heroku heroku keys:add
Select a created key from a list
Go to your app directory, write some beautiful code
Init a git repo git init
git add .
git commit -m 'chore(release): v0.0.1
Create Heroku application heroku create
Deploy your app git push heroku master
Open your app heroku open
All the above answers are proper. The important thing to observe is arrays have length attribute but not length method. Whenever you use strings and arrays in java the three basic models you might face are:
I resolved this by arranging the order in which your JS is being loaded.
You need to have it as jQuery -> datePicker -> Init js
Call your JQuery in your header, datePicker script in head below your jquery and Init JS in footer
I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:
var urlHelper = new UrlHelper(this.ControllerContext);
Or, you could just use the Controller.Url
property if you inherit from Controller
.
Resolved by saving dependent object before the next.
This was happened to me because I was not setting Id (which was not auto generated). and trying to save with relation @ManytoOne
This uses procedural code and a table-valued function. Slow, but easy and predictable.
CREATE FUNCTION [dbo].[Sequence] (@start int, @end int)
RETURNS
@Result TABLE(ID int)
AS
begin
declare @i int;
set @i = @start;
while @i <= @end
begin
insert into @result values (@i);
set @i = @i+1;
end
return;
end
Usage:
SELECT * FROM dbo.Sequence (3,7);
ID
3
4
5
6
7
It's a table, so you can use it in joins with other data. I most frequently use this function as the left side of a join against a GROUP BY hour, day etc to ensure a contiguous sequence of time values.
SELECT DateAdd(hh,ID,'2018-06-20 00:00:00') as HoursInTheDay FROM dbo.Sequence (0,23) ;
HoursInTheDay
2018-06-20 00:00:00.000
2018-06-20 01:00:00.000
2018-06-20 02:00:00.000
2018-06-20 03:00:00.000
2018-06-20 04:00:00.000
(...)
Performance is uninspiring (16 seconds for a million rows) but good enough for many purposes.
SELECT count(1) FROM [dbo].[Sequence] (
1000001
,2000000)
GO
I just wanted to know if the dictionary i was going to try to pull data from had data in it in the first place, this seems to be simplest way.
d = {}
bool(d)
#should return
False
d = {'hello':'world'}
bool(d)
#should return
True
It should be text-align
, not align
If you have a js file that references the jquery, it could be because the js file is in the body and not in the head section (that was my problem). You should move your js file to the head section AFTER the jquery.js reference.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script src="myfile.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
If you are using Carbon (and you should, it's awesome!) with Laravel, you can simply do the following:
->where('created_at', '>=', Carbon::today())
Besides now()
and today()
, you can also use yesterday()
and tomorrow()
and then use the following:
startOfDay()
/endOfDay()
startOfWeek()
/endOfWeek()
startOfMonth()
/endOfMonth()
startOfYear()
/endOfYear()
startOfDecade()
/endOfDecade()
startOfCentury()
/endOfCentury()
To delete all the rows within the table you can use:
db.delete(TABLE_NAME, null, null);
For jquery-ui-dragable with jquery-ui-touch-punch I fixed it similar to Iván Rodríguez, but with one more event override for touchmove:
jQuery.event.special.touchstart = {
setup: function( _, ns, handle ) {
this.addEventListener('touchstart', handle, { passive: !ns.includes('noPreventDefault') });
}
};
jQuery.event.special.touchmove = {
setup: function( _, ns, handle ) {
this.addEventListener('touchmove', handle, { passive: !ns.includes('noPreventDefault') });
}
};
Or no float conversion at all by just specifying floats in the list.
l = [-1.2, 0.0, 1]
x = min(l)
or
l = min([-1.2, 0.0, 1])
Try to see if the following code helps you:
Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)
This seems like that the servlet api version which you using is older than the xsd you are using in web.xml eg 3.0
use this one ****http://java.sun.com/xml/ns/javaee/" id="WebApp_ID" version="2.5"> ****
- (void) viewDidLayoutSubviews {
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
self.edgesForExtendedLayout = UIRectEdgeNone; // iOS 7 specific
CGRect viewBounds = self.view.bounds;
CGFloat topBarOffset = self.topLayoutGuide.length;
viewBounds.origin.y = topBarOffset * -1;
self.view.bounds = viewBounds;
self.navigationController.navigationBar.translucent = NO;
}
}
IDENTITY(int, 1, 1) should do it if you are doing a select into. In SQL 2000, I use to just put the results in a temp table and query that afterwords.
Write the root logger as below for logging on both console and FILE
log4j.rootLogger=ERROR,console,FILE
And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).
hmm - something like this?
set host=%COMPUTERNAME%
echo %host%
EDIT: expanding on jitter's answer and using a technique in an answer to this question to set an environment variable with the result of running a command line app:
@echo off
hostname.exe > __t.tmp
set /p host=<__t.tmp
del __t.tmp
echo %host%
In either case, 'host' is created as an environment variable.
The new Intersection Observer API addresses this question very directly.
This solution will need a polyfill as Safari, Opera and Internet Explorer don't support this yet (the polyfill is included in the solution).
In this solution, there is a box out of view that is the target (observed). When it comes into view, the button at the top in the header is hidden. It is shown once the box leaves the view.
const buttonToHide = document.querySelector('button');_x000D_
_x000D_
const hideWhenBoxInView = new IntersectionObserver((entries) => {_x000D_
if (entries[0].intersectionRatio <= 0) { // If not in view_x000D_
buttonToHide.style.display = "inherit";_x000D_
} else {_x000D_
buttonToHide.style.display = "none";_x000D_
}_x000D_
});_x000D_
_x000D_
hideWhenBoxInView.observe(document.getElementById('box'));
_x000D_
header {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
width: 100vw;_x000D_
height: 30px;_x000D_
background-color: lightgreen;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
position: relative;_x000D_
margin-top: 600px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
position: relative;_x000D_
left: 175px;_x000D_
width: 150px;_x000D_
height: 135px;_x000D_
background-color: lightblue;_x000D_
border: 2px solid;_x000D_
}
_x000D_
<script src="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>_x000D_
<header>_x000D_
<button>NAVIGATION BUTTON TO HIDE</button>_x000D_
</header>_x000D_
<div class="wrapper">_x000D_
<div id="box">_x000D_
</div>_x000D_
</div>
_x000D_
using flask library in Python you can achieve that. remember to store your HTML page to a folder named "templates" inside where you are running your python script.
so your folder would look like
this is a small example of your python script. This simply checks for plagiarism.
from flask import Flask
from flask import request
from flask import render_template
import stringComparison
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template("my-form.html") # this should be the name of your html file
@app.route('/', methods=['POST'])
def my_form_post():
text1 = request.form['text1']
text2 = request.form['text2']
plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
if plagiarismPercent > 50 :
return "<h1>Plagiarism Detected !</h1>"
else :
return "<h1>No Plagiarism Detected !</h1>"
if __name__ == '__main__':
app.run()
This a small template of HTML file that is used
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Enter the texts to be compared</h1>
<form action="." method="POST">
<input type="text" name="text1">
<input type="text" name="text2">
<input type="submit" name="my-form" value="Check !">
</form>
</body>
</html>
This is a small little way through which you can achieve a simple task of comparing two string and which can be easily changed to suit your requirements
Since Facebook's Android SDK v4.0 you need to execute the following:
LoginManager.getInstance().logOut();
This is not sufficient. This will simply clear cached access token and profile so that AccessToken.getCurrentAccessToken()
and Profile.getCurrentProfile()
will now become null.
To completely logout you need to revoke permissions and then call LoginManager.getInstance().logOut();
. To revoke permission execute following graph API -
GraphRequest delPermRequest = new GraphRequest(AccessToken.getCurrentAccessToken(), "/{user-id}/permissions/", null, HttpMethod.DELETE, new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse graphResponse) {
if(graphResponse!=null){
FacebookRequestError error =graphResponse.getError();
if(error!=null){
Log.e(TAG, error.toString());
}else {
finish();
}
}
}
});
Log.d(TAG,"Executing revoke permissions with graph path" + delPermRequest.getGraphPath());
delPermRequest.executeAsync();
If you can't use an HTML parser oriented solution to filter out the tags, here's a simple regex for it.
string noHTML = Regex.Replace(inputHTML, @"<[^>]+>| ", "").Trim();
You should ideally make another pass through a regex filter that takes care of multiple spaces as
string noHTMLNormalised = Regex.Replace(noHTML, @"\s{2,}", " ");
Try this:
Dim strFile As String = "yourfile.txt"
Dim fileExists As Boolean = File.Exists(strFile)
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw.WriteLine( _
IIf(fileExists, _
"Error Message in Occured at-- " & DateTime.Now, _
"Start Error Log for today"))
End Using
If you're using Ramda, you can use the function "once".
A quote from the documentation:
once Function (a… ? b) ? (a… ? b) PARAMETERS Added in v0.1.0
Accepts a function fn and returns a function that guards invocation of fn such that fn can only ever be called once, no matter how many times the returned function is invoked. The first value calculated is returned in subsequent invocations.
var addOneOnce = R.once(x => x + 1);
addOneOnce(10); //=> 11
addOneOnce(addOneOnce(50)); //=> 11
Implicit wait --
Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. So in this case, you are telling WebDriver that it should wait 10 seconds in cases of specified element not available on the UI (DOM).
Explicit wait--
Explicit waits are intelligent waits that are confined to a particular web element. Using explicit waits you are basically telling WebDriver at the max it is to wait for X units of time before it gives up.
It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.
You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.
All of the current answers are addressing the symptom (shared memory pool exhaustion), and not the problem, which is likely not using bind variables in your sql \ JDBC queries, even when it does not seem necessary to do so. Passing queries without bind variables causes Oracle to "hard parse" the query each time, determining its plan of execution, etc.
https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:528893984337
Some snippets from the above link:
"Java supports bind variables, your developers must start using prepared statements and bind inputs into it. If you want your system to ultimately scale beyond say about 3 or 4 users -- you will do this right now (fix the code). It is not something to think about, it is something you MUST do. A side effect of this - your shared pool problems will pretty much disappear. That is the root cause. "
"The way the Oracle shared pool (a very important shared memory data structure) operates is predicated on developers using bind variables."
" Bind variables are SO MASSIVELY important -- I cannot in any way shape or form OVERSTATE their importance. "
In my case, I had to change the cell padding of an element that contained an input checkbox for a table that's being dynamically rendered with DataTables:
<td class="dt-center">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
After implementing the following line code within the initComplete function I was able to produce the correct padding, which fixed the rows from being displayed with an abnormally large height
$('tbody td:has(input.a)').css('padding', '0px');
Now, you can see that the correct styles are being applied to the parent element:
<td class=" dt-center" style="padding: 0px;">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
Essentially, this answer is an extension of @KP's answer, but the more collaboration of implementing this the better. In summation, I hope this helps someone else because it works! Lastly, thank you so much @KP for leading me in the right direction!
Nobody seems to be explaining the difference between an array and an object.
[]
is declaring an array.
{}
is declaring an object.
An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === "object"
to further show you that an array is an object.
The additional features consist of a magic .length
property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as .push()
, .pop()
, .slice()
, .splice()
, etc... You can see a list of array methods here.
An object gives you the ability to associate a property name with a value as in:
var x = {};
x.foo = 3;
x["whatever"] = 10;
console.log(x.foo); // shows 3
console.log(x.whatever); // shows 10
Object properties can be accessed either via the x.foo
syntax or via the array-like syntax x["foo"]
. The advantage of the latter syntax is that you can use a variable as the property name like x[myvar]
and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the x.foo
syntax.
A property name can be any string value.
An array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an ordered, sequential list of numbered indexes starting from 0
and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list .sort()
or to add or remove things from the list.
Use apt to uninstall and remove all MySQL packages:
$ sudo apt-get remove --purge mysql-server mysql-client mysql-common -y
$ sudo apt-get autoremove -y
$ sudo apt-get autoclean
Remove the MySQL folder:
$ rm -rf /etc/mysql
Delete all MySQL files on your server:
$ sudo find / -iname 'mysql*' -exec rm -rf {} \;
Your system should no longer contain default MySQL related files.
I've made a Python function where you enter the table and column to remove as arguments:
def removeColumn(table, column):
columns = []
for row in c.execute('PRAGMA table_info(' + table + ')'):
columns.append(row[1])
columns.remove(column)
columns = str(columns)
columns = columns.replace("[", "(")
columns = columns.replace("]", ")")
for i in ["\'", "(", ")"]:
columns = columns.replace(i, "")
c.execute('CREATE TABLE temptable AS SELECT ' + columns + ' FROM ' + table)
c.execute('DROP TABLE ' + table)
c.execute('ALTER TABLE temptable RENAME TO ' + table)
conn.commit()
As per the info on Duda's and MeBigFatGuy's answers this won't work if there is a foreign key on the table, but this can be fixed with 2 lines of code (creating a new table and not just renaming the temporary table)
I can give an example commonly seen in project.
Here, option --no-ff
(i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff
(i.e. fast-forward merge) is by default.
$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature' // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk // => see details with graph
$ git checkout -b anotherFeature // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk // => see details with graph
(*) Note that here if the newFeature
branch is re-used, instead of creating a new branch, git will have to do a --no-ff
merge anyway. This means fast forward merge is not always eligible.
The command is this:
mysqlcheck -u root -p --auto-repair --check --all-databases
You must supply the password when asked,
or you can run this one but it's not recommended because the password is written in clear text:
mysqlcheck -u root --password=THEPASSWORD --auto-repair --check --all-databases
You should put the form inside each node and use ng-show
and ng-hide
to enable and disable editing, respectively. Something like this:
<li>
<span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span>
<form ng-show="editing" ng-submit="editing = false">
<label>Name:</label>
<input type="text" ng-model="bday.name" placeholder="Name" ng-required/>
<label>Date:</label>
<input type="date" ng-model="bday.date" placeholder="Date" ng-required/>
<br/>
<button class="btn" type="submit">Save</button>
</form>
</li>
The key points here are:
ng-model
to the local scopeng-show
to form
so we can show it while editingspan
with a ng-hide
to hide the content while editingng-click
, that could be in any other element, that toggles editing
to true
ng-submit
to toggle editing
to false
Here is your updated Plunker.
I might be very late but encoutered this problem sometime before and saw this link. Thanks . Please check this shall work.
Goto Create menu -> Section--> Copy email to be inserted
Validate it against FedEx's api. They have an API to generate labels from XML code. The process involves a step to validate the address.
I just replaced and assigned attributes for su to ~/Android/Sdk/system-images/android-22/google_apis/x86/system.img and now on android 5 I always have root even for new systems, it’s enough to install SuperSu.apk
Android 6 is necessary only
adb root
adb shell
>/system/xbin/su --daemon &
>setenfoce 0
after that, SuperSu.apk sees root. But I do not update the binary file
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
//import fremework in .h file
#import <AVFoundation/AVFoundation.h>
{
AVCaptureSession *torchSession;
}
@property(nonatomic,retain)AVCaptureSession *torchSession;
-(IBAction)onoff:(id)sender;
//implement in .m file
@synthesize torchSession;
-(IBAction)onoff:(id)sender
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash])
{
if (device.torchMode == AVCaptureTorchModeOff)
{
[button setTitle:@"OFF" forState:UIControlStateNormal];
AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
AVCaptureSession *session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
[session addInput:flashInput];
[session addOutput:output];
[device unlockForConfiguration];
[output release];
[session commitConfiguration];
[session startRunning];
[self setTorchSession:session];
[session release];
}
else
{
[button setTitle:@"ON" forState:UIControlStateNormal];
[torchSession stopRunning];
}
}
}
- (void)dealloc
{
[torchSession release];
[super dealloc];
}
For Windows Machine :-
Run the below command to Expose docker port randomly during build time
$docker run -d --name MyWebServer -P mediawiki
In the above container list you can see the port assigned as 32768. Try accessing
localhost:32768
You can see the mediawiki page
After git commit
command, you entered to the editor, so first hit i
then start typing. After committing your message hit Ctrl + c
then :wq
(IE9+, FF, Webkit)
Using MutationObserver and falling back to the deprecated Mutation events if needed:
(Example below if only for DOM changes concerning nodes appended or removed)
var observeDOM = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
return function( obj, callback ){
if( !obj || obj.nodeType !== 1 ) return;
if( MutationObserver ){
// define a new observer
var mutationObserver = new MutationObserver(callback)
// have the observer observe foo for changes in children
mutationObserver.observe( obj, { childList:true, subtree:true })
return mutationObserver
}
// browser support fallback
else if( window.addEventListener ){
obj.addEventListener('DOMNodeInserted', callback, false)
obj.addEventListener('DOMNodeRemoved', callback, false)
}
}
})()
//------------< DEMO BELOW >----------------
// add item
var itemHTML = "<li><button>list item (click to delete)</button></li>",
listElm = document.querySelector('ol');
document.querySelector('body > button').onclick = function(e){
listElm.insertAdjacentHTML("beforeend", itemHTML);
}
// delete item
listElm.onclick = function(e){
if( e.target.nodeName == "BUTTON" )
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
}
// Observe a specific DOM element:
observeDOM( listElm, function(m){
var addedNodes = [], removedNodes = [];
m.forEach(record => record.addedNodes.length & addedNodes.push(...record.addedNodes))
m.forEach(record => record.removedNodes.length & removedNodes.push(...record.removedNodes))
console.clear();
console.log('Added:', addedNodes, 'Removed:', removedNodes);
});
// Insert 3 DOM nodes at once after 3 seconds
setTimeout(function(){
listElm.removeChild(listElm.lastElementChild);
listElm.insertAdjacentHTML("beforeend", Array(4).join(itemHTML));
}, 3000);
_x000D_
<button>Add Item</button>
<ol>
<li><button>list item (click to delete)</button></li>
<li><button>list item (click to delete)</button></li>
<li><button>list item (click to delete)</button></li>
<li><button>list item (click to delete)</button></li>
<li><em>…More will be added after 3 seconds…</em></li>
</ol>
_x000D_
If you normalize your data first, then you can avoid all the very complex regular expressions required to validate phone numbers. From my experience, complicated regex patterns can have two unwanted side effects: (1) they can have unexpected behavior that would be a pain to debug later, and (2) they can be slower than simpler regex patterns, which may become noticeable when you are executing regex in a loop.
By keeping your regular expressions as simple as possible, you reduce these risks and your code will be easier for others to follow, partly because it will be more predictable. To use your phone number example, first we can normalize the value by stripping out all non-digits like this:
value = $.trim(value).replace(/\D/g, '');
Now your regex pattern for a US phone number (or any other locale) can be much simpler:
/^1?\d{10}$/
Not only is the regular expression much simpler, it is also easier to follow what's going on: a value optionally leading with number one (US country code) followed by ten digits. If you want to format the validated value to make it look pretty, then you can use this slightly longer regex pattern:
/^1?(\d{3})(\d{3})(\d{4})$/
This means an optional leading number one followed by three digits, another three digits, and ending with four digits. With each group of numbers memorized, you can output it any way you want. Here's a codepen using jQuery Validation to illustrate this for two locales (Singapore and US):
A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.
The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.
For anaconda for python 3.5, I needed to install ncurses
conda install ncurses
After the ncurses
install tab complete, history, and navigating via left and right arrows worked in the interactive shell.
I would suggest, one should not make object of an Activity type class.
MainActivity mActivity = new MainActivity(); // BIG NO TO THIS.
All Activities in Android must go through the Activity lifecycle so that they have a valid context attached to them.
By treating an Activity as a normal Java class, you end up with a null context. As most methods in an Activity are called on its Context, you will get a null pointer exception, which is why your app crashes.
Instead, move all such methods which need to be called from other classes into a Utility class which accepts a valid context in its constructor, and then use that context in the methods to do the work.
I faced the same problem and seems that there have been many changes by google.
I can tell you the steps for installing purely via command line from scratch. I tested it on Ubuntu on 22 Feb 2021.
export ANDROID_SDK_ROOT=/usr/lib/android-sdk
sudo mkdir -p $ANDROID_SDK_ROOT
sudo apt-get install openjdk-8-jdk
Go to https://developer.android.com/studio/index.html Then down to Command line tools only Click on Linux link, accept the agreement and instead of downloading right click and copy link address
cd $ANDROID_SDK_ROOT
sudo wget https://dl.google.com/android/repository/commandlinetools-linux-6858069_latest.zip
sudo unzip commandlinetools-linux-6858069_latest.zip
Rename the unpacked directory from cmdline-tools to tools, and place it under $ANDROID_SDK_ROOT/cmdline-tools, so now it should look like: $ANDROID_SDK_ROOT/cmdline-tools/tools. And inside it, you should have: NOTICE.txt bin lib source.properties.
PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin
This had no effect for me, hence the next step
cd $ANDROID_SDK_ROOT/cmdline-tools/tools/bin
yes | sudo sdkmanager --licenses
Finally, run this inside your project
sudo ./gradlew assembleDebug
This creates an APK named -debug.apk at //build/outputs/apk/debug The file is already signed with the debug key and aligned with zipalign, so you can immediately install it on a device.
https://gist.github.com/guipmourao/3e7edc951b043f6de30ca15a5cc2be40
Android Command line tools sdkmanager always shows: Warning: Could not create settings
"Failed to install the following Android SDK packages as some licences have not been accepted" error
https://developer.android.com/studio/build/building-cmdline#sign_cmdline
Addition: SQL Server 2012 shows some improved performance in this area but doesn't seem to tackle the specific issues noted below. This should apparently be fixed in the next major version after SQL Server 2012!
Your plan shows the single inserts are using parameterised procedures (possibly auto parameterised) so parse/compile time for these should be minimal.
I thought I'd look into this a bit more though so set up a loop (script) and tried adjusting the number of VALUES
clauses and recording the compile time.
I then divided the compile time by the number of rows to get the average compile time per clause. The results are below
Up until 250 VALUES
clauses present the compile time / number of clauses has a slight upward trend but nothing too dramatic.
But then there is a sudden change.
That section of the data is shown below.
+------+----------------+-------------+---------------+---------------+
| Rows | CachedPlanSize | CompileTime | CompileMemory | Duration/Rows |
+------+----------------+-------------+---------------+---------------+
| 245 | 528 | 41 | 2400 | 0.167346939 |
| 246 | 528 | 40 | 2416 | 0.162601626 |
| 247 | 528 | 38 | 2416 | 0.153846154 |
| 248 | 528 | 39 | 2432 | 0.157258065 |
| 249 | 528 | 39 | 2432 | 0.156626506 |
| 250 | 528 | 40 | 2448 | 0.16 |
| 251 | 400 | 273 | 3488 | 1.087649402 |
| 252 | 400 | 274 | 3496 | 1.087301587 |
| 253 | 400 | 282 | 3520 | 1.114624506 |
| 254 | 408 | 279 | 3544 | 1.098425197 |
| 255 | 408 | 290 | 3552 | 1.137254902 |
+------+----------------+-------------+---------------+---------------+
The cached plan size which had been growing linearly suddenly drops but CompileTime increases 7 fold and CompileMemory shoots up. This is the cut off point between the plan being an auto parametrized one (with 1,000 parameters) to a non parametrized one. Thereafter it seems to get linearly less efficient (in terms of number of value clauses processed in a given time).
Not sure why this should be. Presumably when it is compiling a plan for specific literal values it must perform some activity that does not scale linearly (such as sorting).
It doesn't seem to affect the size of the cached query plan when I tried a query consisting entirely of duplicate rows and neither affects the order of the output of the table of the constants (and as you are inserting into a heap time spent sorting would be pointless anyway even if it did).
Moreover if a clustered index is added to the table the plan still shows an explicit sort step so it doesn't seem to be sorting at compile time to avoid a sort at run time.
I tried to look at this in a debugger but the public symbols for my version of SQL Server 2008 don't seem to be available so instead I had to look at the equivalent UNION ALL
construction in SQL Server 2005.
A typical stack trace is below
sqlservr.exe!FastDBCSToUnicode() + 0xac bytes
sqlservr.exe!nls_sqlhilo() + 0x35 bytes
sqlservr.exe!CXVariant::CmpCompareStr() + 0x2b bytes
sqlservr.exe!CXVariantPerformCompare<167,167>::Compare() + 0x18 bytes
sqlservr.exe!CXVariant::CmpCompare() + 0x11f67d bytes
sqlservr.exe!CConstraintItvl::PcnstrItvlUnion() + 0xe2 bytes
sqlservr.exe!CConstraintProp::PcnstrUnion() + 0x35e bytes
sqlservr.exe!CLogOp_BaseSetOp::PcnstrDerive() + 0x11a bytes
sqlservr.exe!CLogOpArg::PcnstrDeriveHandler() + 0x18f bytes
sqlservr.exe!CLogOpArg::DeriveGroupProperties() + 0xa9 bytes
sqlservr.exe!COpArg::DeriveNormalizedGroupProperties() + 0x40 bytes
sqlservr.exe!COptExpr::DeriveGroupProperties() + 0x18a bytes
sqlservr.exe!COptExpr::DeriveGroupProperties() + 0x146 bytes
sqlservr.exe!COptExpr::DeriveGroupProperties() + 0x146 bytes
sqlservr.exe!COptExpr::DeriveGroupProperties() + 0x146 bytes
sqlservr.exe!CQuery::PqoBuild() + 0x3cb bytes
sqlservr.exe!CStmtQuery::InitQuery() + 0x167 bytes
sqlservr.exe!CStmtDML::InitNormal() + 0xf0 bytes
sqlservr.exe!CStmtDML::Init() + 0x1b bytes
sqlservr.exe!CCompPlan::FCompileStep() + 0x176 bytes
sqlservr.exe!CSQLSource::FCompile() + 0x741 bytes
sqlservr.exe!CSQLSource::FCompWrapper() + 0x922be bytes
sqlservr.exe!CSQLSource::Transform() + 0x120431 bytes
sqlservr.exe!CSQLSource::Compile() + 0x2ff bytes
So going off the names in the stack trace it appears to spend a lot of time comparing strings.
This KB article indicates that DeriveNormalizedGroupProperties
is associated with what used to be called the normalization stage of query processing
This stage is now called binding or algebrizing and it takes the expression parse tree output from the previous parse stage and outputs an algebrized expression tree (query processor tree) to go forward to optimization (trivial plan optimization in this case) [ref].
I tried one more experiment (Script) which was to re-run the original test but looking at three different cases.
It can clearly be seen that the longer the strings the worse things get and that conversely the more duplicates the better things get. As previously mentioned duplicates don't affect the cached plan size so I presume that there must be a process of duplicate identification when constructing the algebrized expression tree itself.
Edit
One place where this information is leveraged is shown by @Lieven here
SELECT *
FROM (VALUES ('Lieven1', 1),
('Lieven2', 2),
('Lieven3', 3))Test (name, ID)
ORDER BY name, 1/ (ID - ID)
Because at compile time it can determine that the Name
column has no duplicates it skips ordering by the secondary 1/ (ID - ID)
expression at run time (the sort in the plan only has one ORDER BY
column) and no divide by zero error is raised. If duplicates are added to the table then the sort operator shows two order by columns and the expected error is raised.
Or you can simply update without using join like this:
Update t1 set t1.Description = t2.Description from @tbl2 t2,tbl1 t1
where t1.ID= t2.ID
Here's a custom theme to make the ggplot2 background white and a bunch of other changes that's good for publications and posters. Just tack on +mytheme. If you want to add or change options by +theme after +mytheme, it will just replace those options from +mytheme.
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())
mytheme = list(
theme_classic()+
theme(panel.background = element_blank(),strip.background = element_rect(colour=NA, fill=NA),panel.border = element_rect(fill = NA, color = "black"),
legend.title = element_blank(),legend.position="bottom", strip.text = element_text(face="bold", size=9),
axis.text=element_text(face="bold"),axis.title = element_text(face="bold"),plot.title = element_text(face = "bold", hjust = 0.5,size=13))
)
ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + mytheme + geom_line()
Typically, git commit
brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR
environment variable) for you to edit your commit message in. When you save and exit, the commit completes.
You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.
For this (and most plotting) I would not rely on the Pandas wrappers to matplotlib. Instead, just use matplotlib directly:
import matplotlib.pyplot as plt
plt.scatter(df['col_name_1'], df['col_name_2'])
plt.show() # Depending on whether you use IPython or interactive mode, etc.
and remember that you can access a NumPy array of the column's values with df.col_name_1.values
for example.
I ran into trouble using this with Pandas default plotting in the case of a column of Timestamp values with millisecond precision. In trying to convert the objects to datetime64
type, I also discovered a nasty issue: < Pandas gives incorrect result when asking if Timestamp column values have attr astype >.
@Test
public void testSearchManagementStaff() throws SQLException
{
boolean res=true;
ManagementDaoImp mdi=new ManagementDaoImp();
boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
assertEquals(res,b);
}
You can also have a look at FLTK (C++ and not plain C though)
FLTK (pronounced "fulltick") is a cross-platform C++ GUI toolkit for UNIX®/Linux® (X11), Microsoft® Windows®, and MacOS® X. FLTK provides modern GUI functionality without the bloat and supports 3D graphics via OpenGL® and its built-in GLUT emulation.
FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.
Here are some quickstart screencasts
[Happy New Year!]
pout can pretty print anything you throw at it, for example (borrowing data
from another answer):
data = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
pout.vs(data)
would result in output printed to the screen like:
{
'a': 2,
'b':
{
'y':
{
't2': 5,
't1': 4
},
'x': 3
}
}
or you can return the formatted string output of your object:
v = pout.s(data)
Its primary use case is for debugging so it doesn't choke on object instances or anything and it handles unicode output as you would expect, works in python 2.7 and 3.
disclosure: I'm the author and maintainer of pout.
You will not be able to do that. You can download apps again to the same userid account on different devices, but you cannot transfer those licenses to other userids.
There is no way to do this programatically - I don't think you can do that practically (except for trying to call customer support at the Play Store).
Well, if you are using Dojo Toolkit, it gives us a direct way to encode or decode into Base64.
Try this:
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a Base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:
ModelStateException
that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters)HandleModelStateExceptionAttribute
that catches custom exception and returns HTTP error status with model state error in the bodyThis provides the optimal infrastructure for jQuery Ajax calls to use their full potential with success
and error
handlers.
$.ajax({
type: "POST",
url: "some/url",
success: function(data, status, xhr) {
// handle success
},
error: function(xhr, status, error) {
// handle error
}
});
[HandleModelStateException]
public ActionResult Create(User user)
{
if (!this.ModelState.IsValid)
{
throw new ModelStateException(this.ModelState);
}
// create new user because validation was successful
}
The whole problem is detailed in this blog post where you can find all the code to run this in your application.
use this code
SELECT *
FROM paypal_ipn_orders
GROUP BY payer_email
HAVING COUNT( payer_email) >1
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
This worked for me.
$ echo 54657374696e672031203220330 | xxd -r -p
Testing 1 2 3$
-r
tells it to convert hex to ascii as opposed to its normal mode of doing the opposite
-p
tells it to use a plain format.
Two things you can do:
git checkout -b sillyname
git commit -am "silly message"
git checkout -
or
git stash -u
git branch sillyname stash@{0}
(git checkout -
<-- the dash is a shortcut for the previous branch you were on )
(git stash -u
<-- the -u
means that it also takes unstaged changes )
Not wanting to edit my git config file I followed the info in @mipadi's post and used:
$ git pull origin master
How do I rename a specific column in pandas?
From v0.24+, to rename one (or more) columns at a time,
DataFrame.rename()
with axis=1
or axis='columns'
(the axis
argument was introduced in v0.21
.
Index.str.replace()
for string/regex based replacement.
If you need to rename ALL columns at once,
DataFrame.set_axis()
method with axis=1
. Pass a list-like sequence. Options are available for in-place modification as well.rename
with axis=1
df = pd.DataFrame('x', columns=['y', 'gdp', 'cap'], index=range(5))
df
y gdp cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
With 0.21+, you can now specify an axis
parameter with rename
:
df.rename({'gdp':'log(gdp)'}, axis=1)
# df.rename({'gdp':'log(gdp)'}, axis='columns')
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
(Note that rename
is not in-place by default, so you will need to assign the result back.)
This addition has been made to improve consistency with the rest of the API. The new axis
argument is analogous to the columns
parameter—they do the same thing.
df.rename(columns={'gdp': 'log(gdp)'})
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
rename
also accepts a callback that is called once for each column.
df.rename(lambda x: x[0], axis=1)
# df.rename(lambda x: x[0], axis='columns')
y g c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
For this specific scenario, you would want to use
df.rename(lambda x: 'log(gdp)' if x == 'gdp' else x, axis=1)
Index.str.replace
Similar to replace
method of strings in python, pandas Index and Series (object dtype only) define a ("vectorized") str.replace
method for string and regex-based replacement.
df.columns = df.columns.str.replace('gdp', 'log(gdp)')
df
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
The advantage of this over the other methods is that str.replace
supports regex (enabled by default). See the docs for more information.
set_axis
with axis=1
Call set_axis
with a list of header(s). The list must be equal in length to the columns/index size. set_axis
mutates the original DataFrame by default, but you can specify inplace=False
to return a modified copy.
df.set_axis(['cap', 'log(gdp)', 'y'], axis=1, inplace=False)
# df.set_axis(['cap', 'log(gdp)', 'y'], axis='columns', inplace=False)
cap log(gdp) y
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
Note: In future releases, inplace
will default to True
.
Method Chaining
Why choose set_axis
when we already have an efficient way of assigning columns with df.columns = ...
? As shown by Ted Petrou in this answer set_axis
is useful when trying to chain methods.
Compare
# new for pandas 0.21+
df.some_method1()
.some_method2()
.set_axis()
.some_method3()
Versus
# old way
df1 = df.some_method1()
.some_method2()
df1.columns = columns
df1.some_method3()
The former is more natural and free flowing syntax.
click()
to the QMainWindow custom slot you have created).Code example:
MainWindow.h
// ...
include "newwindow.h"
// ...
public slots:
void openNewWindow();
// ...
private:
NewWindow *mMyNewWindow;
// ...
}
MainWindow.cpp
// ...
MainWindow::MainWindow()
{
// ...
connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
// ...
}
// ...
void MainWindow::openNewWindow()
{
mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
mMyNewWindow->show();
// ...
}
This is an example on how display a custom new window. There are a lot of ways to do this.
Is there a way to find how many values an array has?
Yes!
Try sizeof(array)/sizeof(array[0])
Detecting whether or not I've reached the end of an array would also work.
I dont see any way for this unless your array is an array of characters (i.e string).
P.S : In C++ always use std::vector
. There are several inbuilt functions and an extended functionality.
Avoid loops. What you want to do is:
import numpy as np
data=np.loadtxt(fname="data.txt")## to load the above two column
print data
print data.sum(axis=1)
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};
printMatrix(matrix);
public void printMatrix(int[][] m){
try{
int rows = m.length;
int columns = m[0].length;
String str = "|\t";
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
str += m[i][j] + "\t";
}
System.out.println(str + "|");
str = "|\t";
}
}catch(Exception e){System.out.println("Matrix is empty!!");}
}
Output:
| 1 2 3 |
| 4 5 6 |
| 7 8 9 |
| 10 11 12 |
If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure
I had the same issue, and the following syntax worked for me:
df.filter(df("state")==="TX").show()
I'm using Spark 1.6.
Try negation operator !
before $(this)
:
if (!$(this).parent().next().is('ul')){
select * from table_name
where (date between DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), interval 30 day), interval 1 day) AND CURDATE() )
Or better :
select * from table_name
where (date between DATE_FORMAT(NOW() ,'%Y-%m-01') AND NOW() )
Then you'd want to do this instead:
print str(int(1.0/3.0*100))+'%'
The .0
denotes them as floats and int()
rounds them to integers afterwards again.
The path is in the registry but usually you edit through this interface:
Control Panel
-> System
-> System settings
-> Environment Variables
.PATH
.c:\path;c:\path2
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
In the Visual Studio Shift+Alt+. / Shift+Alt+,
Shift+Alt+.
- match caret;Shift+Alt+,
- remove previous caret; Same function as on VSCode Ctrl+D
.
Much more setting Tool - Options - Environment - keyboard
. Next in the Show commands containing
enter Edit.
.
Also, can use keyboard schema Visual Studio Code
. Available for Visual Studio 2017
For conclusion, nice link Visual Studio All keyboard shortcuts
You can use environment variables in your app.config
for that scenario you describe
<configuration>
<appSettings>
<add key="Dir1" value="%MyBaseDir%\Dir1"/>
</appSettings>
</configuration>
Then you can easily get the path with:
var pathFromConfig = ConfigurationManager.AppSettings["Dir1"];
var expandedPath = Environment.ExpandEnvironmentVariables(pathFromConfig);