what is a SID and Service name
please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm
In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)"
When I have to use one or another? Why do I need two of them?
Consider below mapping in a RAC Environment,
SID SERVICE_NAME
bob1 bob
bob2 bob
bob3 bob
bob4 bob
if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME.
Please refer, https://community.oracle.com/thread/4049517
I've been going back and forth on these two options the last few times I've needed them. Up until recently, my preference has been for the sealed trait/case object option.
1) Scala Enumeration Declaration
object OutboundMarketMakerEntryPointType extends Enumeration {
type OutboundMarketMakerEntryPointType = Value
val Alpha, Beta = Value
}
2) Sealed Traits + Case Objects
sealed trait OutboundMarketMakerEntryPointType
case object AlphaEntryPoint extends OutboundMarketMakerEntryPointType
case object BetaEntryPoint extends OutboundMarketMakerEntryPointType
While neither of these really meet all of what a java enumeration gives you, below are the pros and cons:
Scala Enumeration
Pros: -Functions for instantiating with option or directly assuming accurate (easier when loading from a persistent store) -Iteration over all possible values is supported
Cons: -Compilation warning for non-exhaustive search is not supported (makes pattern matching less ideal)
Case Objects/Sealed traits
Pros: -Using sealed traits, we can pre-instantiate some values while others can be injected at creation time -full support for pattern matching (apply/unapply methods defined)
Cons: -Instantiating from a persistent store - you often have to use pattern matching here or define your own list of all possible 'enum values'
What ultimately made me change my opinion was something like the following snippet:
object DbInstrumentQueries {
def instrumentExtractor(tableAlias: String = "s")(rs: ResultSet): Instrument = {
val symbol = rs.getString(tableAlias + ".name")
val quoteCurrency = rs.getString(tableAlias + ".quote_currency")
val fixRepresentation = rs.getString(tableAlias + ".fix_representation")
val pointsValue = rs.getInt(tableAlias + ".points_value")
val instrumentType = InstrumentType.fromString(rs.getString(tableAlias +".instrument_type"))
val productType = ProductType.fromString(rs.getString(tableAlias + ".product_type"))
Instrument(symbol, fixRepresentation, quoteCurrency, pointsValue, instrumentType, productType)
}
}
object InstrumentType {
def fromString(instrumentType: String): InstrumentType = Seq(CurrencyPair, Metal, CFD)
.find(_.toString == instrumentType).get
}
object ProductType {
def fromString(productType: String): ProductType = Seq(Commodity, Currency, Index)
.find(_.toString == productType).get
}
The .get
calls were hideous - using enumeration instead I can simply call the withName method on the enumeration as follows:
object DbInstrumentQueries {
def instrumentExtractor(tableAlias: String = "s")(rs: ResultSet): Instrument = {
val symbol = rs.getString(tableAlias + ".name")
val quoteCurrency = rs.getString(tableAlias + ".quote_currency")
val fixRepresentation = rs.getString(tableAlias + ".fix_representation")
val pointsValue = rs.getInt(tableAlias + ".points_value")
val instrumentType = InstrumentType.withNameString(rs.getString(tableAlias + ".instrument_type"))
val productType = ProductType.withName(rs.getString(tableAlias + ".product_type"))
Instrument(symbol, fixRepresentation, quoteCurrency, pointsValue, instrumentType, productType)
}
}
So I think my preference going forward is to use Enumerations when the values are intended to be accessed from a repository and case objects/sealed traits otherwise.
There are lot of options available , one of them is :
CREATE TEMPORARY TABLE temp_tb SELECT * FROM orig_tb;
ALTER TABLE temp_tb DROP col_x;
SELECT * FROM temp_tb;
Here the col_x is the column which u dont want to include in select statement.
Take a look at this question : Select all columns except one in MySQL?
You can also use the numpy package:
import numpy as np
A = np.array(a)
maximum_indices = np.where(A==max(a))
This will return an numpy array of all the indices that contain the max value
if you want to turn this to a list:
maximum_indices_list = maximum_indices.tolist()
Given this problem the Activator will work when there is a parameterless ctor. If this is a constraint consider using
System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject()
Math.ceil()
is the correct function to call. I'm guessing a
is an int
, which would make a / 100
perform integer arithmetic. Try Math.ceil(a / 100.0)
instead.
int a = 142;
System.out.println(a / 100);
System.out.println(Math.ceil(a / 100));
System.out.println(a / 100.0);
System.out.println(Math.ceil(a / 100.0));
System.out.println((int) Math.ceil(a / 100.0));
Outputs:
1
1.0
1.42
2.0
2
In February 2017, they merged a PR adding this feature, they released in April 2017.
so to spy on getters/setters you use:
const spy = spyOnProperty(myObj, 'myGetterName', 'get');
where myObj is your instance, 'myGetterName' is the name of that one defined in your class as get myGetterName() {}
and the third param is the type get
or set
.
You can use the same assertions that you already use with the spies created with spyOn
.
So you can for example:
const spy = spyOnProperty(myObj, 'myGetterName', 'get'); // to stub and return nothing. Just spy and stub.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.returnValue(1); // to stub and return 1 or any value as needed.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.callThrough(); // Call the real thing.
Here's the line in the github source code where this method is available if you are interested.
Answering the original question, with jasmine 2.6.1, you would:
const spy = spyOnProperty(myObj, 'valueA', 'get').andReturn(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();
Tony is a pure genius. However to achieve even better auto-completion try setting the triggers to this:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz =.(!+-*/~,[{@#$%^&
(specifically aranged in order of usage for faster performance :)
Here's a solution using simpler functions and no hacks:
all.equal(a, as.integer(a))
What's more, you can test a whole vector at once, if you wish. Here's a function:
testInteger <- function(x){
test <- all.equal(x, as.integer(x), check.attributes = FALSE)
if(test == TRUE){ return(TRUE) }
else { return(FALSE) }
}
You can change it to use *apply
in the case of vectors, matrices, etc.
This should do it if memory serves:
List<MyType> fixed = Arrays.asList(new MyType[100]);
The functionality of map
and filter
was intentionally changed to return iterators, and reduce was removed from being a built-in and placed in functools.reduce
.
So, for filter
and map
, you can wrap them with list()
to see the results like you did before.
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> list(filter(f, range(2, 25)))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> list(map(cube, range(1, 11)))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> import functools
>>> def add(x,y): return x+y
...
>>> functools.reduce(add, range(1, 11))
55
>>>
The recommendation now is that you replace your usage of map and filter with generators expressions or list comprehensions. Example:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> [i for i in range(2, 25) if f(i)]
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> [cube(i) for i in range(1, 11)]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>>
They say that for loops are 99 percent of the time easier to read than reduce, but I'd just stick with functools.reduce
.
Edit: The 99 percent figure is pulled directly from the What’s New In Python 3.0 page authored by Guido van Rossum.
The answers so far will work.. if you only want to use the height without padding, borders, etc.
If you would like to account for padding, borders, and margin, you should use .outerHeight
.
var bottom = $('#bottom').position().top + $('#bottom').outerHeight(true);
If your app is one of:
{
".sh": "bash",
".py": "python",
".rb": "ruby",
".coffee" : "coffee",
".php": "php",
".pl" : "perl",
".js" : "node"
}
and you don't mind a NodeJS dependency then install NodeJS and then:
npm install -g pm2
pm2 start yourapp.yourext --name "fred" # where .yourext is one of the above
pm2 start yourapp.yourext -i 0 --name "fred" # run your app on all cores
pm2 list
To keep all apps running on reboot (and daemonise pm2):
pm2 startup
pm2 save
Now you can:
service pm2 stop|restart|start|status
(also easily allows you to watch for code changes in your app directory and auto restart the app process when a code change happens)
The /g
modifier is used to perform a global match (find all matches rather than stopping after the first)
You can use \d
for digit, as it is shorter than [0-9]
.
JavaScript:
var s = "04.07.2012";
echo(s.replace(/\d/g, "X"));
Output:
XX.XX.XXXX
If you define the ListView
in XAML:
<ListView x:Name="listView"/>
Then you can add columns and populate it in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Add columns
var gridView = new GridView();
this.listView.View = gridView;
gridView.Columns.Add(new GridViewColumn {
Header = "Id", DisplayMemberBinding = new Binding("Id") });
gridView.Columns.Add(new GridViewColumn {
Header = "Name", DisplayMemberBinding = new Binding("Name") });
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
However, it's easier to define the columns in XAML (inside the ListView
definition):
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
And then just populate the list in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
MyItem
DefinitionMyItem
is defined like this:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
You have a selector ul
on line 252
which is setting list-style: square outside none
(a square bullet). You'll have to change it to list-style: none
or just remove the line.
If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:
ul#groups-list.items-list { list-style: none }
Assuming that your docker container is up and running, you can run commands as:
docker exec mycontainer /bin/sh -c "cmd1;cmd2;...;cmdn"
null
is a special value that is not an instance of any class. This is illustrated by the following program:
public class X {
void f(Object o)
{
System.out.println(o instanceof String); // Output is "false"
}
public static void main(String[] args) {
new X().f(null);
}
}
You could try using https://www.printnode.com which is essentially exactly the service that you are looking for. You download and install a desktop client onto the users computer - https://www.printnode.com/download. You can then discover and print to any printers on that user's computer using their JSON API https://www.printnode.com/docs/api/curl/. They have lots of libs here: https://github.com/PrintNode/
Try using the SQL_NO_CACHE (MySQL 5.7) option in your query. (MySQL 5.6 users click HERE )
eg.
SELECT SQL_NO_CACHE * FROM TABLE
This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.
$.ajax("youurl", function(data){
if (data.success == true)
setTimeout(function(){window.location = window.location}, 5000);
})
)
You don't necessarily have to choose between the two paradigms. You can write software with an OO architecture using many functional concepts. FP and OOP are orthogonal in nature.
Take for example C#. You could say it's mostly OOP, but there are many FP concepts and constructs. If you consider Linq, the most important constructs that permit Linq to exist are functional in nature: lambda expressions.
Another example, F#. You could say it's mostly FP, but there are many OOP concepts and constructs available. You can define classes, abstract classes, interfaces, deal with inheritance. You can even use mutability when it makes your code clearer or when it dramatically increases performance.
Many modern languages are multi-paradigm.
As I'm in the same boat (OOP background, learning FP), I'd suggest you some readings I've really appreciated:
Functional Programming for Everyday .NET Development, by Jeremy Miller. A great article (although poorly formatted) showing many techniques and practical, real-world examples of FP on C#.
Real-World Functional Programming, by Tomas Petricek. A great book that deals mainly with FP concepts, trying to explain what they are, when they should be used. There are many examples in both F# and C#. Also, Petricek's blog is a great source of information.
On newer versions of PHP on Windows, the majority of answers here won't work, since the corresponding configuration lines have changed.
For PHP 7.x, you need to uncomment (remove the ;
at the beginning of the line) the following lines:
extension_dir = "ext"
extension=openssl
They do different things. exec
replaces the current process with the new process and never returns. system
invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.
There is also the Out-Null
cmdlet, which you can use in a pipeline, for example, Add-Item | Out-Null
.
NAME
Out-Null
SYNOPSIS
Deletes output instead of sending it to the console.
SYNTAX
Out-Null [-inputObject <psobject>] [<CommonParameters>]
DETAILED DESCRIPTION
The Out-Null cmdlet sends output to NULL, in effect, deleting it.
RELATED LINKS
Out-Printer
Out-Host
Out-File
Out-String
Out-Default
REMARKS
For more information, type: "get-help Out-Null -detailed".
For technical information, type: "get-help Out-Null -full".
There is an in?
method in ActiveSupport
(part of Rails) since v3.1, as pointed out by @campaterson. So within Rails, or if you require 'active_support'
, you can write:
'Unicorn'.in?(['Cat', 'Dog', 'Bird']) # => false
OTOH, there is no in
operator or #in?
method in Ruby itself, even though it has been proposed before, in particular by Yusuke Endoh a top notch member of ruby-core.
As pointed out by others, the reverse method include?
exists, for all Enumerable
s including Array
, Hash
, Set
, Range
:
['Cat', 'Dog', 'Bird'].include?('Unicorn') # => false
Note that if you have many values in your array, they will all be checked one after the other (i.e. O(n)
), while that lookup for a hash will be constant time (i.e O(1)
). So if you array is constant, for example, it is a good idea to use a Set instead. E.g:
require 'set'
ALLOWED_METHODS = Set[:to_s, :to_i, :upcase, :downcase
# etc
]
def foo(what)
raise "Not allowed" unless ALLOWED_METHODS.include?(what.to_sym)
bar.send(what)
end
A quick test reveals that calling include?
on a 10 element Set
is about 3.5x faster than calling it on the equivalent Array
(if the element is not found).
A final closing note: be wary when using include?
on a Range
, there are subtleties, so refer to the doc and compare with cover?
...
I have added a line in list item like below
<View
android:id="@+id/divider"
android:layout_width="match_parent"
android:layout_height="1px"
android:background="@color/dividerColor"/>
1px will draw the thin line.
If you want to hide the divider for the last row then
divider.setVisiblity(View.GONE);
on the onBindViewHolder for the last list Item.
Lately, BitBucket needs you to generate an App Password:
Settings/Access Management/App Passwords.
Another forum provided this answer:
Ahh, figured this out. The following system properties need to be set, so that the "logging.properties" file can be picked up.
Assuming that the tomcat is located under an Eclipse project, add the following under the "Arguments" tab of its launch configuration:
-Dcatalina.base="${project_loc}\<apache-tomcat-5.5.23_loc>"
-Dcatalina.home="${project_loc}\<apache-tomcat-5.5.23_loc>"
-Djava.util.logging.config.file="${project_loc}\<apache-tomcat-5.5.23_loc>\conf\logging.properties"
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
http://www.coderanch.com/t/442412/Tomcat/Tweaking-tomcat-logging-properties-file
The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:
<StackPanel>
<Label Foreground="Red">Red text</Label>
<Label Foreground="Blue">Blue text</Label>
</StackPanel>
In summary, No, there was nothing wrong with your snippet.
Visual Studio defines _DEBUG
when you specify the /MTd
or /MDd
option, NDEBUG
disables standard-C assertions. Use them when appropriate, ie _DEBUG
if you want your debugging code to be consistent with the MS CRT debugging techniques and NDEBUG
if you want to be consistent with assert()
.
If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.
You can use both PHP and javascript. Perform your php codes in the backend and redirect to a php page. On the php page you redirected to add the code below:
<?php if(condition_to_check_for){ ?>
<script type="text/javascript">
window.open('url_goes_here', '_blank');
</script>
<? } ?>
On PostgreSQL manual
There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.
I usually use text
References: http://www.postgresql.org/docs/current/static/datatype-character.html
I used this single line of code to create a new UIImage which is scaled. Set the scale and orientation params to achieve what you want. The first line of code just grabs the image.
// grab the original image
UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
// scaling set to 2.0 makes the image 1/2 the size.
UIImage *scaledImage =
[UIImage imageWithCGImage:[originalImage CGImage]
scale:(originalImage.scale * 2.0)
orientation:(originalImage.imageOrientation)];
Using codecs.open
as Alex Martelli suggested proved to be useful to me.
import codecs
delimiter = ';'
reader = codecs.open("your_filename.csv", 'r', encoding='utf-8')
for line in reader:
row = line.split(delimiter)
# do something with your row ...
if using logging.config.fileConfig with a configuration file use something like:
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S
First add next code in your sp:
BEGIN
dbms_output.enable();
dbms_output.put_line ('TEST LINE');
END;
Compile your code in your Oracle SQL developer. So go to Menu View--> dbms output. Click on Icon Green Plus and select your schema. Run your sp now.
The way to use the ellipsis or varargs inside the method is as if it were an array:
public void PrintWithEllipsis(String...setOfStrings) {
for (String s : setOfStrings)
System.out.println(s);
}
This method can be called as following:
obj.PrintWithEllipsis(); // prints nothing
obj.PrintWithEllipsis("first"); // prints "first"
obj.PrintWithEllipsis("first", "second"); // prints "first\nsecond"
Inside PrintWithEllipsis
, the type of setOfStrings
is an array of String.
So you could save the compiler some work and pass an array:
String[] argsVar = {"first", "second"};
obj.PrintWithEllipsis(argsVar);
For varargs methods, a sequence parameter is treated as being an array of the same type. So if two signatures differ only in that one declares a sequence and the other an array, as in this example:
void process(String[] s){}
void process(String...s){}
then a compile-time error occurs.
Source: The Java Programming Language specification, where the technical term is variable arity parameter
rather than the common term varargs
.
You can even use this one. worked well for me
$("#registerform").attr("action", "register.php?btnsubmit=Save")
$('#registerform').submit();
this will submit btnsubmit =Save as GET value to register.php form.
You have to read the API carefully for this methods. Sometimes you can get confused very easily.
It is either:
if (B.class.isInstance(view))
API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)
or:
if (B.class.isAssignableFrom(view.getClass()))
API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter
or (without reflection and the recommended one):
if (view instanceof B)
first store the values in $rootScope as
.run(function($rootScope){
$rootScope.myData = {name : "nikhil"}
})
.controller('myCtrl', function($scope) {
var a ="Nikhilesh";
$scope.myData.name = a;
});
.controller('myCtrl2', function($scope) {
var b = $scope.myData.name;
)}
$rootScope is the parent of all $scope, each $scope receives a copy of $rootScope data which you can access using $scope itself.
I needed to commit my existing Git repository to an empty SVN repository.
This is how I managed to do this:
$ git checkout master
$ git branch svn
$ git svn init -s --prefix=svn/ --username <user> https://path.to.repo.com/svn/project/
$ git checkout svn
$ git svn fetch
$ git reset --hard remotes/svn/trunk
$ git merge master
$ git svn dcommit
It worked without problems. I hope this helps someone.
Since I had to authorize myself with a different username to the SVN repository (my origin
uses private/public key authentication), I had to use the --username
property.
The answer given is
def set_4(x):
y = []
for i in x:
y.append(i)
y[0] = 4
return y
and
l = [0]
def set_3(x):
x[0] = 3
set_3(l)
print(l[0])
which is the best answer so far as it does what it says in the question. However,it does seem a very clumsy way compared to VB or Pascal.Is it the best method we have?
Not only is it clumsy, it involves mutating the original parameter in some way manually eg by changing the original parameter to a list: or copying it to another list rather than just saying: "use this parameter as a value " or "use this one as a reference". Could the simple answer be there is no reserved word for this but these are great work arounds?
Node.js is an open source command line tool built for the server side JavaScript code. You can download a tarball, compile and install the source. It lets you run JavaScript programs.
The JavaScript is executed by the V8, a JavaScript engine developed by Google which is used in Chrome browser. It uses a JavaScript API to access the network and file system.
It is popular for its performance and the ability to perform parallel operations.
Understanding node.js is the best explanation of node.js I have found so far.
Following are some good articles on the topic.
I'd re-iterate Donny V. answer and Josh's
"The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support."
(and upvote if I had the reputation.)
I can't remember the last time if ever, I was grateful of the fact HttpWebRequest threw exceptions for status codes >= 400. To get around these issues you need to catch the exceptions immediately, and map them to some non-exception response mechanisms in your code...boring, tedious and error prone in itself. Whether it be communicating with a database, or implementing a bespoke web proxy, its 'nearly' always desirable that the Http driver just tell your application code what was returned, and leave it up to you to decide how to behave.
Hence HttpClient is preferable.
Assume that you have the list of ALL keys (you can get this list by iterating through all dictionaries and get their keys). Let's name it listKeys
. Also:
listValues
is the list of ALL values for a single key that you want
to merge.allDicts
: all dictionaries that you want to merge.result = {}
for k in listKeys:
listValues = [] #we will convert it to tuple later, if you want.
for d in allDicts:
try:
fileList.append(d[k]) #try to append more values to a single key
except:
pass
if listValues: #if it is not empty
result[k] = typle(listValues) #convert to tuple, add to new dictionary with key k
Try to place a
return 0;
on the end of your code or just erase the
void
from your main function I hope that I helped
Yes, but note: since the attribute selector (of course) targets the element's attribute, not the DOM node's value property (elem.value), it will not update while the form field is being updated.
Otherwise (with some trickery) I think it could have been used to make a CSS-only substitute for the "placeholder" attribute/functionality. Maybe that's what the OP was after? :)
Note: All of the following instructions apply universally (aka to all OSes) unless otherwise specified.
You will need:
Change the file extension of the .apk
file by either adding a .zip
extension to the filename, or to change .apk
to .zip
.
For example, com.example.apk
becomes com.example.zip
, or com.example.apk.zip
. Note that on Windows and macOS, it may prompt you whether you are sure you want to change the file extension. Click OK or Add if you're using macOS:
Extract the renamed APK file in a specific folder. For example, let that folder be demofolder
.
If it didn't work, try opening the file in another application such as WinZip or 7-Zip.
For macOS, you can try running unzip
in Terminal (available at /Applications/Terminal.app
), where it takes one or more arguments: the file to unzip + optional arguments. See man unzip
for documentation and arguments.
Download dex2jar
(see all releases on GitHub) and extract that zip file in the same folder as stated in the previous point.
Open command prompt (or a terminal) and change your current directory to the folder created in the previous point and type the command d2j-dex2jar.bat classes.dex
and press enter. This will generate classes-dex2jar.jar
file in the same folder.
d2j-dex2jar.bat
with d2j-dex2jar.sh
. In other words, run d2j-jar2dex.sh classes.dex
in the terminal and press enter.Download Java Decompiler (see all releases on Github) and extract it and start (aka double click) the executable/application.
From the JD-GUI window, either drag and drop the generated classes-dex2jar.jar
file into it, or go to File > Open File...
and browse for the jar.
Next, in the menu, go to File > Save All Sources
(Windows: Ctrl+Alt+S, macOS: ?+?+S). This should open a dialog asking you where to save a zip file named `classes-dex2jar.jar.src.zip" consisting of all packages and java files. (You can rename the zip file to be saved)
Extract that zip file (classes-dex2jar.jar.src.zip
) and you should get all java files of the application.
xml
files from APKapktool
website for installation instructions and moreWindows:
myxmlfolder
).myxmlfolder
folder and rename the apktool jar file to apktool.jar
..apk
file in the same folder (i.e myxmlfolder
).Open the command prompt (or terminal) and change your current directory to the folder where apktool
is stored (in this case, myxmlfolder
). Next, type the command apktool if framework-res.apk
.
What we're doing here is that we are installing a framework. For more info, see the docs.
In the command prompt, type the command apktool d filename.apk
(where filename
is the name of apk file). This should decode the file. For more info, see the docs.
This should result in a folder filename.out
being outputted, where filename
is the original name of the apk file without the .apk
file extension. In this folder are all the XML files such as layout, drawables etc.
Source: How to get source code from APK file - Comptech Blogspot
You can add + behind the variable and it will force it to be an integer
var dots = 5
function increase(){
dots = +dots + 5;
}
import os
import ftplib
from contextlib import closing
with closing(ftplib.FTP()) as ftp:
try:
ftp.connect(host, port, 30*5) #5 mins timeout
ftp.login(login, passwd)
ftp.set_pasv(True)
with open(local_filename, 'w+b') as f:
res = ftp.retrbinary('RETR %s' % orig_filename, f.write)
if not res.startswith('226 Transfer complete'):
print('Downloaded of file {0} is not compile.'.format(orig_filename))
os.remove(local_filename)
return None
return local_filename
except:
print('Error during download from FTP')
I have no idea why no-one uses this... (maybe because it's only a webkit thing)
Open console:
monitorEvents(document.body); // logs all events on the body
monitorEvents(document.body, 'mouse'); // logs mouse events on the body
monitorEvents(document.body.querySelectorAll('input')); // logs all events on inputs
This is quite simple:
my_data
is a before defined structure type.
So you want to declare an my_data
-array of some elements, as you would do with
char a[] = { 'a', 'b', 'c', 'd' };
So the array would have 4 elements and you initialise them as
a[0] = 'a', a[1] = 'b', a[1] = 'c', a[1] ='d';
This is called a designated initializer (as i remember right).
and it just indicates that data has to be of type my_dat
and has to be an array that needs to store so many my_data structures that there is a structure with each type member name Peter, James, John and Mike.
On Fedora 29 with Wireshark 3.0.0 only adding a user to the wireshark group is required:
sudo usermod -a -G wireshark $USER
Then log out and log back in (or reboot), and Wireshark should work correctly.
A No Framework JavaScript Approach, checks for both vertical and horizontal
/*
* hasScrollBars
*
* Checks to see if an element has scrollbars
*
* @returns {object}
*/
Element.prototype.hasScrollBars = function() {
return {"vertical": this.scrollHeight > this.style.height, "horizontal": this.scrollWidth > this.style.width};
}
Use it like this
if(document.getElementsByTagName("body")[0].hasScrollBars().vertical){
alert("vertical");
}
if(document.getElementsByTagName("body")[0].hasScrollBars().horizontal){
alert("horizontal");
}
First Try to set proxy using the following command
SET HTTPS_PROXY=http://proxy.***.com:PORT#
Then Try using the command
pip install ModuleName
You misspelled permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
It means something like this:
std::vector<Movie *> movies;
Then you add to the vector as you read lines:
movies.push_back(new Movie(...));
Remember to delete all of the Movie*
objects once you are done with the vector.
It looks like you may have created a Vagrant project with just vagrant init
. That will create your Vagrantfile, but it won't have a box defined.
Instead, you could try
$ vagrant init hashicorp/precise32
$ vagrant up
which uses a standard Ubuntu image. The Vagrant website has a Getting Started which gives some good examples.
You're swapping endianness between your two methods. You have intToByteArray(int a)
assigning the low-order bits into ret[0]
, but then byteArrayToInt(byte[] b)
assigns b[0]
to the high-order bits of the result. You need to invert one or the other, like:
public static byte[] intToByteArray(int a)
{
byte[] ret = new byte[4];
ret[3] = (byte) (a & 0xFF);
ret[2] = (byte) ((a >> 8) & 0xFF);
ret[1] = (byte) ((a >> 16) & 0xFF);
ret[0] = (byte) ((a >> 24) & 0xFF);
return ret;
}
There are multiple REST frameworks out there. I would strongly recommend looking into Slim mini Framework for PHP
Here is a list of others.
As mentioned by others, this is used for front end cache busting. To implement this, I have personally find grunt-cache-bust npm package useful.
A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.
Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute.
A data contract can be defined as follows:
It describes the external format of data passed to and from service operations
It defines the structure and types of data exchanged in service messages
We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract and DataMember attribute.
Try this piece of code to create circular progress bar(pie chart). pass it integer value to draw how many percent of filling area. :)
private void circularImageBar(ImageView iv2, int i) {
Bitmap b = Bitmap.createBitmap(300, 300,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
Paint paint = new Paint();
paint.setColor(Color.parseColor("#c4c4c4"));
paint.setStrokeWidth(10);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(150, 150, 140, paint);
paint.setColor(Color.parseColor("#FFDB4C"));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.FILL);
final RectF oval = new RectF();
paint.setStyle(Paint.Style.STROKE);
oval.set(10,10,290,290);
canvas.drawArc(oval, 270, ((i*360)/100), false, paint);
paint.setStrokeWidth(0);
paint.setTextAlign(Align.CENTER);
paint.setColor(Color.parseColor("#8E8E93"));
paint.setTextSize(140);
canvas.drawText(""+i, 150, 150+(paint.getTextSize()/3), paint);
iv2.setImageBitmap(b);
}
It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress
and the relative URI passed to the GetAsync
method -- or whichever other method of HttpClient
-- only one permutation works. You must place a slash at the end of the BaseAddress
, and you must not place a slash at the beginning of your relative URI, as in the following example.
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}
Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient
.
For modern browsers, the best solution is to use Promises.
Go to https://stackoverflow.com/a/63936671/13720928 to find out more!
Go to the Declaration of the desired object and mark it Shared.
Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX
Updated for Swift 3
This example will show two methods to programmatically add the following constraints the same as if doing it in the Interface Builder:
Width and Height
Center in Container
override func viewDidLoad() {
super.viewDidLoad()
// set up the view
let myView = UIView()
myView.backgroundColor = UIColor.blue
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
// Add constraints code here (choose one of the methods below)
// ...
}
// width and height
myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true
// center in container
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
// width and height
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true
// center in container
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint
Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint
Style.In ES6 you can use Math.sign function to determine if,
1. its +ve no
2. its -ve no
3. its zero (0)
4. its NaN
console.log(Math.sign(1)) // prints 1
console.log(Math.sign(-1)) // prints -1
console.log(Math.sign(0)) // prints 0
console.log(Math.sign("abcd")) // prints NaN
You can also use the SqlConnectionStringBuilder
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
builder.ConnectTimeout = 10;
using (var connection = new SqlConnection(builder.ToString()))
{
// code goes here
}
You could use GNU Awk, see this article of the user guide.
As an improvement to the solution presented in the article (in June 2015), the following gawk command allows double quotes inside double quoted fields; a double quote is marked by two consecutive double quotes ("") there. Furthermore, this allows empty fields, but even this can not handle multiline fields. The following example prints the 3rd column (via c=3
) of textfile.csv:
#!/bin/bash
gawk -- '
BEGIN{
FPAT="([^,\"]*)|(\"((\"\")*[^\"]*)*\")"
}
{
if (substr($c, 1, 1) == "\"") {
$c = substr($c, 2, length($c) - 2) # Get the text within the two quotes
gsub("\"\"", "\"", $c) # Normalize double quotes
}
print $c
}
' c=3 < <(dos2unix <textfile.csv)
Note the use of dos2unix
to convert possible DOS style line breaks (CRLF i.e. "\r\n") and UTF-16 encoding (with byte order mark) to "\n" and UTF-8 (without byte order mark), respectively. Standard CSV files use CRLF as line break, see Wikipedia.
If the input may contain multiline fields, you can use the following script. Note the use of special string for separating records in output (since the default separator newline could occur within a record). Again, the following example prints the 3rd column (via c=3
) of textfile.csv:
#!/bin/bash
gawk -- '
BEGIN{
RS="\0" # Read the whole input file as one record;
# assume there is no null character in input.
FS="" # Suppose this setting eases internal splitting work.
ORS="\n####\n" # Use a special output separator to show borders of a record.
}
{
nof=patsplit($0, a, /([^,"\n]*)|("(("")*[^"]*)*")/, seps)
field=0;
for (i=1; i<=nof; i++){
field++
if (field==c) {
if (substr(a[i], 1, 1) == "\"") {
a[i] = substr(a[i], 2, length(a[i]) - 2) # Get the text within
# the two quotes.
gsub(/""/, "\"", a[i]) # Normalize double quotes.
}
print a[i]
}
if (seps[i]!=",") field=0
}
}
' c=3 < <(dos2unix <textfile.csv)
There is another approach to the problem. csvquote can output contents of a CSV file modified so that special characters within field are transformed so that usual Unix text processing tools can be used to select certain column. For example the following code outputs the third column:
csvquote textfile.csv | cut -d ',' -f 3 | csvquote -u
csvquote
can be used to process arbitrary large files.
/* eslint-disable */
//suppress all warnings between comments
alert('foo');
/* eslint-enable */
This will disable all eslint rules within the block.
Just to add to Joe Kington's answer (not enough reputation for a comment) there is a good example of mixing 2d and 3d plots in the documentation at http://matplotlib.org/examples/mplot3d/mixed_subplots_demo.html which shows projection='3d' working in combination with the Axes3D import.
from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.add_subplot(2, 1, 1)
...
ax = fig.add_subplot(2, 1, 2, projection='3d')
In fact as long as the Axes3D import is present the line
from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.gca(projection='3d')
as used by the OP also works. (checked with matplotlib version 1.3.1)
myList = [1, 2, 3, 100, 5]
sorted(range(len(myList)),key=myList.__getitem__)
[0, 1, 2, 4, 3]
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</ScrollView>
You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking
In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))
In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]:
A B C D
12 0.491683 0.137766 0.859753 -1.041487
13 0.376200 0.575667 1.534179 1.247358
14 0.428739 1.539973 1.057848 -1.254489
In [19]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)].count()
Out[19]:
A 3
B 3
C 3
D 3
dtype: int64
In [20]: len(df[(df['A']>0) & (df['B']>0) & (df['C']>0)])
Out[20]: 3
The easiest way would be to package the Vagrant box and then copy (e.g. scp
or rsync
) it over to the other PC, add it and vagrant up
;-)
For detailed steps, check this out =>
Is there any way to clone a vagrant box that is already installed
generator = myfunct()
while True:
my_element = generator.next()
make sure to catch the exception thrown after the last element is taken
According to this post this error message means:
Heap size is larger than your computer's physical memory.
Edit: Heap is not the only memory that is reserved, I suppose. At least there are other JVM settings like PermGenSpace that ask for the memory. With heap size 128M and a PermGenSpace of 64M you already fill the space available.
Why not downsize other memory settings to free up space for the heap?
if all your value are positive, you can do -max(-n)
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
std::cout << '\7';
Just throw any RuntimeException
from a method marked as @Transactional
.
By default all RuntimeException
s rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor()
and noRollbackFor()
annotation parameters:
@Transactional(rollbackFor=Exception.class)
This will rollback transaction after throwing any exception.
Just as addition to @thatjuan
's answer.
More compatible PHP4 version of this:
if (!function_exists('http_build_query')) {
if (!defined('PHP_QUERY_RFC1738')) {
define('PHP_QUERY_RFC1738', 1);
}
if (!defined('PHP_QUERY_RFC3986')) {
define('PHP_QUERY_RFC3986', 2);
}
function http_build_query($query_data, $numeric_prefix = '', $arg_separator = '&', $enc_type = PHP_QUERY_RFC1738)
{
$data = array();
foreach ($query_data as $key => $value) {
if (is_numeric($key)) {
$key = $numeric_prefix . $key;
}
if (is_scalar($value)) {
$k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($key) : rawurlencode($key);
$v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($value) : rawurlencode($value);
$data[] = "$k=$v";
} else {
foreach ($value as $sub_k => $val) {
$k = "$key[$sub_k]";
$k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($k) : rawurlencode($k);
$v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($val) : rawurlencode($val);
$data[] = "$k=$v";
}
}
}
return implode($arg_separator, $data);
}
}
After a long search, I discovered that a dependency was somehow corrupted on my machine in a maven project. The strange thing was that the dependency was still working correctly in the compiled java code. When I cleaned and rebuilt my maven dependency cache however, the problem went away and IntelliJ recognized the package. You can do this by running:
mvn dependency:purge-local-repository
Intrestingly, the source of my problem hence wasn't IntelliJ, but maven itself.
I downloaded Android Studio and installed it. The installer said:-
Android Studio => ( 500 MB )
Android SDK => ( 2.3 GB )
Android Studio installer is actually an "Android SDK Installer" along with a sometimes useful tool called "Android Studio".
Most importantly:- Android Studio Installer will not just install the SDK. It will also:-
Things which you will have to do manually if you install the SDK from its zip file.
Just take it easy. Install the Android Studio.
****************************** Edit ******************************
So, being inspired by the responses in the comments I would like to update my answer.
The update is that only (and only) if 500MB of hard disk space does not matter much to you than you should go for Android Studio otherwise other answers would be better for you.
Android Studio worked for me as I had a 1TB hard disk which is 2000 times 500MB.
Also, note: that RAM sizse should not a restriction for you as you would not even be running Android Studio.
I came to this solution as I was myself stuck in this problem. I tried other answers but for some reason (maybe my in-competencies) they did not work for me. I decided to go for Android Studio and realized that it was merely 18% of the total installation and SDK was 82% of it. While I used to think otherwise. I am not deleting the answers inspite of negative rating as the answer worked for me. I might work for someone elese with a 1 TB hard disk (which is pretty common these days).
I found I COULD use "if-then" statements in a lambda. For instance:
eval_op = {
'|' : lambda x,y: eval(y) if (eval(x)==0) else eval(x),
'&' : lambda x,y: 0 if (eval(x)==0) else eval(y),
'<' : lambda x,y: 1 if (eval(x)<eval(y)) else 0,
'>' : lambda x,y: 1 if (eval(x)>eval(y)) else 0,
}
If the fields are nullable, then you'll have to handle those nulls. Remember that null is contagious, and concat('foo', null)
simply results in NULL
as well:
SELECT CONCAT(ISNULL(column1, ''),ISNULL(column2,'')) etc...
Basically test each field for nullness, and replace with an empty string if so.
You can't do this with plain vanilla HTML, so JSF can't do much for you here as well.
If you're targeting decent browsers only, then just make use of CSS3:
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<label class="unselectable">Unselectable label</label>
If you'd like to cover older browsers as well, then consider this JavaScript fallback:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2310734</title>
<script>
window.onload = function() {
var labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
disableSelection(labels[i]);
}
};
function disableSelection(element) {
if (typeof element.onselectstart != 'undefined') {
element.onselectstart = function() { return false; };
} else if (typeof element.style.MozUserSelect != 'undefined') {
element.style.MozUserSelect = 'none';
} else {
element.onmousedown = function() { return false; };
}
}
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
If you're already using jQuery, then here's another example which adds a new function disableSelection()
to jQuery so that you can use it anywhere in your jQuery code:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2310734 with jQuery</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.fn.extend({
disableSelection: function() {
this.each(function() {
if (typeof this.onselectstart != 'undefined') {
this.onselectstart = function() { return false; };
} else if (typeof this.style.MozUserSelect != 'undefined') {
this.style.MozUserSelect = 'none';
} else {
this.onmousedown = function() { return false; };
}
});
}
});
$(document).ready(function() {
$('label').disableSelection();
});
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
. Let's replace it in its context:
i + 1 >= len(x)
<=> i >= 0
, the element x[i+1]
doesn't exist. Here, this element doesn't exist since the beginning of the for loop.To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
.
A safer alternative to git's filter-branch
is filter-repo
tool as suggested by git docs here.
git filter-repo --commit-callback '
old_email = b"[email protected]"
correct_name = b"Your Correct Name"
correct_email = b"[email protected]"
if commit.committer_email == old_email :
commit.committer_name = correct_name
commit.committer_email = correct_email
if commit.author_email == old_email :
commit.author_name = correct_name
commit.author_email = correct_email
'
The above command mirrors the logic used in this script but uses filter-repo
instead of filter-branch
.
The code body after commit-callback
option is basically python code used for processing commits. You can write your own logic in python here. See more about commit
object and its attributes here.
Since filter-repo
tool is not bundled with git you need to install it separately.
See Prerequisties and Installation Guide
If you have a python env >= 3.5, you can use pip
to install it.
pip3 install git-filter-repo
Note: It is strongly recommended to try filter-repo
tool on a fresh clone. Also remotes are removed once the operation is done. Read more on why remotes are removed here. Also read the limitations of this tool under INTERNALS section.
I had the same problem after i had changed the passwords in the database.. what i did was the editing of the updated password i had changed earlier and i didn't update in the config.inc.php and the same username under D:\xamp\phpMyAdmin\config.inc
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = **'root'**;
$cfg['Servers'][$i]['password'] = **'epufhy**';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';
You can find the log within you Magento root directory under
var/log
there are two types of log files system.log and exception.log
you need to give the correct permission to var folder, then enable logging from your Magento admin by going to
System > Configuration> Developer > Log Settings > Enable = Yes
system.log is used for general debugging and catches almost all log entries from Magento, including warning, debug and errors messages from both native and custom modules.
exception.log is reserved for exceptions only, for example when you are using try-catch statement.
To output to either the default system.log or the exception.log see the following code examples:
Mage::log('My log entry');
Mage::log('My log message: '.$myVariable);
Mage::log($myArray);
Mage::log($myObject);
Mage::logException($e);
You can create your own log file for more debugging
Mage::log('My log entry', null, 'mylogfile.log');
for Microsoft SQL Server Management Studio 2012,2008.. First Copy your database file .mdf and log file .ldf & Paste in your sql server install file in Programs Files->Microsoft SQL Server->MSSQL10.SQLEXPRESS->MSSQL->DATA. Then open Microsoft Sql Server . Right Click on Databases -> Select Attach...option.
You need to set your @GeneratedId column with strategy GenerationType.IDENTITY instead of GenerationType.AUTO
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "JUD_ID")
private Long _judId;
The configuration here is working for me:
configurations {
customProvidedRuntime
}
dependencies {
compile(
// Spring Boot dependencies
)
customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}
war {
classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}
springBoot {
providedConfiguration = "customProvidedRuntime"
}
Sometimes, when I know that I am working with numbers, I use this logic (if result is not greater than zero
):
if (!$result['column']>0){
}
I open the project,.csproj, using a notepad and delete that missing file reference.
You can now use ts-node, which makes your life as simple as
npm install -D ts-node
npm install -D typescript
ts-node script.ts
Create a table view cell subclass and set it as the class of the prototype. Add the outlets to that class and connect them. Now when you configure the cell you can access the outlets.
Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You CAN include raw HTML in strings.xml, as long as you wrap it in
<![CDATA[ ...raw html... ]]>
Example:
<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>
Then, in your code:
TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));
IMHO, this is several orders of magnitude nicer to work with :-)
Note that it is not possible to use HTML in the message body, according to RFC 2368:
The special hname "body" indicates that the associated hvalue is the body of the message. The "body" hname should contain the content for the first text/plain body part of the message. The mailto URL is primarily intended for generation of short text messages that are actually the content of automatic processing (such as "subscribe" messages for mailing lists), not general MIME bodies.
To expand upon Pavel Minaev's original comment - The GUI for Visual Studio supports relative references with the assumption that your .sln is the root of the relative reference. So if you have a solution C:\myProj\myProj.sln
, any references you add in subfolders of C:\myProj\
are automatically added as relative references.
To add a relative reference in a separate directory, such as C:/myReferences/myDLL.dll
, do the following:
Edit the < HintPath > to be equal to
<HintPath>..\..\myReferences\myDLL.dll</HintPath>
This now references C:\myReferences\myDLL.dll
.
Hope this helps.
$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.
try this jquery library, jQuery Print Element
http://projects.erikzaadi.com/jQueryPlugins/jQuery.printElement/
With examples? Here's a simple one:
public class TwoInjectionStyles {
private Foo foo;
// Constructor injection
public TwoInjectionStyles(Foo f) {
this.foo = f;
}
// Setting injection
public void setFoo(Foo f) { this.foo = f; }
}
Personally, I prefer constructor injection when I can.
In both cases, the bean factory instantiates the TwoInjectionStyles
and Foo
instances and gives the former its Foo
dependency.
Slightly modifying answer by @Yogeesh Seralathan. His answer works perfectly, just run these commands at once.
adb shell input keyevent 26 && adb shell input touchscreen swipe 930 880 930 380 && adb shell input text XXXX && adb shell input keyevent 66
Updating to 2012, when we see that image sizes, and number of images, are growing and growing, in all applications...
We need some distinction between "original image" and "processed image", like thumbnail.
As Jcoby's answer says, there are two options, then, I recommend:
use blob (Binary Large OBject): for original image store, at your table. See Ivan's answer (no problem with backing up blobs!), PostgreSQL additional supplied modules, How-tos etc.
use a separate database with DBlink: for original image store, at another (unified/specialized) database. In this case, I prefer bytea, but blob is near the same. Separating database is the best way for a "unified image webservice".
use bytea (BYTE Array): for caching thumbnail images. Cache the little images to send it fast to the web-browser (to avoiding rendering problems) and reduce server processing. Cache also essential metadata, like width and height. Database caching is the easiest way, but check your needs and server configs (ex. Apache modules): store thumbnails at file system may be better, compare performances. Remember that it is a (unified) web-service, then can be stored at a separate database (with no backups), serving many tables. See also PostgreSQL binary data types manual, tests with bytea column, etc.
NOTE1: today the use of "dual solutions" (database+filesystem) is deprecated (!). There are many advantages to using "only database" instead dual. PostgreSQL have comparable performance and good tools for export/import/input/output.
NOTE2: remember that PostgreSQL have only bytea, not have a default Oracle's BLOB: "The SQL standard defines (...) BLOB. The input format is different from bytea, but the provided functions and operators are mostly the same",Manual.
EDIT 2014: I have not changed the original text above today (my answer was Apr 22 '12, now with 14 votes), I am opening the answer for your changes (see "Wiki mode", you can edit!), for proofreading and for updates.
The question is stable (@Ivans's '08 answer with 19 votes), please, help to improve this text.
Use git-gui (or similar) to perform a git commit --amend
. From the GUI you can add or remove individual files from the commit. You can also modify the commit message.
Just reset your branch to the previous location (for example, using gitk
or git rebase
). Then reapply your changes from a saved copy. After garbage collection in your local repository, it will be like the unwanted commit never happened. To do all of that in a single command, use git reset HEAD~1
.
Word of warning: Careless use of git reset
is a good way to get your working copy into a confusing state. I recommend that Git novices avoid this if they can.
Perform a reverse cherry pick (git-revert) to undo the changes.
If you haven't yet pulled other changes onto your branch, you can simply do...
git revert --no-edit HEAD
Then push your updated branch to the shared repository.
The commit history will show both commits, separately.
Also note: You don't want to do this if someone else may be working on the branch.
git push --delete (branch_name) ## remove public version of branch
Clean up your branch locally then repush...
git push origin (branch_name)
In the normal case, you probably needn't worry about your private-branch commit history being pristine. Just push a followup commit (see 'How to undo a public commit' above), and later, do a squash-merge to hide the history.
When the WSDL is available, it is just two steps you need to follow to invoke that web service.
Step 1: Generate the client side source from a WSDL2Java
tool
Step 2: Invoke the operation using:
YourService service = new YourServiceLocator();
Stub stub = service.getYourStub();
stub.operation();
If you look further, you will notice that the Stub
class is used to invoke the service deployed at the remote location as a web service. When invoking that, your client actually generates the SOAP request and communicates. Similarly the web service sends the response as a SOAP. With the help of a tool like Wireshark, you can view the SOAP messages exchanged.
However since you have requested more explanation on the basics, I recommend you to refer here and write a web service with it's client to learn it further.
There are some gotchas. Assignment in Javascript is from right to left so when you write:
var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
it effectively translates to:
var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));
which effectively translates to:
var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));
Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.
Note: My above example assumes you are running your code in the browser, hence window
. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to global
which is the global context for that environment).
Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.
var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.
Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.
Overall I don't see anything that would break in your code.
Two suggestions:
The way you are combining Buffer
objects is a suboptimal because it has to copy all the pre-existing data on every 'data' event. It would be better to put the chunks in an array and concat
them all at the end.
var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
var buf = Buffer.concat(bufs);
}
For performance, I would look into if the S3 library you are using supports streams. Ideally you wouldn't need to create one large buffer at all, and instead just pass the stdout
stream directly to the S3 library.
As for the second part of your question, that isn't possible. When a function is called, it is allocated its own private context, and everything defined inside of that will only be accessible from other items defined inside that function.
Dumping the file to the filesystem would probably mean less memory usage per request, but file IO can be pretty slow so it might not be worth it. I'd say that you shouldn't optimize too much until you can profile and stress-test this function. If the garbage collector is doing its job you may be overoptimizing.
With all that said, there are better ways anyway, so don't use files. Since all you want is the length, you can calculate that without needing to append all of the buffers together, so then you don't need to allocate a new Buffer at all.
var pause_stream = require('pause-stream');
// Your other code.
var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
var contentLength = bufs.reduce(function(sum, buf){
return sum + buf.length;
}, 0);
// Create a stream that will emit your chunks when resumed.
var stream = pause_stream();
stream.pause();
while (bufs.length) stream.write(bufs.shift());
stream.end();
var headers = {
'Content-Length': contentLength,
// ...
};
s3.putStream(stream, ....);
Be aware that classes that descend from NumberFormat (and most other Format descendants) are not synchronized. It is a common (but dangerous) practice to create format objects and store them in static variables in a util class. In practice, it will pretty much always work until it starts experiencing significant load.
This is how I do it:
using System.IO;
using System.Security.Cryptography;
public string checkMD5(string filename)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
return Encoding.Default.GetString(md5.ComputeHash(stream));
}
}
}
new SecondForm().setVisible(true);
You can either use setVisible(false)
or dispose()
method to disappear current form.
It is also possible to use this:
var user_name = document.forms[0].elements[0];
var user_email = document.forms[0].elements[1];
var user_message = document.forms[0].elements[2];
All the elements of forms are stored in an array by Javascript. This takes the elements from the first form and stores each value into a unique variable.
I might be misunderstanding your question, so apologies if I am.
If you're looking for the words "Quid", "Application Number", etc. to be bold, just wrap them in <strong>
tags:
<strong>Quid</strong>: ...
Hope that helps!
One Way to solve this problem is, push the negative of each element in the priority_queue so the largest element will become the smallest element. At the time of making pop operation, take the negation of each element.
#include<bits/stdc++.h>
using namespace std;
int main(){
priority_queue<int> pq;
int i;
// push the negative of each element in priority_queue, so the largest number will become the smallest number
for (int i = 0; i < 5; i++)
{
cin>>j;
pq.push(j*-1);
}
for (int i = 0; i < 5; i++)
{
cout<<(-1)*pq.top()<<endl;
pq.pop();
}
}
It's usually good enough - unless you're programming assembly - to envisage a pointer containing a numeric memory address, with 1 referring to the second byte in the process's memory, 2 the third, 3 the fourth and so on....
When you want to access the data/value in the memory that the pointer points to - the contents of the address with that numerical index - then you dereference the pointer.
Different computer languages have different notations to tell the compiler or interpreter that you're now interested in the pointed-to object's (current) value - I focus below on C and C++.
Consider in C, given a pointer such as p
below...
const char* p = "abc";
...four bytes with the numerical values used to encode the letters 'a', 'b', 'c', and a 0 byte to denote the end of the textual data, are stored somewhere in memory and the numerical address of that data is stored in p
. This way C encodes text in memory is known as ASCIIZ.
For example, if the string literal happened to be at address 0x1000 and p
a 32-bit pointer at 0x2000, the memory content would be:
Memory Address (hex) Variable name Contents
1000 'a' == 97 (ASCII)
1001 'b' == 98
1002 'c' == 99
1003 0
...
2000-2003 p 1000 hex
Note that there is no variable name/identifier for address 0x1000, but we can indirectly refer to the string literal using a pointer storing its address: p
.
To refer to the characters p
points to, we dereference p
using one of these notations (again, for C):
assert(*p == 'a'); // The first character at address p will be 'a'
assert(p[1] == 'b'); // p[1] actually dereferences a pointer created by adding
// p and 1 times the size of the things to which p points:
// In this case they're char which are 1 byte in C...
assert(*(p + 1) == 'b'); // Another notation for p[1]
You can also move pointers through the pointed-to data, dereferencing them as you go:
++p; // Increment p so it's now 0x1001
assert(*p == 'b'); // p == 0x1001 which is where the 'b' is...
If you have some data that can be written to, then you can do things like this:
int x = 2;
int* p_x = &x; // Put the address of the x variable into the pointer p_x
*p_x = 4; // Change the memory at the address in p_x to be 4
assert(x == 4); // Check x is now 4
Above, you must have known at compile time that you would need a variable called x
, and the code asks the compiler to arrange where it should be stored, ensuring the address will be available via &x
.
In C, if you have a variable that is a pointer to a structure with data members, you can access those members using the ->
dereferencing operator:
typedef struct X { int i_; double d_; } X;
X x;
X* p = &x;
p->d_ = 3.14159; // Dereference and access data member x.d_
(*p).d_ *= -1; // Another equivalent notation for accessing x.d_
To use a pointer, a computer program also needs some insight into the type of data that is being pointed at - if that data type needs more than one byte to represent, then the pointer normally points to the lowest-numbered byte in the data.
So, looking at a slightly more complex example:
double sizes[] = { 10.3, 13.4, 11.2, 19.4 };
double* p = sizes;
assert(p[0] == 10.3); // Knows to look at all the bytes in the first double value
assert(p[1] == 13.4); // Actually looks at bytes from address p + 1 * sizeof(double)
// (sizeof(double) is almost always eight bytes)
++p; // Advance p by sizeof(double)
assert(*p == 13.4); // The double at memory beginning at address p has value 13.4
*(p + 2) = 29.8; // Change sizes[3] from 19.4 to 29.8
// Note earlier ++p and + 2 here => sizes[3]
Sometimes you don't know how much memory you'll need until your program is running and sees what data is thrown at it... then you can dynamically allocate memory using malloc
. It is common practice to store the address in a pointer...
int* p = (int*)malloc(sizeof(int)); // Get some memory somewhere...
*p = 10; // Dereference the pointer to the memory, then write a value in
fn(*p); // Call a function, passing it the value at address p
(*p) += 3; // Change the value, adding 3 to it
free(p); // Release the memory back to the heap allocation library
In C++, memory allocation is normally done with the new
operator, and deallocation with delete
:
int* p = new int(10); // Memory for one int with initial value 10
delete p;
p = new int[10]; // Memory for ten ints with unspecified initial value
delete[] p;
p = new int[10](); // Memory for ten ints that are value initialised (to 0)
delete[] p;
See also C++ smart pointers below.
Often a pointer may be the only indication of where some data or buffer exists in memory. If ongoing use of that data/buffer is needed, or the ability to call free()
or delete
to avoid leaking the memory, then the programmer must operate on a copy of the pointer...
const char* p = asprintf("name: %s", name); // Common but non-Standard printf-on-heap
// Replace non-printable characters with underscores....
for (const char* q = p; *q; ++q)
if (!isprint(*q))
*q = '_';
printf("%s\n", p); // Only q was modified
free(p);
...or carefully orchestrate reversal of any changes...
const size_t n = ...;
p += n;
...
p -= n; // Restore earlier value...
free(p);
In C++, it's best practice to use smart pointer objects to store and manage the pointers, automatically deallocating them when the smart pointers' destructors run. Since C++11 the Standard Library provides two, unique_ptr
for when there's a single owner for an allocated object...
{
std::unique_ptr<T> p{new T(42, "meaning")};
call_a_function(p);
// The function above might throw, so delete here is unreliable, but...
} // p's destructor's guaranteed to run "here", calling delete
...and shared_ptr
for share ownership (using reference counting)...
{
auto p = std::make_shared<T>(3.14, "pi");
number_storage1.may_add(p); // Might copy p into its container
number_storage2.may_add(p); // Might copy p into its container } // p's destructor will only delete the T if neither may_add copied it
In C, NULL
and 0
- and additionally in C++ nullptr
- can be used to indicate that a pointer doesn't currently hold the memory address of a variable, and shouldn't be dereferenced or used in pointer arithmetic. For example:
const char* p_filename = NULL; // Or "= 0", or "= nullptr" in C++
int c;
while ((c = getopt(argc, argv, "f:")) != -1)
switch (c) {
case f: p_filename = optarg; break;
}
if (p_filename) // Only NULL converts to false
... // Only get here if -f flag specified
In C and C++, just as inbuilt numeric types don't necessarily default to 0
, nor bools
to false
, pointers are not always set to NULL
. All these are set to 0/false/NULL when they're static
variables or (C++ only) direct or indirect member variables of static objects or their bases, or undergo zero initialisation (e.g. new T();
and new T(x, y, z);
perform zero-initialisation on T's members including pointers, whereas new T;
does not).
Further, when you assign 0
, NULL
and nullptr
to a pointer the bits in the pointer are not necessarily all reset: the pointer may not contain "0" at the hardware level, or refer to address 0 in your virtual address space. The compiler is allowed to store something else there if it has reason to, but whatever it does - if you come along and compare the pointer to 0
, NULL
, nullptr
or another pointer that was assigned any of those, the comparison must work as expected. So, below the source code at the compiler level, "NULL" is potentially a bit "magical" in the C and C++ languages...
More strictly, initialised pointers store a bit-pattern identifying either NULL
or a (often virtual) memory address.
The simple case is where this is a numeric offset into the process's entire virtual address space; in more complex cases the pointer may be relative to some specific memory area, which the CPU may select based on CPU "segment" registers or some manner of segment id encoded in the bit-pattern, and/or looking in different places depending on the machine code instructions using the address.
For example, an int*
properly initialised to point to an int
variable might - after casting to a float*
- access memory in "GPU" memory quite distinct from the memory where the int
variable is, then once cast to and used as a function pointer it might point into further distinct memory holding machine opcodes for the program (with the numeric value of the int*
effectively a random, invalid pointer within these other memory regions).
3GL programming languages like C and C++ tend to hide this complexity, such that:
If the compiler gives you a pointer to a variable or function, you can dereference it freely (as long as the variable's not destructed/deallocated meanwhile) and it's the compiler's problem whether e.g. a particular CPU segment register needs to be restored beforehand, or a distinct machine code instruction used
If you get a pointer to an element in an array, you can use pointer arithmetic to move anywhere else in the array, or even to form an address one-past-the-end of the array that's legal to compare with other pointers to elements in the array (or that have similarly been moved by pointer arithmetic to the same one-past-the-end value); again in C and C++, it's up to the compiler to ensure this "just works"
Specific OS functions, e.g. shared memory mapping, may give you pointers, and they'll "just work" within the range of addresses that makes sense for them
Attempts to move legal pointers beyond these boundaries, or to cast arbitrary numbers to pointers, or use pointers cast to unrelated types, typically have undefined behaviour, so should be avoided in higher level libraries and applications, but code for OSes, device drivers, etc. may need to rely on behaviour left undefined by the C or C++ Standard, that is nevertheless well defined by their specific implementation or hardware.
Use the built-in function round()
:
>>> round(1.2345,2)
1.23
>>> round(1.5145,2)
1.51
>>> round(1.679,2)
1.68
Or built-in function format()
:
>>> format(1.2345, '.2f')
'1.23'
>>> format(1.679, '.2f')
'1.68'
Or new style string formatting:
>>> "{:.2f}".format(1.2345)
'1.23
>>> "{:.2f}".format(1.679)
'1.68'
Or old style string formatting:
>>> "%.2f" % (1.679)
'1.68'
help on round
:
>>> print round.__doc__
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
You can easily create a new tab; do like the following:
function newTab() {
var form = document.createElement("form");
form.method = "GET";
form.action = "http://www.example.com";
form.target = "_blank";
document.body.appendChild(form);
form.submit();
}
I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with
block, and then it stopped happening.
i followed all the suggested steps, in particular the ones provided from ios_dev but my iPhone was not recognized from Xcode and i was not able to debug over WiFi. Right click on the left panel over my iDevice in "Devices and Simulators" window, then "Connect via IP Address...", inserted the iPhone IP and now it correctly works
Works fine for me in 5.0.27
I just get a warning (not an error) that the table exists;
What you want is charAt
.
var x = 'some string';
alert(x.charAt(0)); // alerts 's'
To obtain readable x tick labels without additional dependencies, you want to use:
... +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +
...
This rotates the tick labels 90° counterclockwise and aligns them vertically at their end (hjust = 1
) and their centers horizontally with the corresponding tick mark (vjust = 0.5
).
Full example:
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
Note, that vertical/horizontal justification parameters vjust
/hjust
of element_text
are relative to the text. Therefore, vjust
is responsible for the horizontal alignment.
Without vjust = 0.5
it would look like this:
q + theme(axis.text.x = element_text(angle = 90, hjust = 1))
Without hjust = 1
it would look like this:
q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
If for some (wired) reason you wanted to rotate the tick labels 90° clockwise (such that they can be read from the left) you would need to use: q + theme(axis.text.x = element_text(angle = -90, vjust = 0.5, hjust = -1))
.
All of this has already been discussed in the comments of this answer but I come back to this question so often, that I want an answer from which I can just copy without reading the comments.
No, he must have been confused about the MD5 dictionaries.
Cryptographic hashes (MD5, etc...) are one way and you can't get back to the original message with only the digest unless you have some other information about the original message, etc. that you shouldn't.
Based on clamum's answer, and Kevin Vuilleumier's comment about the other flag responsible for the behavior, I made this toggle that switches between on-top and not on-top with a button press.
private void button1_Click(object sender, EventArgs e)
{
if (on)
{
button1.Text = "yes on top";
IntPtr HwndTopmost = new IntPtr(-1);
SetWindowPos(this.Handle, HwndTopmost, 0, 0, 0, 0, TopmostFlags);
on = false;
}
else
{
button1.Text = "not on top";
IntPtr HwndTopmost = new IntPtr(-2);
SetWindowPos(this.Handle, HwndTopmost, 0, 0, 0, 0, TopmostFlags);
on = true;
}
}
Try starting the project using the python_boilerplate template. It largely follows the best practices (e.g. those here), but is better suited in case you find yourself willing to split your project into more than one egg at some point (and believe me, with anything but the simplest projects, you will. One common situation is where you have to use a locally-modified version of someone else's library).
Where do you put the source?
PROJECT_ROOT/src/<egg_name>
.Where do you put application startup scripts?
entry_point
in one of the eggs.Where do you put the IDE project cruft?
PROJECT_ROOT/.<something>
in the root of the project, and this is fine.Where do you put the unit/acceptance tests?
PROJECT_ROOT/src/<egg_name>/tests
directory. I personally prefer to use py.test
to run them.Where do you put non-Python data such as config files?
pkg_resources
package from setuptools
, or since Python 3.7 via the importlib.resources
module from the standard library.PROJECT_ROOT/config
. For deployment there can be various options. On Windows one can use %APP_DATA%/<app-name>/config
, on Linux, /etc/<app-name>
or /opt/<app-name>/config
.PROJECT_ROOT/var
during development, and under /var
during Linux deployment.PROJECT_ROOT/src/<egg_name>/native
Documentation would typically go into PROJECT_ROOT/doc
or PROJECT_ROOT/src/<egg_name>/doc
(this depends on whether you regard some of the eggs to be a separate large projects). Some additional configuration will be in files like PROJECT_ROOT/buildout.cfg
and PROJECT_ROOT/setup.cfg
.
Just call dict()
on the list of tuples directly
>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}
I've noticed from my experience that producing a new line INSIDE a <xsl:variable>
clause doesn't work.
I was trying to do something like:
<xsl:variable name="myVar">
<xsl:choose>
<xsl:when test="@myValue != ''">
<xsl:text>My value: </xsl:text>
<xsl:value-of select="@myValue" />
<xsl:text></xsl:text> <!--NEW LINE-->
<xsl:text>My other value: </xsl:text>
<xsl:value-of select="@myOtherValue" />
</xsl:when>
</xsl:choose>
<xsl:variable>
<div>
<xsl:value-of select="$myVar"/>
</div>
Anything I tried to put in that "new line" (the empty <xsl:text>
node) just didn't work (including most of the simpler suggestions in this page), not to mention the fact that HTML just won't work there, so eventually I had to split it to 2 variables, call them outside the <xsl:variable>
scope and put a simple <br/>
between them, i.e:
<xsl:variable name="myVar1">
<xsl:choose>
<xsl:when test="@myValue != ''">
<xsl:text>My value: </xsl:text>
<xsl:value-of select="@myValue" />
</xsl:when>
</xsl:choose>
<xsl:variable>
<xsl:variable name="myVar2">
<xsl:choose>
<xsl:when test="@myValue != ''">
<xsl:text>My other value: </xsl:text>
<xsl:value-of select="@myOtherValue" />
</xsl:when>
</xsl:choose>
<xsl:variable>
<div>
<xsl:value-of select="$myVar1"/>
<br/>
<xsl:value-of select="$myVar2"/>
</div>
Yeah, I know, it's not the most sophisticated solution but it works, just sharing my frustration experience with XSLs ;)
The following code center the Window
in the center of the current monitor (ie where the mouse pointer is located).
public static final void centerWindow(final Window window) {
GraphicsDevice screen = MouseInfo.getPointerInfo().getDevice();
Rectangle r = screen.getDefaultConfiguration().getBounds();
int x = (r.width - window.getWidth()) / 2 + r.x;
int y = (r.height - window.getHeight()) / 2 + r.y;
window.setLocation(x, y);
}
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
The problem with your code is in the line:
for(i in length(namevector))
You need to ask yourself: what is length(namevector)
? It's one number. So essentially you're saying:
for(i in 11)
df[,i] <- NA
Or more simply:
df[,11] <- NA
That's why you're getting an error. What you want is:
for(i in namevector)
df[,i] <- NA
Or more simply:
df[,namevector] <- NA
The configuration seem alright, except that you should use excludeFilters
instead of excludes
:
@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}
Idea is to avoid using a Signal like above. Pumping int values into a struct prevents those values from changing (in the struct). I had the following Problem: loop var i would change before DoSomething(i) was called (i was incremented at end of loop before ()=> DoSomething(i,ii) was called). With the structs it doesn't happen anymore. Nasty bug to find: DoSomething(i, ii) looks great, but never sure if it gets called each time with a different value for i (or just a 100 times with i=100), hence -> struct
struct Job { public int P1; public int P2; }
…
for (int i = 0; i < 100; i++) {
var job = new Job { P1 = i, P2 = i * i}; // structs immutable...
Task.Run(() => DoSomething(job));
}
SELECT Email, COUNT(*)
FROM user_log
WHILE Email IS NOT NULL
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC
MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TYPE=MyISAM' at line 36
Which correction below:
CREATE TABLE users_online (
ip varchar(15) NOT NULL default '',
time int(11) default NULL,
PRIMARY KEY (ip),
UNIQUE KEY id (ip),
KEY id_2 (ip)
TYPE=MyISAM;
)
#
# Data untuk tabel `users_online`
#
INSERT INTO users_online VALUES ('127.0.0.1', 1158666872);
Lambda's cleaned up C# 2.0's anonymous delegate syntax...for example
Strings.Find(s => s == "hello");
Was done in C# 2.0 like this:
Strings.Find(delegate(String s) { return s == "hello"; });
Functionally, they do the exact same thing, its just a much more concise syntax.
Try replacing apt-get
with yum
as Amazon Linux based AMI uses the yum
command instead of apt-get
.
The Comments of @crates work for me,
Step 1: Simply press on ctrl+H
Step 2: press on RegEX key
Step 3: write this in the Find: ^[\s]*?[\n\r]+
Step 4: replace all
How do you get string concatenation, aside from long SQL strings in PreparedStatements (that you could easily provide in a text file and load as a resource anyway) that you break over several lines?
You aren't creating SQL strings directly are you? That's the biggest no-no in programming. Please use PreparedStatements, and supply the data as parameters. It reduces the chance of SQL Injection vastly.
Quick sort's complexity varies greatly with the selection of pivot value. for example if you always choose first element as an pivot, algorithm's complexity becomes as worst as O(n^2). here is an smart method to choose pivot element- 1. choose the first, mid, last element of the array. 2. compare these three numbers and find the number which is greater than one and smaller than other i.e. median. 3. make this element as pivot element.
choosing the pivot by this method splits the array in nearly two half and hence the complexity reduces to O(nlog(n)).
IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.
The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY
property value of the BindingProvider
(every proxy implements javax.xml.ws.BindingProvider
interface):
...
EchoService service = new EchoService();
Echo port = service.getEchoPort();
/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
System.out.println("Server said: " + echo.echo(args[0]));
...
The drawback is that this only works when the original WSDL is still accessible. Not recommended.
The second option is to get the endpoint URL from the WSDL.
...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService");
EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();
System.out.println("Server said: " + echo.echo(args[0]));
...
You need to have an instance of a class to use its methods. Or if you don't need to access any of classes' variables (not static parameters) then you can define the method as static and it can be used even if the class isn't instantiated. Just add @staticmethod
decorator to your methods.
class MathsOperations:
@staticmethod
def testAddition (x, y):
return x + y
@staticmethod
def testMultiplication (a, b):
return a * b
docs: http://docs.python.org/library/functions.html#staticmethod
Example 1:
0 means ignore
1 means show
User.find({}, { createdAt: 0, updatedAt: 0, isActive: 0, _id : 1 }).then(...)
Example 2:
User.findById(id).select("_id, isActive").then(...)
I don't believe there is a built-in function for that. But it's easy enough to write with a regex
function isLetter(str) {
return str.length === 1 && str.match(/[a-z]/i);
}
Using netbeans New Entity Classes from Database with a mysql auto_increment column, creates you an attribute with the following hibernate.hbm.xml: id is auto increment
In case you want to use that padding space... then here's something:
All the colors are background colors.
In my case
I Followed This answer
Changed the location of project.
Tried another android device [Build and success install]
Tried on my android device [Build and success install * Uninstall any previous version of same app on device]
Edit- Again it happend
I had this error message and lot of others like
x-version is deprecated and use y-version instead and it'll be removed in 2019
and all of my project started giving same error messages suddenly.
Android studio was giving warnings about my antivirus program. I tried configuring it but didn't work.
Finally I uninstalled QuickHeal antivirus from my system and all is well now
$x
is always a scalar. The hint is the sigil $
: any variable (or dereferencing of some other type) starting with $
is a scalar. (See perldoc perldata for more about data types.)
A reference is just a particular type of scalar.
The built-in function ref
will tell you what kind of reference it is. On the other hand, if you have a blessed reference, ref
will only tell you the package name the reference was blessed into, not the actual core type of the data (blessed references can be hashrefs, arrayrefs or other things). You can use Scalar::Util 's reftype
will tell you what type of reference it is:
use Scalar::Util qw(reftype);
my $x = bless {}, 'My::Foo';
my $y = { };
print "type of x: " . ref($x) . "\n";
print "type of y: " . ref($y) . "\n";
print "base type of x: " . reftype($x) . "\n";
print "base type of y: " . reftype($y) . "\n";
...produces the output:
type of x: My::Foo
type of y: HASH
base type of x: HASH
base type of y: HASH
For more information about the other types of references (e.g. coderef, arrayref etc), see this question: How can I get Perl's ref() function to return REF, IO, and LVALUE? and perldoc perlref.
Note: You should not use ref
to implement code branches with a blessed object (e.g. $ref($a) eq "My::Foo" ? say "is a Foo object" : say "foo not defined";
) -- if you need to make any decisions based on the type of a variable, use isa
(i.e if ($a->isa("My::Foo") { ...
or if ($a->can("foo") { ...
). Also see polymorphism.
I followed the link shared by lisachenko and found another link to this blog: http://guilhembichot.blogspot.co.uk/2013/11/with-recursive-and-mysql.html
The post lays out ways of emulating the 2 uses of SQL WITH. Really good explanation on how these work to do a similar query as SQL WITH.
1) Use WITH so you don't have to perform the same sub query multiple times
CREATE VIEW D AS (SELECT YEAR, SUM(SALES) AS S FROM T1 GROUP BY YEAR);
SELECT D1.YEAR, (CASE WHEN D1.S>D2.S THEN 'INCREASE' ELSE 'DECREASE' END) AS TREND
FROM
D AS D1,
D AS D2
WHERE D1.YEAR = D2.YEAR-1;
DROP VIEW D;
2) Recursive queries can be done with a stored procedure that makes the call similar to a recursive with query.
CALL WITH_EMULATOR(
"EMPLOYEES_EXTENDED",
"
SELECT ID, NAME, MANAGER_ID, 0 AS REPORTS
FROM EMPLOYEES
WHERE ID NOT IN (SELECT MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID IS NOT NULL)
",
"
SELECT M.ID, M.NAME, M.MANAGER_ID, SUM(1+E.REPORTS) AS REPORTS
FROM EMPLOYEES M JOIN EMPLOYEES_EXTENDED E ON M.ID=E.MANAGER_ID
GROUP BY M.ID, M.NAME, M.MANAGER_ID
",
"SELECT * FROM EMPLOYEES_EXTENDED",
0,
""
);
And this is the code or the stored procedure
# Usage: the standard syntax:
# WITH RECURSIVE recursive_table AS
# (initial_SELECT
# UNION ALL
# recursive_SELECT)
# final_SELECT;
# should be translated by you to
# CALL WITH_EMULATOR(recursive_table, initial_SELECT, recursive_SELECT,
# final_SELECT, 0, "").
# ALGORITHM:
# 1) we have an initial table T0 (actual name is an argument
# "recursive_table"), we fill it with result of initial_SELECT.
# 2) We have a union table U, initially empty.
# 3) Loop:
# add rows of T0 to U,
# run recursive_SELECT based on T0 and put result into table T1,
# if T1 is empty
# then leave loop,
# else swap T0 and T1 (renaming) and empty T1
# 4) Drop T0, T1
# 5) Rename U to T0
# 6) run final select, send relult to client
# This is for *one* recursive table.
# It would be possible to write a SP creating multiple recursive tables.
delimiter |
CREATE PROCEDURE WITH_EMULATOR(
recursive_table varchar(100), # name of recursive table
initial_SELECT varchar(65530), # seed a.k.a. anchor
recursive_SELECT varchar(65530), # recursive member
final_SELECT varchar(65530), # final SELECT on UNION result
max_recursion int unsigned, # safety against infinite loop, use 0 for default
create_table_options varchar(65530) # you can add CREATE-TABLE-time options
# to your recursive_table, to speed up initial/recursive/final SELECTs; example:
# "(KEY(some_column)) ENGINE=MEMORY"
)
BEGIN
declare new_rows int unsigned;
declare show_progress int default 0; # set to 1 to trace/debug execution
declare recursive_table_next varchar(120);
declare recursive_table_union varchar(120);
declare recursive_table_tmp varchar(120);
set recursive_table_next = concat(recursive_table, "_next");
set recursive_table_union = concat(recursive_table, "_union");
set recursive_table_tmp = concat(recursive_table, "_tmp");
# Cleanup any previous failed runs
SET @str =
CONCAT("DROP TEMPORARY TABLE IF EXISTS ", recursive_table, ",",
recursive_table_next, ",", recursive_table_union,
",", recursive_table_tmp);
PREPARE stmt FROM @str;
EXECUTE stmt;
# If you need to reference recursive_table more than
# once in recursive_SELECT, remove the TEMPORARY word.
SET @str = # create and fill T0
CONCAT("CREATE TEMPORARY TABLE ", recursive_table, " ",
create_table_options, " AS ", initial_SELECT);
PREPARE stmt FROM @str;
EXECUTE stmt;
SET @str = # create U
CONCAT("CREATE TEMPORARY TABLE ", recursive_table_union, " LIKE ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
SET @str = # create T1
CONCAT("CREATE TEMPORARY TABLE ", recursive_table_next, " LIKE ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
if max_recursion = 0 then
set max_recursion = 100; # a default to protect the innocent
end if;
recursion: repeat
# add T0 to U (this is always UNION ALL)
SET @str =
CONCAT("INSERT INTO ", recursive_table_union, " SELECT * FROM ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# we are done if max depth reached
set max_recursion = max_recursion - 1;
if not max_recursion then
if show_progress then
select concat("max recursion exceeded");
end if;
leave recursion;
end if;
# fill T1 by applying the recursive SELECT on T0
SET @str =
CONCAT("INSERT INTO ", recursive_table_next, " ", recursive_SELECT);
PREPARE stmt FROM @str;
EXECUTE stmt;
# we are done if no rows in T1
select row_count() into new_rows;
if show_progress then
select concat(new_rows, " new rows found");
end if;
if not new_rows then
leave recursion;
end if;
# Prepare next iteration:
# T1 becomes T0, to be the source of next run of recursive_SELECT,
# T0 is recycled to be T1.
SET @str =
CONCAT("ALTER TABLE ", recursive_table, " RENAME ", recursive_table_tmp);
PREPARE stmt FROM @str;
EXECUTE stmt;
# we use ALTER TABLE RENAME because RENAME TABLE does not support temp tables
SET @str =
CONCAT("ALTER TABLE ", recursive_table_next, " RENAME ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
SET @str =
CONCAT("ALTER TABLE ", recursive_table_tmp, " RENAME ", recursive_table_next);
PREPARE stmt FROM @str;
EXECUTE stmt;
# empty T1
SET @str =
CONCAT("TRUNCATE TABLE ", recursive_table_next);
PREPARE stmt FROM @str;
EXECUTE stmt;
until 0 end repeat;
# eliminate T0 and T1
SET @str =
CONCAT("DROP TEMPORARY TABLE ", recursive_table_next, ", ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# Final (output) SELECT uses recursive_table name
SET @str =
CONCAT("ALTER TABLE ", recursive_table_union, " RENAME ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# Run final SELECT on UNION
SET @str = final_SELECT;
PREPARE stmt FROM @str;
EXECUTE stmt;
# No temporary tables may survive:
SET @str =
CONCAT("DROP TEMPORARY TABLE ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# We are done :-)
END|
delimiter ;
You seek the all-powerful *?
From the docs, Greedy versus Non-Greedy
the non-greedy qualifiers
*?
,+?
,??
, or{m,n}?
[...] match as little text as possible.
Useful simple class are forked by me on: https://gist.github.com/kiuz/816e24aa787c2d102dd0
public class OSValidator {
private static String OS = System.getProperty("os.name").toLowerCase();
public static void main(String[] args) {
System.out.println(OS);
if (isWindows()) {
System.out.println("This is Windows");
} else if (isMac()) {
System.out.println("This is Mac");
} else if (isUnix()) {
System.out.println("This is Unix or Linux");
} else if (isSolaris()) {
System.out.println("This is Solaris");
} else {
System.out.println("Your OS is not support!!");
}
}
public static boolean isWindows() {
return OS.contains("win");
}
public static boolean isMac() {
return OS.contains("mac");
}
public static boolean isUnix() {
return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
}
public static boolean isSolaris() {
return OS.contains("sunos");
}
public static String getOS(){
if (isWindows()) {
return "win";
} else if (isMac()) {
return "osx";
} else if (isUnix()) {
return "uni";
} else if (isSolaris()) {
return "sol";
} else {
return "err";
}
}
}
I put the following at the top of the faulting PHP file and the error was no longer display:
error_reporting(E_ERROR | E_PARSE);
on the checkout page, look for the 'cancel_return' hidden form element:
set the value of the cancel_return form element to the URL you wish to return to:
(Strictly speaking not an answer to the question, but in my experience likely to be useful when looking for class variables)
A class method can often play many of the roles a class variable would in other languages (e.g. changed configuration during tests):
@interface MyCls: NSObject
+ (NSString*)theNameThing;
- (void)doTheThing;
@end
@implementation
+ (NSString*)theNameThing { return @"Something general"; }
- (void)doTheThing {
[SomeResource changeSomething:[self.class theNameThing]];
}
@end
@interface MySpecialCase: MyCls
@end
@implementation
+ (NSString*)theNameThing { return @"Something specific"; }
@end
Now, an object of class MyCls
calls Resource:changeSomething:
with the string @"Something general"
upon a call to doTheThing:
, but an object derived from MySpecialCase
with the string @"Something specific"
.
pandas
based solution with creating dataframe:
import pandas as pd
l = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
df = pd.DataFrame(l)
print(df)
0 1 2
0 a b c
1 aaaaaaaaaa b c
2 a bbbbbbbbbb c
To remove index and header values to create output what you want you could use to_string
method:
result = df.to_string(index=False, header=False)
print(result)
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
Sure. A function's type consists of the types of its argument and its return type. Here we specify that the callback
parameter's type must be "function that accepts a number and returns type any
":
class Foo {
save(callback: (n: number) => any) : void {
callback(42);
}
}
var foo = new Foo();
var strCallback = (result: string) : void => {
alert(result);
}
var numCallback = (result: number) : void => {
alert(result.toString());
}
foo.save(strCallback); // not OK
foo.save(numCallback); // OK
If you want, you can define a type alias to encapsulate this:
type NumberCallback = (n: number) => any;
class Foo {
// Equivalent
save(callback: NumberCallback) : void {
callback(42);
}
}
If you are using Sql Server 2008 or better, you can use something called a Table-Valued Parameter (TVP) instead of serializing & deserializing your list data every time you want to pass it to a stored procedure.
Let's start by creating a simple schema to serve as our playground:
CREATE DATABASE [TestbedDb]
GO
USE [TestbedDb]
GO
/* First, setup the sample program's account & credentials*/
CREATE LOGIN [testbedUser] WITH PASSWORD=N'µ×?
?S[°¿Q¥½q?_Ĭ¼Ð)3õļ%dv', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON
GO
CREATE USER [testbedUser] FOR LOGIN [testbedUser] WITH DEFAULT_SCHEMA=[dbo]
GO
EXEC sp_addrolemember N'db_owner', N'testbedUser'
GO
/* Now setup the schema */
CREATE TABLE dbo.Table1 ( t1Id INT NOT NULL PRIMARY KEY );
GO
INSERT INTO dbo.Table1 (t1Id)
VALUES
(1),
(2),
(3),
(4),
(5),
(6),
(7),
(8),
(9),
(10);
GO
With our schema and sample data in place, we are now ready to create our TVP stored procedure:
CREATE TYPE T1Ids AS Table (
t1Id INT
);
GO
CREATE PROCEDURE dbo.FindMatchingRowsInTable1( @Table1Ids AS T1Ids READONLY )
AS
BEGIN
SET NOCOUNT ON;
SELECT Table1.t1Id FROM dbo.Table1 AS Table1
JOIN @Table1Ids AS paramTable1Ids ON Table1.t1Id = paramTable1Ids.t1Id;
END
GO
With both our schema and API in place, we can call the TVP stored procedure from our program like so:
// Curry the TVP data
DataTable t1Ids = new DataTable( );
t1Ids.Columns.Add( "t1Id",
typeof( int ) );
int[] listOfIdsToFind = new[] {1, 5, 9};
foreach ( int id in listOfIdsToFind )
{
t1Ids.Rows.Add( id );
}
// Prepare the connection details
SqlConnection testbedConnection =
new SqlConnection(
@"Data Source=.\SQLExpress;Initial Catalog=TestbedDb;Persist Security Info=True;User ID=testbedUser;Password=letmein12;Connect Timeout=5" );
try
{
testbedConnection.Open( );
// Prepare a call to the stored procedure
SqlCommand findMatchingRowsInTable1 = new SqlCommand( "dbo.FindMatchingRowsInTable1",
testbedConnection );
findMatchingRowsInTable1.CommandType = CommandType.StoredProcedure;
// Curry up the TVP parameter
SqlParameter sqlParameter = new SqlParameter( "Table1Ids",
t1Ids );
findMatchingRowsInTable1.Parameters.Add( sqlParameter );
// Execute the stored procedure
SqlDataReader sqlDataReader = findMatchingRowsInTable1.ExecuteReader( );
while ( sqlDataReader.Read( ) )
{
Console.WriteLine( "Matching t1ID: {0}",
sqlDataReader[ "t1Id" ] );
}
}
catch ( Exception e )
{
Console.WriteLine( e.ToString( ) );
}
/* Output:
* Matching t1ID: 1
* Matching t1ID: 5
* Matching t1ID: 9
*/
There is probably a less painful way to do this using a more abstract API, such as Entity Framework. However, I do not have the time to see for myself at this time.
From $http.get
docs, the second parameter is a configuration object:
get(url, [config]);
Shortcut method to perform
GET
request.
You may change your code to:
$http.get('accept.php', {
params: {
source: link,
category_id: category
}
});
Or:
$http({
url: 'accept.php',
method: 'GET',
params: {
source: link,
category_id: category
}
});
As a side note, since Angular 1.6: .success
should not be used anymore, use .then
instead:
$http.get('/url', config).then(successCallback, errorCallback);
shell_exec('mv filename dest_filename');
Others have given you the answer about appendChild.
Calling document.write()
on a page that is not open (e.g. has finished loading) first calls document.open()
which clears the entire content of the document (including the script calling document.write), so it's rarely a good idea to do that.
In a parent component you can use @ViewChild() to access child component's method/variable.
@Component({
selector: 'app-number-parent',
templateUrl: './number-parent.component.html'
})
export class NumberParentComponent {
@ViewChild(NumberComponent)
private numberComponent: NumberComponent;
increase() {
this.numberComponent.increaseByOne();
}
decrease() {
this.numberComponent.decreaseByOne();
}
}
Update:
Angular 8 onwards -
@ViewChild(NumberComponent, { static: false })
The way to set JFrame to full-screen, is to set MAXIMIZED_BOTH
option which stands for MAXIMIZED_VERT | MAXIMIZED_HORIZ
, which respectively set the frame to maximize vertically and horizontally
package Example;
import java.awt.GraphicsConfiguration;
import javax.swing.JFrame;
import javax.swing.JButton;
public class JFrameExample
{
static JFrame frame;
static GraphicsConfiguration gc;
public static void main(String[] args)
{
frame = new JFrame(gc);
frame.setTitle("Full Screen Example");
frame.setExtendedState(MAXIMIZED_BOTH);
JButton button = new JButton("exit");
b.addActionListener(new ActionListener(){@Override
public void actionPerformed(ActionEvent arg0){
JFrameExample.frame.dispose();
System.exit(0);
}});
frame.add(button);
frame.setVisible(true);
}
}
typeof callback === "function"
Make sure that all these libs are in your class path:
compile(group: 'com.sun.jersey', name: 'jersey-core', version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-server', version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-servlet', version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-json', version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-client', version: '1.19.4')
compile(group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-jaxrs', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-xc', version: '1.9.2')
Add "Pojo Mapping" and "Jackson Provider" to the jersey client config:
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
clientConfig.getClasses().add(JacksonJsonProvider.class);
This solve to me!
ClientResponse response = null;
response = webResource
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
MyClass myclass = response.getEntity(MyClass.class);
System.out.println(myclass);
}
When one should inline :
1.When one want to avoid overhead of things happening when function is called like parameter passing , control transfer, control return etc.
2.The function should be small,frequently called and making inline is really advantageous since as per 80-20 rule,try to make those function inline which has major impact on program performance.
As we know that inline is just a request to compiler similar to register and it will cost you at Object code size.
public async Task<bool> Update(MyObject item)
{
Context.Entry(await Context.MyDbSet.FirstOrDefaultAsync(x => x.Id == item.Id)).CurrentValues.SetValues(item);
return (await Context.SaveChangesAsync()) > 0;
}
Try this,
get-music:
rsync -avzru --delete-excluded server:/media/10001/music/ /media/Incoming/music/
put-music:
rsync -avzru --delete-excluded /media/Incoming/music/ server:/media/10001/music/
sync-music: get-music put-music
I just test this and it worked for me. I'm doing a 2-way sync between Windows7 (using cygwin with the rsync package installed) and FreeNAS fileserver (FreeNAS runs on FreeBSD with rsync package pre-installed).
You can't expect ObjectInputStream
to automagically convert text into objects. The hexadecimal 54657374
is "Test"
as text. You must be sending it directly as bytes.
From a "sniff the network packet" point of view a GET request is safe, as the browser will first establish the secure connection and then send the request containing the GET parameters. But GET url's will be stored in the users browser history / autocomplete, which is not a good place to store e.g. password data in. Of course this only applies if you take the broader "Webservice" definition that might access the service from a browser, if you access it only from your custom application this should not be a problem.
So using post at least for password dialogs should be preferred. Also as pointed out in the link littlegeek posted a GET URL is more likely to be written to your server logs.
Use Control.BringToFront
:
myForm.BringToFront();
Another great open source PHP ORM that we use is PHPSmartDb. It is stable and makes your code more secure and clean. The database functionality within it is hands down the easiest I have ever used with PHP 5.3.
Bootstrap 4.x
With Bootstrap 4 (and Font Awesome), we still can use the input-group
wrapper around our form-control
element, and now we can use an input-group-append
(or input-group-prepend
) wrapper with an input-group-text
to get the job done:
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Search" aria-label="Search" aria-describedby="my-search">
<div class="input-group-append">
<span class="input-group-text" id="my-search"><i class="fas fa-filter"></i></span>
</div>
</div>
It will look something like this (thanks to KyleMit for the screenshot):
Learn more by visiting the Input group documentation.
Here's how you can get history to follow just a couple of files from another branch with a minimum of fuss, even if a more "simple" merge would have brought over a lot more changes that you don't want.
First, you'll take the unusual step of declaring in advance that what you're about to commit is a merge, without Git doing anything at all to the files in your working directory:
git merge --no-ff --no-commit -s ours branchname1
... where "branchname" is whatever you claim to be merging from. If you were to commit right away, it would make no changes, but it would still show ancestry from the other branch. You can add more branches, tags, etc. to the command line if you need to, as well. At this point though, there are no changes to commit, so get the files from the other revisions, next.
git checkout branchname1 -- file1 file2 etc.
If you were merging from more than one other branch, repeat as needed.
git checkout branchname2 -- file3 file4 etc.
Now the files from the other branch are in the index, ready to be committed, with history.
git commit
And you'll have a lot of explaining to do in that commit message.
Please note though, in case it wasn't clear, that this is a messed up thing to do. It is not in the spirit of what a "branch" is for, and cherry-pick is a more honest way to do what you'd be doing, here. If you wanted to do another "merge" for other files on the same branch that you didn't bring over last time, it will stop you with an "already up to date" message. It's a symptom of not branching when we should have, in that the "from" branch should be more than one different branch.
To do something after certain div load from function .load()
.
I think this exactly what you need:
$('#divIDer').load(document.URL + ' #divIDer',function() {
// call here what you want .....
//example
$('#mydata').show();
});
you can show one line output then set property Line=0 and show multiple line output then set property Line=1 and more
[self.yourLableName sizeToFit];
I like to write a small plugin to make things cleaner:
$.fn.setClass = function(classes) {
this.attr('class', classes);
return this;
};
That way you can simply do
$('button').setClass('btn btn-primary');
Could you not have simply added:
align-items:center;
to a new class in your row div. Essentially:
<div class="row align_center">
.align_center { align-items:center; }
ps -fC PROCESSNAME
ps and grep is a dangerous combination -- grep tries to match everything on each line (thus the all too common: grep -v grep hack). ps -C doesn't use grep, it uses the process table for an exact match. Thus, you'll get an accurate list with: ps -fC sh rather finding every process with sh somewhere on the line.
None of the solutions provided here solved the problems/use-cases I had.
What I have provided here, is the best I have found/made so far. I will update it when I find new edge-cases that it doesn't handle.
\b
#Word cannot begin with special characters
(?<![@.,%&#-])
#Protocols are optional, but take them with us if they are present
(?<protocol>\w{2,10}:\/\/)?
#Domains have to be of a length of 1 chars or greater
((?:\w|\&\#\d{1,5};)[.-]?)+
#The domain ending has to be between 2 to 15 characters
(\.([a-z]{2,15})
#If no domain ending we want a port, only if a protocol is specified
|(?(protocol)(?:\:\d{1,6})|(?!)))
\b
#Word cannot end with @ (made to catch emails)
(?![@])
#We accept any number of slugs, given we have a char after the slash
(\/)?
#If we have endings like ?=fds include the ending
(?:([\w\d\?\-=#:%@&.;])+(?:\/(?:([\w\d\?\-=#:%@&;.])+))*)?
#The last char cannot be one of these symbols .,?!,- exclude these
(?<![.,?!-])
Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.
So for your specific example you would need:
<div id="logapp">
<table>
<tbody>
<tr v-repeat="logs">
<td v-html="fail"></td>
<td v-html="type"></td>
<td v-html="description"></td>
<td v-html="stamp"></td>
<td v-html="id"></td>
</tr>
</tbody>
</table>
</div>
One of the possible implementations:
File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();
when used with the XML content:
<credentials>
<user>testusr</user>
<password>testpwd</password>
</credentials>
results in "testusr"
and "testpwd"
getting assigned to the usr
and pwd
references above.
In my case just run the command and worked like charm.
php artisan route:clear
If you want to delete file first close all the connections and streams. after that delete the file.
To append
a file use >>
echo "hello world" >> read.txt
cat read.txt
echo "hello siva" >> read.txt
cat read.txt
then the output should be
hello world # from 1st echo command
hello world # from 2nd echo command
hello siva
To overwrite
a file use >
echo "hello tom" > read.txt
cat read.txt
then the out put is
hello tom
I see users in comments wondering how to disable cell editing while allowing row deletion : I managed to do this by setting all columns individually to read only, instead of the DataGrid itself.
<DataGrid IsReadOnly="False">
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True"/>
<DataGridTextColumn IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
Starting from Bootstrap v4 you can simply add the following to your div
class attribute: mt-2 (margin top 2)
<div class="mt-2 col-md-12">
This will have a two-point top margin!
</div>
More examples are given in the docs: Bootstrap v4 docs
VLookup
You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4".
External Reference
To reference a cell of the same Workbook use the following pattern:
<Sheetname>!<Cell>
Example:
Table1!A1
To reference a cell of a different Workbook use this pattern:
[<Workbook_name>]<Sheetname>!<Cell>
Example:
[MyWorkbook]Table1!A1
Have a look at the AlertDialog docs. As it states, to add a custom view to your alert dialog you need to find the frameLayout and add your view to that like so:
FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
Most likely you are going to want to create a layout xml file for your view, and inflate it:
LayoutInflater inflater = getLayoutInflater();
View twoEdits = inflater.inflate(R.layout.my_layout, f1, false);
I know this question is a bit older, but perhaps you're still open for hints or workarounds:
Create a RelativeLayout "wrap_content" with the button image as the background or the button itself as the first element of the layout. Get a LinearLayout and set it to "layout_centerInParent" and "wrap_content". Then set your Drawable as an Imageview. At last set a TextView with your text (locale).
so basically you have this structure:
RelativeLayout
Button
LinearLayout
ImageView
TextView
or like this:
RelativeLayout with "android-specific" button image as background
LinearLayout
ImageView
TextView
I know with this solution there are many elements to deal with, but you can create very easy your own custom button with it and also set the exact position of text and drawables :)
Not Found Exceptions
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail
and firstOrFail
methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException
will be thrown:
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:
Route::get('/api/flights/{id}', function ($id) {
return App\Flight::findOrFail($id);
});
Try the following. It is simple, but I haven't figured out a graceful way to exit yet.
import cv2.cv as cv
import time
cv.NamedWindow("camera", 0)
capture = cv.CaptureFromCAM(0)
while True:
img = cv.QueryFrame(capture)
cv.ShowImage("camera", img)
if cv.WaitKey(10) == 27:
break
cv.DestroyAllWindows()
The COLLATE keyword specify what kind of character set and rules (order, confrontation rules) you are using for string values.
For example in your case you are using Latin rules with case insensitive (CI) and accent sensitive (AS)
You can refer to this Documentation
Since everybody was posting here his own code, I'm gonna do that too...
I like Crockford because he introduced real object oriented patterns in Javascript. But he also came up with a new misunderstanding, the "that" one.
So why is he using "that = this"? It has nothing to do with private functions at all. It has to do with inner functions!
Because according to Crockford this is buggy code:
Function Foo( ) {
this.bar = 0;
var foobar=function( ) {
alert(this.bar);
}
}
So he suggested doing this:
Function Foo( ) {
this.bar = 0;
that = this;
var foobar=function( ) {
alert(that.bar);
}
}
So as I said, I'm quite sure that Crockford was wrong his explanation about that and this (but his code is certainly correct). Or was he just fooling the Javascript world, to know who is copying his code? I dunno...I'm no browser geek ;D
EDIT
Ah, that's what is all about: What does 'var that = this;' mean in JavaScript?
So Crockie was really wrong with his explanation....but right with his code, so he's still a great guy. :))
Sometimes trailing zeros matter
In [4]: def split_float(x):
...: '''split float into parts before and after the decimal'''
...: before, after = str(x).split('.')
...: return int(before), (int(after)*10 if len(after)==1 else int(after))
...:
...:
In [5]: split_float(105.10)
Out[5]: (105, 10)
In [6]: split_float(105.01)
Out[6]: (105, 1)
In [7]: split_float(105.12)
Out[7]: (105, 12)
The way to do this using the Extention Methods, instead of the linq query syntax would be like this:
var results = workOrders.Join(plans,
wo => wo.WorkOrderNumber,
p => p.WorkOrderNumber,
(order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);
I've done something like this to find out the lower cases.
SELECT *
FROM YourTable
where BINARY_CHECKSUM(lower(ColumnName)) = BINARY_CHECKSUM(ColumnName)
Here's a variant of this answer that uses metaclasses to avoid the messy syntax, and use the typing
-style List[int]
syntax:
class template(type):
def __new__(metacls, f):
cls = type.__new__(metacls, f.__name__, (), {
'_f': f,
'__qualname__': f.__qualname__,
'__module__': f.__module__,
'__doc__': f.__doc__
})
cls.__instances = {}
return cls
def __init__(cls, f): # only needed in 3.5 and below
pass
def __getitem__(cls, item):
if not isinstance(item, tuple):
item = (item,)
try:
return cls.__instances[item]
except KeyError:
cls.__instances[item] = c = cls._f(*item)
item_repr = '[' + ', '.join(repr(i) for i in item) + ']'
c.__name__ = cls.__name__ + item_repr
c.__qualname__ = cls.__qualname__ + item_repr
c.__template__ = cls
return c
def __subclasscheck__(cls, subclass):
for c in subclass.mro():
if getattr(c, '__template__', None) == cls:
return True
return False
def __instancecheck__(cls, instance):
return cls.__subclasscheck__(type(instance))
def __repr__(cls):
import inspect
return '<template {!r}>'.format('{}.{}[{}]'.format(
cls.__module__, cls.__qualname__, str(inspect.signature(cls._f))[1:-1]
))
With this new metaclass, we can rewrite the example in the answer I link to as:
@template
def List(member_type):
class List(list):
def append(self, member):
if not isinstance(member, member_type):
raise TypeError('Attempted to append a "{0}" to a "{1}" which only takes a "{2}"'.format(
type(member).__name__,
type(self).__name__,
member_type.__name__
))
list.append(self, member)
return List
l = List[int]()
l.append(1) # ok
l.append("one") # error
This approach has some nice benefits
print(List) # <template '__main__.List[member_type]'>
print(List[int]) # <class '__main__.List[<class 'int'>, 10]'>
assert List[int] is List[int]
assert issubclass(List[int], List) # True