There's absolutely no need to install qemu-kvm
(and all its dependencies) if you only want to run the Android Studio Emulator.
The only thing you have to do is to give your user (i.e. the one you are logged in with) the right to access the /dev/kvm
-device.
This is done in three simple steps.
First:Create the kvm
-group
groupadd -r kvm
The option -r
creates a system group, i.e. with a GID <= 999 (see /etc/login.defs
=> SYS_GID_MAX
)
Change permissions on /dev/kvm
. This could be done as part of the qemu-kvm
-installation, because one of the dependencies is installing qemu-system-common
(on current Ubuntu systems, package name may vary), which in turn installs the file /lib/udev/rules.d/60-qemu-system-common.rules
containing the following:
KERNEL=="kvm", GROUP="kvm", MODE="0660"
So if you are just create a file /etc/udev/rules.d/60-qemu-permissions.rules
containing the above line, you are done with the first step.
Add your username to the group by executing
usermod -a -G kvm <your_username>
- the -a
is important for adding your user to the kvm-group. Without that you will overwrite the group-settings for your user to only belonging to "kvm"...
That's it.
For the new udev rule and group setting to take effect it's easiest to reboot and login again.
You can also execute
udevadm control --reload-rules && udevadm trigger
for reloading the rules but you still have to logout and login again with regard to the new group.
For what it is worth, an additional consideration when using .NET 4.0 is that if a valid endpoint is not found in your configuration, a default endpoint will be automatically created and used.
The default endpoint will use all default values so if you think you have a valid service configuration with a large value for maxReceivedMessageSize etc., but there is something wrong with the configuration, you would still get the 400 Bad Request since a default endpoint would be created and used.
This is done silently so it is hard to detect. You will see messages to this effect (e.g. 'No Endpoint found for Service, creating Default Endpoint' or similar) if you turn on tracing on the server but there is no other indication (to my knowledge).
First off, a PetStore
is not a farm.
Let's get past this though. You actually don't need access to the private members, you have everything you need in the public interface:
Animal_* getAnimal_(int i);
void addAnimal_(Animal_* newAnimal);
These are the methods you're given access to and these are the ones you should use.
I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ??
Simple, you call addAnimal
. It's public
and it also increments sizeF
.
Also, note that
PetStore()
{
idF=0;
};
is equivalent to
PetStore() : Farm()
{
idF=0;
};
i.e. the base constructor is called, base members are initialized.
The answer seems to be just no.
Although there are many good other answers, they either just hide the uglyness (which I did not ask for) or introduce new problems (edge cases).
To avoid many if-else structures, let JavaScript do the trick automatically:
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
<select name="location" id="location">
<option value="x">x</option>
<option value="y">y</option>
</select>
<script type="text/javascript">
document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>
Iterate through the entrySet()
like so:
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
Read more about Map
.
In the VSCode status bar, it must be showing typescript version - like this
Clicking on that version number will show you this, different versions available.
If you are using the VSCode version then switching to Workspace version solves the problem if it is VScode issue rather than your tsconfig.json
(I am already using that one, so not highlighted)
OK, figured it out now - thanks to Jobi whose answer was close, but not quite.
From a WPF application, here's my code that works:
First a helper class:
private class OldWindow : System.Windows.Forms.IWin32Window
{
IntPtr _handle;
public OldWindow(IntPtr handle)
{
_handle = handle;
}
#region IWin32Window Members
IntPtr System.Windows.Forms.IWin32Window.Handle
{
get { return _handle; }
}
#endregion
}
Then, to use this:
System.Windows.Forms.FolderBrowserDialog dlg = new FolderBrowserDialog();
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
System.Windows.Forms.DialogResult result = dlg.ShowDialog(win);
I'm sure I can wrap this up better, but basically it works. Yay! :-)
System images are pre-installed Android operating systems, and are only used by emulators. If you use your real Android device for debugging, you no longer need them, so you can remove them all.
The cleanest way to remove them is using SDK Manager. Open up SDK Manager and uncheck those system images and then apply.
Also feel free to remove other components (e.g. old SDK levels) that are of no use.
You can also use the [Required]
data annotation attribute to solve this:
public class Foo
{
public string FooId { get; set; }
public Boo Boo { get; set; }
}
public class Boo
{
public string BooId { get; set; }
[Required]
public Foo Foo {get; set; }
}
Foo
is required for Boo
.
I know many solutions have been posted already, but mine is still somewhat different. It works for the HTML5 Version of the like button and only uses css to hide the count box. Don't forget to add the appId
to test.
CSS:
<style type="text/css">
.fb-like span {
display: block;
height: 22px;
overflow: hidden;
position: relative;
width: 140px /* set this to fit your needs when support international sites */;
}
.fb-like iframe {
height: 62px;
overflow: hidden;
position: absolute;
top: -41px;
width: 55px;
}
</style>
FB Like Button:
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=xxxxxxxxxxxx";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-send="true" data-layout="box_count" data-width="450" data-show-faces="false"></div>
What did the trick for me was to change the target machine from “ANY CPU” to “x64” or maybe in your case “x86” depending in your target machine’s architecture. I would try this first before moving into a more complex solution which indicates a more complex problem.
Try this expression:
typeof(variable) != "undefined" && variable !== null
This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.
You can use it like this:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
Quoting from the SQLite documentation:
Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching)
...which I didn't know.But it works:
sqlite> create table products (name string);
sqlite> insert into products values ("Blue jeans");
sqlite> select * from products where name = 'Blue Jeans';
sqlite> select * from products where name like 'Blue Jeans';
Blue jeans
So you could do something like this:
name = 'Blue jeans'
if prod = Product.find(:conditions => ['name LIKE ?', name])
# update product or whatever
else
prod = Product.create(:name => name)
end
Not #find_or_create
, I know, and it may not be very cross-database friendly, but worth looking at?
You need to set it in the value itself, not in the prepared statement SQL string.
So, this should do for a prefix-match:
notes = notes
.replace("!", "!!")
.replace("%", "!%")
.replace("_", "!_")
.replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'");
pstmt.setString(1, notes + "%");
or a suffix-match:
pstmt.setString(1, "%" + notes);
or a global match:
pstmt.setString(1, "%" + notes + "%");
If you have
varname <- c("a", "b", "d")
you can do
get(varname[1]) + 2
for
a + 2
or
assign(varname[1], 2 + 2)
for
a <- 2 + 2
So it looks like you use GET when you want to evaluate a formula that uses a variable (such as a concatenate), and ASSIGN when you want to assign a value to a pre-declared variable.
Syntax for assign: assign(x, value)
x: a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.
value: value to be assigned to x.
If you want to start with a file you can do this
[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName
For getting month in string variable use the code below
For example the month of September:
M -> 9
MM -> 09
MMM -> Sep
MMMM -> September
String monthname=(String)android.text.format.DateFormat.format("MMMM", new Date())
If you want to run .py files in Windows, Try installing Git bash Then download python(Required Version) from python.org and install in the main c drive folder
For me, its :
"C:\Python38"
then open Git Bash and go to the respective folder where your .py file is stored :
For me, its :
File Location : "Downloads" File Name : Train.py
So i changed my Current working Directory From "C:/User/(username)/" to "C:/User/(username)/Downloads"
then i will run the below command
" /c/Python38/python Train.py "
and it will run successfully.
But if it give the below error :
from sklearn.model_selection import train_test_split ModuleNotFoundError: No module named 'sklearn'
Then Do not panic :
and use this command :
" /c/Python38/Scripts/pip install sklearn "
and after it has installed sklearn go back and run the previous command :
" /c/Python38/python Train.py "
and it will run successfully.
!!!!HAPPY LEARNING !!!!
If you don't declare a function and it only appears after being called, it is automatically assumed to be int
, so in your case, you didn't declare
void my_print (char *);
void my_print2 (char *);
before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *);
and int my_print2 (char *);
and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types
.
As Brian suggested, declare those two methods before main.
In case you use a different database schemas than ".dbo" or your db is containing Pk´s, which are composed by several fields, please don´t use the the solution of Carter Medlin, otherwise you will damage your db!!!
When you are working with different schemas try this (don´t forget to make a backup of your database before!):
DECLARE @sql AS NVARCHAR(max)=''
select @sql = @sql +
'ALTER INDEX ALL ON ' + SCHEMA_NAME( t.schema_id) +'.'+ '['+ t.[name] + '] DISABLE;'+CHAR(13)
from
sys.tables t
where type='u'
select @sql = @sql +
'ALTER INDEX ' + i.[name] + ' ON ' + SCHEMA_NAME( t.schema_id) +'.'+'[' + t.[name] + '] REBUILD;'+CHAR(13)
from
sys.key_constraints i
join
sys.tables t on i.parent_object_id=t.object_id
where i.type='PK'
exec dbo.sp_executesql @sql;
go
After doing some Fk-free actions, you can switch back with
DECLARE @sql AS NVARCHAR(max)=''
select @sql = @sql +
'ALTER INDEX ALL ON ' + SCHEMA_NAME( t.schema_id) +'.'+'[' + t.[name] + '] REBUILD;'+CHAR(13)
from
sys.tables t
where type='u'
print @sql
exec dbo.sp_executesql @sql;
exec sp_msforeachtable "ALTER TABLE ? WITH NOCHECK CHECK CONSTRAINT ALL";
This question has several answers but I want to add something more because when I used unset
or array_diff
I had several problems to play with the indexes of the new array when the specific element was removed (because the initial index are saved)
I get back to the example :
$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$array_without_strawberries = array_diff($array, array('strawberry'));
or
$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[array_search('strawberry', $array)]);
If you print the result you will obtain :
foreach ($array_without_strawberries as $data) {
print_r($data);
}
Result :
> apple
> orange
> blueberry
> kiwi
But the indexes will be saved and so you will access to your element like :
$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[3] > blueberry
$array_without_strawberries[4] > kiwi
And so the final array are not re-indexed. So you need to add after the unset
or array_diff
:
$array_without_strawberries = array_values($array);
After that your array will have a normal index :
$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[2] > blueberry
$array_without_strawberries[3] > kiwi
Related to this post : Re-Index Array
Hope it will help
Most people responding don't even seem to know what an array pointer is...
The problem is that you do pointer arithmetics with an array pointer: ptr + 1 will mean "jump 5 bytes ahead since ptr points at a 5 byte array".
Do like this instead:
#include <stdio.h>
int main()
{
char (*ptr)[5];
char arr[5] = {'a','b','c','d','e'};
int i;
ptr = &arr;
for(i=0; i<5; i++)
{
printf("\nvalue: %c", (*ptr)[i]);
}
}
Take the contents of what the array pointer points at and you get an array. So they work just like any pointer in C.
Import timedelta
and date
first.
from datetime import timedelta, date
And date.today()
will return today's datetime, may be you want
EndDate = date.today() + timedelta(days=10)
Though this is not directly related to the OP's exact question but I just found out that using a Oracle reserved word in your query (in my case the alias IN
) can cause the same error.
Example:
SELECT * FROM TBL_INDEPENTS IN
JOIN TBL_VOTERS VO on IN.VOTERID = VO.VOTERID
Or if its in the query itself as a field name
SELECT ..., ...., IN, ..., .... FROM SOMETABLE
That would also throw that error. I hope this helps someone.
while setting the color you can set color like this
[UIColor colorWithRed:19/255.0 green:144/255.0 blue:255/255.0 alpha:1.0]
You have to insert your <table>
into a <div>
that it has fixed size, and in <div>
style you have to set overflow: scroll
.
A DTO is a dumb object - it just holds properties and has getters and setters, but no other logic of any significance (other than maybe a compare()
or equals()
implementation).
Typically model classes in MVC (assuming .net MVC here) are DTOs, or collections/aggregates of DTOs
I want columns One and Two to shrink/grow to fit rather than being fixed.
Have you tried: flex-basis: auto
or this:
flex: 1 1 auto
, which is short for:
flex-grow: 1
(grow proportionally)flex-shrink: 1
(shrink proportionally)flex-basis: auto
(initial size based on content size)or this:
main > section:first-child {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:nth-child(2) {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:last-child {
flex: 20 1 auto;
display: flex;
flex-direction: column;
}
Related:
When you create a new window using open
, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document
object.
Here is an example:
var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');
the following code works for me. It requires openCV (import cv2).
The code is composed of an infinite loop that is continuously looking for a key pressed. In this case, when the 'q' key is pressed, the program ends. Other keys can be pressed (in this example 'b' or 'k') to perform different actions such as change a variable value or execute a function.
import cv2
while True:
k = cv2.waitKey(1) & 0xFF
# press 'q' to exit
if k == ord('q'):
break
elif k == ord('b'):
# change a variable / do something ...
elif k == ord('k'):
# change a variable / do something ...
In shell build phases you can write to stderr using the following format:
<filename>:<linenumber>: error | warn | note : <message>\n
It's the same format gcc uses to show errors. The filename:linenumber part can be omitted. Depending on the mode (error, warn, note), Xcode will show your message with a red or yellow badge.
If you include an absolute file path and a line number (if the error occurred in a file), double clicking the error in the build log lets Xcode open the file and jumps to the line, even if it is not part of the project. Very handy.
from datetime import datetime, timezone
def utc_now():
return datetime.utcnow().replace(tzinfo=timezone.utc)
Essentially, an operating system's windowing system exposes some API calls that you can perform to do jobs like create a window, or put a button on the window. Basically, you get a suite of header files and you can call functions in those imported libraries, just like you'd do with stdlib and printf
.
Each operating system comes with its own GUI toolkit, suite of header files, and API calls, and their own way of doing things. There are also cross platform toolkits like GTK, Qt, and wxWidgets that help you build programs that work anywhere. They achieve this by having the same API calls on each platform, but a different implementation for those API functions that call down to the native OS API calls.
One thing they'll all have in common, which will be different from a CLI program, is something called an event loop. The basic idea there is somewhat complicated, and difficult to compress, but in essence it means that not a hell of a lot is going in in your main class/main function, except:
There are plenty of resources about event based programming. If you have any experience with JavaScript, it's the same basic idea, except that you, the scripter have no access or control over the event loop itself, or what events there are, your only job is to write and register handlers.
You should keep in mind that GUI programming is incredibly complicated and difficult, in general. If you have the option, it's actually much easier to just integrate an embedded webserver into your program and have an HTML/web based interface. The one exception that I've encountered is Apple's Cocoa+Xcode +interface builder + tutorials that make it easily the most approachable environment for people new to GUI programming that I've seen.
SWIFT 2 UPDATE
Here's how to find out which button was tapped + send data to another ViewController from that button's indexPath.row
as I'm assuming that's the point for most!
@IBAction func yourButton(sender: AnyObject) {
var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(position)
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
UITableViewCell
print(indexPath?.row)
print("Tap tap tap tap")
}
For those who are using a ViewController class and added a tableView, I'm using a ViewController instead of a TableViewController so I manually added the tableView in order to access it.
Here is the code for passing data to another VC when tapping that button and passing the cell's indexPath.row
@IBAction func moreInfo(sender: AnyObject) {
let yourOtherVC = self.storyboard!.instantiateViewControllerWithIdentifier("yourOtherVC") as! YourOtherVCVIewController
var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(position)
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
UITableViewCell
print(indexPath?.row)
print("Button tapped")
yourOtherVC.yourVarName = [self.otherVCVariable[indexPath!.row]]
self.presentViewController(yourNewVC, animated: true, completion: nil)
}
You can use this command
$ git rev-list HEAD
You can also use the head
Unix command to show the latest n
HEAD
commits like
$ git rev-list HEAD | head - 2
I think this may help you , both index and columns of the values.
value you are looking for is not duplicated:
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
value=poz.iloc[0,0]
index=poz.index.item()
column=poz.columns.item()
you can get its index and column
duplicated:
matrix=pd.DataFrame([[1,1],[1,np.NAN]],index=['q','g'],columns=['f','h'])
matrix
Out[83]:
f h
q 1 1.0
g 1 NaN
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
index=poz.stack().index.tolist()
index
Out[87]: [('q', 'f'), ('q', 'h'), ('g', 'f')]
you will get a list
My problem was that the old assemblies were in the _bin_deployableAssemblies folder under the Web Application. This meant the old assemblies were overwriting the GAC assemblies when building the project.
TO 'user'@'%'
% is a wildcard - you can also do '%.domain.com'
or '%.123.123.123'
and things like that if you need.
Answer to your first question is As every object in java has only one lock(monitor)
andwait(),notify(),notifyAll()
are used for monitor sharing thats why they are part of Object
class rather than Thread
class.
If you want to localize string later, then those answers aren't enough, I would suggest something like:
<TextBlock>
<Hyperlink NavigateUri="http://labsii.com/">
<Hyperlink.Inlines>
<Run Text="Click here"/>
</Hyperlink.Inlines>
</Hyperlink>
</TextBlock>
CodeIgniter User Guide says:
$this->uri->segment(n)
Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this: http://example.com/index.php/news/local/metro/crime_is_up
The segment numbers would be this:
1. news 2. local 3. metro 4. crime_is_up
So segment
refers to your url structure segment. By the above example, $this->uri->segment(3)
would be 'metro'
, while $this->uri->segment(4)
would be 'crime_is_up'
.
Do you have multiple Radio Buttons on the page..
Because what I see is that you are assigning the events to all the radio button's on the page when you click on a radio button
from sysinternals.com with du.exe or du64.exe -l 1 . or 2 levels down: **du -l 2 c:**
Much shorter than Linux though ;)
A new extension function based on Paul Grimshaw's answer. I cleaned it up and added the ability to handle unexpected data. (Empty Data, Embedded Quotes, and comma's in the headings...)
It also returns a string which is more flexible. It returns Null if the table object does not contain any structure.
public static string ToCsv(this DataTable dataTable) {
StringBuilder sbData = new StringBuilder();
// Only return Null if there is no structure.
if (dataTable.Columns.Count == 0)
return null;
foreach (var col in dataTable.Columns) {
if (col == null)
sbData.Append(",");
else
sbData.Append("\"" + col.ToString().Replace("\"", "\"\"") + "\",");
}
sbData.Replace(",", System.Environment.NewLine, sbData.Length - 1, 1);
foreach (DataRow dr in dataTable.Rows) {
foreach (var column in dr.ItemArray) {
if (column == null)
sbData.Append(",");
else
sbData.Append("\"" + column.ToString().Replace("\"", "\"\"") + "\",");
}
sbData.Replace(",", System.Environment.NewLine, sbData.Length - 1, 1);
}
return sbData.ToString();
}
You call it as follows:
var csvData = dataTableOject.ToCsv();
Add height: 1px
to parent container. Works in Chrome, FF, Safari.
You can use a GROUP BY to group items by type and id. Then you can use the MAX() Aggregate function to get the most recent service month. The below returns a result set with ChargeId, ChargeType, and MostRecentServiceMonth
SELECT
CHARGEID,
CHARGETYPE,
MAX(SERVICEMONTH) AS "MostRecentServiceMonth"
FROM INVOICE
GROUP BY CHARGEID, CHARGETYPE
Generic method for setting a enum as datasource for drop downs
Display would be name. Selected value would be Enum itself
public IList<KeyValuePair<string, T>> GetDataSourceFromEnum<T>() where T : struct,IConvertible
{
IList<KeyValuePair<string, T>> list = new BindingList<KeyValuePair<string, T>>();
foreach (string value in Enum.GetNames(typeof(T)))
{
list.Add(new KeyValuePair<string, T>(value, (T)Enum.Parse(typeof(T), value)));
}
return list;
}
Its quite simple dear you can use range validator
<asp:TextBox ID="TextBox2" runat="server" TextMode="Number"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox2"
ErrorMessage="Invalid number. Please enter the number between 0 to 20."
MaximumValue="20" MinimumValue="0" Type="Integer"></asp:RangeValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox2" ErrorMessage="This is required field, can not be blank."></asp:RequiredFieldValidator>
otherwise you can use javascript
<script>
function minmax(value, min, max)
{
if(parseInt(value) < min || isNaN(parseInt(value)))
return 0;
else if(parseInt(value) > max)
return 20;
else return value;
}
</script>
<input type="text" name="TextBox1" id="TextBox1" maxlength="5"
onkeyup="this.value = minmax(this.value, 0, 20)" />
The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.
I recommend the jquery.post() method.
Update December 2013:
git-what-branch
(Perl script, see below) does not seem to be maintained anymore.git-when-merged
is an alternative written in Python that's working very well for me.
It is based on "Find merge commit which include a specific commit".
git when-merged [OPTIONS] COMMIT [BRANCH...]
Find when a commit was merged into one or more branches.
Find the merge commit that broughtCOMMIT
into the specified BRANCH(es).Specifically, look for the oldest commit on the first-parent history of
BRANCH
that contains theCOMMIT
as an ancestor.
Original answer September 2010:
Sebastien Douche just twitted (16 minutes before this SO answer):
git-what-branch: Discover what branch a commit is on, or how it got to a named branch
This is a Perl script from Seth Robertson that seems very interesting:
SYNOPSIS
git-what-branch [--allref] [--all] [--topo-order | --date-order ]
[--quiet] [--reference-branch=branchname] [--reference=reference]
<commit-hash/tag>...
OVERVIEW
Tell us (by default) the earliest causal path of commits and merges to cause the requested commit got onto a named branch. If a commit was made directly on a named branch, that obviously is the earliest path.
By earliest causal path, we mean the path which merged into a named branch the earliest, by commit time (unless
--topo-order
is specified).PERFORMANCE
If many branches (e.g. hundreds) contain the commit, the system may take a long time (for a particular commit in the Linux tree, it took 8 second to explore a branch, but there were over 200 candidate branches) to track down the path to each commit.
Selection of a particular--reference-branch --reference tag
to examine will be hundreds of times faster (if you have hundreds of candidate branches).EXAMPLES
# git-what-branch --all 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4
1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4 first merged onto master using the following minimal temporal path:
v2.6.12-rc3-450-g1f9c381 merged up at v2.6.12-rc3-590-gbfd4bda (Thu May 5 08:59:37 2005)
v2.6.12-rc3-590-gbfd4bda merged up at v2.6.12-rc3-461-g84e48b6 (Tue May 3 18:27:24 2005)
v2.6.12-rc3-461-g84e48b6 is on master
v2.6.12-rc3-461-g84e48b6 is on v2.6.12-n
[...]
This program does not take into account the effects of cherry-picking the commit of interest, only merge operations.
@WebFilter(urlPatterns="/*")
public class XSSFilter implements Filter {
private static final org.apache.log4j.Logger LOGGER = LogManager.getLogger(XSSFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("Initiating XSSFilter... ");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpRequestWrapper requestWrapper = new HttpRequestWrapper(req);
chain.doFilter(requestWrapper, response);
}
@Override
public void destroy() {
LOGGER.info("Destroying XSSFilter... ");
}
}
You need to implement Filter and need to be annotated with @WebFilter(urlPatterns="/*")
And in Application or Configuration class you need to add @ServletComponentScan By this it your filter will get registered.
You need to enclose the date time value in quotes:
DECLARE @Test AS DATETIME
SET @Test = '2011-02-15'
PRINT @Test
Is it possible to get this above example:
jQuery.fn.highlight = function (str, className)
{
var regex = new RegExp(str, "g");
return this.each(function ()
{
this.innerHTML = this.innerHTML.replace(
regex,
"<span class=\"" + className + "\">" + str + "</span>"
);
});
};
not to replace text inside html-tags like , this otherwise breakes the page.
Personally, I don't see the point of making it a property at all if you're not going to do anything at all beyond the auto-property. Just leave it as a field. The encapsulation benefit for these item are just red herrings, because there's nothing behind them to encapsulate. If you ever need to change the underlying implementation you're still free to refactor them as properties without breaking any dependent code.
Hmm... maybe this will be the subject of it's own question later
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
The Easiest Way to do
public function update(Request $request, $id)
{
$coupon = Coupon::where('name','=',$request->name)->first();
if($coupon->id != $id){
$validatedData = $request->validate([
'discount' => 'required',
'name' => 'required|unique:coupons|max:255',
]);
}
$requestData = $request->all();
$coupon = Coupon::findOrFail($id);
$coupon->update($requestData);
return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');
}
no it will not call destructor for class A, you should call it explicitly (like PoweRoy told), delete line 'delete ptr;' in example to compare ...
#include <iostream>
class A
{
public:
A(){};
~A();
};
A::~A()
{
std::cout << "Destructor of A" << std::endl;
}
class B
{
public:
B(){ptr = new A();};
~B();
private:
A* ptr;
};
B::~B()
{
delete ptr;
std::cout << "Destructor of B" << std::endl;
}
int main()
{
B* b = new B();
delete b;
return 0;
}
Using list slicing. The syntax is basically my_list[start_index:end_index]
>>> i = [0,1,2,3,4,5]
>>> i[:3] # same as i[0:3] - grabs from first to third index (0->2)
[0, 1, 2]
>>> i[3:] # same as i[3:len(i)] - grabs from fourth index to end
[3, 4, 5]
To get the first half of the list, you slice from the first index to len(i)//2
(where //
is the integer division - so 3//2 will give the floored result of
1, instead of the invalid list index of
1.5`):
>>> i[:len(i)//2]
[0, 1, 2]
..and the swap the values around to get the second half:
>>> i[len(i)//2:]
[3, 4, 5]
If you want to use hex codes, you should add -e
option to enable interpretation of backslash escapes by echo (but the result is the same as with echo
CtrlRCtrlB). And as wallyk said, you probably want to add -n
to prevent the output of a newline:
echo -en '\x12\x02' > /dev/ttyS0
Also make sure that /dev/ttyS0
is the port you want.
Instead of comparing a maxima to the mean, one can also compare the maxima to adjacent minima where the minima are only defined above a noise threshold. If the local maximum is > 3 times (or other confidence factor) either adjacent minima, then that maxima is a peak. The peak determination is more accurate with wider moving windows. The above uses a calculation centered on the middle of the window, by the way, rather than a calculation at the end of the window (== lag).
Note that a maxima has to be seen as an increase in signal before and a decrease after.
.on() is for jQuery version 1.7 and above. If you have an older version, use this:
$("#SomeId").live("click",function(){
//do stuff;
});
You can remove some extra spacing as well if you place a border-collapse: collapse;
CSS statement on your table.
Yahoo! Maps Web Services - Geocoding API accurately geocodes UK postcodes, unlike Google's API.
Unfortunately yahoo has deprecated this service, you could visit http://developer.yahoo.com/geo/placefinder/ for yahoo's service
I stumbled upon this thread as I had a similar requirement where I needed to set (or update) an Environment Variable (permanently).
So I looked in to - How to set an environment variable permanently from Command Prompt and it was very simple!
setx JAVA_LOC C:/Java/JDK
Then I just implemented the same in my code Here's what I used (suppose - JAVA_LOC is the env. variable name)
String cmdCommand = "setx JAVA_LOC " + "C:/Java/JDK";
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("cmd.exe", "/c", cmdCommand);
processBuilder.start();
ProcessBuilder fires-up a cmd.exe and passes the command that you want. The environment variable is retained even if you kill JVM/reboot the system as it has no relation with the JVM/Program's lifecycle.
You can switch to assembly layout in GDB:
(gdb) layout asm
See here for more information. The current assembly instruction will be shown in assembler window.
+---------------------------------------------------------------------------+
¦0x7ffff740d756 <__libc_start_main+214> mov 0x39670b(%rip),%rax #¦
¦0x7ffff740d75d <__libc_start_main+221> mov 0x8(%rsp),%rsi ¦
¦0x7ffff740d762 <__libc_start_main+226> mov 0x14(%rsp),%edi ¦
¦0x7ffff740d766 <__libc_start_main+230> mov (%rax),%rdx ¦
¦0x7ffff740d769 <__libc_start_main+233> callq *0x18(%rsp) ¦
>¦0x7ffff740d76d <__libc_start_main+237> mov %eax,%edi ¦
¦0x7ffff740d76f <__libc_start_main+239> callq 0x7ffff7427970 <exit> ¦
¦0x7ffff740d774 <__libc_start_main+244> xor %edx,%edx ¦
¦0x7ffff740d776 <__libc_start_main+246> jmpq 0x7ffff740d6b9 <__libc_start¦
¦0x7ffff740d77b <__libc_start_main+251> mov 0x39ca2e(%rip),%rax #¦
¦0x7ffff740d782 <__libc_start_main+258> ror $0x11,%rax ¦
¦0x7ffff740d786 <__libc_start_main+262> xor %fs:0x30,%rax ¦
¦0x7ffff740d78f <__libc_start_main+271> callq *%rax ¦
+---------------------------------------------------------------------------+
multi-thre process 3718 In: __libc_start_main Line: ?? PC: 0x7ffff740d76d
#3 0x00007ffff7466eb5 in _IO_do_write () from /lib/x86_64-linux-gnu/libc.so.6
#4 0x00007ffff74671ff in _IO_file_overflow ()
from /lib/x86_64-linux-gnu/libc.so.6
#5 0x0000000000408756 in ?? ()
#6 0x0000000000403980 in ?? ()
#7 0x00007ffff740d76d in __libc_start_main ()
from /lib/x86_64-linux-gnu/libc.so.6
(gdb)
You can also use fpdf class available at: http://www.fpdf.org. It gives options for both outputting to a file and displaying on browser.
Have a go at Selenium (http://seleniumhq.org) or WatiN (http://watin.sourceforge.net) to save yourself some work.
Try the following:
@MvcHtmlString.Create(Model.CommentText.Replace(Environment.NewLine, "<br />"))
According to marcind's
comment on this related question, the ASP.NET MVC team is looking to implement something similar to the <%:
and <%=
for the Razor view engine.
We can turn any question about HTML encoding into a discussion on harmful user inputs, but enough of that already exists.
Anyway, take care of potential harmful user input.
@MvcHtmlString.Create(Html.Encode(Model.CommentText).Replace(Environment.NewLine, "<br />"))
@Html.Raw(Html.Encode(Model.CommentText).Replace("\n", "<br />"))
Here's a cleaner solution:
def median(lst):
quotient, remainder = divmod(len(lst), 2)
if remainder:
return sorted(lst)[quotient]
return sum(sorted(lst)[quotient - 1:quotient + 1]) / 2.
Note: Answer changed to incorporate suggestion in comments.
You can use iteritems()
:
for name, values in df.iteritems():
print('{name}: {value}'.format(name=name, value=values[0]))
Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.
Initial GeoJsonResponse class:
from pyexample.responses import Response
class GeoJsonResponse(Response):
def __init__(self, geo_json_data):
Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:
from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):
E TypeError: module() takes at most 2 arguments (3 given)
=================================== ERRORS ====================================
___________________ ERROR collecting tests/test_geojson.py ____________________
test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)
class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)
ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response
C:\Python37\lib\site-packages\aenum__init__.py:163
(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])
The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:
I was importing the module:
from pyexample.responses import Response
when I should have been importing the class:
from pyexample.responses.Response import Response
Hope this helps someone. (In my defense, it's still pretty early.)
The web host is not really playing foul. It's not strictly according to the rules - but compared with some some of the amazing inventions intended to prevent spam, its not a particularly bad one.
If you really do want to send mail from '@gmail.com' why not just use the gmail SMTP service? If you can't reconfigure the server where PHP is running, then there are lots of email wrapper tools out there which allow you to specify a custom SMTP relay phpmailer springs to mind.
C.
What about something as easy as this:
String.Format("{0:dd/MM/yyyy}", d2)
JSON.parse
is available in TypeScript, so you can just use it :
JSON.parse('{"name": "Bob", "error": false}') // Returns a value of type 'any'
However, you will often want to parse a JSON object while making sure it matches a certain type, rather than dealing with a value of type any
. In that case, you can define a function such as the following :
function parse_json<TargetType extends Object>(
json: string,
type_definitions: { [Key in keyof TargetType]: (raw_value: any) => TargetType[Key] }
): TargetType {
const raw = JSON.parse(json);
const result: any = {};
for (const key in type_definitions) result[key] = type_definitions[key](raw[key]);
return result;
}
This function takes a JSON string and an object containing individual functions that load each field of the object you are creating. You can use it like so:
const value = parse_json(
'{"name": "Bob", "error": false}',
{ name: String, error: Boolean, }
);
Default access modifier - If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes).
I agree with tnguyen80's response. Please note that when there is a specific string value in query better to given entire query in double quotes.
For example:
$hive -e "select * from table where city = 'London' and id >=100" > /home/user/outputdirectory/city details.csv
Just use GETDATE()
or GETUTCDATE()
(if you want to get the "universal" UTC time, instead of your local server's time-zone related time).
INSERT INTO [Business]
([IsDeleted]
,[FirstName]
,[LastName]
,[LastUpdated]
,[LastUpdatedBy])
VALUES
(0, 'Joe', 'Thomas',
GETDATE(), <LastUpdatedBy, nvarchar(50),>)
Here's an example, first the method signature:
private string[] SplitInternal()
{
return Regex.Matches(Format, @"([^/\[\]]|\[[^]]*\])+")
.Cast<Match>()
.Select(m => m.Value)
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();
}
Here's the test:
/// <summary>
///A test for SplitInternal
///</summary>
[TestMethod()]
[DeploymentItem("Git XmlLib vs2008.dll")]
public void SplitInternalTest()
{
string path = "pair[path/to/@Key={0}]/Items/Item[Name={1}]/Date";
object[] values = new object[] { 2, "Martin" };
XPathString xp = new XPathString(path, values);
PrivateObject param0 = new PrivateObject(xp);
XPathString_Accessor target = new XPathString_Accessor(param0);
string[] expected = new string[] {
"pair[path/to/@Key={0}]",
"Items",
"Item[Name={1}]",
"Date"
};
string[] actual;
actual = target.SplitInternal();
CollectionAssert.AreEqual(expected, actual);
}
MFMailComposeViewController is the way to go after the release of iPhone OS 3.0 software. You can look at the sample code or the tutorial I wrote.
This will happen if the host page is HTTPS and the included javascript source path is HTTP. The two protocols must be the same, HTTPS. The tell tail sign would be to check under Firebug and notice that the JS is "denied access".
Use regex in data annotation
[RegularExpression("([0-9]+)", ErrorMessage = "Please enter valid Number")]
public int MaxJsonLength { get; set; }
What this means is that your web page is referring to content which is in the folder one level up from your page, but your page is already in the website's root folder, so the relative path is invalid. Judging by your exception message it looks like an image control is causing the problem.
You must have something like:
<asp:Image ImageUrl="..\foo.jpg" />
But since the page itself is in the root folder of the website, it cannot refer to content one level up, which is what the leading ..\
is doing.
The best way to find out the REAL type of an object (including BOTH the native Object or DataType name (such as String, Date, Number, ..etc) AND the REAL type of an object (even custom ones); is by grabbing the name property of the object prototype's constructor:
Native Type Ex1:
var string1 = "Test";
console.log(string1.__proto__.constructor.name);
displays:
String
Ex2:
var array1 = [];
console.log(array1.__proto__.constructor.name);
displays:
Array
Custom Classes:
function CustomClass(){_x000D_
console.log("Custom Class Object Created!");_x000D_
}_x000D_
var custom1 = new CustomClass();_x000D_
_x000D_
console.log(custom1.__proto__.constructor.name);
_x000D_
displays:
CustomClass
Older MySQL versions this is enough:
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN (SELECT * FROM `cars` ORDER BY `carPrice`) as `cars`
ON cars.belongsToUser=users.id
WHERE `id`='4'
Nowdays, if you use MariaDB the subquery should be limited.
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN (SELECT * FROM `cars` ORDER BY `carPrice` LIMIT 18446744073709551615) as `cars`
ON cars.belongsToUser=users.id
WHERE `id`='4'
This code works for me: check this link
This is my code when i stop and start service in activity
case R.id.buttonStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
}
And in service class:
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
HAPPY CODING!
In case anyone was still looking and came across this SO post like I did.
<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">
def contact():
if "open" in request.form:
pass
elif "close" in request.form:
pass
return render_template('contact.html')
Simple, concise, and it works. Don't even need to instantiate a form object.
May be helpful... :)
$(document).ready(function() {
$('#buutonId').on('click', function() {
$('#modalId').modal('open');
});
});
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[@name="genderS"]:checked').val();
anymore, which was working in jQuery 1.7 (with the @).
template system, useful if you want to create colorful line text without creating full style for every block
var tpl = 'background-color:greenyellow; border:3px solid orange; font-size:18px; font-weight: bold;padding:3px 5px;color:';
console.log('%cNo #1' + '.%cRed Text' + '%cBlue Text',
tpl+'magenta', tpl+'red', tpl+'blue');
The way that I find being the cleanest is the following one :
#bar::before {
display: block;
content: " ";
margin-top: -150px;
height: 150px;
visibility: hidden;
pointer-events: none;
}
If you need to target multiple classes use:
#main_text .title, #main_text .title2 {
/* Properties */
}
In my case, there was a package with the same name as a missing import in the generated databinding class.. It seems like the compiler got confused.
It didn't work, because QuerySets are not JSON serializable.
1) In case of json.dumps
you have to explicitely convert your QuerySet to JSON serializable objects:
class Model(model.Model):
def as_dict(self):
return {
"id": self.id,
# other stuff
}
And the serialization:
dictionaries = [ obj.as_dict() for obj in self.get_queryset() ]
return HttpResponse(json.dumps({"data": dictionaries}), content_type='application/json')
2) In case of serializers. Serializers accept either JSON serializable object or QuerySet, but a dictionary containing a QuerySet is neither. Try this:
serializers.serialize("json", self.get_queryset())
Read more about it here:
I think you might be able to use the ExpandProperty
parameter of Select-Object
.
For example, to get the list of the current directory and just have the Name property displayed, one would do the following:
ls | select -Property Name
This is still returning DirectoryInfo or FileInfo objects. You can always inspect the type coming through the pipeline by piping to Get-Member (alias gm
).
ls | select -Property Name | gm
So, to expand the object to be that of the type of property you're looking at, you can do the following:
ls | select -ExpandProperty Name
In your case, you can just do the following to have a variable be an array of strings, where the strings are the Name property:
$objects = ls | select -ExpandProperty Name
--feature
and --no-feature
at the same time (last one wins)This allows users to make a shell alias with --feature
, and overriding it with --no-feature
.
parser.add_argument('--feature', default=True, action=argparse.BooleanOptionalAction)
I recommend mgilson's answer:
parser.add_argument('--feature', dest='feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
--feature
and --no-feature
at the same timeYou can use a mutually exclusive group:
feature_parser = parser.add_mutually_exclusive_group(required=False)
feature_parser.add_argument('--feature', dest='feature', action='store_true')
feature_parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
You can use this helper if you are going to set many of them:
def add_bool_arg(parser, name, default=False):
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--' + name, dest=name, action='store_true')
group.add_argument('--no-' + name, dest=name, action='store_false')
parser.set_defaults(**{name:default})
add_bool_arg(parser, 'useful-feature')
add_bool_arg(parser, 'even-more-useful-feature')
Don't listen to every people telling you that namespaces are just name-spaces.
They are important because they are considered by the compiler to apply the interface principle. Basically, it can be explained by an example:
namespace ns {
class A
{
};
void print(A a)
{
}
}
If you wanted to print an A object, the code would be this one:
ns::A a;
print(a);
Note that we didn't explicitly mention the namespace when calling the function. This is the interface principle: C++ consider a function taking a type as an argument as being part of the interface for that type, so no need to specify the namespace because the parameter already implied the namespace.
Now why this principle is important? Imagine that the class A author did not provide a print() function for this class. You will have to provide one yourself. As you are a good programmer, you will define this function in your own namespace, or maybe in the global namespace.
namespace ns {
class A
{
};
}
void print(A a)
{
}
And your code can start calling the print(a) function wherever you want. Now imagine that years later, the author decides to provide a print() function, better than yours because he knows the internals of his class and can make a better version than yours.
Then C++ authors decided that his version of the print() function should be used instead of the one provided in another namespace, to respect the interface principle. And that this "upgrade" of the print() function should be as easy as possible, which means that you won't have to change every call to the print() function. That's why "interface functions" (function in the same namespace as a class) can be called without specifying the namespace in C++.
And that's why you should consider a C++ namespace as an "interface" when you use one and keep in mind the interface principle.
If you want better explanation of this behavior, you can refer to the book Exceptional C++ from Herb Sutter
<select ng-model="divs" ng-options="(d.group+' - '+d.sub) for d in divisions | orderBy:['group','sub']" />
User array instead of multiple orderBY
Try using entity codes such as 
for CR, 

for LF, and 	
for TAB.
For example:
<div title="1)	A
2)	B">Hover Me</div>
_x000D_
D3 has hundreds of examples, some of which are suitable for this question.
Examples without drag and drop, that are fixed:
Examples without drag and drop, that are interactive:
Examples with dragging and dropping:
This answer is based off of Glenn Dayton's answer.
Taking into account that getRunningTasks()
is deprecated and getRunningAppProcesses()
is not reliable, I came to decision to combine 2 approaches mentioned in StackOverflow:
private boolean isAppInForeground(Context context)
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
{
ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
return foregroundTaskPackageName.toLowerCase().equals(context.getPackageName().toLowerCase());
}
else
{
ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(appProcessInfo);
if (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)
{
return true;
}
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
// App is foreground, but screen is locked, so show notification
return km.inKeyguardRestrictedInputMode();
}
}
echo do_shortcode('[CONTACT-US-FORM]');
Use this in your template.
Look here for more: Do Shortcode
In order to assign these to variables, be sure not to add spaces in front or after the equals sign:
set filepath=%~dp1
set filename=%~nx1
Then you should have no issues.
Alternatively if you do not want a gradual transition between show and hide (e.g. a blinking text cursor) you could use something like:
/* Also use prefixes with @keyframes and animation to support current browsers */
@keyframes blinker {
from { visibility: visible }
to { visibility: hidden }
/* Alternatively you can do this:
0% { visibility: visible; }
50% { visibility: hidden; }
100% { visibility: visible; }
if you don't want to use `alternate` */
}
.cursor {
animation: blinker steps(1) 500ms infinite alternate;
}
Every 1s
.cursor
will go from visible
to hidden
.
If CSS animation is not supported (e.g. in some versions of Safari) you can fallback to this simple JS interval:
(function(){
var show = 'visible'; // state var toggled by interval
var time = 500; // milliseconds between each interval
setInterval(function() {
// Toggle our visible state on each interval
show = (show === 'hidden') ? 'visible' : 'hidden';
// Get the cursor elements
var cursors = document.getElementsByClassName('cursor');
// We could do this outside the interval callback,
// but then it wouldn't be kept in sync with the DOM
// Loop through the cursor elements and update them to the current state
for (var i = 0; i < cursors.length; i++) {
cursors[i].style.visibility = show;
}
}, time);
})()
This simple JavaScript is actually very fast and in many cases may even be a better default than the CSS. It's worth noting that it is lots of DOM calls that make JS animations slow (e.g. JQuery's $.animate()).
It also has the second advantage that if you add .cursor
elements later, they will still animate at exactly the same time as other .cursor
s since the state is shared, this is impossible with CSS as far as I am aware.
It does not work because your foobar.go
source file is not in a directory called foobar
. go build
and go install
try to match directories, not source files.
$GOPATH
to a valid directory, e.g. export GOPATH="$HOME/go"
foobar.go
to $GOPATH/src/foobar/foobar.go
and building should work just fine.Additional recommended steps:
$GOPATH/bin
to your $PATH
by: PATH="$GOPATH/bin:$PATH"
main.go
to a subfolder of $GOPATH/src
, e.g. $GOPATH/src/test
go install test
should now create an executable in $GOPATH/bin
that can be called by typing test
into your terminal.This is because your Image name contains "-" symbol . the only allowed characters are [a-zA-Z0-9_.]
Thanks
string1.equals(string2)
is the way.
It returns true
if string1
is equals to string2
in value. Else, it will return false
.
boot2docker together with VirtualBox Guest Additions
How to mount /Users into boot2docker
tl;dr Build your own custom boot2docker.iso with VirtualBox Guest Additions (see link) or download http://static.dockerfiles.io/boot2docker-v1.0.1-virtualbox-guest-additions-v4.3.12.iso and save it to ~/.boot2docker/boot2docker.iso.
I've found the best way to program the font sizes of a website are to define a base font size for the body
and then use em's (or rem's) for every other font-size
I declare after that. That's personal preference I suppose, but it's served me well and also made it very easy to incorporate a more responsive design.
As far as using rem units go, I think it's good to find a balance between being progressive in your code, but to also offer support for older browsers. Check out this link about browser support for rem units, that should help out a good amount on your decision.
Given returned json from your://site.com:
[{text:"Text1", val:"Value1"},
{text:"Text2", val:"Value2"},
{text:"Text3", val:"Value3"}]
Use this:
$.getJSON("your://site.com", function(json){
$('#select').empty();
$('#select').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#select').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
Here's the best practice (in my humble experience). Selecting these four packages will also update all other dependencies to the appropriate versions that will help you keep your environment consistent. The latter is a common problem others have expressed in earlier responses. This solution doesn't need the terminal.
Initialize the SQL Server Browser Service.
Just use look-arounds to solve this:
(?<=^|,)garp(?=$|,)
The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.
Nope.
But lo! If you use std::vector<Car>
, like you should be (never ever use new[]
), then you can specify exactly how elements should be constructed*.
*Well sort of. You can specify the value of which to make copies of.
Like this:
#include <iostream>
#include <vector>
class Car
{
private:
Car(); // if you don't use it, you can just declare it to make it private
int _no;
public:
Car(int no) :
_no(no)
{
// use an initialization list to initialize members,
// not the constructor body to assign them
}
void printNo()
{
// use whitespace, itmakesthingseasiertoread
std::cout << _no << std::endl;
}
};
int main()
{
int userInput = 10;
// first method: userInput copies of Car(5)
std::vector<Car> mycars(userInput, Car(5));
// second method:
std::vector<Car> mycars; // empty
mycars.reserve(userInput); // optional: reserve the memory upfront
for (int i = 0; i < userInput; ++i)
mycars.push_back(Car(i)); // ith element is a copy of this
// return 0 is implicit on main's with no return statement,
// useful for snippets and short code samples
}
With the additional function:
void printCarNumbers(Car *cars, int length)
{
for(int i = 0; i < length; i++) // whitespace! :)
std::cout << cars[i].printNo();
}
int main()
{
// ...
printCarNumbers(&mycars[0], mycars.size());
}
Note printCarNumbers
really should be designed differently, to accept two iterators denoting a range.
Felt the need to add this better answer, as nothing except BackgroundWorker
seemed to help me, and the answer dealing with that thus far was woefully incomplete. This is how you would update a XAML page called MainWindow
that has an Image tag like this:
<Image Name="imgNtwkInd" Source="Images/network_on.jpg" Width="50" />
with a BackgroundWorker
process to show if you are connected to the network or not:
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
public partial class MainWindow : Window
{
private BackgroundWorker bw = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
// Set up background worker to allow progress reporting and cancellation
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
// This is your main work process that records progress
bw.DoWork += new DoWorkEventHandler(SomeClass.DoWork);
// This will update your page based on that progress
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
// This starts your background worker and "DoWork()"
bw.RunWorkerAsync();
// When this page closes, this will run and cancel your background worker
this.Closing += new CancelEventHandler(Page_Unload);
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
BitmapImage bImg = new BitmapImage();
bool connected = false;
string response = e.ProgressPercentage.ToString(); // will either be 1 or 0 for true/false -- this is the result recorded in DoWork()
if (response == "1")
connected = true;
// Do something with the result we got
if (!connected)
{
bImg.BeginInit();
bImg.UriSource = new Uri("Images/network_off.jpg", UriKind.Relative);
bImg.EndInit();
imgNtwkInd.Source = bImg;
}
else
{
bImg.BeginInit();
bImg.UriSource = new Uri("Images/network_on.jpg", UriKind.Relative);
bImg.EndInit();
imgNtwkInd.Source = bImg;
}
}
private void Page_Unload(object sender, CancelEventArgs e)
{
bw.CancelAsync(); // stops the background worker when unloading the page
}
}
public class SomeClass
{
public static bool connected = false;
public void DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
int i = 0;
do
{
connected = CheckConn(); // do some task and get the result
if (bw.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
Thread.Sleep(1000);
// Record your result here
if (connected)
bw.ReportProgress(1);
else
bw.ReportProgress(0);
}
}
while (i == 0);
}
private static bool CheckConn()
{
bool conn = false;
Ping png = new Ping();
string host = "SomeComputerNameHere";
try
{
PingReply pngReply = png.Send(host);
if (pngReply.Status == IPStatus.Success)
conn = true;
}
catch (PingException ex)
{
// write exception to log
}
return conn;
}
}
For more information: https://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx
React Hooks (16.8+):
const Dropdown = ({
options
}) => {
const [selectedOption, setSelectedOption] = useState(options[0].value);
return (
<select
value={selectedOption}
onChange={e => setSelectedOption(e.target.value)}>
{options.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
);
};
ALTER TABLE users
ADD COLUMN "priv_user" BOOLEAN DEFAULT FALSE;
you can also directly specify NOT NULL
ALTER TABLE users
ADD COLUMN "priv_user" BOOLEAN NOT NULL DEFAULT FALSE;
UPDATE: following is only true for versions before postgresql 11.
As Craig mentioned on filled tables it is more efficient to split it into steps:
ALTER TABLE users ADD COLUMN priv_user BOOLEAN;
UPDATE users SET priv_user = 'f';
ALTER TABLE users ALTER COLUMN priv_user SET NOT NULL;
ALTER TABLE users ALTER COLUMN priv_user SET DEFAULT FALSE;
I found the proper solution for this error! Either you don't have any database installed or your default database in this file config/database.php is set to some other database like this
'default' => 'sqlite',
'default' => env('DB_CONNECTION', 'sqlite'), //laravel 5.2
change the default to which one you have installed or install that database which is made to be default! I had installed mysql and php artisan migrate worked after i changed that line to this:
'default' => 'mysql',
'default' => env('DB_CONNECTION', 'mysql'), //laravel5.2
maybe this article can help you link here
Write-through: Write is done synchronously both to the cache and to the backing store.
Write-back (or Write-behind): Writing is done only to the cache. A modified cache block is written back to the store, just before it is replaced.
Write-through: When data is updated, it is written to both the cache and the back-end storage. This mode is easy for operation but is slow in data writing because data has to be written to both the cache and the storage.
Write-back: When data is updated, it is written only to the cache. The modified data is written to the back-end storage only when data is removed from the cache. This mode has fast data write speed but data will be lost if a power failure occurs before the updated data is written to the storage.
import java.io.*;
import java.net.*;
class serversvi1
{
public static void main(String svi[]) throws IOException
{
try
{
ServerSocket servsock=new ServerSocket(5510);
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
System.out.println(fil+" :is file transfer");
File myfile=new File(fil);
while(true)
{
Socket sock=servsock.accept();
byte[] mybytearray=new byte[(int)myfile.length()];
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(myfile));
bis.read(mybytearray,0,mybytearray.length);
OutputStream os=sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
catch(Exception saranvi)
{
System.out.print(saranvi);
}
}
}
import java.io.*;
import java.net.*;
class clientsvi1
{
public static void main(String svi[])throws IOException
{
try
{
Socket sock=new Socket("localhost",5510);
byte[] bytearray=new byte[1024];
InputStream is=sock.getInputStream();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
FileOutputStream fos=new FileOutputStream(fil);
BufferedOutputStream bos=new BufferedOutputStream(fos);
int bytesread=is.read(bytearray,0,bytearray.length);
bos.write(bytearray,0,bytesread);
System.out.println("out.txt file is received");
bos.close();
sock.close();
}
catch(Exception SVI)
{
System.out.print(SVI);
}
}
}
Add cast RemoteWebDriver
to driver
initialize and you will have the .setLogLevel
method:
import java.util.logging.Level;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class PrintLogTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/Users/.../chromedriver");
WebDriver driver = new ChromeDriver();
//here
((RemoteWebDriver) driver).setLogLevel(Level.INFO);
driver.get("https://google.com/");
driver.findElement(By.name("q")).sendKeys("automation test");
driver.quit();
}
}
Example output:
Jun 15, 2020 4:27:04 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executing: get [430aec21a9beb6340a4185c4ea6a693d, get {url=https://google.com/}]
Jun 15, 2020 4:27:06 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executed: [430aec21a9beb6340a4185c4ea6a693d, get {url=https://google.com/}]
Jun 15, 2020 4:27:06 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executing: findElement [430aec21a9beb6340a4185c4ea6a693d, findElement {using=name, value=q}]
Jun 15, 2020 4:27:06 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executed: [430aec21a9beb6340a4185c4ea6a693d, findElement {using=name, value=q}]
...
...
At least I've tried it on ChromeDriver()
and FirefoxDriver()
and it working fine.
There are actually two ways of doing this:
st = "Line 1" + vbCrLf + "Line 2"
st = "Line 1" + vbNewLine + "Line 2"
These even work for message boxes (and all other places where strings are used).
To set transparent you can set opaque of panel to false like
JPanel panel = new JPanel();
panel.setOpaque(false);
But to make it transculent use alpha property of color attribute like
JPanel panel = new JPanel();
panel.setBackground(new Color(0,0,0,125));
where last parameter of Color is for alpha and alpha value ranges between 0 and 255 where 0 is full transparent and 255 is fully opaque
On Linux, give read/write permissions to the entire folder containing the database file.
Also, SELinux might be blocking the write. You need to set the correct permissions.
In my SELinux Management GUI (on Fedora 19), I checked the box on the line labelled httpd_unified (Unify HTTPD handling of all content files), and I was good to go.
I came across this today and fixed the problem by removing the IISUrl from the Project file:
Delete the following line:
<IISUrl>http://localhost:xxxxx </IISUrl>
Reload project
there are three ways you can use: the RETURN value, and OUTPUT parameter and a result set
ALSO, watch out if you use the pattern: SELECT @Variable=column FROM table ...
if there are multiple rows returned from the query, your @Variable will only contain the value from the last row returned by the query.
RETURN VALUE
since your query returns an int field, at least based on how you named it. you can use this trick:
CREATE PROCEDURE GetMyInt
( @Param int)
AS
DECLARE @ReturnValue int
SELECT @ReturnValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN @ReturnValue
GO
and now call your procedure like:
DECLARE @SelectedValue int
,@Param int
SET @Param=1
EXEC @SelectedValue = GetMyInt @Param
PRINT @SelectedValue
this will only work for INTs, because RETURN can only return a single int value and nulls are converted to a zero.
OUTPUT PARAMETER
you can use an output parameter:
CREATE PROCEDURE GetMyInt
( @Param int
,@OutValue int OUTPUT)
AS
SELECT @OutValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO
and now call your procedure like:
DECLARE @SelectedValue int
,@Param int
SET @Param=1
EXEC GetMyInt @Param, @SelectedValue OUTPUT
PRINT @SelectedValue
Output parameters can only return one value, but can be any data type
RESULT SET for a result set make the procedure like:
CREATE PROCEDURE GetMyInt
( @Param int)
AS
SELECT MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO
use it like:
DECLARE @ResultSet table (SelectedValue int)
DECLARE @Param int
SET @Param=1
INSERT INTO @ResultSet (SelectedValue)
EXEC GetMyInt @Param
SELECT * FROM @ResultSet
result sets can have many rows and many columns of any data type
Extend the string prototype to use throughout your project
String.prototype.alphaNumeric = function() {
return this.replace(/[^a-z0-9]/gi,'');
}
Usage:
"I don't know what to say?".alphaNumeric();
//Idontknowwhattosay
i had the same problem, my solution was apply the required attribute to all elements
<input type="checkbox" name="checkin_days[]" required="required" value="0" /><span class="w">S</span>
<input type="checkbox" name="checkin_days[]" required="required" value="1" /><span class="w">M</span>
<input type="checkbox" name="checkin_days[]" required="required" value="2" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="3" /><span class="w">W</span>
<input type="checkbox" name="checkin_days[]" required="required" value="4" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="5" /><span class="w">F</span>
<input type="checkbox" name="checkin_days[]" required="required" value="6" /><span class="w">S</span>
when the user check one of the elements i remove the required attribute from all elements:
var $checkedCheckboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]:checked'),
$checkboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]');
$checkboxes.click(function() {
if($checkedCheckboxes.length) {
$checkboxes.removeAttr('required');
} else {
$checkboxes.attr('required', 'required');
}
});
If the purpose is to obtain a bitmap, this is very simple:
Canvas canvas = new Canvas();
canvas.setBitmap(image);
canvas.drawBitmap(image2, new Matrix(), null);
In the end, image will contain the overlap of image and image2.
I took the answer above by @sbgoran and modified it for my case same as the question needed, to treat arrays as sets (i.e. order is not important for diff)
const deepDiffMapper = function () {
return {
VALUE_CREATED: "created",
VALUE_UPDATED: "updated",
VALUE_DELETED: "deleted",
VALUE_UNCHANGED: "unchanged",
map: function(obj1: any, obj2: any) {
if (this.isFunction(obj1) || this.isFunction(obj2)) {
throw "Invalid argument. Function given, object expected.";
}
if (this.isValue(obj1) || this.isValue(obj2)) {
return {
type: this.compareValues(obj1, obj2),
data: obj2 === undefined ? obj1 : obj2
};
}
if (this.isArray(obj1) || this.isArray(obj2)) {
return {
type: this.compareArrays(obj1, obj2),
data: this.getArrayDiffData(obj1, obj2)
};
}
const diff: any = {};
for (const key in obj1) {
if (this.isFunction(obj1[key])) {
continue;
}
let value2 = undefined;
if (obj2[key] !== undefined) {
value2 = obj2[key];
}
diff[key] = this.map(obj1[key], value2);
}
for (const key in obj2) {
if (this.isFunction(obj2[key]) || diff[key] !== undefined) {
continue;
}
diff[key] = this.map(undefined, obj2[key]);
}
return diff;
},
getArrayDiffData: function(arr1: Array<any>, arr2: Array<any>) {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
if (arr1 === undefined || arr2 === undefined) {
return arr1 === undefined ? arr1 : arr2;
}
const deleted = [...arr1].filter(x => !set2.has(x));
const added = [...arr2].filter(x => !set1.has(x));
return {
added, deleted
};
},
compareArrays: function(arr1: Array<any>, arr2: Array<any>) {
const set1 = new Set(arr1);
const set2 = new Set(arr2);
if (_.isEqual(_.sortBy(arr1), _.sortBy(arr2))) {
return this.VALUE_UNCHANGED;
}
if (arr1 === undefined) {
return this.VALUE_CREATED;
}
if (arr2 === undefined) {
return this.VALUE_DELETED;
}
return this.VALUE_UPDATED;
},
compareValues: function (value1: any, value2: any) {
if (value1 === value2) {
return this.VALUE_UNCHANGED;
}
if (this.isDate(value1) && this.isDate(value2) && value1.getTime() === value2.getTime()) {
return this.VALUE_UNCHANGED;
}
if (value1 === undefined) {
return this.VALUE_CREATED;
}
if (value2 === undefined) {
return this.VALUE_DELETED;
}
return this.VALUE_UPDATED;
},
isFunction: function (x: any) {
return Object.prototype.toString.call(x) === "[object Function]";
},
isArray: function (x: any) {
return Object.prototype.toString.call(x) === "[object Array]";
},
isDate: function (x: any) {
return Object.prototype.toString.call(x) === "[object Date]";
},
isObject: function (x: any) {
return Object.prototype.toString.call(x) === "[object Object]";
},
isValue: function (x: any) {
return !this.isObject(x) && !this.isArray(x);
}
};
}();
String line = "This order was32354 placed for QT ! OK?";
String regex = "[^\\d]+";
String[] str = line.split(regex);
System.out.println(str[1]);
For Visual Studio you'll want to right click on your project in the solution explorer and then click on Properties.
Next open Configuration Properties and then Linker.
Now you want to add the folder you have the Allegro libraries in to Additional Library Directories,
Linker -> Input you'll add the actual library files under Additional Dependencies.
For the Header Files you'll also want to include their directories under C/C++ -> Additional Include Directories.
If there is a dll have a copy of it in your main project folder, and done.
I would recommend putting the Allegro files in the your project folder and then using local references in for the library and header directories.
Doing this will allow you to run the application on other computers without having to install Allergo on the other computer.
This was written for Visual Studio 2008. For 2010 it should be roughly the same.
If you're using Spring framework already, use the following method:
import static org.springframework.web.util.HtmlUtils.htmlUnescape;
...
String result = htmlUnescape(source);
Use ThenByDescending
:
var hold = MyList.OrderBy(x => x.StartDate)
.ThenByDescending(x => x.EndDate)
.ToList();
You can also use query syntax and say:
var hold = (from x in MyList
orderby x.StartDate, x.EndDate descending
select x).ToList();
ThenByDescending
is an extension method on IOrderedEnumerable
which is what is returned by OrderBy
. See also the related method ThenBy
.
In case you're here looking for something to list the keys of an n-depth nested object as a flat array:
const getObjectKeys = (obj, prefix = '') => {_x000D_
return Object.entries(obj).reduce((collector, [key, val]) => {_x000D_
const newKeys = [ ...collector, prefix ? `${prefix}.${key}` : key ]_x000D_
if (Object.prototype.toString.call(val) === '[object Object]') {_x000D_
const newPrefix = prefix ? `${prefix}.${key}` : key_x000D_
const otherKeys = getObjectKeys(val, newPrefix)_x000D_
return [ ...newKeys, ...otherKeys ]_x000D_
}_x000D_
return newKeys_x000D_
}, [])_x000D_
}_x000D_
_x000D_
console.log(getObjectKeys({a: 1, b: 2, c: { d: 3, e: { f: 4 }}}))
_x000D_
In Angular use 'extends' to define the interface for an 'Array' of objects.
Using an indexer will give you an error as its not an Array interface so doesn't contain the properties and methods.
e.g
error TS2339: Property 'find' does not exist on type 'ISelectOptions2'.
// good
export interface ISelectOptions1 extends Array<ISelectOption> {}
// bad
export interface ISelectOptions2 {
[index: number]: ISelectOption;
}
interface ISelectOption {
prop1: string;
prop2?: boolean;
}
If your redirect is in PHP, nothing should be echoed to the user before the redirect instruction.
See header for more info.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
Otherwise, you can use Javascript to redirect the user.
Just use
window.location = "http://www.google.com/"
After some time researching I've gathered some pieces that made me get to this solution. Once that CookieSyncManager is deprecated, this may be the best way to set a specific cookie for a webview in Kotlin nowadays, you shouldn't need anything else.
private fun setCookie(){
val webView = WebView(this) // this = context
val cookieManager = CookieManager.getInstance()
cookieManager.acceptCookie()
val domain = "https://www.yourdomain.com/"
webView.webViewClient = WebViewClient()
webView.settings.javaScriptEnabled = true
cookieManager.setCookie(domain,"$cookieKey=$cookieValue")
cookieManager.setAcceptThirdPartyCookies(webView, true)
webView.loadUrl(domain)
}
To add to Glenn's great answer, here's what I did to find which files were faulty:
find . -name "*.png" -type f -print0 | xargs \
-0 pngcrush_1_8_8_w64.exe -n -q > pngError.txt 2>&1
I used the find and xargs because pngcrush could not handle lots of arguments (which were returned by **/*.png
). The -print0
and -0
is required to handle file names containing spaces.
Then search in the output for these lines: iCCP: Not recognizing known sRGB profile that has been edited
.
./Installer/Images/installer_background.png:
Total length of data found in critical chunks = 11286
pngcrush: iCCP: Not recognizing known sRGB profile that has been edited
And for each of those, run mogrify on it to fix them.
mogrify ./Installer/Images/installer_background.png
Doing this prevents having a commit changing every single png file in the repository when only a few have actually been modified. Plus it has the advantage to show exactly which files were faulty.
I tested this on Windows with a Cygwin console and a zsh shell. Thanks again to Glenn who put most of the above, I'm just adding an answer as it's usually easier to find than comments :)
If you use Integer.toHexString
you will end-up with missed zeros when you convert colors like 0xFF000123
.
Here is my kotlin based solution which doesn't require neither android specific classes nor java. So you could use it in multiplatform project as well:
fun Int.toRgbString(): String =
"#${red.toStringComponent()}${green.toStringComponent()}${blue.toStringComponent()}".toUpperCase()
fun Int.toArgbString(): String =
"#${alpha.toStringComponent()}${red.toStringComponent()}${green.toStringComponent()}${blue.toStringComponent()}".toUpperCase()
private fun Int.toStringComponent(): String =
this.toString(16).let { if (it.length == 1) "0${it}" else it }
inline val Int.alpha: Int
get() = (this shr 24) and 0xFF
inline val Int.red: Int
get() = (this shr 16) and 0xFF
inline val Int.green: Int
get() = (this shr 8) and 0xFF
inline val Int.blue: Int
get() = this and 0xFF
You can detect the orientation change, but I don't think you can prevent it.
Iterators make your code more generic.
Every standard library container provides an iterator hence if you change your container class in future the loop wont be affected.
Adding to Eric Jablow's answer, here is a possible solution (it worked for me - linux mint 14 /nadia)
find /path/to/search/ -type f -name "glob-to-find-files" | xargs cp -t /target/path/
You can refer to "How can I use xargs to copy files that have spaces and quotes in their names?" as well.
If you only need the index of a character the most simple, quick solution (as already pointed out by Pascal) is:
let index = string.characters.index(of: ".")
let intIndex = string.distance(from: string.startIndex, to: index)
try the following extension
extension UIView {
func addTapGesture(action : @escaping ()->Void ){
let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
tap.action = action
tap.numberOfTapsRequired = 1
self.addGestureRecognizer(tap)
self.isUserInteractionEnabled = true
}
@objc func handleTap(_ sender: MyTapGestureRecognizer) {
sender.action!()
}
}
class MyTapGestureRecognizer: UITapGestureRecognizer {
var action : (()->Void)? = nil
}
and then use it :
submitBtn.addTapGesture {
//your code
}
you can even use it for cell
cell.addTapGesture {
//your code
}
While writing this question, I discovered the answer. Installing a CA from Safari no longer automatically trusts it. I had to manually trust it from the Certificate Trust Settings panel (also mentioned in this question).
I debated canceling the question, but I thought it might be helpful to have some of the relevant code and log details someone might be looking for. Also, I never encountered the issue until iOS 11. I even went back and reconfirmed that it automatically works up through iOS 10.
I've never needed to touch that settings panel before, because any installed certificates were automatically trusted. Maybe it will change by the time iOS 11 ships, but I doubt it. Hopefully this helps save someone the time I wasted.
If anyone knows why this behaves differently for some people on different versions of iOS, I'd love to know in comments.
Update 1: Checking out the first iOS 12 beta, it looks like things remain the same. This question/answer/comments are still relevant on iOS 12.
Update 2: Same solution seems to be needed on iOS 13 beta builds as well.
What happens is that your close button is placed inside your .clickable
div, so the click event will be triggered in both elements.
The event bubbling will make the click event propagate from the child nodes to their parents. So your .close_button
callback will be executed first, and when .clickable
is reached, it will toggle the classes again. As this run very fast you can't notice the two events happened.
/ \
--------------------| |-----------------
| .clickable | | |
| ----------------| |----------- |
| | .close_button | | | |
| ------------------------------ |
| event bubbling |
----------------------------------------
To prevent your event from reaching .clickable
, you need to add the event parameter to your callback function and then call the stopPropagation
method on it.
$(".close_button").click(function (e) {
$("#spot1").addClass("spot");
$("#spot1").removeClass("grown");
e.stopPropagation();
});
Fiddle: http://jsfiddle.net/u4GCk/1/
More info about event order in general: http://www.quirksmode.org/js/events_order.html (that's where I picked that pretty ASCII art =])
TextView tekst = (TextView) findViewById(R.id.editText1);
You cannot cast EditText
to TextView
.
textBox1.Focus()
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.ScrollToCaret();
didn't work for me (Windows 8.1, whatever the reason).
And since I'm still on .NET 2.0, I can't use ScrollToEnd.
But this works:
public class Utils
{
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern int SendMessage(System.IntPtr hWnd, int wMsg, System.IntPtr wParam, System.IntPtr lParam);
private const int WM_VSCROLL = 0x115;
private const int SB_BOTTOM = 7;
/// <summary>
/// Scrolls the vertical scroll bar of a multi-line text box to the bottom.
/// </summary>
/// <param name="tb">The text box to scroll</param>
public static void ScrollToBottom(System.Windows.Forms.TextBox tb)
{
if(System.Environment.OSVersion.Platform != System.PlatformID.Unix)
SendMessage(tb.Handle, WM_VSCROLL, new System.IntPtr(SB_BOTTOM), System.IntPtr.Zero);
}
}
VB.NET:
Public Class Utils
<System.Runtime.InteropServices.DllImport("user32.dll", CharSet := System.Runtime.InteropServices.CharSet.Auto)> _
Private Shared Function SendMessage(hWnd As System.IntPtr, wMsg As Integer, wParam As System.IntPtr, lParam As System.IntPtr) As Integer
End Function
Private Const WM_VSCROLL As Integer = &H115
Private Const SB_BOTTOM As Integer = 7
''' <summary>
''' Scrolls the vertical scroll bar of a multi-line text box to the bottom.
''' </summary>
''' <param name="tb">The text box to scroll</param>
Public Shared Sub ScrollToBottom(tb As System.Windows.Forms.TextBox)
If System.Environment.OSVersion.Platform <> System.PlatformID.Unix Then
SendMessage(tb.Handle, WM_VSCROLL, New System.IntPtr(SB_BOTTOM), System.IntPtr.Zero)
End If
End Sub
End Class
Official Kotlin Way:
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
// Check if the key event was the Back button and if there's history
if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
myWebView.goBack()
return true
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event)
}
https://developer.android.com/guide/webapps/webview.html#NavigatingHistory
Put this in your window constructor
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
.NET FrameworkSupported in: 4, 3.5, 3.0
.NET Framework Client ProfileSupported in: 4, 3.5 SP1
While all of the answers are good and correct, simple solution in one line is:
$check = 9;
either:
echo ($check & 1 ? 'Odd' : 'Even');
or:
echo ($check % 2 ? 'Odd' : 'Even');
works very well.
Please refer following tutorial
i hope it will helpful for you but prior you have to read documentation of NSError
This is very interesting link i found recently ErrorHandling
I actually prefer to use the html button form element and make it runat=server. The button element can hold other elements inside it. You can even add formatting inside it with span's or strong's. Here is an example:
<button id="BtnSave" runat="server"><img src="Images/save.png" />Save</button>
This is not a direct answer for the question but it may help someone. My point is you only call preventDefault() based on some conditions as there is no point of having an event if you call preventDefault() for all the cases. So having if conditions and calling preventDefault() only when the condition/s satisfied will work the function in usual way for the other cases.
$('.btnEdit').click(function(e) {
var status = $(this).closest('tr').find('td').eq(3).html().trim();
var tripId = $(this).attr('tripId');
if (status == 'Completed') {
e.preventDefault();
alert("You can't edit completed reservations");
} else if (tripId != '') {
e.preventDefault();
alert("You can't edit a reservation which is already attached to a trip");
}
//else it will continue as usual
});
Append a ?v=random_string to the url. If you are using this idea with Facebook share, make sure that the og:url param in the response matches the url you are sharing. This will work with google plus too.
For Facebook, you can also force recrawl by making a post request to https://graph.facebook.com
{id: url,
scrape: true}
alter system set timed_statistics=true
--or
alter session set timed_statistics=true --if want to trace your own session
-- must be big enough:
select value from v$parameter p
where name='max_dump_file_size'
-- Find out sid and serial# of session you interested in:
select sid, serial# from v$session
where ...your_search_params...
--you can begin tracing with 10046 event, the fourth parameter sets the trace level(12 is the biggest):
begin
sys.dbms_system.set_ev(sid, serial#, 10046, 12, '');
end;
--turn off tracing with setting zero level:
begin
sys.dbms_system.set_ev(sid, serial#, 10046, 0, '');
end;
/*possible levels: 0 - turned off 1 - minimal level. Much like set sql_trace=true 4 - bind variables values are added to trace file 8 - waits are added 12 - both bind variable values and wait events are added */
--same if you want to trace your own session with bigger level:
alter session set events '10046 trace name context forever, level 12';
--turn off:
alter session set events '10046 trace name context off';
--file with raw trace information will be located:
select value from v$parameter p
where name='user_dump_dest'
--name of the file(*.trc) will contain spid:
select p.spid from v$session s, v$process p
where s.paddr=p.addr
and ...your_search_params...
--also you can set the name by yourself:
alter session set tracefile_identifier='UniqueString';
--finally, use TKPROF
to make trace file more readable:
C:\ORACLE\admin\databaseSID\udump>
C:\ORACLE\admin\databaseSID\udump>tkprof my_trace_file.trc output=my_file.prf
TKPROF: Release 9.2.0.1.0 - Production on Wed Sep 22 18:05:00 2004
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
C:\ORACLE\admin\databaseSID\udump>
--to view state of trace file use:
set serveroutput on size 30000;
declare
ALevel binary_integer;
begin
SYS.DBMS_SYSTEM.Read_Ev(10046, ALevel);
if ALevel = 0 then
DBMS_OUTPUT.Put_Line('sql_trace is off');
else
DBMS_OUTPUT.Put_Line('sql_trace is on');
end if;
end;
/
Just kind of translated http://www.sql.ru/faq/faq_topic.aspx?fid=389 Original is fuller, but anyway this is better than what others posted IMHO
Below is the code that works well but my values overlap in sheet "Final" everytime the condition of <=11
meets in sheet "Calculator"
I would like you to kindly support me to modify the code so that the cursor should move to next blank cell and values keeps on adding up like a list.
Dim i As Integer
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Calculator")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Final")
For i = 2 To ws1.Range("A65536").End(xlUp).Row
If ws1.Cells(i, 4) <= 11 Then
ws2.Cells(i, 1).Value = Left(Worksheets("Calculator").Cells(i, 1).Value, Len(Worksheets("Calculator").Cells(i, 1).Value) - 0)
ws2.Cells(i, 2) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:D"), 4, False)
ws2.Cells(i, 3) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:E"), 5, False)
ws2.Cells(i, 4) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:B"), 2, False)
ws2.Cells(i, 5) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:C"), 3, False)
End If
Next i
You can call bash
directly, use the -c
flag:
bash -c "diff <(sort file1) <(sort file2) > $@"
Of course, you may not be able to redirect to the variable $@, but when I tried to do this, I got -bash: $@: ambiguous redirect
as an error message, so you may want to look into that before you get too into this (though I'm using bash 3.2.something, so maybe yours works differently).
Try:
dmesg -T| grep -E -i -B100 'killed process'
Where -B100
signifies the number of lines before the kill happened.
Omit -T on Mac OS.
I had a similar problem when I recreated my workspace that was fixed in the following way:
Go to Eclipse -> Preferences, under Java select "Installed JREs" and check one of the boxes to specify a default JRE. Click OK and then go back to your project's properties. Go to the "Java Build Path" section and choose the "Libraries" tab. Remove the unbound System Default library, then click the "Add Library" button. Select "JRE System Library" and you should be good to go!
You could use a reset button styled with an image...
<form action="" method="get">
<input type="text" name="search" required="required" placeholder="type here" />
<input type="reset" value="" alt="clear" />
</form>
<style>
input[type="text"]
{
height: 38px;
font-size: 15pt;
}
input[type="text"]:invalid + input[type="reset"]{
display: none;
}
input[type="reset"]
{
background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
background-position: center center;
background-repeat: no-repeat;
height: 38px;
width: 38px;
border: none;
background-color: transparent;
cursor: pointer;
position: relative;
top: -9px;
left: -44px;
}
</style>
See it in action here: http://jsbin.com/uloli3/63
It is related to generics in java. If I mentioned ArrayList<String>
that means I can add only String type object to that ArrayList.
The two major benefits of generics in Java are:
The important needs to be inside the ;
td.rule2 div { background-color: #ffff00 !important; }
in fact i believe this should override it
td.rule2 { background-color: #ffff00 !important; }
If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime
//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);
I have nothing against gotos in general, but I can think of several reasons why you wouldn't want to use them for a loop like you mentioned:
There are multiple ways to do this in particular with Python 3.0 and above
Approach 1
This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
Approach 2
This approach is recommended because it provides more detail about each exception. It includes:
The only drawback is tracback needs to be imported.
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()
Please replace
app.set('view engin', 'html');
with
app.set('view engine', 'ejs');
NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.
You can use INSERT with SELECT UNION ALL:
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
...
Only for small datasets though, which should be fine for your 4 records.
#!/usr/bin/expect -f
spawn scp -r BASE.zip [email protected]:/tmp
expect "password:"
send "wifinetworks\r"
expect "*\r"
expect "\r"
From the Jenkins wiki:
The JVM launch parameters of these Windows services are controlled by an XML file jenkins.xml and jenkins-slave.xml respectively. These files can be found in $JENKINS_HOME and in the slave root directory respectively, after you've install them as Windows services.
The file format should be self-explanatory. Tweak the arguments for example to give JVM a bigger memory.
https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+as+a+Windows+service
Possible that public/private config is incorrect. please follow the steps to do it. execute command anywhere in window
ssh-keygen -o -f ~/.ssh/id_rsa
now go to the c://users/xyz/.ssh/ and open the id_rsa key (path can vary) now go to the gitlab and userprofile> setting>ssh keys and add your key here. now try clone
The best solution for me is the custom pipe from @Kamalakar but with a slight modification to allow passing the format:
import { Pipe, PipeTransform} from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'dateFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {
transform(value: any, format: any): any {
return super.transform(value, format);
}
}
And then called as:
console.log('Formatted date:', this._dateFormatPipe.transform(new Date(), 'MMM/dd/yyyy'));
System.Windows.Forms.MessageBox.Show("My message here");
Make sure the System.Windows.Forms
assembly is referenced your project.
You could use the JS confirm function.
<form onSubmit="if(!confirm('Is the form filled out correctly?')){return false;}">
<input type="submit" />
</form>
This would work just fine, set the height to desired pixel
#inner-right{
height: 100px;
overflow:auto;
}
This one works!
floor(loge(n) / loge(2)) + 1
To include negative numbers, you can add an extra bit to specify the sign.
floor(loge(abs(n)) / loge(2)) + 2
You can use a similar construct by using the sys.columns
table io sys.objects
.
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(N'[dbo].[Person]')
AND name = 'ColumnName'
)
use this class inside nav tag
class="navbar navbar-expand-lg navbar-light bg-light sticky-top"
For bootstrap 4
You need some sort of Inter Process Communication. Use a pipe or a shared buffer.
Is there a command that does?
thread apply all where
You can always extend String
prototype like this:
// Checks that string starts with the specific string
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.slice(0, str.length) == str;
};
}
// Checks that string ends with the specific string...
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function (str) {
return this.slice(-str.length) == str;
};
}
And use it like this:
var str = 'Hello World';
if( str.startsWith('Hello') ) {
// your string starts with 'Hello'
}
if( str.endsWith('World') ) {
// your string ends with 'World'
}
Most answers are missing some points:
Role and authority are not the same thing in Spring. See here for more details.
Role names are equal to rolePrefix
+ authority
.
The default role prefix is ROLE_
, however, it is configurable. See here.
Therefore, a proper role check needs to respect the role prefix if it is configured.
Unfortunately, the role prefix customization in Spring is a bit hacky, in many places the default prefix, ROLE_
is hardcoded, but in addition to that, a bean of type GrantedAuthorityDefaults
is checked in the Spring context, and if it exists, the custom role prefix it has is respected.
Bringing all this information together, a better role checker implementation would be something like:
@Component
public class RoleChecker {
@Autowired(required = false)
private GrantedAuthorityDefaults grantedAuthorityDefaults;
public boolean hasRole(String role) {
String rolePrefix = grantedAuthorityDefaults != null ? grantedAuthorityDefaults.getRolePrefix() : "ROLE_";
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::getAuthorities)
.map(Collection::stream)
.orElse(Stream.empty())
.map(GrantedAuthority::getAuthority)
.map(authority -> rolePrefix + authority)
.anyMatch(role::equals);
}
}
Probably somewhere you have DBconnection->close();
and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close();
in __destruct()
(because __destruct
is event, after which there will be a need for execution of queries)
Your Call works if it were a Table Valued Function. Since its a scalar function, you need to call it like:
SELECT dbo.fn_HomePageSlider(9, 3025) AS MyResult
Incase its useful to others, the following is what worked for me:
On my machine, although npm proxy was set correctly, npm install
waits forever doing something like sill extract. Re-trying npm install
waits forever on the same package again and again.
After waiting for a long timeout, npm install
printed an error message implying that git was trying to fetch something.
The problem vanished after configuring git proxy using the below command:
git config --global http.proxy https://proxy-server:port
Note the https
in the value of http.proxy
without which the configuration did not take effect. Proxy server settings (http / https / port) might vary for users; hence its worth spending a bit of time experimenting with npm and git proxy server settings.
29 = 512 values, because that's how many combinations of zeroes and ones you can have.
What those values represent however will depend on the system you are using. If it's an unsigned integer, you will have:
000000000 = 0 (min)
000000001 = 1
...
111111110 = 510
111111111 = 511 (max)
In two's complement, which is commonly used to represent integers in binary, you'll have:
000000000 = 0
000000001 = 1
...
011111110 = 254
011111111 = 255 (max)
100000000 = -256 (min) <- yay integer overflow
100000001 = -255
...
111111110 = -2
111111111 = -1
In general, with k bits you can represent 2k values. Their range will depend on the system you are using:
Unsigned: 0 to 2k-1
Signed: -2k-1 to 2k-1-1
Try that way:
<a href="javascript:void(0)" onclick="this.onclick = false; fireThisFunctionOnlyOnce()"> Fire function </a>
In simple words:
sudo find / | grep -i mysql
This worked like a charm for me. Just went through the list and ensured that anything MySQL related was deleted.
I am using Linux Mint : After installing LAMP along with PhpMyAdmin, I linked both the configuration files of Apache and PhpMyAdmin. It did the trick. Following are the commands.
sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf
sudo /etc/init.d/apache2 reload
Here in simpler words:
DOM
Tree model parser (Object based) (Tree of nodes).
DOM loads the file into the memory and then parse- the file.
Has memory constraints since it loads the whole XML file before parsing.
DOM is read and write (can insert or delete nodes).
If the XML content is small, then prefer DOM parser.
Backward and forward search is possible for searching the tags and evaluation of the information inside the tags. So this gives the ease of navigation.
Slower at run time.
SAX
Event based parser (Sequence of events).
SAX parses the file as it reads it, i.e. parses node by node.
No memory constraints as it does not store the XML content in the memory.
SAX is read only i.e. can’t insert or delete the node.
Use SAX parser when memory content is large.
SAX reads the XML file from top to bottom and backward navigation is not possible.
Faster at run time.
Another method is to see if you've surpassed the error checking in your code by accident. Search all your code for any instance of error_reporting(). If you call it without parameters, it just returns the current level, and is harmless. If you call it with a parameter, such as 0 (zero), it will turn off error reporting.
You can test for this in CodeIgnitor by looking at their core library under ../system/core/Common.php and finding a section that's at about line 615 that looks like:
if (($severity & error_reporting()) !== $severity)
{
return;
}
Add something like:
if (($severity & error_reporting()) !== $severity)
{
echo "Suppressing errors!";
return;
}
and you should be able to trap for surpassed errors, and debug from there.
Just in case someone is using Bootstrap 4. It seems we can no longer use .modal-backdrop.in
, but must now use .modal-backdrop.show
. Fade effect preserved.
.modal-backdrop.show {
opacity: 0.7;
}
This code worked for me.
<?php_x000D_
$decoded = base64_decode($base64);_x000D_
$file = 'invoice.pdf';_x000D_
file_put_contents($file, $decoded);_x000D_
_x000D_
if (file_exists($file)) {_x000D_
header('Content-Description: File Transfer');_x000D_
header('Content-Type: application/octet-stream');_x000D_
header('Content-Disposition: attachment; filename="'.basename($file).'"');_x000D_
header('Expires: 0');_x000D_
header('Cache-Control: must-revalidate');_x000D_
header('Pragma: public');_x000D_
header('Content-Length: ' . filesize($file));_x000D_
readfile($file);_x000D_
exit;_x000D_
}_x000D_
?>
_x000D_
I don't have enough rep here to add this as a comment, but IMO it's good style to write your headers with #include guards anyway, which as noted by Paranaix a few hours ago would prevent a multiple-definition error. Unless you're already using a separate CPP file, it's not necessary to use one just to initialize static non-integral members.
#ifndef FOO_H
#define FOO_H
#include "bar.h"
class foo
{
private:
static bar i;
};
bar foo::i = VALUE;
#endif
I see no need to use a separate CPP file for this. Sure, you can, but there's no technical reason why you should have to.
There is another way. There is a program called PowerRun which allows for elevated cmd to be run. Even with TrustedInstaller rights. It allows for both console and GUI commands.