Honestly I don't find there to be many cases where IoC containers are needed, and most of the time, they just add unneeded complexity.
If you are using it just for making construction of an object simpler, I'd have to ask, are you instantiating this object in more than one location? Would a singleton not suit your needs? Are you changing the configuration at runtime? (Switching data source types, etc).
If yes, then you might need an IoC container. If not, then you're just moving the initialization away from where the developer can easily see it.
Who said that an interface is better than inheritance anyway? Say you're testing a Service. Why not use constructor DI, and create mocks of the dependencies using inheritance? Most services I use only have a few dependencies. Doing unit testing this way prevents maintaining a ton of useless interfaces and means you don't have to use Resharper to quickly find the declaration of a method.
I believe that for most implementations, saying that IoC Containers remove unneeded code is a myth.
First, there's setting up the container in the first place. Then you still have to define each object that needs to be initialized. So you don't save code in initialization, you move it (unless your object is used more than once. Is it better as a Singleton?). Then, for each object you've initialized in this way, you have to create and maintain an interface.
Anyone have any thoughts on this?
Rather than contrast DI and IoC directly, it may be helpful to start from the beginning: every non-trivial application depends on other pieces of code.
So I am writing a class, MyClass
, and I need to call a method of YourService
... somehow I need to acquire an instance of YourService
. The simplest, most straightforward way is to instantiate it myself.
YourService service = new YourServiceImpl();
Direct instantiation is the traditional (procedural) way to acquire a dependency. But it has a number of drawbacks, including tight coupling of MyClass
to YourServiceImpl
, making my code difficult to change and difficult to test. MyClass
doesn't care what the implementation of YourService
looks like, so MyClass
doesn't want to be responsible for instantiating it.
I'd prefer to invert that responsibility from MyClass
to something outside MyClass
. The simplest way to do that is just to move the instantiation call (new YourServiceImpl();
) into some other class. I might name this other class a Locator, or a Factory, or any other name; but the point is that MyClass
is no longer responsible for YourServiceImpl
. I've inverted that dependency. Great.
Problem is, MyClass
is still responsible for making the call to the Locator/Factory/Whatever. Since all I've done to invert the dependency is insert a middleman, now I'm coupled to the middleman (even if I'm not coupled to the concrete objects the middleman gives me).
I don't really care where my dependencies come from, so I'd prefer not to be responsible for making the call(s) to retrieve them. Inverting the dependency itself wasn't quite enough. I want to invert control of the whole process.
What I need is a totally separate piece of code that MyClass
plugs into (call it a framework). Then the only responsibility I'm left with is to declare my dependency on YourService
. The framework can take care of figuring out where and when and how to get an instance, and just give MyClass
what it needs. And the best part is that MyClass
doesn't need to know about the framework. The framework can be in control of this dependency wiring process. Now I've inverted control (on top of inverting dependencies).
There are different ways of connecting MyClass
into a framework. Injection is one such mechanism whereby I simply declare a field or parameter that I expect a framework to provide, typically when it instantiates MyClass
.
I think the hierarchy of relationships among all these concepts is slightly more complex than what other diagrams in this thread are showing; but the basic idea is that it is a hierarchical relationship. I think this syncs up with DIP in the wild.
Inversion of control is when you go to the grocery store and your wife gives you the list of products to buy.
In programming terms, she passed a callback function getProductList()
to the function you are executing - doShopping()
.
It allows user of the function to define some parts of it, making it more flexible.
Spring.Net is quite solid, but the documentation took some time to wade through. Autofac is good, and while .Net 2.0 is supported, you need VS 2008 to compile it, or else use the command line to build your app.
We started seeing this error "New transaction is not allowed because there are other threads running in the session" after migrating from EF5 to EF6.
Google brought us here but we are not calling SaveChanges()
inside the loop. The errors were raised when executing a stored procedure using the ObjectContext.ExecuteFunction inside a foreach loop reading from the DB.
Any call to ObjectContext.ExecuteFunction wraps the function in a transaction. Beginning a transaction while there is already an open reader causes the error.
It is possible to disable wrapping the SP in a transaction by setting the following option.
_context.Configuration.EnsureTransactionsForFunctionsAndCommands = false;
The EnsureTransactionsForFunctionsAndCommands
option allows the SP to run without creating its own transaction and the error is no longer raised.
DbContextConfiguration.EnsureTransactionsForFunctionsAndCommands Property
Haven't used Python in several years, but I would say that it has more to do with it being a dynamically typed language than anything else. For a simple example, in Java, if I wanted to test that something wrote to standard out appropriately I could use DI and pass in any PrintStream to capture the text being written and verify it. When I'm working in Ruby, however, I can dynamically replace the 'puts' method on STDOUT to do the verify, leaving DI completely out of the picture. If the only reason I'm creating an abstraction is to test the class that's using it (think File system operations or the clock in Java) then DI/IoC creates unnecessary complexity in the solution.
MSDN has a Developer's Guide to Dependency Injection Using Unity that may be useful.
The Developer's Guide starts with the basics of what dependency injection is, and continues with examples of how to use Unity for dependency injection. As of the February 2014 the Developer's Guide covers Unity 3.0, which was released in April 2013.
In my case, I have used 2 different context with Unitofwork and Ioc container so i see this problem insistanting while service layer try to make inject second repository to DI. The reason is that exist module has containing other module instance and container supposed to gettng a call from not constractured new repository.. i write here for whome in my shooes
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
You cannot set the min
value of a SeekBar (always 0) and you cannot set the step
value of a SeekBar (always 1).
To set the value from 60 to 180 with a step of 1:
int step = 1;
int max = 180;
int min = 60;
// Ex :
// If you want values from 3 to 5 with a step of 0.1 (3, 3.1, 3.2, ..., 5)
// this means that you have 21 possible values in the seekbar.
// So the range of the seek bar will be [0 ; (5-3)/0.1 = 20].
seekbar.setMax( (max - min) / step );
seekbar.setOnSeekBarChangeListener(
new OnSeekBarChangeListener()
{
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser)
{
// Ex :
// And finally when you want to retrieve the value in the range you
// wanted in the first place -> [3-5]
//
// if progress = 13 -> value = 3 + (13 * 0.1) = 4.3
double value = min + (progress * step);
}
}
);
I put another example within the code so that you understand the math.
The option --list-packets
parses pgp data from a file and outputs its structure - in a very technical way, though. When parsing a public key, you can easily extract the user ids and the key ids of the signatures.
Be wary that this command only parses the data format, it does no validation of signatures or similar things.
CSS provides only two values for its "list-style-position" - inside and outside. With "inside" second lines are flush with the list points not with the superior line:
In ordered lists, without intervention, if you give "list-style-position" the value "inside", the second line of a long list item will have no indent, but will go back to the left edge of the list (i.e. it will left-align with the number of the item). This is peculiar to ordered lists and doesn't happen in unordered lists.
If you instead give "list-style-position" the value "outside", the second line will have the same indent as the first line.
I had a list with a border and had this problem. With "list-style-position" set to "inside", my list didn't look like I wanted it to. But with "list-style-position" set to "outside", the numbers of the list items fell outside the box.
I solved this by simply setting a wider left margin for the whole list, which pushed the whole list toward the right, back into the position it was in before.
CSS:
ol.classname {margin:0;padding:0;}
ol.classname li {margin:0.5em 0 0 0;padding-left:0;list-style-position:outside;}
HTML:
<ol class="classname" style="margin:0 0 0 1.5em;">
Some times there is a chance where rails server not closed properly. You can find process used by rails
ps aux | grep rails
Output will be like
user 12609 9.8 0.5 66456 45480 pts/0 Sl+ 21:06 0:02 /home/user/.rvm/rubies/ruby-2.2.0-preview1/bin/ruby bin/rails s
Here process_id 12609 is used by your rails server.
You can kill it easily by command
kill -9 12609
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
Object.defineProperties(Element.prototype,{
group : {
value: function (str, context) {
// str is valid css selector like :not([attr_name]) or .class_name
var t = "to_select_siblings___";
var parent = context ? context : this.parentNode;
parent.setAttribute(t, '');
var rez = document.querySelectorAll("[" + t + "] " + (context ? '' : ">") + this.nodeName + (str || "")).toArray();
parent.removeAttribute(t);
return rez;
}
},
siblings: {
value: function (str, context) {
var rez=this.group(str,context);
rez.splice(rez.indexOf(this), 1);
return rez;
}
},
nth: {
value: function(str,context){
return this.group(str,context).indexOf(this);
}
}
}
Ex
/* html */
<ul id="the_ul"> <li></li> ....<li><li>....<li></li> </ul>
/*js*/
the_ul.addEventListener("click",
function(ev){
var foo=ev.target;
foo.setAttribute("active",true);
foo.siblings().map(function(elm){elm.removeAttribute("active")});
alert("a click on li" + foo.nth());
});
You can use linear indexing to access each element.
for idx = 1:numel(array)
element = array(idx)
....
end
This is useful if you don't need to know what i,j,k, you are at. However, if you don't need to know what index you are at, you are probably better off using arrayfun()
The accepted answer, although it compiles, is incorrect.
+ (MySingleton*)sharedInstance
{
@synchronized(self) <-------- self does not exist at class scope
{
if (sharedInstance == nil)
sharedInstance = [[MySingleton alloc] init];
}
return sharedInstance;
}
Per Apple documentation:
... You can take a similar approach to synchronize the class methods of the associated class, using the Class object instead of self.
Even if using self works, it shouldn't and this looks like a copy and paste mistake to me. The correct implementation for a class factory method would be:
+ (MySingleton*)getInstance
{
@synchronized([MySingleton class])
{
if (sharedInstance == nil)
sharedInstance = [[MySingleton alloc] init];
}
return sharedInstance;
}
this is the solution to close menu when click on anchor then apply this line in list item
data-target="#sidenav-collapse-main" data-toggle="collapse"
the real example that work for me is below
<li class="nav-item" data-target="#sidenav-collapse-main" data-
toggle="collapse" >
<a class="nav-link" routerLinkActive="active" routerLink="/admin/users">
<i class="ni ni-single-02 text-orange"></i> Users
</a>
</li>
Received this same error on SQL Server 2017 trying to link to Oracle 12c. We were able to use Oracle's SQL Developer to connect to the source database, but the linked server kept throwing the 7302 error.
In the end, we stopped all SQL Services, then re-installed the ODAC components. Started the SQL Services back up and voila!
In other words, you want to pipe stdout into one filter (tee bbb.out
) and stderr into another filter (tee ccc.out
). There is no standard way to pipe anything other than stdout into another command, but you can work around that by juggling file descriptors.
{ { ./aaa.sh | tee bbb.out; } 2>&1 1>&3 | tee ccc.out; } 3>&1 1>&2
See also How to grep standard error stream (stderr)? and When would you use an additional file descriptor?
In bash (and ksh and zsh), but not in other POSIX shells such as dash, you can use process substitution:
./aaa.sh > >(tee bbb.out) 2> >(tee ccc.out)
Beware that in bash, this command returns as soon as ./aaa.sh
finishes, even if the tee
commands are still executed (ksh and zsh do wait for the subprocesses). This may be a problem if you do something like ./aaa.sh > >(tee bbb.out) 2> >(tee ccc.out); process_logs bbb.out ccc.out
. In that case, use file descriptor juggling or ksh/zsh instead.
You can try this
click Help>Install New Software on the menu bar
A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b
the value you get is 2^16 - 56 or 65536 - 56.
Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8
using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8
when casting to a char
, which translates to the positive number 65480
.
From the language specification:
5.1.4. Widening and Narrowing Primitive Conversion
First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).
To get the right point use char c = (char) (b & 0xFF)
which first converts the byte value of b
to the positive integer 200
by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8
becomes 0x000000C8
or the positive number 200
in decimals.
Above is a direct explanation of what happens during conversion between the byte
, int
and char
primitive types.
If you want to encode/decode characters from bytes, use Charset
, CharsetEncoder
, CharsetDecoder
or one of the convenience methods such as new String(byte[] bytes, Charset charset)
or String#toBytes(Charset charset)
. You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets
.
What is meta_key
? Strip out all of the meta_value
conditionals, reduce, and you end up with this:
SELECT
*
FROM
meta_data
WHERE
(
(meta_key = 'lat')
)
AND
(
(meta_key = 'long')
)
GROUP BY
item_id
Since meta_key
can never simultaneously equal two different values, no results will be returned.
Based on comments throughout this question and answers so far, it sounds like you're looking for something more along the lines of this:
SELECT
*
FROM
meta_data
WHERE
(
(meta_key = 'lat')
AND
(
(meta_value >= '60.23457047672217')
OR
(meta_value <= '60.23457047672217')
)
)
OR
(
(meta_key = 'long')
AND
(
(meta_value >= '24.879140853881836')
OR
(meta_value <= '24.879140853881836')
)
)
GROUP BY
item_id
Note the OR
between the top-level conditionals. This is because you want records which are lat
or long
, since no single record will ever be lat
and long
.
I'm still not sure what you're trying to accomplish by the inner conditionals. Any non-null value will match those numbers. So maybe you can elaborate on what you're trying to do there. I'm also not sure about the purpose of the GROUP BY
clause, but that might be outside the context of this question entirely.
How about simply:
#!/bin/bash
pids=""
for i in `seq 0 9`; do
doCalculations $i &
pids="$pids $!"
done
wait $pids
...code continued here ...
Update:
As pointed by multiple commenters, the above waits for all processes to be completed before continuing, but does not exit and fail if one of them fails, it can be made to do with the following modification suggested by @Bryan, @SamBrightman, and others:
#!/bin/bash
pids=""
RESULT=0
for i in `seq 0 9`; do
doCalculations $i &
pids="$pids $!"
done
for pid in $pids; do
wait $pid || let "RESULT=1"
done
if [ "$RESULT" == "1" ];
then
exit 1
fi
...code continued here ...
If class has only one empty constructor (like Activity or Fragment etc, android classes):
Class<?> myClass = Class.forName("com.example.MyClass");
Constructor<?> constructor = myClass.getConstructors()[0];
The expression $(document).ready(function() deprecated in jQuery3.
See working fiddle with jQuery 3 here
Take into account I didn't include the showless button.
Here's the code:
JS
$(function () {
x=3;
$('#myList li').slice(0, 3).show();
$('#loadMore').on('click', function (e) {
e.preventDefault();
x = x+5;
$('#myList li').slice(0, x).slideDown();
});
});
CSS
#myList li{display:none;
}
#loadMore {
color:green;
cursor:pointer;
}
#loadMore:hover {
color:black;
}
predQuery[preId]=='undefined'
You're testing against the string 'undefined'
; you've confused this test with the typeof
test which would return a string. You probably mean to be testing against the special value undefined
:
predQuery[preId]===undefined
Note the strict-equality operator to avoid the generally-unwanted match null==undefined
.
However there are two ways you can get an undefined
value: either preId
isn't a member of predQuery
, or it is a member but has a value set to the special undefined
value. Often, you only want to check whether it's present or not; in that case the in
operator is more appropriate:
!(preId in predQuery)
Easy way to get this working is using:
var cloneArray = JSON.parse(JSON.stringify(originalArray));
I have issues with getting arr.concat()
or arr.splice(0)
to give a deep copy. Above snippet works perfectly.
To have a transparent background while not using a time delay (especially needed in modern web applications where people can stop using it for a while and want a predictable behavior of the interface), use this:
input:-webkit-autofill {
-webkit-background-clip: text;
}
body {
background: lightblue;
}
input {
background: transparent;
}
input.no-autofill-bkg:-webkit-autofill {
-webkit-background-clip: text;
}
_x000D_
<input type="text" name="email" />
<input type="text" name="email" class="no-autofill-bkg" />
_x000D_
Working on: Chrome 83 / 84.0.4147.89, Edge 84.0.522.44
If you decide to re-post my solution, I only ask that you include my name or link to this.
To answer the original question: yes, you can access the index value of a row in apply()
. It is available under the key name
and requires that you specify axis=1
(because the lambda processes the columns of a row and not the rows of a column).
Working example (pandas 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40
You can do
jQuery.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
followed by
$(selector).reverse().each(...)
SELECT CLASS,
isnull([AZ],0),
isnull([CA],0),
isnull([TX],0)
FROM #TEMP
PIVOT (SUM(DATA)
FOR STATE IN ([AZ], [CA], [TX])) AS PVT
ORDER BY CLASS
All of these answers are excellent if you want to use optional parameters, but another Pythonic possibility is to use a classmethod to generate a factory-style pseudo-constructor:
def __init__(self, num_holes):
# do stuff with the number
@classmethod
def fromRandom(cls):
return cls( # some-random-number )
a=1
for i in *.jpg; do
mv -- "$i" "$a.jpg"
a=`expr $a + 1`
done
You can ssh to your server and run this command
ln -s /usr/share/phpmyadmin /var/www/phpmyadmin
It worked for me..
Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.framework to your target.
Here's some sample code:
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController () {
MPMoviePlayerController *moviePlayerController;
}
@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Instantiate a movie player controller and add it to your view
NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[moviePlayerController.view setFrame:self.movieView.bounds]; // player's frame must match parent's
[self.movieView addSubview:moviePlayerController.view];
// Configure the movie player controller
moviePlayerController.controlStyle = MPMovieControlStyleNone;
[moviePlayerController prepareToPlay];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Start the movie
[moviePlayerController play];
}
@end
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.
FOR /d %%K in ("n:\test*") DO (
FOR /d %%J in ("%%K*") DO (
FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"
)
)
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged
Update (2010/10/01): Yesss, Sun Java Finally Uploaded To The Ubuntu 10.10 Maverick Official Partner Repository.
Update (2010/09/27): Readers might want to check Sun Java6 Packages [updated]. I still expect official packages to be available in the partner repos at releast time though.
For an unknown reason, the sun-java6-jdk are not yet available in the partner repositories.
So either downloaded the required packages from http://archive.canonical.com/pool/partner/s/sun-java6/ and install them with dpkg -i
.
Or temporarily replace the maverick partner repository
http://archive.canonical.com/ubuntu maverick partner
by the lucid one (replace maverick
by lucid
in the above line, let me know if you need more help to do this). Then, install sun-java6. And revert the change.
It is not an import problem. You simply call .dropDuplicates()
on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...)
is pyspark.sql.dataframe.DataFrame
, after you apply .collect()
it is a plain Python list
, and lists don't provide dropDuplicates
method. What you want is something like this:
(df1 = sqlContext
.createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
.dropDuplicates())
df1.collect()
I want to leave this here because I struggled with this when compiling for Android in Windows with the Android SDK.
CMake distinguishes between TARGET and HOST platform.
My TARGET was Android so the variables like CMAKE_SYSTEM_NAME had the value "Android" and the variable WIN32 from the other answer here was not defined. But I wanted to know if my HOST system was Windows because I needed to do a few things differently when compiling on either Windows or Linux or IOs. To do that I used CMAKE_HOST_SYSTEM_NAME which I found is barely known or mentioned anywhere because for most people TARGEt and HOST are the same or they don't care.
Hope this helps someone somewhere...
I just remove other active popovers before the new popover is shown (bootstrap 3):
$(".my-popover").popover();
$(".my-popover").on('show.bs.popover',function () {
$('.popover.in').remove();
});
Try these:
Make sure that output path of project is correct (Project > Properties > Build > Output path)
Go in menu to Build > Configuration Manager, and check if your main/entry project has checked Build. If not, check it.
It's also possible by using rsync
, for example:
rsync -va --delete-after src/ dst/
where:
-v
, --verbose
: increase verbosity-a
, --archive
: archive mode; equals -rlptgoD
(no -H,-A,-X
)--delete-after
: delete files on the receiving side be done after the transfer has completedIf you've root privileges, prefix with sudo
to override potential permission issues.
The openssl
documentation says that file supplied as the -in
argument must be in PEM format.
Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer
is not PEM format rather it is PKCS7.
In order to create my .p12
, I had to first convert the certificate to PEM:
openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
and then execute
openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:
WHILE EXISTS (SELECT 1
FROM YourTable
WHERE <yourCondition>)
DELETE TOP(10000) FROM YourTable
WHERE <yourCondition>
/**
* ??????????????,????????
* English: Calculating the difference between the given time and the current time and then showing the results.
*/
function date2Text(date) {
var milliseconds = new Date() - date;
var timespan = new TimeSpan(milliseconds);
if (milliseconds < 0) {
return timespan.toString() + "??";
}else{
return timespan.toString() + "?";
}
}
/**
* ???????????
* English: Using a function to calculate the time interval
* @param milliseconds ???
*/
var TimeSpan = function (milliseconds) {
milliseconds = Math.abs(milliseconds);
var days = Math.floor(milliseconds / (1000 * 60 * 60 * 24));
milliseconds -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(milliseconds / (1000 * 60 * 60));
milliseconds -= hours * (1000 * 60 * 60);
var mins = Math.floor(milliseconds / (1000 * 60));
milliseconds -= mins * (1000 * 60);
var seconds = Math.floor(milliseconds / (1000));
milliseconds -= seconds * (1000);
return {
getDays: function () {
return days;
},
getHours: function () {
return hours;
},
getMinuts: function () {
return mins;
},
getSeconds: function () {
return seconds;
},
toString: function () {
var str = "";
if (days > 0 || str.length > 0) {
str += days + "?";
}
if (hours > 0 || str.length > 0) {
str += hours + "??";
}
if (mins > 0 || str.length > 0) {
str += mins + "??";
}
if (days == 0 && (seconds > 0 || str.length > 0)) {
str += seconds + "?";
}
return str;
}
}
}
Try this
$('#testID').addClass('nameOfClass');
or
$('#testID').removeClass('nameOfClass');
I second bigvax comment earlier but you need to make sure that you add
jQuery("#jQueryUIAccordion").({ active: false,
collapsible: true });
otherwise you wont be able to open the first accordion after collapsing them.
$('.close').click(function () {
$('.ui-accordion-header').removeClass('ui-accordion-header-active ui-state-active ui-corner-top').addClass('ui-corner-all').attr({'aria-selected':'false','tabindex':'-1'});
$('.ui-accordion-header .ui-icon').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
$('.ui-accordion-content').removeClass('ui-accordion-content-active').attr({'aria-expanded':'false','aria-hidden':'true'}).hide();
}
I had to do something like this
CREATE OR REPLACE FUNCTION MYFUNC()
RETURNS VOID AS $$
DO
$do$
BEGIN
DECLARE
myvar int;
...
END
$do$
$$ LANGUAGE SQL;
In addition to the other answers, there is a big benefit to using the DisplayAttribute
when you want to localize the fields. You can lookup the name in a localization database using the DisplayAttribute and it will use whatever translation you wish.
Also, you can let MVC generate the templates for you by using Html.EditorForModel()
and it will generate the correct label for you.
Ultimately, it's up to you. But the MVC is very "Model-centric", which is why data attributes are applied to models, so that metadata exists in a single place. It's not like it's a huge amount of extra typing you have to do.
For legacy code in Python 2.7, can do it via BeautifulSoup4:
>>> bs4.dammit import EntitySubstitution
>>> esub = EntitySubstitution()
>>> esub.substitute_html("r&d")
'r&d'
Don't use int
. Files over 2 gigabytes in size are common as dirt these days
Don't use unsigned int
. Files over 4 gigabytes in size are common as some slightly-less-common dirt
IIRC the standard library defines off_t
as an unsigned 64 bit integer, which is what everyone should be using. We can redefine that to be 128 bits in a few years when we start having 16 exabyte files hanging around.
If you're on windows, you should use GetFileSizeEx - it actually uses a signed 64 bit integer, so they'll start hitting problems with 8 exabyte files. Foolish Microsoft! :-)
The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
Here is a great resource from Microsoft which includes a high level features overview for each .NET release since 1.0 up to the present day. It also include information about the associated Visual Studio release and Windows version compatibility.
The simplest change would be something like this:
public static void main (String[] args) throws Exception {
testconnect obj = new testconnect();
obj.con2 = DriverManager.getConnection(obj.getConnectionUrl2());
obj.con2.close();
}
if($var !== '' && $var !== NULL)
{
echo $var;
}
Defining a custom __call__()
method in the meta-class allows the class's instance to be called as a function, not always modifying the instance itself.
In [1]: class A:
...: def __init__(self):
...: print "init"
...:
...: def __call__(self):
...: print "call"
...:
...:
In [2]: a = A()
init
In [3]: a()
call
You can use this function to add an child to a DOM element.
function addElement(parentId, elementTag, elementId, html)
{
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function removeElement(elementId)
{
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
In Windows platform, these file types are used for certificate information. Normally used for SSL certificate and Public Key Infrastructure (X.509).
for more information visit:Certificate Files: .Cer x .Pvk x .Pfx
Above formula requires a minus sign in the first line: "=IF(A1<-999500000000"
=IF(A1<-999500000000,TEXT(A1,"#,##.#0,,,"" TB"""),
IF(A1<-9995000000,TEXT(A1,"#,##.#0,,,"" GB"""),
IF(A1<-9995000,TEXT(A1,"#,##0,,"" MB"""),
IF(A1<-9995,TEXT(A1,"#,##0,"" KB"""),
IF(A1<-1000,TEXT(A1,"#,##0"" B """),
IF(A1<0,TEXT(A1,"#,##0"" B """),
IF(A1<1000,TEXT(A1,"#,##0"" B """),
IF(A1<999500,TEXT(A1,"#,##0,"" KB"""),
IF(A1<999500000,TEXT(A1,"#,##0,,"" MB"""),
IF(A1<999500000000,TEXT(A1,"#,##.#0,,,"" GB"""),
TEXT(A1,"#,##.#0,,,,"" TB""")))))))))))
in Swift 5
extension Date {
static var currentTimeStamp: Int64{
return Int64(Date().timeIntervalSince1970 * 1000)
}
}
call like this:
let timeStamp = Date.currentTimeStamp
print(timeStamp)
Thanks @lenooh
You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?
CREATE PROCEDURE sp_generate_insertscripts
(
@TABLENAME VARCHAR(MAX),
@FILTER_CONDITION VARCHAR(MAX)='' -- where TableId = 5 or some value
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @TABLE_NAME VARCHAR(MAX),
@CSV_COLUMN VARCHAR(MAX),
@QUOTED_DATA VARCHAR(MAX),
@TEXT VARCHAR(MAX),
@FILTER VARCHAR(MAX)
SET @TABLE_NAME=@TABLENAME
SELECT @FILTER=@FILTER_CONDITION
SELECT @CSV_COLUMN=STUFF
(
(
SELECT ',['+ NAME +']' FROM sys.all_columns
WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
is_identity!=1 FOR XML PATH('')
),1,1,''
)
SELECT @QUOTED_DATA=STUFF
(
(
SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns
WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND
is_identity!=1 FOR XML PATH('')
),1,1,''
)
SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER
--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT
EXECUTE (@TEXT)
SET NOCOUNT OFF
END
What about ordering desc by the desired property,
blah = blah.OrderByDescending(x => x.Property);
And then doing something like
if (!descending)
{
blah = blah.Reverse()
}
else
{
// Already sorted desc ;)
}
Is it Reverse() too slow?
I am giving an extract from the book "C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari"
Here’s a demonstration on the use of LinkedList:
var tune = new LinkedList<string>();
tune.AddFirst ("do"); // do
tune.AddLast ("so"); // do - so
tune.AddAfter (tune.First, "re"); // do - re- so
tune.AddAfter (tune.First.Next, "mi"); // do - re - mi- so
tune.AddBefore (tune.Last, "fa"); // do - re - mi - fa- so
tune.RemoveFirst(); // re - mi - fa - so
tune.RemoveLast(); // re - mi - fa
LinkedListNode<string> miNode = tune.Find ("mi");
tune.Remove (miNode); // re - fa
tune.AddFirst (miNode); // mi- re - fa
foreach (string s in tune) Console.WriteLine (s);
You can use a HTML table:
<table>
<tr>
<td>
<div id="bloc1">your content</div>
</td>
<td>
<div id="bloc2">your content</div>
</td>
</tr>
</table>
Take a look at the Activator.CreateInstance method.
In my case I wanted to tear down the underlying connection in which case I had to call socket.disconnect(true)
as you can see is needed from the source here
You can use like below, for iOS 13* and Swift 4.
1 -> Set View controller-based status bar appearance to NO
extension UIApplication {
var statusBarView: UIView? {
if #available(iOS 13.0, *) {
let statusBar = UIView()
statusBar.frame = UIApplication.shared.statusBarFrame
UIApplication.shared.keyWindow?.addSubview(statusBar)
return statusBar
} else {
let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
return statusBar
}
}
use in didFinishLaunchingWithOptions
UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
InetAddress.getByName also works for ip address.
From the JavaDoc
The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.
Try using the trigger property for this:
$('select').select2().trigger('change');
To test the efficiancy of earlier awnser by Konrad Holl, I did a quick comparison with what I thought would be the slow way of doing it:
package util.collections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
*
* @author Earl Bosch
* @param <E> Comparable Element
*
*/
public class SortedList<E extends Comparable> implements List<E> {
/**
* The list of elements
*/
private final List<E> list = new ArrayList();
public E first() {
return list.get(0);
}
public E last() {
return list.get(list.size() - 1);
}
public E mid() {
return list.get(list.size() >>> 1);
}
@Override
public void clear() {
list.clear();
}
@Override
public boolean add(E e) {
list.add(e);
Collections.sort(list);
return true;
}
@Override
public int size() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public boolean contains(Object obj) {
return list.contains((E) obj);
}
@Override
public Iterator<E> iterator() {
return list.iterator();
}
@Override
public Object[] toArray() {
return list.toArray();
}
@Override
public <T> T[] toArray(T[] arg0) {
return list.toArray(arg0);
}
@Override
public boolean remove(Object obj) {
return list.remove((E) obj);
}
@Override
public boolean containsAll(Collection<?> c) {
return list.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
list.addAll(c);
Collections.sort(list);
return true;
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public boolean removeAll(Collection<?> c) {
return list.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return list.retainAll(c);
}
@Override
public E get(int index) {
return list.get(index);
}
@Override
public E set(int index, E element) {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public void add(int index, E element) {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public E remove(int index) {
return list.remove(index);
}
@Override
public int indexOf(Object obj) {
return list.indexOf((E) obj);
}
@Override
public int lastIndexOf(Object obj) {
return list.lastIndexOf((E) obj);
}
@Override
public ListIterator<E> listIterator() {
return list.listIterator();
}
@Override
public ListIterator<E> listIterator(int index) {
return list.listIterator(index);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException("Not supported.");
}
}
Turns out its about twice as fast! I think its because of SortedLinkList slow get - which make's it not a good choice for a list.
Compared times for same random list:
Seems glazedlists.SortedList is really fast...
I was also lost around getMeasuredWidth()
and getMeasuredHeight()
getHeight()
and getWidth()
for a long time.......... later i found that getting the view's width and height in onSizeChanged()
is the best way to do this........ you can dynamically get your CURRENT width and CURRENT height of your view by overriding the onSizeChanged(
) method.
might wanna take a look at this which has an elaborate code snippet. New Blog Post: how to get width and height dimensions of a customView (extends View) in Android http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html
use CHAR(10)
for New Line in SQL
char(9)
for Tab
and Char(13)
for Carriage Return
brew install python3
create alias in your shell profile
alias pip3="python3 -m pip"
in my .zshrc
? ~ pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)
GUID is Microsoft's implementation of the UUID standard.
Per Wikipedia:
The term GUID usually refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.
An updated quote from that same Wikipedia article:
RFC 4122 itself states that UUIDs "are also known as GUIDs". All this suggests that "GUID", while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…
I think somewhere in your codebase are you @Autowiring
the concrete class ServiceImpl
where you should be autowiring it's interface (presumably MyService
).
One way is to associating unique properties with your file while creation.
properties = "{ \
key='somekey' and \
value='somevalue'
}"
then create a query.
query = "title = " + "\'" + title + "\'" + \
AND + "mimeType = " + "\'" + mimeType + "\'" + \
AND + "trashed = false" + \
AND + "properties has " + properties
All the file properties(title, etc) already known to you can go here + properties.
I don't think this is the express global size limit, but specifically the connect.json middleware limit. This is 100kb by default when you use express.bodyParser()
and don't provide a limit
option.
Try:
app.post('/api/0.1/people', express.bodyParser({limit: '5mb'}), yourHandler);
I realize this was asked some time ago, but after reading this thread, I found the solution for XCode 4.2: Product -> Edit Scheme -> Diagnostics Tab -> Enable Zombie Objects
Helped me find a message being sent to a deallocated object.
You can try this:
/*iPad landscape oriented styles */
@media only screen and (device-width:768px)and (orientation:landscape){
.yourstyle{
}
}
/*iPad Portrait oriented styles */
@media only screen and (device-width:768px)and (orientation:portrait){
.yourstyle{
}
}
Try linux command chsh
.
The detailed command is chsh -s /bin/bash
.
It will prompt you to enter your password.
Your default login shell is /bin/bash
now. You must log out and log back in to see this change.
The following is quoted from man page:
The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account
This command will change the default login shell permanently.
Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh
.
You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:
You can use System.arraycopy
for either of these. Both of these are O(n), since they copy all but 1 element.
If you will be removing the first element often, consider using LinkedList
instead. You can use LinkedList.remove
, which is from the Queue
interface, for convenience. With LinkedList
, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator
to that position. However, accessing an arbitrary element by index is O(n).
This has bitten me a second time so I thought might be worth mentioning. The line listen_addresses = '*' in the postgresql.conf is by default commented. Be sure to uncomment (remove the pound sign, # at the beginning) it after updating otherwise, remote connections will continue to be blocked.
With C++17 str::string
receives data()
overload that returns a pointer to modifieable buffer so string can be used in strtok
directly without any hacks:
#include <string>
#include <iostream>
#include <cstring>
#include <cstdlib>
int main()
{
::std::string text{"pop dop rop"};
char const * const psz_delimiter{" "};
char * psz_token{::std::strtok(text.data(), psz_delimiter)};
while(nullptr != psz_token)
{
::std::cout << psz_token << ::std::endl;
psz_token = std::strtok(nullptr, psz_delimiter);
}
return EXIT_SUCCESS;
}
output
pop
dop
rop
Another issue of that page if you use multiple playstore accounts:
In some cases you still get a 404, even if you are currently logged in with the right account, the one you joined the beta community with. As a workaround, you can clear the browser cache, use another browser for the beta signup, or just use the incognito mode of your browser.
I prefer to use "await" command and async functions to get rid of confusions of promises,
In this case I would write an asynchronous function first, this will be used instead of the anonymous function called under "promise.then" part of this question :
async function SubFunction(output){
// Call to database , returns a promise, like an Ajax call etc :
const response = await axios.get( GetApiHost() + '/api/some_endpoint')
// Return :
return response;
}
and then I would call this function from main function :
async function justTesting() {
const lv_result = await SubFunction(output);
return lv_result + 1;
}
Noting that I returned both main function and sub function to async functions here.
Simply use Browserify, what is something like a compiler that process your files before it go into production and packs the file in bundles.
Think you have a main.js file that require the files of your project, when you run browserify in it, it simply process all and creates a bundle with all your files, allowing the use of the require
calls synchronously in the browser without HTTP requests and with very little overhead for the performance and for the size of the bundle, for example.
See the link for more info: http://browserify.org/
Just another alternative using sp_executesql (tested only in SQL 2016). As previous posts noticed, atomicity must be handled elsewhere.
CREATE FUNCTION [dbo].[fn_get_service_version_checksum2]
(
@ServiceId INT
)
RETURNS INT
AS
BEGIN
DECLARE @Checksum INT;
SELECT @Checksum = dbo.fn_get_service_version(@ServiceId);
DECLARE @LatestVersion INT = (SELECT MAX(ServiceVersion) FROM [ServiceVersion] WHERE ServiceId = @ServiceId);
-- Check whether the current version already exists and that it's the latest version.
IF EXISTS(SELECT TOP 1 1 FROM [ServiceVersion] WHERE ServiceId = @ServiceId AND [Checksum] = @Checksum AND ServiceVersion = @LatestVersion)
RETURN @LatestVersion;
-- Insert the new version to the table.
EXEC sp_executesql N'
INSERT INTO [ServiceVersion] (ServiceId, ServiceVersion, [Checksum], [Timestamp])
VALUES (@ServiceId, @LatestVersion + 1, @Checksum, GETUTCDATE());',
N'@ServiceId INT = NULL, @LatestVersion INT = NULL, @Checksum INT = NULL',
@ServiceId = @ServiceId,
@LatestVersion = @LatestVersion,
@Checksum = @Checksum
;
RETURN @LatestVersion + 1;
END;
You just need to feed the path to your file to pd.read_excel
import pandas as pd
file_path = "./my_excel.xlsx"
data_frame = pd.read_excel(file_path)
Checkout the documentation to explore parameters like skiprows
to ignore rows when loading the excel
If after the *, you alias the id column that is breaking the query a secondtime... and give it a new name... it magically starts working.
select IDENTITY( int ) as TempID, *, SectionID as Fix2IDs
into #TempSections
from Files_Sections
This can also get the filename
import java.nio.file.Paths;
import java.nio.file.Path;
Path path = Paths.get("/abc/def/ghfj.doc");
System.out.println(path.getFileName().toString());
Will print ghfj.doc
I added a ticket to add an option of some sort here:
https://github.com/pydata/pandas/issues/1450
In the meantime, result.fillna('')
should do what you want
EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values
, empty strings will stay empty strings in the result
use className->function(); instead className::function() ;
Shift-Alt-J
is a useful keyboard shortcut in Eclipse for creating Javadoc comment templates.
Invoking the shortcut on a class, method or field declaration will create a Javadoc template:
public int doAction(int i) {
return i;
}
Pressing Shift-Alt-J
on the method declaration gives:
/**
* @param i
* @return
*/
public int doAction(int i) {
return i;
}
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
You can use NullableValueTypes (like int?) for this. The code would be like this:
private void Example(int? arg1, int? arg2)
{
if(!arg1.HasValue)
{
//do something
}
if(!arg2.HasValue)
{
//do something else
}
}
You cannot use primitive types in HashMap
. int
, or double
don't work. You have to use its enclosing type. for an example
Map<String,Integer> m = new HashMap<String,Integer>();
Now both are objects, so this will work.
In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:
.collapse-row.collapsed + tr {
display: none;
}
'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.
Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/
python supports arbitrarily large integers naturally:
example:
>>> 10**1000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
You could even get, for example of a huge integer value, fib(4000000).
But still it does not (for now) supports an arbitrarily large float !!
If you need one big, large, float then check up on the decimal Module. There are examples of use on these foruns: OverflowError: (34, 'Result too large')
Another reference: http://docs.python.org/2/library/decimal.html
You can even using the gmpy module if you need a speed-up (which is likely to be of your interest): Handling big numbers in code
Another reference: https://code.google.com/p/gmpy/
Asterisk symbol (*) is used to check values in the array, not the array itself.
$validator = Validator::make($request->all(), [
"names" => "required|array|min:3",
"names.*" => "required|string|distinct|min:3",
]);
In the example above:
EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:
$data = $request->validate([
"name" => "required|array|min:3",
"name.*" => "required|string|distinct|min:3",
]);
As to me, the below code does't work, when it runs,the image will step to the next quickly without your press:
import cv2
img = cv2.imread('sof.jpg') # load a dummy image
while(1):
cv2.imshow('img',img)
k = cv2.waitKey(33)
if k==27: # Esc key to stop
break
elif k==-1: # normally -1 returned,so don't print it
continue
else:
print k # else print its value
But this works:
def test_wait_key():
lst_img_path = [
'/home/xy/yy_face_head/face_det_test/111.png',
'/home/xy/yy_face_head/face_det_test/222.png'
#.....more path ...
]
for f_path in lst_img_path:
img = cv2.imread(f_path)
cv2.imshow('tmp', img)
c = cv2.waitKey(0) % 256
if c == ord('a'):
print "pressed a"
else:
print 'you press %s' % chr(c)
Output as below:
git reset --hard HEAD
git fetch --all
git reset --hard origin/your_branch
I think you should not rely on the implicit conversion. It is a bad practice.
Instead you should try like this:
datenum >= to_date('11/26/2013','mm/dd/yyyy')
or like
datenum >= date '2013-09-01'
You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:
#!/bin/bash
sudo -u username command1
command2
sudo -u username command3
command4
When running as root, sudo doesn't ask for a password.
This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:
bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$
I have modified the above solutions and replaced Files.walk
with Files.list
. This also assumes the directory you are zipping only contains file and not any sub directories.
private void zipDirectory(Path dirPath) throws IOException {
String zipFilePathStr = dirPath.toString() + ".zip";
Path zipFilePath = Files.createFile(Paths.get(zipFilePathStr));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(zipFilePath))) {
Files.list(dirPath)
.filter(filePath-> !Files.isDirectory(filePath))
.forEach(filePath-> {
ZipEntry zipEntry = new ZipEntry(dirPath.relativize(filePath).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(filePath, zs);
zs.closeEntry();
}
catch (IOException e) {
System.err.println(e);
}
});
}
}
To see how the repr works within a class, run the following code, first with and then without the repr method.
class Coordinate (object):
def __init__(self,x,y):
self.x = x
self.y = y
def getX(self):
# Getter method for a Coordinate object's x coordinate.
# Getter methods are better practice than just accessing an attribute directly
return self.x
def getY(self):
# Getter method for a Coordinate object's y coordinate
return self.y
def __repr__(self): #remove this and the next line and re-run
return 'Coordinate(' + str(self.getX()) + ',' + str(self.getY()) + ')'
>>>c = Coordinate(2,-8)
>>>print(c)
Definitely not both. Other than that I'd have to say it's a personal preference. I'd use css if I had many images the same size to reduce code.
.my_images img {width: 20px; height:20px}
In the long term CSS may win out due to HTML attribute deprecation and more likely due to the growth of vector image formats like SVG where it can actually make sense to scale images using non-pixel based units like % or em.
They have different semantics, even if they happen to have equivalent results on your particular data.
If building a temp table, move the ORDER BY clause from inside the temp table code block to the outside.
Not allowed:
SELECT * FROM (
SELECT A FROM Y
ORDER BY Y.A
) X;
Allowed:
SELECT * FROM (
SELECT A FROM Y
) X
ORDER BY X.A;
You need to #include <stdlib.h>
. Otherwise it's defined as int malloc()
which is incompatible with the built-in type void *malloc(size_t)
.
Converting Bitmap
to File
needs to be done in background (NOT IN THE MAIN THREAD) it hangs the UI specially if the bitmap
was large
File file;
public class fileFromBitmap extends AsyncTask<Void, Integer, String> {
Context context;
Bitmap bitmap;
String path_external = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg";
public fileFromBitmap(Bitmap bitmap, Context context) {
this.bitmap = bitmap;
this.context= context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// before executing doInBackground
// update your UI
// exp; make progressbar visible
}
@Override
protected String doInBackground(Void... params) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// back to main thread after finishing doInBackground
// update your UI or take action after
// exp; make progressbar gone
sendFile(file);
}
}
Calling it
new fileFromBitmap(my_bitmap, getApplicationContext()).execute();
you MUST use the file
in onPostExecute
.
To change directory of file
to be stored in cache
replace line :
file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
with :
file = new File(context.getCacheDir(), "temporary_file.jpg");
The answer here is not clear, so I wanted to add more detail.
Using the link provided above, I performed the following step.
In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.
This information is available at the link the OP posted in the Answer.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
SELECT name, COUNT(name) AS count
FROM table
GROUP BY name
UNION ALL
SELECT 'SUM' name, COUNT(name)
FROM table
OUTPUT:
name count
-------------------------------------------------- -----------
alpha 1
beta 3
Charlie 2
SUM 6
Depending on the Java version (or JDK, SDK, JRE... i dunno, im new to the Java ecosystem), the JsonObject
is abstract. So, this is a new implementation:
import javax.json.Json;
import javax.json.JsonObject;
...
try (PrintWriter out = response.getWriter()) {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
JsonObject json = Json.createObjectBuilder().add("foo", "bar").build();
out.print(json.toString());
}
You also encounter this if you run an Application on a Scheduled Task in Non-Interactive mode.
As soon as you show a Dialog it throws the error:
Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.
You can see its a MessageBox causing the problem in the stack trace:
at System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, Boolean showHelp)
If you're running your app on a Scheduled Task send an email instead of showing a Dialog.
As Herman pointed out, you can get the index and element from each iteration.
{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}
Working example:
package main
import (
"html/template"
"os"
)
type EntetiesClass struct {
Name string
Value int32
}
// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`
func main() {
data := map[string][]EntetiesClass{
"Yoga": {{"Yoga", 15}, {"Yoga", 51}},
"Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
}
t := template.New("t")
t, err := t.Parse(htmlTemplate)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}
Output:
Pilates
3
6
9
Yoga
15
51
Playground: http://play.golang.org/p/4ISxcFKG7v
If you're on linux then you can grab the guest processes with
ps axuw | grep vmware-vmx
As @Dubas pointed out, you should be able to pick out the errant process by the path name to the VMD
If you are in Windows and the error message shows VT-x is not available
make sure Hyper-V is disabled in Windows components.
This function will clear the sheet data starting from specified row and column :
Sub ClearWKSData(wksCur As Worksheet, iFirstRow As Integer, iFirstCol As Integer)
Dim iUsedCols As Integer
Dim iUsedRows As Integer
iUsedRows = wksCur.UsedRange.Row + wksCur.UsedRange.Rows.Count - 1
iUsedCols = wksCur.UsedRange.Column + wksCur.UsedRange.Columns.Count - 1
If iUsedRows > iFirstRow And iUsedCols > iFirstCol Then
wksCur.Range(wksCur.Cells(iFirstRow, iFirstCol), wksCur.Cells(iUsedRows, iUsedCols)).Clear
End If
End Sub
Try this:
<h2>Favorite color</h2>
<select name="color">
<option value=""></option>
<option>Pink</option>
<option>Red</option>
<option>Blue</option>
</select>
The first option in the drop down would be blank.
You can list the tags on remote repository with ls-remote
, and then check if it's there. Supposing the remote reference name is origin
in the following.
git ls-remote --tags origin
And you can list tags local with tag
.
git tag
You can compare the results manually or in script.
Besides all of the other suggestions, there is one other thing you need to consider. Is your helloworld.jar a console program? If it is, then I don't believe you'll be able to make it into a double-clickable jar file. Console programs use the regular cmd.exe shell window for their input and output. Usually the jar "launcher" is bound to javaw.exe which doesn't create a command-shell window.
In Solution Explorer:
I use this to install add-ons like HTML editors and third-party file browsers.
If it's just a true/false test, have your function return 0
for success, and return 1
for failure. The test would then be:
if function_name; then
do something
else
error condition
fi
use the attribute "innerHTML"
somehow select the table:
var a = document.getElementById('table, div, whatever node, id')
a.innerHTML = your_text
Pass multiple parameter for VB.NET 3.5
Public Class MyWork
Public Structure thread_Data
Dim TCPIPAddr As String
Dim TCPIPPort As Integer
End Structure
Dim STthread_Data As thread_Data
STthread_Data.TCPIPAddr = "192.168.2.2"
STthread_Data.TCPIPPort = 80
Dim multiThread As Thread = New Thread(AddressOf testthread)
multiThread.SetApartmentState(ApartmentState.MTA)
multiThread.Start(STthread_Data)
Private Function testthread(ByVal STthread_Data As thread_Data)
Dim IPaddr as string = STthread_Data.TCPIPAddr
Dim IPport as integer = STthread_Data.TCPIPPort
'Your work'
End Function
End Class
2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.
Hope that will help.
This will definitely work............
You have to just replace your <ScrollView ></ScrollView>
in layout XML file with this Custom ScrollView
like <com.tmd.utils.VerticalScrollview > </com.tmd.utils.VerticalScrollview >
package com.tmd.utils;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ScrollView;
public class VerticalScrollview extends ScrollView{
public VerticalScrollview(Context context) {
super(context);
}
public VerticalScrollview(Context context, AttributeSet attrs) {
super(context, attrs);
}
public VerticalScrollview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action)
{
case MotionEvent.ACTION_DOWN:
Log.i("VerticalScrollview", "onInterceptTouchEvent: DOWN super false" );
super.onTouchEvent(ev);
break;
case MotionEvent.ACTION_MOVE:
return false; // redirect MotionEvents to ourself
case MotionEvent.ACTION_CANCEL:
Log.i("VerticalScrollview", "onInterceptTouchEvent: CANCEL super false" );
super.onTouchEvent(ev);
break;
case MotionEvent.ACTION_UP:
Log.i("VerticalScrollview", "onInterceptTouchEvent: UP super false" );
return false;
default: Log.i("VerticalScrollview", "onInterceptTouchEvent: " + action ); break;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
super.onTouchEvent(ev);
Log.i("VerticalScrollview", "onTouchEvent. action: " + ev.getAction() );
return true;
}
}
If you want to add the current date into the database, I would avoid calculating the date in Java to begin with. Determining "now" on the Java (client) side leads to possible inconsistencies in the database if the client side is mis-configured, has the wrong time, wrong timezone, etc. Instead, the date can be set on the server side in a manner such as the following:
requestSQL = "INSERT INTO CREDIT_REQ_TITLE_ORDER (" +
"REQUEST_ID, ORDER_DT, FOLLOWUP_DT) " +
"VALUES(?, SYSDATE, SYSDATE + 30)";
...
prs.setInt(1, new Integer(requestID));
This way, only one bind parameter is required and the dates are calculated on the server side will be consistent. Even better would be to add an insert trigger to CREDIT_REQ_TITLE_ORDER
and have the trigger insert the dates. That can help enforce consistency between different client apps (for example, someone trying to do a fix via sqlplus.
Here's one more for you that not only performs the php -l
check for you, but also does some secondary analysis for mistakes that would not be considered invalid (e.g. declaring a variable with a double equal sign).
for more information on How to create Circle Android Custom Progress Bar view this link
Step 01 You should create an xml file on drawable file for configure the appearance of progress bar . So Im creating my xml file as circular_progress_bar.xml.
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="120"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="140">
<item android:id="@android:id/background">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:useLevel="false"
android:angle="0"
android:type="sweep"
android:thicknessRatio="50.0">
<solid android:color="#000000"/>
</shape>
</item>
<item android:id="@android:id/progress">
<rotate
android:fromDegrees="120"
android:toDegrees="120">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:angle="0"
android:type="sweep"
android:thicknessRatio="50.0">
<solid android:color="#ffffff"/>
</shape>
</rotate>
</item>
</layer-list>
Step 02 Then create progress bar on your xml file Then give the name of xml file on your drawable folder as the parth of android:progressDrawable
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginLeft="0dp"
android:layout_centerHorizontal="true"
android:indeterminate="false"
android:max="100"
android:progressDrawable="@drawable/circular_progress_bar" />
Step 03 Visual the progress bar using thread
package com.example.progress;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private ProgressBar progBar;
private TextView text;
private Handler mHandler = new Handler();
private int mProgressStatus=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progBar= (ProgressBar)findViewById(R.id.progressBar);
text = (TextView)findViewById(R.id.textView1);
dosomething();
}
public void dosomething() {
new Thread(new Runnable() {
public void run() {
final int presentage=0;
while (mProgressStatus < 63) {
mProgressStatus += 1;
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progBar.setProgress(mProgressStatus);
text.setText(""+mProgressStatus+"%");
}
});
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
What you are looking for is a "diff algorithm". A quick google search led me to this solution. I did not test it, but maybe it will do what you need.
This is perhaps the best explanations on why to use lambda expressions -> https://youtu.be/j9nj5dTo54Q
In summary, it's to improve code readability, reduce chances of errors by reusing rather than replicating code, and leverage optimization happening behind the scenes.
The command git config --list
will list the settings. There you should also find user.name
and user.email
.
In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.
Source: Mongodb.
If you are using mongo sheel, just do:
db.Datetime.remove({})
In your case, you need:
You didn't show me the delete button, so this button is just an example:
<a class="button__delete"></a>
Change the controller to:
exports.destroy = function(req, res, next) {
Datetime.remove({}, function(err) {
if (err) {
console.log(err)
} else {
res.end('success');
}
}
);
};
Insert this ajax delete method in your client js file:
$(document).ready(function(){
$('.button__delete').click(function() {
var dataId = $(this).attr('data-id');
if (confirm("are u sure?")) {
$.ajax({
type: 'DELETE',
url: '/',
success: function(response) {
if (response == 'error') {
console.log('Err!');
}
else {
alert('Success');
location.reload();
}
}
});
} else {
alert('Canceled!');
}
});
});
Array elements in Java are initialized to default values when created. For numbers this means they are initialized to 0, for references they are null and for booleans they are false.
To fill the array with something else you can use Arrays.fill() or as part of the declaration
int[] a = new int[] {0, 0, 0, 0};
There are no shortcuts in Java to fill arrays with arithmetic series as in some scripting languages.
Just add the name of the table between DELETE
and FROM
from where you want to delete records, because we have to specify the table to delete. Also remove the ORDER BY
clause because there is nothing to order while deleting records.
So your final query should be like this:
DELETE WorkRecord2
FROM WorkRecord2
INNER JOIN Employee
ON EmployeeRun=EmployeeNo
WHERE Company = '1'
AND Date = '2013-05-06';
Easy! The default should be the first option. Done! That would lead you to unobtrusive JavaScript, because JavaScript isn't needed :)
Try the following:
SELECT DISTINCT(ip), name, COUNT(name) nameCnt,
time, price, SUM(price) priceSum
FROM tablename
WHERE time >= $yesterday AND time <$today
GROUP BY ip, name
Giphy Gotcha
After following the 2 requirements listed above (must end in .gif
and using the image syntax), if you are having trouble with a gif from giphy:
Be sure you have the correct giphy url! You can't just add .gif
to the end of this one and have it work.
If you just copy the url from a browser, you will get something like:
https://giphy.com/gifs/gol-automaton-game-of-life-QfsvYoBSSpfbtFJIVo
You need to instead click on "Copy Link" and then grab the "GIF Link" specifically. Notice the correct one points to media.giphy.com
instead of just giphy.com
:
use this connection string :
Server=HARIHARAN-PC\SQLEXPRESS;Intial Catalog=persons;Integrated Security=True;
rename person with your database name
The way i do it is:
var obj = new Object();
obj.name = "Raj";
obj.age = 32;
obj.married = false;
var jsonString= JSON.stringify(obj);
I guess this way can reduce chances for errors.
I would suggest you try this jQuery plugin print element
It can let you just print the element you selected.
put export { Home };
at the end of the Home.js file
To UrlEncode without using System.Web:
String s = System.Net.WebUtility.UrlEncode(str);
//fix some different between WebUtility.UrlEncode and HttpUtility.UrlEncode
s = Regex.Replace(s, "(%[0-9A-F]{2})", c => c.Value.ToLowerInvariant());
more details: https://www.samnoble.co.uk/2014/05/21/beware-webutility-urlencode-vs-httputility-urlencode/
Check out DateTime.Compare method
docker-compose down
If VPN is connected, then disconnect it and try again to up docker container:
docker-compose up -d container_name
try this, this gonna work, I have tried this and this works.
<!DOCTYPE html>
<html>
<body>
<form action="#">
<select required>
<option value="">None</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
</body>
</html>
This can also be due to the build check box not being ticked for the current platform project in the build configuration. Click Build | Configuration manager, then make sure the test projects have a tick in the build column for the platform that you're using (for example 'x86').
This was definitely the solution that worked for me.
If you look at the documentation you can take just the properties you're interested in from the window
object i.e.
protocol + '//' + hostname + pathname
You can try jstorage javascript plugin, it is an elegant way to maintain sessions check this http://www.jstorage.info/
include the jStorage.js script into your html
<script src="jStorage.js"></script>
Then in your javascript place the sessiontoken into the a key like this
$.jStorage.set("YOUR_KEY",session_id);
Where "YOUR_KEY" is the key using which you can access you session_id , like this:
var id = $.jStorage.get("YOUR_KEY");
You can also use remove to remove a value by index as well.
n = [1, 3, 5]
n.remove(n[1])
n would then refer to [1, 5]
Do you want an incrementing integer column returned with your recordset? If so: -
--Check for existance
if exists (select * from dbo.sysobjects where [id] = object_id(N'dbo.t') AND objectproperty(id, N'IsUserTable') = 1)
drop table dbo.t
go
--create dummy table and insert data
create table dbo.t(x char(1) not null primary key, y char(1) not null)
go
set nocount on
insert dbo.t (x,y) values ('A','B')
insert dbo.t (x,y) values ('C','D')
insert dbo.t (x,y) values ('E','F')
--create temp table to add an identity column
create table dbo.#TempWithIdentity(i int not null identity(1,1) primary key,x char(1) not null unique,y char(1) not null)
--populate the temporary table
insert into dbo.#TempWithIdentity(x,y) select x,y from dbo.t
--return the data
select i,x,y from dbo.#TempWithIdentity
--clean up
drop table dbo.#TempWithIdentity
I had to add [AllowAnonymous] to the ActionResult functions in my login page because the user was not authenticated yet.
With Java 8, you actually can
List<TestB> variable = collectionOfListA
.stream()
.map(e -> (TestB) e)
.collect(Collectors.toList());
I think may be more automatic, grunt task usemin take care to do all this jobs for you, only need some configuration:
I found this implementation very easy to use. Also has a generous BSD-style license:
jsSHA: https://github.com/Caligatio/jsSHA
I needed a quick way to get the hex-string representation of a SHA-256 hash. It only took 3 lines:
var sha256 = new jsSHA('SHA-256', 'TEXT');
sha256.update(some_string_variable_to_hash);
var hash = sha256.getHash("HEX");
I work with artificially created images,i.e. I create them by myself and then train a neural network on them to perform a certain task. So, I created these images, saved them, but when I tried to open them ( with cv2.imread(...)), I got this error.It turned out that when saving artificially created images you need to add dtype=np.uint8. That resolved the issue for me!
select region,sum(number) total
from
(
select region,number
from cash_table
union all
select region,number
from cheque_table
) t
group by region
You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.
Here are a couple of useful helper functions for you, they show the usage of all parameters.
#include <string>
std::string wstrtostr(const std::wstring &wstr)
{
// Convert a Unicode string to an ASCII string
std::string strTo;
char *szTo = new char[wstr.length() + 1];
szTo[wstr.size()] = '\0';
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
strTo = szTo;
delete[] szTo;
return strTo;
}
std::wstring strtowstr(const std::string &str)
{
// Convert an ASCII string to a Unicode String
std::wstring wstrTo;
wchar_t *wszTo = new wchar_t[str.length() + 1];
wszTo[str.size()] = L'\0';
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
wstrTo = wszTo;
delete[] wszTo;
return wstrTo;
}
--
Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.
So you can understand this better:
//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
*pX = 10;
}
int main(int argc, char ** argv)
{
int X;
fillXWith10(&X);
return 0;
}
Rectangle bounds = Screen.GetBounds(Point.Empty);
using(Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using(Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save("test.jpg", ImageFormat.Jpeg);
}
for capturing current window use
Rectangle bounds = this.Bounds;
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(bounds.Left,bounds.Top), Point.Empty, bounds.Size);
}
bitmap.Save("C://test.jpg", ImageFormat.Jpeg);
}
Now, adding view-source:
before the site-address.com works on Chrome - Android.
Source: https://www.quora.com/How-can-I-view-a-webpage-source-code-in-Google-chrome-mobile-version
I faced this issue on chrome before and the cause for it is that there was a div has min-height set to a value. The solution was to reset min-height while printing as follows:
@media print {
.wizard-content{
min-height: 0;
}
}
Updating @tangy answer from above to the current version of scikit-learn: 0.23.2 (StratifiedShuffleSplit documentation).
from sklearn.model_selection import StratifiedShuffleSplit
n_splits = 1 # We only want a single split in this case
sss = StratifiedShuffleSplit(n_splits=n_splits, test_size=0.25, random_state=0)
for train_index, test_index in sss.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
Use null to define something as having no value, use undefined when you expect something might not be defined at all.
For example, if a variable has no value, assign it as null.
var weDontHaveAValue = null;
If you expect that something might be not defined at all, e.g. an optional options argument, use undefined.
if (typeof args.optionalParam !== 'undefined') { }
In my .bash_profile I have :
# No Proxy
function noproxy
{
/usr/local/sbin/noproxy #turn off proxy server
unset http_proxy HTTP_PROXY https_proxy HTTPs_PROXY
}
# Proxy
function setproxy
{
sh /usr/local/sbin/proxyon #turn on proxy server
http_proxy=http://127.0.0.1:8118/
HTTP_PROXY=$http_proxy
https_proxy=$http_proxy
HTTPS_PROXY=$https_proxy
export http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
}
So when I want to disable the proxy, the function(s) run in the login shell and sets the variables as expected and wanted.
While Ben Jackson is correct, I thought I would add how I've been using that solution as well. Below is a very simple script I use (that I call gitadd) to add all changes except a select few that I keep listed in a file called .gittrackignore
(very similar to how .gitignore works).
#!/bin/bash
set -e
git add -A
git reset `cat .gittrackignore`
And this is what my current .gittrackignore
looks like.
project.properties
I'm working on an Android project that I compile from the command line when deploying. This project depends on SherlockActionBar, so it needs to be referenced in project.properties, but that messes with the compilation, so now I just type gitadd
and add all of the changes to git without having to un-add project.properties every single time.
Check out this solution VBA Compact Current Database.
Basically it says this should work
Public Sub CompactDB()
CommandBars("Menu Bar").Controls("Tools").Controls ("Database utilities"). _
Controls("Compact and repair database...").accDoDefaultAction
End Sub
All angular services are singletons:
Docs (see Services as singletons): https://docs.angularjs.org/guide/services
Lastly, it is important to realize that all Angular services are application singletons. This means that there is only one instance of a given service per injector.
Basically the difference between the service and factory is as follows:
app.service('myService', function() {
// service is just a constructor function
// that will be called with 'new'
this.sayHello = function(name) {
return "Hi " + name + "!";
};
});
app.factory('myFactory', function() {
// factory returns an object
// you can run some code before
return {
sayHello : function(name) {
return "Hi " + name + "!";
}
}
});
Check out this presentation about $provide: http://slides.wesalvaro.com/20121113/#/
Those slides were used in one of the AngularJs meetups: http://blog.angularjs.org/2012/11/more-angularjs-meetup-videos.html
Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).
If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel
public class ThisViewModel : ViewModelBase
{
TypeOfAncestorViewModel Parent { get; set; }
}
and bind against that directly instead.
<TextBox Text="{Binding Parent}" />
I don't actually find any of the presented solutions here to be fully complete so I'll add my own. Nothing new here. You can stitch this together from the other presented solutions plus various comments.
There are at least two things you'll have to make sure:
Make sure you pass the table name to the getTables()
method,
rather than passing a null value. In the first case you let the
database server filter the result for you, in the second you request
a list of all tables from the server and then filter the list
locally. The former is much faster if you are only searching for a
single table.
Make sure to check the table name from the resultset with an equals
match. The reason is that the getTables()
does pattern matching on
the query for the table and the _
character is a wildcard in SQL.
Suppose you are checking for the existence of a table named
EMPLOYEE_SALARY
. You'll then get a match on EMPLOYEESSALARY
too
which is not what you want.
Ohh, and do remember to close those resultsets. Since Java 7 you would want to use a try-with-resources statement for that.
Here's a complete solution:
public static boolean tableExist(Connection conn, String tableName) throws SQLException {
boolean tExists = false;
try (ResultSet rs = conn.getMetaData().getTables(null, null, tableName, null)) {
while (rs.next()) {
String tName = rs.getString("TABLE_NAME");
if (tName != null && tName.equals(tableName)) {
tExists = true;
break;
}
}
}
return tExists;
}
You may want to consider what you pass as the types
parameter (4th parameter) on your getTables()
call. Normally I would just leave at null
because you don't want to restrict yourself. A VIEW is as good as a TABLE, right? These days many databases allow you to update through a VIEW so restricting yourself to only TABLE type is in most cases not the way to go. YMMV.
For Swift 5:
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return nil }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return nil
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
Then, whenever you want to put HTML text in a UITextView use:
textView.attributedText = htmlText.htmlToAttributedString
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
from here
There's a great example here:
https://kb.novaordis.com/index.php/Gradle_Pass_Configuration_on_Command_Line
Which details that you can pass parameters and then provide a default in an ext variable like so:
gradle -Dmy_app.color=blue
and then reference in Gradle as:
ext {
color = System.getProperty("my_app.color", "red");
}
And then anywhere in your build script you can reference it as course anywhere you can reference it as project.ext.color
More tips here: https://kb.novaordis.com/index.php/Gradle_Variables_and_Properties
This may sound dumb, but it may be a fresh, or damaged install, so is the JDK installed? If not, go to the download site and download the latest version of Java JRE. Like I said, this may sound dumb, but it solved my problem.
http://www.oracle.com/technetwork/java/javase/downloads/index.html
I don't know if this will be helpful for someone, but I had the same problem.
I wrote pip install xlrd
in the anaconda prompt while in the specific environment and it said it was installed, but when I looked at the installed packages it wasn't there.
What solved the problem was "moving" (I don't know the terminology for it) into the Scripts
folder of the specific environment and do the pip install xlrd
there.
Hope this is useful for someone :D
You must ensure the URL contains embed rather watch as the /embed
endpoint allows outside requests, whereas the /watch
endpoint does not.
<iframe width="420" height="315" src="https://www.youtube.com/embed/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>
I am using PuTTY and the vi editor. If I select five lines using my mouse and I want to delete those lines, how can I do that?
Forget the mouse. To remove 5 lines, either:
Also, how can I select the lines using my keyboard as I can in Windows where I press Shift and move the arrows to select the text? How can I do that in vi?
As I said, either use Shift-v to enter linewise selection mode or v to enter characterwise selection mode or Ctrl-v to enter blockwise selection mode. Then move with h, j, k and l.
I suggest spending some time with the Vim Tutor (run vimtutor
) to get more familiar with Vim in a very didactic way.
It seems to me you have not called srand first. Usage example here.
List<int>[] a = new List<int>[100];
You still would have to allocate each individual list in the array before you can use it though:
for (int i = 0; i < a.Length; i++)
a[i] = new List<int>();
Have you tried using the .command
filename extension?
I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:
function utf8_to_latin2($str)
{
return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
{
mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
"From: $form\r\n".
"Reply-To: $reply\r\n".
"X-Mailer: PHP/" . phpversion());
}
I have made another mailer function, because apple device could not read well the previous version.
function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
$s= "=?utf-8?b?".base64_encode($s)."?=";
$headers = "MIME-Version: 1.0\r\n";
$headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
$headers.= "Content-Type: text/plain;charset=utf-8\r\n";
$headers.= "Reply-To: $reply\r\n";
$headers.= "X-Mailer: PHP/" . phpversion();
mail($to, $s, $body, $headers);
}
You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;
package main
import (
"fmt"
"encoding/json"
)
type Data struct {
Votes *Votes `json:"votes"`
Count string `json:"count,omitempty"`
}
type Votes struct {
OptionA string `json:"option_A"`
}
func main() {
s := `{ "votes": { "option_A": "3" } }`
data := &Data{
Votes: &Votes{},
}
err := json.Unmarshal([]byte(s), data)
fmt.Println(err)
fmt.Println(data.Votes)
s2, _ := json.Marshal(data)
fmt.Println(string(s2))
data.Count = "2"
s3, _ := json.Marshal(data)
fmt.Println(string(s3))
}
https://play.golang.org/p/ScuxESTW5i
Based on your most recent comment you could address that by using an interface{}
to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{}
which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.
Following, in my opinion will solve the problem
a. As per what David German suggested. However this only applicable for the particular projects you are in b. Add in "~/Desktop/Python_Tutorials/diveintopython/py" into a new PythonPath under Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter --> Libraries subtab --> NewFolder
Hope it helps.
Exclusive ranges do have some benefits:
For one thing each item in range(0,n)
is a valid index for lists of length n
.
Also range(0,n)
has a length of n
, not n+1
which an inclusive range would.
The problem is that jQuery doesn't trigger the native click
event for <a>
elements so that navigation doesn't happen (the normal behavior of an <a>
), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).
To trigger it manually, try:
var a = $("<a>")
.attr("href", "http://i.stack.imgur.com/L8rHf.png")
.attr("download", "img.png")
.appendTo("body");
a[0].click();
a.remove();
DEMO: http://jsfiddle.net/HTggQ/
Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
I was getting this error by saving an object to the shared preferences as a gson converted string. The gson String was no good, so retrieving and deserializing the object was not actually working correctly. This meant any subsequent accesses to the object resulted in this error. Scary :)
It should usually work using the method Dave described in his answer. (I can confirm seeing "TextFX Characters" in the Available tab in Plugin Manager.)
If it does not, you can try downloading the zip file from here and put its contents (it's one file called NppTextFX.dll
) inside the plugins
folder where Notepad++ is installed. I suggest doing this while Notepad++ itself is not running.
At a minimum, change this:
function BlockID() {
var IDs = new Array();
images['s'] = "Images/Block_01.png";
images['g'] = "Images/Block_02.png";
images['C'] = "Images/Block_03.png";
images['d'] = "Images/Block_04.png";
return IDs;
}
To this:
function BlockID() {
var IDs = new Object();
IDs['s'] = "Images/Block_01.png";
IDs['g'] = "Images/Block_02.png";
IDs['C'] = "Images/Block_03.png";
IDs['d'] = "Images/Block_04.png";
return IDs;
}
There are a couple fixes to point out. First, images
is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images
to IDs
. Second, you want to return an Object
, not an Array
. An object can be assigned property values akin to an associative array or hash -- an array cannot. So we change the declaration of var IDs = new Array();
to var IDs = new Object();
.
After those changes your code will run fine, but it can be simplified further. You can use shorthand notation (i.e., object literal property value shorthand) to create the object and return it immediately:
function BlockID() {
return {
"s":"Images/Block_01.png"
,"g":"Images/Block_02.png"
,"C":"Images/Block_03.png"
,"d":"Images/Block_04.png"
};
}
You just declared a jagged array. Such kind of arrays can have different sizes for all dimensions. For example:
string[][] jaggedStrings = {
new string[] {"x","y","z"},
new string[] {"x","y"},
new string[] {"x"}
};
In your case you need regular array. See answers above. More about jagged arrays
In force layouts simply setting the 'height' and 'width' attributes will not work to re-center/move the plot into the svg container. However, there's a very simple answer that works for Force Layouts found here. In summary:
Use same (any) eventing you like.
window.on('resize', resize);
Then assuming you have svg & force variables:
var svg = /* D3 Code */;
var force = /* D3 Code */;
function resize(e){
// get width/height with container selector (body also works)
// or use other method of calculating desired values
var width = $('#myselector').width();
var height = $('#myselector').height();
// set attrs and 'resume' force
svg.attr('width', width);
svg.attr('height', height);
force.size([width, height]).resume();
}
In this way, you don't re-render the graph entirely, we set the attributes and d3 re-calculates things as necessary. This at least works when you use a point of gravity. I'm not sure if that's a prerequisite for this solution. Can anyone confirm or deny ?
Cheers, g
NumPy 1.8 introduced np.full()
, which is a more direct method than empty()
followed by fill()
for creating an array filled with a certain value:
>>> np.full((3, 5), 7)
array([[ 7., 7., 7., 7., 7.],
[ 7., 7., 7., 7., 7.],
[ 7., 7., 7., 7., 7.]])
>>> np.full((3, 5), 7, dtype=int)
array([[7, 7, 7, 7, 7],
[7, 7, 7, 7, 7],
[7, 7, 7, 7, 7]])
This is arguably the way of creating an array filled with certain values, because it explicitly describes what is being achieved (and it can in principle be very efficient since it performs a very specific task).
To answer your specific example:
// your example
Location.X = Cursor.Position.X;
Location.Y = Cursor.Position.Y;
// sample code
Console.WriteLine("x: " + Cursor.Position.X + " y: " + Cursor.Position.Y);
Don't forget to add using System.Windows.Forms;
, and adding the reference to it (right click on references > add reference > .NET tab > Systems.Windows.Forms > ok)
Take a look at the @Deprecated
annotation.
Try this
$.cookie('_cookieName', null, { path: '/' });
The { path: '/' } do the job for you
Here is the JSfiddle Demo
I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order
so you can check if it's greater than zero:
<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p>
function verifyorder() {
var order = document.getElementById('value').value;
if (+order > 0) {
alert(+order);
return true;
}
else {
alert("Sorry, you need to enter a positive integer value, try again");
document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
}
}
Are you trying to pass the command line arguments to the program AS you launch it? I am working on something right now that does exactly this, and it was a lot simpler than I thought. If I go into the command line, and type
C:\folder\app.exe/xC:\folder\file.txt
then my application launches, and creates a file in the specified directory with the specified name.
I wanted to do this through a Powershell script on a remote machine, and figured out that all I needed to do was put
$s = New-PSSession -computername NAME -credential LOGIN
Invoke-Command -session $s -scriptblock {C:\folder\app.exe /xC:\folder\file.txt}
Remove-PSSession $s
(I have a bunch more similar commands inside the session, this is just the minimum it requires to run) notice the space between the executable, and the command line arguments. It works for me, but I am not sure exactly how your application works, or if that is even how you pass arguments to it.
*I can also have my application push the file back to my own local computer by changing the script-block to
C:\folder\app.exe /x"\\LocalPC\DATA (C)\localfolder\localfile.txt"
You need the quotes if your file-path has a space in it.
EDIT: actually, this brought up some silly problems with Powershell launching the application as a service or something, so I did some searching, and figured out that you can call CMD to execute commands for you on the remote computer. This way, the command is carried out EXACTLY as if you had just typed it into a CMD window on the remote machine. Put the command in the scriptblock into double quotes, and then put a cmd.exe /C before it. like this:
cmd.exe /C "C:\folder\app.exe/xC:\folder\file.txt"
this solved all of the problems that I have been having recently.
EDIT EDIT: Had more problems, and found a much better way to do it.
start-process -filepath C:\folder\app.exe -argumentlist "/xC:\folder\file.txt"
and this doesn't hang up your terminal window waiting for the remote process to end. Just make sure you have a way to terminate the process if it doesn't do that on it's own. (mine doesn't, required the coding of another argument)
I like Dave Everitt's answer with the « line-height » but it only works by specifying the « height » and then we have to add « !important » to line-height ...
.cercle {
font-size: 2em;
width: 2em;
height: 2em;
text-align: center;
line-height: 2em!important;
background: #666;
color: #fff;
border-radius: 2em;
}
type in Windows cmd.exe
cd %userprofile%\.android
dir
copy adbkey.pub adb_keys
dir
copy the file adb_keys to your phone folder /data/misc/adb. Reboot the phone. RSA Key is now authorized.
from: How to solve ADB device unauthorized in Android ADB host device?
now follow the instructions for adb connect, or use any app for preparing. i prefer ADB over WIFI Widget from Mehdy Bohlool, it works without root.
Well, you can do css tables instead of html tables. This keeps your html semantically correct, but allows you to use tables for layout purposes.
This seems to make more sense than using float hacks.
<html>
<head>
<style>
#content-wrapper{
display:table;
}
#content{
display:table-row;
}
#content>div{
display:table-cell
}
/*adding some extras for demo purposes*/
#content-wrapper{
width:100%;
height:100%;
top:0px;
left:0px;
position:absolute;
}
#nav{
width:100px;
background:yellow;
}
#body{
background:blue;
}
</style>
</head>
<body>
<div id="content-wrapper">
<div id="content">
<div id="nav">
Left hand content
</div>
<div id="body">
Right hand content
</div>
</div>
</div>
</body>
</html>
You can avoid event bubbling by checking target of event.
For example if you have input nested to the div element where you have handler for click event, and you don't want to handle it, when input is clicked, you can just pass event.target
into your handler and check is handler should be executed based on properties of target.
For example you can check if (target.localName === "input") { return}
.
So, it's a way to "avoid" handler execution
Not really - the background image is bounded by the element it's applied to, and the overflow properties only apply to the content (i.e. markup) within an element.
You can add another div into your footer div and apply the background image to that, though, and have that overflow instead.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/foobar/i$ index.php [NE,L]