Based on Wakas Bukhary answer, you could make it async by puting the last line in the response scope.
$('#myform').submit(function(event) {
event.preventDefault(); //this will prevent the default submit
var _this = $(this); //store form so it can be accessed later
$.ajax('GET', 'url').then(function(resp) {
// your code here
_this.unbind('submit').submit(); // continue the submit unbind preventDefault
})
}
Use the DataGridView.ReadOnly
property
The code in the MSDN example illustrates the use of this property in a DataGridView
control intended primarily for display. In this example, the visual appearance of the control is customized in several ways and the control is configured for limited interactivity.
Observe these settings in the sample code:
// Set property values appropriate for read-only
// display and limited interactivity
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.DisableResizing;
use this code below as progress.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dip" />
<gradient
android:startColor="#ff9d9e9d"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:angle="270"
/>
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
</layer-list>
where:
after that use it in the layout containing the xml:
<SeekBar
android:id="@+id/myseekbar"
...
android:progressDrawable="@drawable/progress"
/>
you can also customize the thumb by using a custom icon seek_thumb.png:
android:thumb="@drawable/seek_thumb"
For Swift 2.0
Instead of implementing the methods that are required to draw the CollectionViewCells
:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
return CGSizeMake(50, 50);
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets
{
return UIEdgeInsetsMake(5, 5, 5, 5); //top,left,bottom,right
}
Use UICollectionViewFlowLayout
func createCollectionView() {
let flowLayout = UICollectionViewFlowLayout()
// Now setup the flowLayout required for drawing the cells
let space = 5.0 as CGFloat
// Set view cell size
flowLayout.itemSize = CGSizeMake(50, 50)
// Set left and right margins
flowLayout.minimumInteritemSpacing = space
// Set top and bottom margins
flowLayout.minimumLineSpacing = space
// Finally create the CollectionView
let collectionView = UICollectionView(frame: CGRectMake(10, 10, 300, 400), collectionViewLayout: flowLayout)
// Then setup delegates, background color etc.
collectionView?.dataSource = self
collectionView?.delegate = self
collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
collectionView?.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView!)
}
Then implement the UICollectionViewDataSource
methods as required:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20;
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell:UICollectionViewCell=collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as UICollectionViewCell;
cell.backgroundColor = UIColor.greenColor();
return cell;
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
Try this,
ArrayList<Double> numb= new ArrayList<Double>(Arrays.asList(1.38, 2.56, 4.3));
SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data
WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.
SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON
This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.
With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.
It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.
Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.
REST is over only HTTP
Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.
P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284
Maybe it's a little outdated, but since this is the first hit when you google cmake clean
, I will add this:
Since you can start a build in the build dir with a specified target with
cmake --build . --target xyz
you can of course run
cmake --build . --target clean
to run the clean
target in the generated build files.
Just wrap floated elements in a <div>
and give it this CSS:
.wrapper {
display: table;
margin: auto;
}
Use the following code below inside updatepanel.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args){
if (args.get_error() != undefined){
args.set_errorHandled(true);
}
}
</script>
This should work in SQL Server:
update ud
set assid = sale.assid
from sale
where sale.udid = id
Attach a String() string
method to any named type and enjoy any custom "ToString" functionality:
package main
import "fmt"
type bin int
func (b bin) String() string {
return fmt.Sprintf("%b", b)
}
func main() {
fmt.Println(bin(42))
}
Playground: http://play.golang.org/p/Azql7_pDAA
Output
101010
You can see that JSONObject extends a HashMap
, so you can simply use it as a HashMap:
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
for (Map.Entry in jsonChildOBject.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
As Hemerson Varela already said in Php 7.1 count(null)
will throw an error
and hasOne
returns null
if no row exists. Since you have a hasOne
relation I would use the empty
method to check:
$model = RepairItem::find($id);
if (!empty($temp = $request->input('option'))) {
$option = $model->option;
if(empty($option)){
$option = $model->option()->create();
}
$option->someAttribute = temp;
$option->save();
};
But this is superfluous. There is no need to check if the relation exists, to determine if you should do an update
or a create
call. Simply use the updateOrCreate method. This is equivalent to the above:
$model = RepairItem::find($id);
if (!empty($temp = $request->input('option'))) {
$model->option()
->updateOrCreate(['repair_item_id' => $model->id],
['option' => $temp]);
}
On Mac, head -n -1 wont work. And, I was trying to find a simple solution [ without worrying about processing time ] to solve this problem only using "head" and/or "tail" commands.
I tried the following sequence of commands and was happy that I could solve it just using "tail" command [ with the options available on Mac ]. So, if you are on Mac, and want to use only "tail" to solve this problem, you can use this command :
cat file.txt | tail -r | tail -n +2 | tail -r
1> tail -r : simply reverses the order of lines in its input
2> tail -n +2 : this prints all the lines starting from the second line in its input
This is an old thread but CSS3 has a solution.
position: sticky;
Have a look at this blog post.
Demonstration:
Instead of simply setting the font size to 16px, you can:
scale()
CSS transform and negative margins to shrink the input field down to the correct size.For example, suppose your input field is originally styled with:
input[type="text"] {
border-radius: 5px;
font-size: 12px;
line-height: 20px;
padding: 5px;
width: 100%;
}
If you enlarge the field by increasing all dimensions by 16 / 12 = 133.33%, then reduce using scale()
by 12 / 16 = 75%, the input field will have the correct visual size (and font size), and there will be no zoom on focus.
As scale()
only affects the visual size, you will also need to add negative margins to reduce the field's logical size.
With this CSS:
input[type="text"] {
/* enlarge by 16/12 = 133.33% */
border-radius: 6.666666667px;
font-size: 16px;
line-height: 26.666666667px;
padding: 6.666666667px;
width: 133.333333333%;
/* scale down by 12/16 = 75% */
transform: scale(0.75);
transform-origin: left top;
/* remove extra white space */
margin-bottom: -10px;
margin-right: -33.333333333%;
}
the input field will have a logical font size of 16px while appearing to have 12px text.
I have a blog post where I go into slightly more detail, and have this example as viewable HTML:
No input zoom in Safari on iPhone, the pixel perfect way
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
Here's a simple solution that uses TextView itself with a TextChangedListened added to it:
expressionView = (TextView) findViewById(R.id.expressionView);
expressionView.addTextChangedListener(textAutoResizeWatcher(expressionView, 25, 55));
private TextWatcher textAutoResizeWatcher(final TextView view, final int MIN_SP, final int MAX_SP) {
return new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override
public void afterTextChanged(Editable editable) {
final int widthLimitPixels = view.getWidth() - view.getPaddingRight() - view.getPaddingLeft();
Paint paint = new Paint();
float fontSizeSP = pixelsToSp(view.getTextSize());
paint.setTextSize(spToPixels(fontSizeSP));
String viewText = view.getText().toString();
float widthPixels = paint.measureText(viewText);
// Increase font size if necessary.
if (widthPixels < widthLimitPixels){
while (widthPixels < widthLimitPixels && fontSizeSP <= MAX_SP){
++fontSizeSP;
paint.setTextSize(spToPixels(fontSizeSP));
widthPixels = paint.measureText(viewText);
}
--fontSizeSP;
}
// Decrease font size if necessary.
else {
while (widthPixels > widthLimitPixels || fontSizeSP > MAX_SP) {
if (fontSizeSP < MIN_SP) {
fontSizeSP = MIN_SP;
break;
}
--fontSizeSP;
paint.setTextSize(spToPixels(fontSizeSP));
widthPixels = paint.measureText(viewText);
}
}
view.setTextSize(fontSizeSP);
}
};
}
private float pixelsToSp(float px) {
float scaledDensity = getResources().getDisplayMetrics().scaledDensity;
return px/scaledDensity;
}
private float spToPixels(float sp) {
float scaledDensity = getResources().getDisplayMetrics().scaledDensity;
return sp * scaledDensity;
}
This approach will increase or decrease the font size as needed to fit the text, respecting the MIN_SP and MAX_SP bounds received as parameters.
another easy way using re will be
import re, clr
text = 'some string... this part will be removed.'
text= re.search(r'(\A.*)\.\.\..+',url,re.DOTALL|re.IGNORECASE).group(1)
// text = some string
In bootstrap tooltip just use data-html="true"
To summarize, you can calculate the height of a label by using its string and calling boundingRectWithSize
. You must provide the font
as an attribute, and include .usesLineFragmentOrigin
for multi-line labels.
let labelWidth = label.frame.width
let maxLabelSize = CGSize(width: labelWidth, height: CGFloat.greatestFiniteMagnitude)
let actualLabelSize = label.text!.boundingRect(with: maxLabelSize, options: [.usesLineFragmentOrigin], attributes: [.font: label.font], context: nil)
let labelHeight = actualLabelSize.height(withWidth:labelWidth)
Some extensions to do just that:
extension UILabel {
func textHeight(withWidth width: CGFloat) -> CGFloat {
guard let text = text else {
return 0
}
return text.height(withWidth: width, font: font)
}
func attributedTextHeight(withWidth width: CGFloat) -> CGFloat {
guard let attributedText = attributedText else {
return 0
}
return attributedText.height(withWidth: width)
}
}
extension String {
func height(withWidth width: CGFloat, font: UIFont) -> CGFloat {
let maxSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let actualSize = self.boundingRect(with: maxSize, options: [.usesLineFragmentOrigin], attributes: [.font : font], context: nil)
return actualSize.height
}
}
extension NSAttributedString {
func height(withWidth width: CGFloat) -> CGFloat {
let maxSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let actualSize = boundingRect(with: maxSize, options: [.usesLineFragmentOrigin], context: nil)
return actualSize.height
}
}
UILabel+Utility.h
#import <UIKit/UIKit.h>
@interface UILabel (Utility)
- (CGFloat)textHeightForWidth:(CGFloat)width;
- (CGFloat)attributedTextHeightForWidth:(CGFloat)width;
@end
UILabel+Utility.m
@implementation NSString (Utility)
- (CGFloat)heightForWidth:(CGFloat)width font:(UIFont *)font {
CGSize maxSize = CGSizeMake(width, CGFLOAT_MAX);
CGSize actualSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil].size;
return actualSize.height;
}
@end
@implementation NSAttributedString (Utility)
- (CGFloat)heightForWidth:(CGFloat)width {
CGSize maxSize = CGSizeMake(width, CGFLOAT_MAX);
CGSize actualSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
return actualSize.height;
}
@end
@implementation UILabel (Utility)
- (CGFloat)textHeightForWidth:(CGFloat)width {
return [self.text heightForWidth:width font:self.font];
}
- (CGFloat)attributedTextHeightForWidth:(CGFloat)width {
return [self.attributedText heightForWidth:width];
}
@end
The following works in Firefox interestingly enough if I remove the write line it doesn't work. Anyone have any insight why the write line is needed.
<script type="text/javascript">
document.write(".");
document.body.style.MozUserSelect='none';
</script>
Ran in to this problem a while ago. Website couldn't access video file on local PC due to security settings (understandable really) ONLY way I could get around it was to run a webserver on the local PC (server2Go) and all references to the video file from the web were to the localhost/video.mp4
<div id="videoDiv">
<video id="video" src="http://127.0.0.1:4001/videos/<?php $videoFileName?>" width="70%" controls>
</div>
<!--End videoDiv-->
Not an ideal solution but worked for me.
Keep'em short: Optimizing Storage of Small Objects, SERVER-863. Silly but true.
I guess pretty much the same rules that apply to relation databases should apply here. And after so many decades there is still no agreement whether RDBMS tables should be named singular or plural...
MongoDB speaks JavaScript, so utilize JS naming conventions of camelCase.
MongoDB official documentation mentions you may use underscores, also built-in identifier is named _id
(but this may be be to indicate that _id
is intended to be private, internal, never displayed or edited.
This will test if strings are made up of some combination or digits, the dollar sign, and a commas. Is that what you're looking for?
import re s1 = 'Testing string' s2 = '1234,12345$' regex = re.compile('[0-9,$]+$') if ( regex.match(s1) ): print "s1 matched" else: print "s1 didn't match" if ( regex.match(s2) ): print "s2 matched" else: print "s2 didn't match"
I think it's worth putting a few timings up here for some perspective.
All timings done on OS-X 10.5.8 with python2.7
John Clement's answer:
python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop
David Wolever's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop
OP's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop
Note that I'm purposefully putting the smallest item last in the list to make .index
as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.
Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).
Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIEFILE => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',
/**
* Or set header
* CURLOPT_HTTPHEADER => [
'Cookie: foo=bar;baz=foo',
]
*/
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo $response;
The dot itself is not an operator, .^
is.
The .^
is a pointwise¹ (i.e. element-wise) power, as .*
is the pointwise product.
.^
Array power.A.^B
is the matrix with elementsA(i,j)
to theB(i,j)
power. The sizes ofA
andB
must be the same or be compatible.
C.f.
¹) Hence the dot.
OK I found the problem, I was checking in the wrong place which is for the whole IDE's look and feel at File->Settings->Appearance
The correct place to change the editor appearance is through File->Settings->Editor->Colors &Fonts
and then choose the scheme there. The imported settings appear there :)
Note: The theme site seems to have moved.
If you facing an issue related to pre-receive hook declined in git while doing Push. You may have the below reasons:
You can resolve this issue by the below steps:
Some of the comments mention this as well, but asp net core does all this work for you.
If you have a query string that matches the name it will be available in the controller.
https://myapi/some-endpoint/123?someQueryString=YayThisWorks
[HttpPost]
[Route("some-endpoint/{someValue}")]
public IActionResult SomeEndpointMethod(int someValue, string someQueryString)
{
Debug.WriteLine(someValue);
Debug.WriteLine(someQueryString);
return Ok();
}
Ouputs:
123
YayThisWorks
var newElementsAppended = $(newHtml).appendTo("#myDiv");
newElementsAppended.effects("highlight", {}, 2000);
none of these methods worked for me, so I just solved this with CSS:
.upvotes:before {
content:"";
float: left;
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
max_allowed_packet
is set in mysql config, not on php side
[mysqld]
max_allowed_packet=16M
You can see it's curent value in mysql like this:
SHOW VARIABLES LIKE 'max_allowed_packet';
You can try to change it like this, but it's unlikely this will work on shared hosting:
SET GLOBAL max_allowed_packet=16777216;
You can read about it here http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html
EDIT
The [mysqld] is necessary to make the max_allowed_packet
working since at least mysql version 5.5.
Recently setup an instance on AWS EC2 with Drupal and Solr Search Engine, which required 32M max_allowed_packet
. It you set the value under [mysqld_safe]
(which is default settings came with the mysql installation) mode in /etc/my.cnf, it did no work. I did not dig into the problem. But after I change it to [mysqld]
and restarted the mysqld, it worked.
It's declared inside a closure, which means it can only be accessed there. If you want a variable accessible globally, you can remove the var
:
$(function(){
value = "10";
});
value; // "10"
This is equivalent to writing window.value = "10";
.
How to use an IF statement in the MySQL "select list":
select if (1>2, 2, 3); //returns 3
select if(1<2,'yes','no'); //returns yes
SELECT IF(STRCMP('test','test1'),'no','yes'); //returns no
How to use an IF statement in the MySQL where clause search condition list:
create table penguins (id int primary key auto_increment, name varchar(100))
insert into penguins (name) values ('rico')
insert into penguins (name) values ('kowalski')
insert into penguins (name) values ('skipper')
select * from penguins where 3 = id
-->3 skipper
select * from penguins where (if (true, 2, 3)) = id
-->2 kowalski
How to use an IF statement in the MySQL "having clause search conditions":
select * from penguins
where 1=1
having (if (true, 2, 3)) = id
-->1 rico
Use an IF statement with a column used in the select list to make a decision:
select (if (id = 2, -1, 1)) item
from penguins
where 1=1
--> 1
--> -1
--> 1
If statements embedded in SQL queries is a bad "code smell". Bad code has high "WTF's per minute" during code review. This is one of those things. If I see this in production with your name on it, I'm going to automatically not like you.
Simplistically, in UNIX, you have the concept of processes and programs. A process is an environment in which a program executes.
The simple idea behind the UNIX "execution model" is that there are two operations you can do.
The first is to fork()
, which creates a brand new process containing a duplicate (mostly) of the current program, including its state. There are a few differences between the two processes which allow them to figure out which is the parent and which is the child.
The second is to exec()
, which replaces the program in the current process with a brand new program.
From those two simple operations, the entire UNIX execution model can be constructed.
To add some more detail to the above:
The use of fork()
and exec()
exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.
The fork()
call makes a near duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations, but the idea is to create as close a copy as possible). Only one process calls fork()
but two processes return from that call - sounds bizarre but it's really quite elegant
The new process (called the child) gets a different process ID (PID) and has the PID of the old process (the parent) as its parent PID (PPID).
Because the two processes are now running exactly the same code, they need to be able to tell which is which - the return code of fork()
provides this information - the child gets 0, the parent gets the PID of the child (if the fork()
fails, no child is created and the parent gets an error code).
That way, the parent knows the PID of the child and can communicate with it, kill it, wait for it and so on (the child can always find its parent process with a call to getppid()
).
The exec()
call replaces the entire current contents of the process with a new program. It loads the program into the current process space and runs it from the entry point.
So, fork()
and exec()
are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find
- the shell forks, then the child loads the find
program into memory, setting up all command line arguments, standard I/O and so forth.
But they're not required to be used together. It's perfectly acceptable for a program to call fork()
without a following exec()
if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions).
This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork a copy of themselves to process a specific request while the parent goes back to listening. For this situation, the program contains both the parent and the child code.
Similarly, programs that know they're finished and just want to run another program don't need to fork()
, exec()
and then wait()/waitpid()
for the child. They can just load the child directly into their current process space with exec()
.
Some UNIX implementations have an optimized fork()
which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork()
until the program attempts to change something in that space. This is useful for those programs using only fork()
and not exec()
in that they don't have to copy an entire process space. Under Linux, fork()
only makes a copy of the page tables and a new task structure, exec()
will do the grunt work of "separating" the memory of the two processes.
If the exec
is called following fork
(and this is what happens mostly), that causes a write to the process space and it is then copied for the child process, before modifications are allowed.
Linux also has a vfork()
, even more optimised, which shares just about everything between the two processes. Because of that, there are certain restrictions in what the child can do, and the parent halts until the child calls exec()
or _exit()
.
The parent has to be stopped (and the child is not permitted to return from the current function) since the two processes even share the same stack. This is slightly more efficient for the classic use case of fork()
followed immediately by exec()
.
Note that there is a whole family of exec
calls (execl
, execle
, execve
and so on) but exec
in context here means any of them.
The following diagram illustrates the typical fork/exec
operation where the bash
shell is used to list a directory with the ls
command:
+--------+
| pid=7 |
| ppid=4 |
| bash |
+--------+
|
| calls fork
V
+--------+ +--------+
| pid=7 | forks | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash | | bash |
+--------+ +--------+
| |
| waits for pid 22 | calls exec to run ls
| V
| +--------+
| | pid=22 |
| | ppid=7 |
| | ls |
V +--------+
+--------+ |
| pid=7 | | exits
| ppid=4 | <---------------+
| bash |
+--------+
|
| continues
V
To return a resolved promise, you can use:
return $q.defer().resolve();
If you need to resolve something or return data:
return $q.defer().resolve(function(){
var data;
return data;
});
import data from './data.json';
export class AppComponent {
json:any = data;
}
See this article for more details.
use str
try:
some_method()
except Exception as e:
s = str(e)
Also, most exception classes will have an args
attribute. Often, args[0]
will be an error message.
It should be noted that just using str
will return an empty string if there's no error message whereas using repr
as pyfunc recommends will at least display the class of the exception. My take is that if you're printing it out, it's for an end user that doesn't care what the class is and just wants an error message.
It really depends on the class of exception that you are dealing with and how it is instantiated. Did you have something in particular in mind?
I have faced similar problem, using the same post and and this link I have resolved my issue.
var http = new XMLHttpRequest();
var url = "MY_URL.Com/login.aspx";
var params = 'eid=' +userEmailId+'&pwd='+userPwd
http.open("POST", url, true);
// Send the proper header information along with the request
//http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length"
//http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection"
// Call a function when the state
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
This link has completed information.
Assuming that your Sheet1
is not necessary active you would need to use this improved code of yours:
i = ActiveWorkbook.Worksheets("Sheet1").Range("A2" , Worksheets("Sheet1").Range("A2").End(xlDown)).Rows.Count
Look into full worksheet reference for second argument for Range(arg1, arg2)
which important in this situation.
There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.
Step 1:
The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session
variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:
var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));
The above code should only be run once and only if you are not already storing an array in your localStorage session
variable. If you are already doing this skip to step 2.
Step 2:
Modify your function like so:
function SaveDataToLocalStorage(data)
{
var a = [];
// Parse the serialized data back into an aray of objects
a = JSON.parse(localStorage.getItem('session')) || [];
// Push the new data (whether it be an object or anything else) onto the array
a.push(data);
// Alert the array value
alert(a); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
localStorage.setItem('session', JSON.stringify(a));
}
This should take care of the rest for you. When you parse it out, it will become an array of objects.
Hope this helps.
const FPS = 30;
let lastTimestamp = 0;
function update(timestamp) {
requestAnimationFrame(update);
if (timestamp - lastTimestamp < 1000 / FPS) return;
/* <<< PUT YOUR CODE HERE >>> */
lastTimestamp = timestamp;
}
update();
There are two ways to do this. One is to use form validation to never let any number over 50 be entered by a user. Form validation docs.
If there is no user involved in the process, or you're not using a form to enter data, then you'll have to override the model's save
method to throw an exception or limit the data going into the field.
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
To be honest I don't know that you can. If you just set up a test instance and open Excel twice, because that is what you are talking about happening, if you name one workbook "test1" and another "test2" if you try to move a workbook, or even a worksheet between the two applications they are totally unaware of each other. I also notice odd behavior while simply manually cutting and pasting from Excel instance 1 and Excel instance 2.
You may have to write two macros kind of a drop off and then a pick up from a location that you share between them. Maybe a command button on the tool bar.
Maybe one of the super excel guys on here have a better answer.
The problem I think is that the view is still the activity, not the fragment. The fragments doesn't have any independent view of its own and is attached to the parent activities view. Thats why the event ends up in the Activity, not the fragment. Its unfortunate, but I think you will need some code to make this work.
What I've been doing during conversions is simply adding a click listener that calls the old event handler.
for instance:
final Button loginButton = (Button) view.findViewById(R.id.loginButton);
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
onLoginClicked(v);
}
});
Here is what I find works
form name
Use a default select option
, for example...
<option value="-1" selected>Please Select</option>
So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.
This input
<input type="submit">
should be
<input name="Submit" type="submit" value="Submit">
whenever I use a form that fails, it is a failure due to the difference in calling the button name submit
and name as Submit
.
You should also set your enctype attribute for your form as forms fail on my web host if it's not set.
In case when X derives from Y you can also use ToList<T>
method instead of Cast<T>
listOfX.ToList<Y>()
It seems arbitrary to me because I don't know how you would get the number as any type, but what about checking Abs(number) != number? Maybe && number != 0
Updated answer
Here is how to change the box model used by the input/textarea/select elements so that they all behave the same way. You need to use the box-sizing
property which is implemented with a prefix for each browser
-ms-box-sizing:content-box;
-moz-box-sizing:content-box;
-webkit-box-sizing:content-box;
box-sizing:content-box;
This means that the 2px difference we mentioned earlier does not exist..
example at http://www.jsfiddle.net/gaby/WaxTS/5/
note: On IE it works from version 8 and upwards..
Original
if you reset their borders then the select
element will always be 2 pixels less than the input
elements..
I have achieved this with following
Edit > Blank Operations > Remove Unnecessary Blank and EOL
you could always create a new list which is a result of adding two lists.
>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]
Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.
I found I had the same error. I was compiling a code with both lapack and blas. When I switched the order that the two libraries were called the error went away.
"LAPACK_LIB = -llapack -lblas" worked where "LAPACK_LIB = -lblas -llapack" gave the error described above.
You can turn an array into a stream by using Arrays.stream()
:
int[] ns = new int[] {1,2,3,4,5};
Arrays.stream(ns);
Once you've got your stream, you can use any of the methods described in the documentation, like sum()
or whatever. You can map
or filter
like in Python by calling the relevant stream methods with a Lambda function:
Arrays.stream(ns).map(n -> n * 2);
Arrays.stream(ns).filter(n -> n % 4 == 0);
Once you're done modifying your stream, you then call toArray()
to convert it back into an array to use elsewhere:
int[] ns = new int[] {1,2,3,4,5};
int[] ms = Arrays.stream(ns).map(n -> n * 2).filter(n -> n % 4 == 0).toArray();
I guess the most effective way to find duplicates in a list is:
from collections import Counter
def duplicates(values):
dups = Counter(values) - Counter(set(values))
return list(dups.keys())
print(duplicates([1,2,3,6,5,2]))
It uses Counter
once on all the elements, and then on all unique elements. Subtracting the first one with the second will leave out the duplicates only.
you should try this
~/Views/Shared/parts/UMFview.ascx
place the ~/Views/
before your code
Here a simple solution with only java.*
and javax.crypto.*
dependencies for encryption of bytes providing confidentiality and integrity. It shall be indistinguishable under a choosen plaintext attack for short messages in the order of kilobytes.
It uses AES
in the GCM
mode with no padding, a 128bit key is derived by PBKDF2
with lots of iterations and a static salt from the provided password. This makes sure brute forcing passwords is hard and distributes the entropy over the entire key.
A random initialisation vector (IV) is generated and will be prepended to the ciphertext. Furthermore, the static byte 0x01
is prepended as the first byte as a 'version'.
The entire message goes into the message authentication code (MAC) generated by AES/GCM
.
Here it goes, zero external dependencies encryption class providing confidentiality and integrity:
package ch.n1b.tcrypt.utils;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
* This class implements AES-GCM symmetric key encryption with a PBKDF2 derived password.
* It provides confidentiality and integrity of the plaintext.
*
* @author Thomas Richner
* @created 2018-12-07
*/
public class AesGcmCryptor {
// https://crypto.stackexchange.com/questions/26783/ciphertext-and-tag-size-and-iv-transmission-with-aes-in-gcm-mode
private static final byte VERSION_BYTE = 0x01;
private static final int VERSION_BYTE_LENGTH = 1;
private static final int AES_KEY_BITS_LENGTH = 128;
// fixed AES-GCM constants
private static final String GCM_CRYPTO_NAME = "AES/GCM/NoPadding";
private static final int GCM_IV_BYTES_LENGTH = 12;
private static final int GCM_TAG_BYTES_LENGTH = 16;
// can be tweaked, more iterations = more compute intensive to brute-force password
private static final int PBKDF2_ITERATIONS = 1024;
// protects against rainbow tables
private static final byte[] PBKDF2_SALT = hexStringToByteArray("4d3fe0d71d2abd2828e7a3196ea450d4");
public String encryptString(char[] password, String plaintext) throws CryptoException {
byte[] encrypted = null;
try {
encrypted = encrypt(password, plaintext.getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException //
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException //
| InvalidKeySpecException e) {
throw new CryptoException(e);
}
return byteArrayToHexString(encrypted);
}
public String decryptString(char[] password, String ciphertext)
throws CryptoException {
byte[] ct = hexStringToByteArray(ciphertext);
byte[] plaintext = null;
try {
plaintext = decrypt(password, ct);
} catch (AEADBadTagException e) {
throw new CryptoException(e);
} catch ( //
NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeySpecException //
| InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException //
| BadPaddingException e) {
throw new CryptoException(e);
}
return new String(plaintext, StandardCharsets.UTF_8);
}
/**
* Decrypts an AES-GCM encrypted ciphertext and is
* the reverse operation of {@link AesGcmCryptor#encrypt(char[], byte[])}
*
* @param password passphrase for decryption
* @param ciphertext encrypted bytes
* @return plaintext bytes
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeySpecException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws IllegalArgumentException if the length or format of the ciphertext is bad
* @throws CryptoException
*/
public byte[] decrypt(char[] password, byte[] ciphertext)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException,
InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
// input validation
if (ciphertext == null) {
throw new IllegalArgumentException("ciphertext cannot be null");
}
if (ciphertext.length <= VERSION_BYTE_LENGTH + GCM_IV_BYTES_LENGTH + GCM_TAG_BYTES_LENGTH) {
throw new IllegalArgumentException("ciphertext too short");
}
// the version must match, we don't decrypt other versions
if (ciphertext[0] != VERSION_BYTE) {
throw new IllegalArgumentException("wrong version: " + ciphertext[0]);
}
// input seems legit, lets decrypt and check integrity
// derive key from password
SecretKey key = deriveAesKey(password, PBKDF2_SALT, AES_KEY_BITS_LENGTH);
// init cipher
Cipher cipher = Cipher.getInstance(GCM_CRYPTO_NAME);
GCMParameterSpec params = new GCMParameterSpec(GCM_TAG_BYTES_LENGTH * 8,
ciphertext,
VERSION_BYTE_LENGTH,
GCM_IV_BYTES_LENGTH
);
cipher.init(Cipher.DECRYPT_MODE, key, params);
final int ciphertextOffset = VERSION_BYTE_LENGTH + GCM_IV_BYTES_LENGTH;
// add version and IV to MAC
cipher.updateAAD(ciphertext, 0, ciphertextOffset);
// decipher and check MAC
return cipher.doFinal(ciphertext, ciphertextOffset, ciphertext.length - ciphertextOffset);
}
/**
* Encrypts a plaintext with a password.
* <p>
* The encryption provides the following security properties:
* Confidentiality + Integrity
* <p>
* This is achieved my using the AES-GCM AEAD blockmode with a randomized IV.
* <p>
* The tag is calculated over the version byte, the IV as well as the ciphertext.
* <p>
* Finally the encrypted bytes have the following structure:
* <pre>
* +-------------------------------------------------------------------+
* | | | | |
* | version | IV bytes | ciphertext bytes | tag |
* | | | | |
* +-------------------------------------------------------------------+
* Length: 1B 12B len(plaintext) bytes 16B
* </pre>
* Note: There is no padding required for AES-GCM, but this also implies that
* the exact plaintext length is revealed.
*
* @param password password to use for encryption
* @param plaintext plaintext to encrypt
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws InvalidKeySpecException
*/
public byte[] encrypt(char[] password, byte[] plaintext)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
InvalidKeySpecException {
// initialise random and generate IV (initialisation vector)
SecretKey key = deriveAesKey(password, PBKDF2_SALT, AES_KEY_BITS_LENGTH);
final byte[] iv = new byte[GCM_IV_BYTES_LENGTH];
SecureRandom random = SecureRandom.getInstanceStrong();
random.nextBytes(iv);
// encrypt
Cipher cipher = Cipher.getInstance(GCM_CRYPTO_NAME);
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_BYTES_LENGTH * 8, iv);
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
// add IV to MAC
final byte[] versionBytes = new byte[]{VERSION_BYTE};
cipher.updateAAD(versionBytes);
cipher.updateAAD(iv);
// encrypt and MAC plaintext
byte[] ciphertext = cipher.doFinal(plaintext);
// prepend VERSION and IV to ciphertext
byte[] encrypted = new byte[1 + GCM_IV_BYTES_LENGTH + ciphertext.length];
int pos = 0;
System.arraycopy(versionBytes, 0, encrypted, 0, VERSION_BYTE_LENGTH);
pos += VERSION_BYTE_LENGTH;
System.arraycopy(iv, 0, encrypted, pos, iv.length);
pos += iv.length;
System.arraycopy(ciphertext, 0, encrypted, pos, ciphertext.length);
return encrypted;
}
/**
* We derive a fixed length AES key with uniform entropy from a provided
* passphrase. This is done with PBKDF2/HMAC256 with a fixed count
* of iterations and a provided salt.
*
* @param password passphrase to derive key from
* @param salt salt for PBKDF2 if possible use a per-key salt, alternatively
* a random constant salt is better than no salt.
* @param keyLen number of key bits to output
* @return a SecretKey for AES derived from a passphrase
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
private SecretKey deriveAesKey(char[] password, byte[] salt, int keyLen)
throws NoSuchAlgorithmException, InvalidKeySpecException {
if (password == null || salt == null || keyLen <= 0) {
throw new IllegalArgumentException();
}
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, keyLen);
SecretKey pbeKey = factory.generateSecret(spec);
return new SecretKeySpec(pbeKey.getEncoded(), "AES");
}
/**
* Helper to convert hex strings to bytes.
* <p>
* May be used to read bytes from constants.
*/
private static byte[] hexStringToByteArray(String s) {
if (s == null) {
throw new IllegalArgumentException("Provided `null` string.");
}
int len = s.length();
if (len % 2 != 0) {
throw new IllegalArgumentException("Invalid length: " + len);
}
byte[] data = new byte[len / 2];
for (int i = 0; i < len - 1; i += 2) {
byte b = (byte) toHexDigit(s, i);
b <<= 4;
b |= toHexDigit(s, i + 1);
data[i / 2] = b;
}
return data;
}
private static int toHexDigit(String s, int pos) {
int d = Character.digit(s.charAt(pos), 16);
if (d < 0) {
throw new IllegalArgumentException("Cannot parse hex digit: " + s + " at " + pos);
}
return d;
}
private static String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
public class CryptoException extends Exception {
public CryptoException(Throwable cause) {
super(cause);
}
}
}
Here the entire project with a nice CLI: https://github.com/trichner/tcrypt
Edit: now with appropriate encryptString
and decryptString
Try this (ES5)
console.log($("#" + d));
ES6
console.log($(`#${d}`));
You need to create a TypeReference
object for each generic type you use and use that for deserialization. For example -
mapper.readValue(jsonString, new TypeReference<Data<String>>() {});
The browser's native JSON API may not give you back your idOld function after you call JSON.stringify, however, if can stringify your JSON yourself (maybe use Crockford's json2.js instead of browser's API), then if you have a string of JSON e.g.
var person_json = "{ \"age:\" : 20, \"isOld:\": false, isOld: function() { return this.age > 60; } }";
then you can call
eval("(" + person + ")")
, and you will get back your function in the json object.
1.Inner Join: Also called as Join. It returns the rows present in both the Left table, and right table only if there is a match. Otherwise, it returns zero records.
Example:
SELECT
e1.emp_name,
e2.emp_salary
FROM emp1 e1
INNER JOIN emp2 e2
ON e1.emp_id = e2.emp_id
2.Full Outer Join: Also called as Full Join. It returns all the rows present in both the Left table, and right table.
Example:
SELECT
e1.emp_name,
e2.emp_salary
FROM emp1 e1
FULL OUTER JOIN emp2 e2
ON e1.emp_id = e2.emp_id
3.Left Outer join: Or simply called as Left Join. It returns all the rows present in the Left table and matching rows from the right table (if any).
4.Right Outer Join: Also called as Right Join. It returns matching rows from the left table (if any), and all the rows present in the Right table.
Advantages of Joins
The way to close resources are context managers, aka the with
statement:
class Foo(object):
def __init__(self):
self.bar = None
def __enter__(self):
if self.bar != 'open':
print 'opening the bar'
self.bar = 'open'
return self # this is bound to the `as` part
def close(self):
if self.bar != 'closed':
print 'closing the bar'
self.bar = 'close'
def __exit__(self, *err):
self.close()
if __name__ == '__main__':
with Foo() as foo:
print foo, foo.bar
output:
opening the bar
<__main__.Foo object at 0x17079d0> open
closing the bar
2) Python's objects get deleted when their reference count is 0. In your example the del foo
removes the last reference so __del__
is called instantly. The GC has no part in this.
class Foo(object):
def __del__(self):
print "deling", self
if __name__ == '__main__':
import gc
gc.disable() # no gc
f = Foo()
print "before"
del f # f gets deleted right away
print "after"
output:
before
deling <__main__.Foo object at 0xc49690>
after
The gc
has nothing to do with deleting your and most other objects. It's there to clean up when simple reference counting does not work, because of self-references or circular references:
class Foo(object):
def __init__(self, other=None):
# make a circular reference
self.link = other
if other is not None:
other.link = self
def __del__(self):
print "deling", self
if __name__ == '__main__':
import gc
gc.disable()
f = Foo(Foo())
print "before"
del f # nothing gets deleted here
print "after"
gc.collect()
print gc.garbage # The GC knows the two Foos are garbage, but won't delete
# them because they have a __del__ method
print "after gc"
# break up the cycle and delete the reference from gc.garbage
del gc.garbage[0].link, gc.garbage[:]
print "done"
output:
before
after
[<__main__.Foo object at 0x22ed8d0>, <__main__.Foo object at 0x22ed950>]
after gc
deling <__main__.Foo object at 0x22ed950>
deling <__main__.Foo object at 0x22ed8d0>
done
3) Lets see:
class Foo(object):
def __init__(self):
raise Exception
def __del__(self):
print "deling", self
if __name__ == '__main__':
f = Foo()
gives:
Traceback (most recent call last):
File "asd.py", line 10, in <module>
f = Foo()
File "asd.py", line 4, in __init__
raise Exception
Exception
deling <__main__.Foo object at 0xa3a910>
Objects are created with __new__
then passed to __init__
as self
. After a exception in __init__
, the object will typically not have a name (ie the f =
part isn't run) so their ref count is 0. This means that the object is deleted normally and __del__
is called.
You can also do:
start notepad "C:\Users\kemp\INSTALL\Text1.txt"
The C:\Users\kemp\Install\
is your PATH. The Text1.txt is the FILE.
This error could be an indication that variable with the same name has been used in your code earlier, but for other purposes. Possibly, a variable has been given a name that coincides with the existing function used later in the code.
If you want an all-purpose local development stack for any operating system where you can choose from different PHP, MySQL and Web server versions and are also not afraid of using Docker, you could go for the devilbox.
The devilbox is a modern and highly customisable dockerized PHP stack supporting full LAMP and MEAN and running on all major platforms. The main goal is to easily switch and combine any version required for local development. It supports an unlimited number of projects for which vhosts and DNS records are created automatically. Email catch-all and popular development tools will be at your service as well. Configuration is not necessary, as everything is pre-setup with mass virtual hosting.
Getting it up and running is pretty straight-forward:
# Get the devilbox
$ git clone https://github.com/cytopia/devilbox
$ cd devilbox
# Create docker-compose environment file
$ cp env-example .env
# Edit your configuration
$ vim .env
# Start all containers
$ docker-compose up
Links:
In SQL Server , cast text as datetime
select cast('5/21/2013 9:45:48' as datetime)
If, for example, x = 5 and is stored as string, you can also just:
x = x + 0
and the new x would be stored as a numeric value.
Please use the below code and let me know
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(c, "root", "MyNewPass");
System.out.println("connection done");
PreparedStatement ps=con.prepareStatement(q);
System.out.println(q);
rs=ps.executeQuery();
System.out.println("done2");
while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.
}
catch (Exception e) {
// TODO: handle exception
System.out.println("Failed");
}
myfolder/welcome.jsp
is the relative path of your jsp
page. So, change it as per your jsp
page path.
Some people, like me, will benefit from using the :focus-within
pseudo-class.
Using it will apply the css you want to a div, for instance.
You can read more here https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within
Easiest way is to use --link, however the newer versions of docker are moving away from that and in fact that switch will be removed soon.
The link below offers a nice how too, on connecting two containers. You can skip the attach portion, since that is just a useful how to on adding items to images.
https://deis.com/blog/2016/connecting-docker-containers-1/
The part you are interested in is the communication between two containers. The easiest way, is to refer to the DB container by name from the webserver container.
Example:
you named the db container db1
and the webserver container web0
. The containers should both be on the bridge network, which means the web container should be able to connect to the DB container by referring to it's name.
So if you have a web config file for your app, then for DB host you will use the name db1
.
if you are using an older version of docker, then you should use --link.
Example:
Step 1: docker run --name db1 oracle/database:12.1.0.2-ee
then when you start the web app. use:
Step 2: docker run --name web0 --link db1 webapp/webapp:3.0
and the web app will be linked to the DB. However, as I said the --link switch will be removed soon.
I'd use docker compose instead, which will build a network for you. However; you will need to download docker compose for your system. https://docs.docker.com/compose/install/#prerequisites
an example setup is like this:
file name is base.yml
version: "2"
services:
webserver:
image: "moodlehq/moodle-php-apache:7.1
depends_on:
- db
volumes:
- "/var/www/html:/var/www/html"
- "/home/some_user/web/apache2_faildumps.conf:/etc/apache2/conf-enabled/apache2_faildumps.conf"
environment:
MOODLE_DOCKER_DBTYPE: pgsql
MOODLE_DOCKER_DBNAME: moodle
MOODLE_DOCKER_DBUSER: moodle
MOODLE_DOCKER_DBPASS: "m@0dl3ing"
HTTP_PROXY: "${HTTP_PROXY}"
HTTPS_PROXY: "${HTTPS_PROXY}"
NO_PROXY: "${NO_PROXY}"
db:
image: postgres:9
environment:
POSTGRES_USER: moodle
POSTGRES_PASSWORD: "m@0dl3ing"
POSTGRES_DB: moodle
HTTP_PROXY: "${HTTP_PROXY}"
HTTPS_PROXY: "${HTTPS_PROXY}"
NO_PROXY: "${NO_PROXY}"
this will name the network a generic name, I can't remember off the top of my head what that name is, unless you use the --name switch.
IE docker-compose --name setup1 up base.yml
NOTE: if you use the --name switch, you will need to use it when ever calling docker compose, so docker-compose --name setup1 down
this is so you can have more then one instance of webserver and db, and in this case, so docker compose knows what instance you want to run commands against; and also so you can have more then one running at once. Great for CI/CD, if you are running test in parallel on the same server.
Docker compose also has the same commands as docker so docker-compose --name setup1 exec webserver do_some_command
best part is, if you want to change db's or something like that for unit test you can include an additional .yml file to the up command and it will overwrite any items with similar names, I think of it as a key=>value replacement.
Example:
db.yml
version: "2"
services:
webserver:
environment:
MOODLE_DOCKER_DBTYPE: oci
MOODLE_DOCKER_DBNAME: XE
db:
image: moodlehq/moodle-db-oracle
Then call docker-compose --name setup1 up base.yml db.yml
This will overwrite the db. with a different setup. When needing to connect to these services from each container, you use the name set under service, in this case, webserver and db.
I think this might actually be a more useful setup in your case. Since you can set all the variables you need in the yml files and just run the command for docker compose when you need them started. So a more start it and forget it setup.
NOTE: I did not use the --port
command, since exposing the ports is not needed for container->container communication. It is needed only if you want the host to connect to the container, or application from outside of the host. If you expose the port, then the port is open to all communication that the host allows. So exposing web on port 80 is the same as starting a webserver on the physical host and will allow outside connections, if the host allows it. Also, if you are wanting to run more then one web app at once, for whatever reason, then exposing port 80 will prevent you from running additional webapps if you try exposing on that port as well. So, for CI/CD it is best to not expose ports at all, and if using docker compose with the --name switch, all containers will be on their own network so they wont collide. So you will pretty much have a container of containers.
UPDATE: After using features further and seeing how others have done it for CICD programs like Jenkins. Network is also a viable solution.
Example:
docker network create test_network
The above command will create a "test_network" which you can attach other containers too. Which is made easy with the --network
switch operator.
Example:
docker run \
--detach \
--name db1 \
--network test_network \
-e MYSQL_ROOT_PASSWORD="${DBPASS}" \
-e MYSQL_DATABASE="${DBNAME}" \
-e MYSQL_USER="${DBUSER}" \
-e MYSQL_PASSWORD="${DBPASS}" \
--tmpfs /var/lib/mysql:rw \
mysql:5
Of course, if you have proxy network settings you should still pass those into the containers using the "-e" or "--env-file" switch statements. So the container can communicate with the internet. Docker says the proxy settings should be absorbed by the container in the newer versions of docker; however, I still pass them in as an act of habit. This is the replacement for the "--link" switch which is going away. Once the containers are attached to the network you created you can still refer to those containers from other containers using the 'name' of the container. Per the example above that would be db1
. You just have to make sure all containers are connected to the same network, and you are good to go.
For a detailed example of using network in a cicd pipeline, you can refer to this link: https://git.in.moodle.com/integration/nightlyscripts/blob/master/runner/master/run.sh
Which is the script that is ran in Jenkins for a huge integration tests for Moodle, but the idea/example can be used anywhere. I hope this helps others.
Here's a solution that doesn't use JS at all. It uses checkboxes instead.
You can hide the checkbox by adding this to your CSS:
.container input{
display: none;
}
And then add some styling to make it look like a button.
Create procedure [dbo].[a]
@examdate varchar(10) ,
@examdate1 varchar(10)
AS
Select tbl.sno,mark,subject1,
Convert(varchar(10),examdate,103) from tbl
where
(Convert(datetime,examdate,103) >= Convert(datetime,@examdate,103)
and (Convert(datetime,examdate,103) <= Convert(datetime,@examdate1,103)))
use css overflow:scroll;
property. you need to specify height and width then you will be able to scroll horizontally and vertically or either one of two scroll by setting overflow-x:auto;
or overflow-y:auto;
Readers should notice that the key= method:
ut.sort(key=lambda x: x.count, reverse=True)
is many times faster than adding rich comparison operators to the objects. I was surprised to read this (page 485 of "Python in a Nutshell"). You can confirm this by running tests on this little program:
#!/usr/bin/env python
import random
class C:
def __init__(self,count):
self.count = count
def __cmp__(self,other):
return cmp(self.count,other.count)
longList = [C(random.random()) for i in xrange(1000000)] #about 6.1 secs
longList2 = longList[:]
longList.sort() #about 52 - 6.1 = 46 secs
longList2.sort(key = lambda c: c.count) #about 9 - 6.1 = 3 secs
My, very minimal, tests show the first sort is more than 10 times slower, but the book says it is only about 5 times slower in general. The reason they say is due to the highly optimizes sort algorithm used in python (timsort).
Still, its very odd that .sort(lambda) is faster than plain old .sort(). I hope they fix that.
There are two ways to implement this:
1.
$date = strtotime(date);
$new_date = date('d-m-Y', $date);
2.
$cls_date = new DateTime($date);
echo $cls_date->format('d-m-Y');
Save sub object first and then call final repository save method.
@PostMapping("/save")
public String save(@ModelAttribute("shortcode") @Valid Shortcode shortcode, BindingResult result) {
Shortcode existingShortcode = shortcodeService.findByShortcode(shortcode.getShortcode());
if (existingShortcode != null) {
result.rejectValue(shortcode.getShortcode(), "This shortode is already created.");
}
if (result.hasErrors()) {
return "redirect:/shortcode/create";
}
**shortcode.setUser(userService.findByUsername(shortcode.getUser().getUsername()));**
shortcodeService.save(shortcode);
return "redirect:/shortcode/create?success";
}
Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.
If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).
If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.
SELECT * FROM [server].[database].[schema].[table]
This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.
docker run -it -name YOUR_NAME IMAGE_ID /bin/bash
$>vi path_to_file
While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).
So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.
If you are not able to upgrade your Python version to 2.7.9, and want to suppress warnings,
you can downgrade your 'requests' version to 2.5.3:
pip install requests==2.5.3
There are some libraries around there:
Commons-BeanUtils: ConvertUtils -> Utility methods for converting String scalar values to objects of the specified Class, String arrays to arrays of the specified Class.
Commons-Lang: ArrayUtils -> Operations on arrays, primitive arrays (like int[]) and primitive wrapper arrays (like Integer[]).
Spring framework: Spring has an excellent support for PropertyEditors, that can also be used to transform Objects to/from Strings.
Dozer: Dozer is a powerful, yet simple Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.
ModelMapper: ModelMapper is an intelligent object mapping framework that automatically maps objects to each other. It uses a convention based approach to map objects while providing a simple refactoring safe API for handling specific use cases.
MapStruct: MapStruct is a compile-time code generator for bean mappings, resulting in fast (no usage of reflection or similar), dependency-less and type-safe mapping code at runtime.
Orika: Orika uses byte code generation to create fast mappers with minimal overhead.
Selma: Compile-time code-generator for mappings
JMapper: Bean mapper generation using Annotation, XML or API (seems dead, last updated 2 years ago)
Smooks: The Smooks JavaBean Cartridge allows you to create and populate Java objects from your message data (i.e. bind data to) (suggested by superfilin in comments). (No longer under active development)
Commons-Convert: Commons-Convert aims to provide a single library dedicated to the task of converting an object of one type to another. The first stage will focus on Object to String and String to Object conversions. (seems dead, last update 2010)
Transmorph: Transmorph is a free java library used to convert a Java object of one type into an object of another type (with another signature, possibly parameterized). (seems dead, last update 2013)
EZMorph: EZMorph is simple java library for transforming an Object to another Object. It supports transformations for primitives and Objects, for multidimensional arrays and transformations with DynaBeans (seems dead, last updated 2008)
Morph: Morph is a Java framework that eases the internal interoperability of an application. As information flows through an application, it undergoes multiple transformations. Morph provides a standard way to implement these transformations. (seems dead, last update 2008)
Lorentz: Lorentz is a generic object-to-object conversion framework. It provides a simple API to convert a Java objects of one type into an object of another type. (seems dead)
OTOM: With OTOM, you can copy any data from any object to any other object. The possibilities are endless. Welcome to "Autumn". (seems dead)
Use the <embed>
element:
<embed src="file.swf" width="854" height="480"></embed>
Although all of the answers above are good, I would like to propose a new method instead of using the symbolic link method in public html directory as proposed BEST in the accepted answer. You need to have access to your server virtual host configurations.
It is about configuring virtual host of your web server directly pointing to the repository directory. In Apache you can do it like:
DocumentRoot /var/www/html/website/your-git-repo
Here is an example of a virtual host file:
<VirtualHost *:443>
ServerName example.com
DocumentRoot /path/to/your-git-repo
...
...
...
...
</VirtualHost>
You'd likely only want to use this if you were coding to some hardware (e.g. a memory mapped device) which had strict requirements for register ordering and alignment.
However, this looks like a pretty blunt tool to achieve that end. A better approach would be to code a mini-driver in assembler and give it a C calling interface rather than fumbling around with this pragma.
With current version of Angular Material (6.4.7) you can use a custom class:
let dialogRef = dialog.open(UserProfileComponent, {
panelClass: 'my-class'
});
Now put your class somewhere global (haven't been able to make this work elsewhere), e.g. in styles.css
:
.my-class .mat-dialog-container{
height: 400px;
width: 600px;
border-radius: 10px;
background: lightcyan;
color: #039be5;
}
Done!
add setOnItemSelectedListener to spinner reference and get the data like that`
mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
selectedSize=adapterView.getItemAtPosition(position).toString();
i got tired of it always detaching so i just use a shell script to build it out for all my modules. i assume all submodules are on master: here is the script:
#!/bin/bash
echo "Good Day Friend, building all submodules while checking out from MASTER branch."
git submodule update
git submodule foreach git checkout master
git submodule foreach git pull origin master
execute it from your parent module
The dash type of a linestyle
is given by the linetype
, which does also select the line color unless you explicitely set an other one with linecolor
.
However, the support for dashed lines depends on the selected terminal:
png
(uses libgd
)pngcairo
, support dashed lines, but it is disables by default. To enable it, use set termoption dashed
, or set terminal pngcairo dashed ...
.linetype
, use the test
command:Running
set terminal pngcairo dashed
set output 'test.png'
test
set output
gives:
whereas, the postscript
terminal shows different dash patterns:
set terminal postscript eps color colortext
set output 'test.eps'
test
set output
Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:
A new dashtype
parameter was introduced:
To get the predefined dash patterns, use e.g.
plot x dashtype 2
You can also specify custom dash patterns like
plot x dashtype (3,5,10,5),\
2*x dashtype '.-_'
The terminal options dashed
and solid
are ignored. By default all lines are solid. To change them to dashed, use e.g.
set for [i=1:8] linetype i dashtype i
The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic
:
To merge one branch into another, such as merging "feature_x" branch into "master" branch:
git checkout master
git merge feature_x
This page is the first result for several search engines when looking for "git merge one branch into another". However, the original question is more specific and special case than the title would suggest.
It is also more complex than both the subject and the search expression. As such, this is a minimal but explanatory answer for the benefit of most visitors.
var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>');
var radio = rad_id.getElementsByTagName("input");
radio[0].checked = true;
//this for javascript in asp.net try this in .aspx page
// if you select other radiobutton increase [0] to [1] or [2] like this
Wrap the modal into a connected container and perform the async operation in here. This way you can reach both the dispatch to trigger actions and the onClose prop too. To reach dispatch
from props, do not pass mapDispatchToProps
function to connect
.
class ModalContainer extends React.Component {
handleDelete = () => {
const { dispatch, onClose } = this.props;
dispatch({type: 'DELETE_POST'});
someAsyncOperation().then(() => {
dispatch({type: 'DELETE_POST_SUCCESS'});
onClose();
})
}
render() {
const { onClose } = this.props;
return <Modal onClose={onClose} onSubmit={this.handleDelete} />
}
}
export default connect(/* no map dispatch to props here! */)(ModalContainer);
The App where the modal is rendered and its visibility state is set:
class App extends React.Component {
state = {
isModalOpen: false
}
handleModalClose = () => this.setState({ isModalOpen: false });
...
render(){
return (
...
<ModalContainer onClose={this.handleModalClose} />
...
)
}
}
Here is a simple javascript only solution
function displayOverlay(text) {
$("<table id='overlay'><tbody><tr><td>" + text + "</td></tr></tbody></table>").css({
"position": "fixed",
"top": 0,
"left": 0,
"width": "100%",
"height": "100%",
"background-color": "rgba(0,0,0,.5)",
"z-index": 10000,
"vertical-align": "middle",
"text-align": "center",
"color": "#fff",
"font-size": "30px",
"font-weight": "bold",
"cursor": "wait"
}).appendTo("body");
}
function removeOverlay() {
$("#overlay").remove();
}
Demo:
http://jsfiddle.net/UziTech/9g0pko97/
Gist:
I am using Oracle SQL Developer,
In this tool, I had to enable DBMS output to view the results printed by dbms_output.put_line
You can find this option in the result pane where other query results are displayed. so, in the result pane, I have 7 tabs. 1st tab named as Results, next one is Script Output and so on. Out of this you can find a tab named as "DBMS Output" select this tab, then the 1st icon (looks like a dialogue icon) is Enable DBMS Output. Click this icon. Then you execute the PL/SQL, then select "DBMS Output tab, you should be able to see the results there.
I have a similar situation but I want a consistent way to be able to use DateTime.Parse from the filename as well, so I went with
DateTime.Now.ToString("s").Replace(":", ".") // <-- 2016-10-25T16.50.35
When I want to parse, I can simply reverse the Replace call. This way I don't have to type in any yymmdd stuff or guess what formats DateTime.Parse allows.
Please never do this in real projects:
document.getElementById("span").innerHTML = "String".fontsize(25);
_x000D_
<span id="span"></span>
_x000D_
SELECT CAST(DATEDIFF(S, '1970-01-01', SYSDATETIME()) AS BIGINT) * 1000
This does not give you full precision, but DATEDIFF(MS...
causes overflow. If seconds are good enough, this should do it.
I might understand the question incorrectly, but if you want to declare an array of a certain shape but with nothing inside, the following might be helpful:
Initialise empty array:
>>> a = np.zeros((0,3)) #or np.empty((0,3)) or np.array([]).reshape(0,3)
>>> a
array([], shape=(0, 3), dtype=float64)
Now you can use this array to append rows of similar shape to it. Remember that a numpy array is immutable, so a new array is created for each iteration:
>>> for i in range(3):
... a = np.vstack([a, [i,i,i]])
...
>>> a
array([[ 0., 0., 0.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
np.vstack and np.hstack is the most common method for combining numpy arrays, but coming from Matlab I prefer np.r_ and np.c_:
Concatenate 1d:
>>> a = np.zeros(0)
>>> for i in range(3):
... a = np.r_[a, [i, i, i]]
...
>>> a
array([ 0., 0., 0., 1., 1., 1., 2., 2., 2.])
Concatenate rows:
>>> a = np.zeros((0,3))
>>> for i in range(3):
... a = np.r_[a, [[i,i,i]]]
...
>>> a
array([[ 0., 0., 0.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
Concatenate columns:
>>> a = np.zeros((3,0))
>>> for i in range(3):
... a = np.c_[a, [[i],[i],[i]]]
...
>>> a
array([[ 0., 1., 2.],
[ 0., 1., 2.],
[ 0., 1., 2.]])
Uri resourceUri = new Uri(@"/cCleaner;component/Images/cleanerblack.png", UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
var brush = new ImageBrush();
brush.ImageSource = temp;
frame8.Background = brush;
Here's an extremely simple answer
yourPlot +
theme(
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black")
)
It's that easy. Source: the end of this article
The code:
public class Test {
public static void main(String args[]) {
String string = args[0];
System.out.println("last character: " +
string.substring(string.length() - 1));
}
}
The output of java Test abcdef
:
last character: f
Here is my approach to extract the decision rules in a form that can be used in directly in sql, so the data can be grouped by node. (Based on the approaches of previous posters.)
The result will be subsequent CASE
clauses that can be copied to an sql statement, ex.
SELECT COALESCE(*CASE WHEN <conditions> THEN > <NodeA>*, > *CASE WHEN
<conditions> THEN <NodeB>*, > ....)NodeName,* > FROM <table or view>
import numpy as np
import pickle
feature_names=.............
features = [feature_names[i] for i in range(len(feature_names))]
clf= pickle.loads(trained_model)
impurity=clf.tree_.impurity
importances = clf.feature_importances_
SqlOut=""
#global Conts
global ContsNode
global Path
#Conts=[]#
ContsNode=[]
Path=[]
global Results
Results=[]
def print_decision_tree(tree, feature_names, offset_unit='' ''):
left = tree.tree_.children_left
right = tree.tree_.children_right
threshold = tree.tree_.threshold
value = tree.tree_.value
if feature_names is None:
features = [''f%d''%i for i in tree.tree_.feature]
else:
features = [feature_names[i] for i in tree.tree_.feature]
def recurse(left, right, threshold, features, node, depth=0,ParentNode=0,IsElse=0):
global Conts
global ContsNode
global Path
global Results
global LeftParents
LeftParents=[]
global RightParents
RightParents=[]
for i in range(len(left)): # This is just to tell you how to create a list.
LeftParents.append(-1)
RightParents.append(-1)
ContsNode.append("")
Path.append("")
for i in range(len(left)): # i is node
if (left[i]==-1 and right[i]==-1):
if LeftParents[i]>=0:
if Path[LeftParents[i]]>" ":
Path[i]=Path[LeftParents[i]]+" AND " +ContsNode[LeftParents[i]]
else:
Path[i]=ContsNode[LeftParents[i]]
if RightParents[i]>=0:
if Path[RightParents[i]]>" ":
Path[i]=Path[RightParents[i]]+" AND not " +ContsNode[RightParents[i]]
else:
Path[i]=" not " +ContsNode[RightParents[i]]
Results.append(" case when " +Path[i]+" then ''" +"{:4d}".format(i)+ " "+"{:2.2f}".format(impurity[i])+" "+Path[i][0:180]+"''")
else:
if LeftParents[i]>=0:
if Path[LeftParents[i]]>" ":
Path[i]=Path[LeftParents[i]]+" AND " +ContsNode[LeftParents[i]]
else:
Path[i]=ContsNode[LeftParents[i]]
if RightParents[i]>=0:
if Path[RightParents[i]]>" ":
Path[i]=Path[RightParents[i]]+" AND not " +ContsNode[RightParents[i]]
else:
Path[i]=" not "+ContsNode[RightParents[i]]
if (left[i]!=-1):
LeftParents[left[i]]=i
if (right[i]!=-1):
RightParents[right[i]]=i
ContsNode[i]= "( "+ features[i] + " <= " + str(threshold[i]) + " ) "
recurse(left, right, threshold, features, 0,0,0,0)
print_decision_tree(clf,features)
SqlOut=""
for i in range(len(Results)):
SqlOut=SqlOut+Results[i]+ " end,"+chr(13)+chr(10)
For all date related functionality, you should consider using Joda Library. Java's date api's are very poorly designed. Joda provides very nice API.
In ASP.Net you can use System.Web.HttpUtility
to safely encode the cookie value before writing to the cookie and convert it back to its original form on reading it out.
// Encode
HttpUtility.UrlEncode(cookieData);
// Decode
HttpUtility.UrlDecode(encodedCookieData);
This will stop ampersands and equals signs spliting a value into a bunch of name/value pairs as it is written to a cookie.
The file may be existing but may have a different path. Try writing the absolute path for the file.
Try os.listdir()
function to check that atleast python sees the file.
Try it like this:
file1 = open(r'Drive:\Dir\recentlyUpdated.yaml')
Safe and memory-saving:
with open("out1.txt", "w") as fw, open("in.txt","r") as fr:
fw.writelines(l for l in fr if "tests/file/myword" in l)
It doesn't create temporary lists (what readline
and []
would do, which is a non-starter if the file is huge), all is done with generator comprehensions, and using with
blocks ensure that the files are closed on exit.
You can use mb_chars
. This respects umlaute:
class String
# Only capitalize first letter of a string
def capitalize_first
self[0] = self[0].mb_chars.upcase
self
end
end
Example:
"ümlaute".capitalize_first
#=> "Ümlaute"
curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.
Something like that:
@Before("execution(* com.yourpackage..*.*(..))")
public void monitor(JoinPoint jp) {
if (jp.getTarget().getClass().isAnnotationPresent(Monitor.class)) {
// perform the monitoring actions
}
}
Note that you must not have any other advice on the same class before this one, because the annotations will be lost after proxying.
Use GitZip online tool. It allows to download a sub-directory of a github repository as a zip file. No git commands needed!
Python
element.get_attribute("attribute name")
Java
element.getAttribute("attribute name")
Ruby
element.attribute("attribute name")
C#
element.GetAttribute("attribute name");
To convert any date, for example utc:
moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()
fscanf
- "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure.
In the case of an input failure before any data could be successfully read, EOF is returned."
So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF
.
You should check for EOF when you call fscanf
, not check the array slot for EOF.
You are asking the wrong question. In databases is not the operator performance that matters, is always the SARGability of the expression, and the coverability of the overall query. Performance of the operator itself is largely irrelevant.
So, how do LIKE
and =
compare in terms of SARGability? LIKE
, when used with an expression that does not start with a constant (eg. when used LIKE '%something'
) is by definition non-SARGabale. But does that make =
or LIKE 'something%'
SARGable? No. As with any question about SQL performance the answer does not lie with the query of the text, but with the schema deployed. These expression may be SARGable if an index exists to satisfy them.
So, truth be told, there are small differences between =
and LIKE
. But asking whether one operator or other operator is 'faster' in SQL is like asking 'What goes faster, a red car or a blue car?'. You should eb asking questions about the engine size and vechicle weight, not about the color... To approach questions about optimizing relational tables, the place to look is your indexes and your expressions in the WHERE clause (and other clauses, but it usually starts with the WHERE).
For me, I just had to type "yes" at the prompt which asks "Are you sure you want to continue connecting (yes/no)?" rather than just pressing Enter.
Hope this will help you. Assumed that login form has: username and password inputs.
if(isset($_POST['username']) && trim($_POST['username']) != "" && isset($_POST['password']) && trim($_POST['password']) != ""){
//login
} else {
//register
}
In Kotlin language you can do it in this way:
val values = arrayOf(
"cat",
"dog",
"chicken"
)
ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
values
).also {
it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = it
}
I know this question is pretty old but just want to share my findings.
My laptop is able to handle program which spawns 25,000
threads and all those threads write some data in MySql database at regular interval of 2 seconds.
I ran this program with 10,000 threads
for 30 minutes continuously
then also my system was stable and I was able to do other normal operations like browsing, opening, closing other programs, etc.
With 25,000 threads
system slows down
but it remains responsive.
With 50,000 threads
system stopped responding
instantly and I had to restart my system manually.
My system details are as follows :
Processor : Intel core 2 duo 2.13 GHz
RAM : 4GB
OS : Windows 7 Home Premium
JDK Version : 1.6
Before running I set jvm argument -Xmx2048m
.
Hope it helps.
At the risk of irritating you;
You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.
Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.
What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.
It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.
In short, it's just unnecessarily conflating the matter when there is no need to.
Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit()
than ini_set()
.
Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)
Set a cookie:
res.cookie('cookie', 'monster')
https://expressjs.com/en/4x/api.html#res.cookie
Read a cookie:
(using cookie-parser middleware)
req.cookies['cookie']
You can still unit test a void method by asserting that it had the appropriate side effect. In your method1
example, your unit test might look something like:
public void checkIfValidElementsWithDollarSign() {
checkIfValidElement("$",19);
assert ErrorFile.errorMessages.contains("There is a dollar sign in the specified parameter");
}
Use:
var x = {
'key': 1
};
if ('key' in x) {
console.log('has');
}
_x000D_
On the command line execute:
php --ini
You will get something like:
Configuration File (php.ini) Path: /etc/php5/cli
Loaded Configuration File: /etc/php5/cli/php.ini
Scan for additional .ini files in: /etc/php5/cli/conf.d
Additional .ini files parsed: /etc/php5/cli/conf.d/curl.ini,
/etc/php5/cli/conf.d/pdo.ini,
/etc/php5/cli/conf.d/pdo_sqlite.ini,
/etc/php5/cli/conf.d/sqlite.ini,
/etc/php5/cli/conf.d/sqlite3.ini,
/etc/php5/cli/conf.d/xdebug.ini,
/etc/php5/cli/conf.d/xsl.ini
That's from my local dev-machine. However, the second line is the interesting one. If there is nothing mentioned, have a look at the first one. That is the path, where PHP looks for the php.ini
.
You can grep the same information using phpinfo()
in a script and call it with a browser. Its mentioned in the first block of the output. php -i
does the same for the command line, but its quite uncomfortable.
I solved is by using android:background instead of app:srcCompact.
This is caused by xmlns:app="http://schemas.android.com/apk/res-auto". As people have suggested above, you could use /lib-auto or /lib/your-package but I got suspicious namespace error when I tried using /lib-auto and unexpected namespace prefix error with /lib/my-package .
This can by be achieved by using space or view.
Space is lightweight but not much flexible.
View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is more customizable, you can add background, draw shapes like space.
Implementing Space :
(Eg: Space For 20 vertical and 10 horizontal density pixels)
<Space
android:layout_width="10dp"
android:layout_height="20dp"/>
Implementing View :
(Eg: View For 20 vertical and 10 horizontal density pixels including a background color)
<View
android:layout_width="10dp"
android:layout_height="20dp"
android:background="@color/bg_color"/>
Space for string formatting using HTML entity:
 
for non-breakable whitespace.
 
for regular space.
Connect to the server as "system" using SID. Execute this query:
select value from v$parameter where name like '%service_name%';
It worked for me.
If you use underscore.js then these type of null and undefined check are hidden by the library.
So your code will look like this -
var currentData = new Array();
if (_.isEmpty(currentData)) return false;
Ti.API.info("is exists " + currentData[index]);
return true;
It looks much more readable now.
I was having same issue in IE9. I followed the above answer and I added the line:
<meta http-equiv="X-UA-Compatible" content="IE=8;FF=3;OtherUA=4" />
in my <head>
and it worked.
@bdiamante's answer may only partially help you. If you still get a message after you've suppressed warnings, it's because the pandas
library itself is printing the message. There's not much you can do about it unless you edit the Pandas source code yourself. Maybe there's an option internally to suppress them, or a way to override things, but I couldn't find one.
Suppose that you want to ensure a clean working environment. At the top of your script, you put pd.reset_option('all')
. With Pandas 0.23.4, you get the following:
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning: html.bord
er has been deprecated, use display.html.border instead
(currently both are identical)
warnings.warn(d.msg, FutureWarning)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning:
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
warnings.warn(d.msg, FutureWarning)
>>>
Following the @bdiamante's advice, you use the warnings
library. Now, true to it's word, the warnings have been removed. However, several pesky messages remain:
>>> import warnings
>>> warnings.simplefilter(action='ignore', category=FutureWarning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
>>>
In fact, disabling all warnings produces the same output:
>>> import warnings
>>> warnings.simplefilter(action='ignore', category=Warning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
>>>
In the standard library sense, these aren't true warnings. Pandas implements its own warnings system. Running grep -rn
on the warning messages shows that the pandas
warning system is implemented in core/config_init.py
:
$ grep -rn "html.border has been deprecated"
core/config_init.py:207:html.border has been deprecated, use display.html.border instead
Further chasing shows that I don't have time for this. And you probably don't either. Hopefully this saves you from falling down the rabbit hole or perhaps inspires someone to figure out how to truly suppress these messages!
You need to select the entire column where you have the dates, so click the "text to columns" button, and select delimited > uncheck all the boxes and go until you click the button finish.
This will make the cell format and then the values will be readed as date.
Hope it will helped.
You might have to move the mouse to any particular location after context click() like this -
Actions action = new Actions(driver);
actions.contextClick(link).moveByOffset(x,y).click().build().perform();
To understand how moveByOffset(x,y) works look here;
I hope this works. You will have to calculate the offset values for x and y;
best way would be to find the size of each option button after right clicking and then if you click on the 2nd option .
x = width of option button/2
y = 2*(size of each option button)
Ran into the same issue and researched this for a few minutes.
I was taught to use Windows 3.1 and DOS, remember those days? Shortly after I worked with Macintosh computers strictly for some time, then began to sway back to Windows after buying a x64-bit machine.
There are actual reasons behind these changes (some would say historical significance), that are necessary for programmers to continue their work.
Most of the changes are mentioned above:
Program Files
vs Program Files (x86)
In the beginning the 16/86bit files were written on, '86' Intel processors.
System32
really means System64
(on 64-bit Windows)
When developers first started working with Windows7, there were several compatibility issues where other applications where stored.
SysWOW64
really means SysWOW32
Essentially, in plain english, it means 'Windows on Windows within a 64-bit machine'. Each folder is indicating where the DLLs are located for applications it they wish to use them.
Here are two links with all the basic info you need:
Hope this clears things up!
Yep ! I finally Find it.
implement following code on your button click event, to pop up action sheet as given in the image of question.
UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:@"How many?"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
if(IsDateSelected==YES)
{
theDatePicker.datePickerMode = UIDatePickerModeDate;
theDatePicker.maximumDate=[NSDate date];
}else {
theDatePicker.datePickerMode = UIDatePickerModeTime;
}
self.dtpicker = theDatePicker;
[theDatePicker release];
[dtpicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerDateToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)];
[barItems addObject:doneBtn];
[pickerDateToolbar setItems:barItems animated:YES];
[aac addSubview:pickerDateToolbar];
[aac addSubview:dtpicker];
[aac showInView:self.view];
[aac setBounds:CGRectMake(0,0,320, 464)];
Maybe you could try
List<Article> findAllByPublicationDate(Date publicationDate);
The detail could be checked in this article:
Try this solution. I have used databinding for binding view. You can use common "findViewById()" function.
public class ActCPExpense extends BaseActivity implements View.OnClickListener, {
private static final String TAG = ActCPExpense.class.getSimpleName();
private Context mContext;
private ActCpLossBinding mBinding;
private ViewPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.act_cp_loss);
mBinding = DataBindingUtil.setContentView(this, R.layout.act_cp_loss);
mContext = ActCPExpense.this;
initViewsAct();
} catch (Exception e) {
LogUtils.LOGE(TAG, e);
}
}
private void initViewsAct() {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(FragmentCPPayee.newInstance(), "Title");
mBinding.viewpager.setAdapter(adapter);
mBinding.tab.setViewPager(mBinding.viewpager);
}
@Override
public boolean onOptionsItemSelected(MenuItem itemActUtility) {
int i = itemActUtility.getItemId();
if (i == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(itemActUtility);
}
@Override
public void onClick(View view) {
super.onClick(view);
int id = view.getId();
if (id == R.id.btnAdd) {
addFragment();
} else if (id == R.id.btnDelete) {
removeFragment();
}
}
private void addFragment(){
adapter.addFragment(FragmentCPPayee.newInstance("Title");
adapter.notifyDataSetChanged();
mBinding.tab.setViewPager(mBinding.viewpager);
}
private void removeFragment(){
adapter.removeItem(mBinding.viewpager.getCurrentItem());
mBinding.tab.setViewPager(mBinding.viewpager);
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public int getItemPosition(@NonNull Object object) {
return PagerAdapter.POSITION_NONE;
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void removeItem(int pos) {
destroyItem(null, pos, mFragmentList.get(pos));
mFragmentList.remove(pos);
mFragmentTitleList.remove(pos);
adapter.notifyDataSetChanged();
mBinding.viewpager.setCurrentItem(pos - 1, false);
}
@Override
public CharSequence getPageTitle(int position) {
return "Title " + String.valueOf(position + 1);
}
}
}
Yes the restOfTheUrl
is not returning only required value but we can get the value by using UriTemplate
matching.
I have solved the problem, so here the working solution for the problem:
@RequestMapping("/{id}/**")
public void foo(@PathVariable("id") int id, HttpServletRequest request) {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
/*We can use UriTemplate to map the restOfTheUrl*/
UriTemplate template = new UriTemplate("/{id}/{value}");
boolean isTemplateMatched = template.matches(restOfTheUrl);
if(isTemplateMatched) {
Map<String, String> matchTemplate = new HashMap<String, String>();
matchTemplate = template.match(restOfTheUrl);
String value = matchTemplate.get("value");
/*variable `value` will contain the required detail.*/
}
}
One big difference is that Enumeration
s come with support for instantiating them from some name
String. For example:
object Currency extends Enumeration {
val GBP = Value("GBP")
val EUR = Value("EUR") //etc.
}
Then you can do:
val ccy = Currency.withName("EUR")
This is useful when wishing to persist enumerations (for example, to a database) or create them from data residing in files. However, I find in general that enumerations are a bit clumsy in Scala and have the feel of an awkward add-on, so I now tend to use case object
s. A case object
is more flexible than an enum:
sealed trait Currency { def name: String }
case object EUR extends Currency { val name = "EUR" } //etc.
case class UnknownCurrency(name: String) extends Currency
So now I have the advantage of...
trade.ccy match {
case EUR =>
case UnknownCurrency(code) =>
}
As @chaotic3quilibrium pointed out (with some corrections to ease reading):
Regarding "UnknownCurrency(code)" pattern, there are other ways to handle not finding a currency code string than "breaking" the closed set nature of the
Currency
type.UnknownCurrency
being of typeCurrency
can now sneak into other parts of an API.It's advisable to push that case outside
Enumeration
and make the client deal with anOption[Currency]
type that would clearly indicate there is really a matching problem and "encourage" the user of the API to sort it out him/herself.
To follow up on the other answers here, the main drawbacks of case object
s over Enumeration
s are:
Can't iterate over all instances of the "enumeration". This is certainly the case, but I've found it extremely rare in practice that this is required.
Can't instantiate easily from persisted value. This is also true but, except in the case of huge enumerations (for example, all currencies), this doesn't present a huge overhead.
Sometimes the Maven command line is sufficient when scripting something related to the project version, e.g. for artifact retrieval via URL from a repository:
mvn help:evaluate -Dexpression=project.version -q -DforceStdout
Usage example:
VERSION=$( mvn help:evaluate -Dexpression=project.version -q -DforceStdout )
ARTIFACT_ID=$( mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout )
GROUP_ID_URL=$( mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout | sed -e 's#\.#/#g' )
curl -f -S -O http://REPO-URL/mvn-repos/${GROUP_ID_URL}/${ARTIFACT_ID}/${VERSION}/${ARTIFACT_ID}-${VERSION}.jar
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
Try this:
v=spf1 ip4:abc.de.fgh.ij ip4:klm.no.pqr.st ~all
This means the Xcode you are using is not compatible with the iOS version on the device. (You have updated iOS on the device, but have not updated Xcode.)
Open the App Store app and update Xcode.
If there aren't any updates - go here and download the latest version (not beta) of Xcode.
Any algorithm/library that supports a preset dictionary, e.g. zlib.
This way you can prime the compressor with the same kind of text that is likely to appear in the input. If the files are similar in some way (e.g. all URLs, all C programs, all StackOverflow posts, all ASCII-art drawings) then certain substrings will appear in most or all of the input files.
Every compression algorithm will save space if the same substring is repeated multiple times in one input file (e.g. "the" in English text or "int" in C code.)
But in the case of URLs certain strings (e.g. "http://www.", ".com", ".html", ".aspx" will typically appear once in each input file. So you need to share them between files somehow rather than having one compressed occurrence per file. Placing them in a preset dictionary will achieve this.
Something that is not relevant for the OP, but maybe for someone else in the future:
For pixels (px
), if the value is "0", the unit can be omitted: right: 0
and right: 0px
both work.
However I noticed that in Firefox and Chrome this is not the case for the seconds unit (s
). While transition: right 1s ease 0s
works, transition: right 1s ease 0
(missing unit s
for last value transition-delay
) does not (it does work in Edge however).
In the following example, you'll see that right
works for both 0px
and 0
, but transition
only works for 0s
and it doesn't work with 0
.
#box {_x000D_
border: 1px solid black;_x000D_
height: 240px;_x000D_
width: 260px;_x000D_
margin: 50px;_x000D_
position: relative;_x000D_
}_x000D_
.jump {_x000D_
position: absolute;_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
color: white;_x000D_
padding: 5px;_x000D_
}_x000D_
#jump1 {_x000D_
background-color: maroon;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
transition: right 1s ease 0s;_x000D_
}_x000D_
#jump2 {_x000D_
background-color: green;_x000D_
top: 60px;_x000D_
right: 0;_x000D_
transition: right 1s ease 0s;_x000D_
}_x000D_
#jump3 {_x000D_
background-color: blue;_x000D_
top: 120px;_x000D_
right: 0px;_x000D_
transition: right 1s ease 0;_x000D_
}_x000D_
#jump4 {_x000D_
background-color: gray;_x000D_
top: 180px;_x000D_
right: 0;_x000D_
transition: right 1s ease 0;_x000D_
}_x000D_
#box:hover .jump {_x000D_
right: 50px;_x000D_
}
_x000D_
<div id="box">_x000D_
<div class="jump" id="jump1">right: 0px<br>transition: right 1s ease 0s</div>_x000D_
<div class="jump" id="jump2">right: 0<br>transition: right 1s ease 0s</div>_x000D_
<div class="jump" id="jump3">right: 0px<br>transition: right 1s ease 0</div>_x000D_
<div class="jump" id="jump4">right: 0<br>transition: right 1s ease 0</div>_x000D_
</div>
_x000D_
It opens a popup to select the fields for which getter/setter methods to be generated. Select the fields and click on "Generate" button.
Using @Adrian tips, I found a solution:
I'm using GROUP BY and COUNT. I tried to use DISTINCT with ORDER BY but I'm getting error message: "not a SELECTed expression"
select id from
(
SELECT id FROM a -- returns 1,4,2,3
UNION ALL -- changed to ALL
SELECT id FROM b -- returns 2,1
)
GROUP BY id ORDER BY count(id);
Thanks Adrian and this blog.
@jing: "The DirectoryInfo solution is much faster then this (especially for network path)"
I cant confirm this. It seems as if Directory.GetFiles triggers a filesystem or network cache. The first request takes a while, but the following requests are much faster, even if new files were added. In my test I did a Directory.getfiles and a info.GetFiles with the same patterns and both run equally
GetFiles done 437834 in00:00:20.4812480
process files done 437834 in00:00:00.9300573
GetFiles by Dirinfo(2) done 437834 in00:00:20.7412646
I reworked the example you provided in the js fiddle : http://jsfiddle.net/zravs3hp/
I renamed your container
div to overlay
, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.
The resulting html is :
<div class="overlay">
<div id="loading-img"></div>
</div>
<div class="content">
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
<button id="button">Submit</button>
</div>
The css of the overlay is the following
.overlay {
background: #e9e9e9; <- I left your 'gray' background
display: none; <- Not displayed by default
position: absolute; <- This and the following properties will
top: 0; make the overlay, the element will expand
right: 0; so as to cover the whole body of the page
bottom: 0;
left: 0;
opacity: 0.5;
}
I added some dummy text so as to have something to overlay.
Then, in the click
handler we just need to show the overlay :
$("#button").click(function () {
$(".overlay").show();
});
TASK:
Let's consider the following example:
if (!answer.isSuccessful()) {
result = "wrong"
} else {
result = answer.body().string()
}
return result
We need the following equivalent in Kotlin:
return ( !answer.isSuccessful() )
?
"wrong":
answer.body().string()
SOLUTION 1.a. You can use if-expression
in Kotlin:
return if (!answer.isSuccessful()) "wrong" else answer.body().string()
SOLUTION 1.b. It can be much better if you flip this if-expression
(let's do it without not
):
return if (answer.isSuccessful()) answer.body().string() else "wrong"
SOLUTION 2. Kotlin’s Elvis operator ?:
can do a job even better:
return answer.body()?.string() ?: "wrong"
SOLUTION 3. Or use an Extension function
for the corresponding Answer
class:
fun Answer.bodyOrNull(): Body? = if (isSuccessful()) body() else null
SOLUTION 4. Using the Extension function
you can reduce a code thanks to Elvis operator
:
return answer.bodyOrNull()?.string() ?: "wrong"
SOLUTION 5. Or just use when
operator:
when (!answer.isSuccessful()) {
parseInt(str) -> result = "wrong"
else -> result = answer.body().string()
}
Update: Note that this answer is pretty ineffective now. The Garbage Collector acts aggressively on SoftReference and WeakReference, so this code is NOT suitable for new apps. (Instead, try libraries like Universal Image Loader suggested in other answers.)
Thanks to James for the code, and Bao-Long for the suggestion of using SoftReference. I implemented the SoftReference changes on James' code. Unfortunately SoftReferences caused my images to be garbage collected too quickly. In my case it was fine without the SoftReference stuff, because my list size is limited and my images are small.
There's a discussion from a year ago regarding the SoftReferences on google groups: link to thread. As a solution to the too-early garbage collection, they suggest the possibility of manually setting the VM heap size using dalvik.system.VMRuntime.setMinimumHeapSize(), which is not very attractive to me.
public DrawableManager() {
drawableMap = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable fetchDrawable(String urlString) {
SoftReference<Drawable> drawableRef = drawableMap.get(urlString);
if (drawableRef != null) {
Drawable drawable = drawableRef.get();
if (drawable != null)
return drawable;
// Reference has expired so remove the key from drawableMap
drawableMap.remove(urlString);
}
if (Constants.LOGGING) Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawableRef = new SoftReference<Drawable>(drawable);
drawableMap.put(urlString, drawableRef);
if (Constants.LOGGING) Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", "
+ drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
+ drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
return drawableRef.get();
} catch (MalformedURLException e) {
if (Constants.LOGGING) Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
return null;
} catch (IOException e) {
if (Constants.LOGGING) Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
return null;
}
}
public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
SoftReference<Drawable> drawableRef = drawableMap.get(urlString);
if (drawableRef != null) {
Drawable drawable = drawableRef.get();
if (drawable != null) {
imageView.setImageDrawable(drawableRef.get());
return;
}
// Reference has expired so remove the key from drawableMap
drawableMap.remove(urlString);
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
imageView.setImageDrawable((Drawable) message.obj);
}
};
Thread thread = new Thread() {
@Override
public void run() {
//TODO : set imageView to a "pending" image
Drawable drawable = fetchDrawable(urlString);
Message message = handler.obtainMessage(1, drawable);
handler.sendMessage(message);
}
};
thread.start();
}
There is one more hint that not in this conversation. for asp.net core 3.1 first add the key that you need to put it in the header, something like this:
Response.Headers.Add("your-key-to-use-it-axios", "your-value");
where you define the cors policy (normaly is in Startup.cs
) you should add this key to WithExposedHeaders like this.
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.WithExposedHeaders("your-key-to-use-it-axios"));
});
}
you can add all the keys here. now in your client side you can easily access to the your-key-to-use-it-axios by using the response result.
localStorage.setItem("your-key", response.headers["your-key-to-use-it-axios"]);
you can after use it in all the client side by accessing to it like this:
const jwt = localStorage.getItem("your-key")
Use fmod()
from <cmath>
. If you do not want to include the C header file:
template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
return !mod ? x : x - mod * static_cast<long long>(x / mod);
}
//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);
ntext
will always store its data in a separate database page, while nvarchar(max)
will try to store the data within the database record itself.
So nvarchar(max)
is somewhat faster (if you have text that is smaller as 8 kB). I also noticed that the database size will grow slightly slower, this is also good.
Go nvarchar(max)
.
$url = 'http://legis.senado.leg.br/dadosabertos/materia/tramitando';
$xml = file_get_contents("xml->{$url}");
$xml = simplexml_load_file($url);
@Frode F. gave the right answer.
By the Way Invoke-WebRequest
also prints you the 200 OK
and a lot of bla, bla, bla... which might be useful but I still prefer the Invoke-RestMethod
which is lighter.
Also, keep in mind that you need to use | ConvertTo-Json
for the body only, not the header:
$body = @{
"UserSessionId"="12345678"
"OptionalEmail"="[email protected]"
} | ConvertTo-Json
$header = @{
"Accept"="application/json"
"connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
"Content-Type"="application/json"
}
Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML
and you can then append a | ConvertTo-HTML
at the end of the request for better readability
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
this works wonders - no its turn to call this procedure form code with DataTable with schema exactly matching the custType create table customer ( id int identity(1,1) primary key, name varchar(50), cnt varchar(10) )
create type custType as table
(
ctId int,
ctName varchar(20)
)
insert into customer values('y1', 'c1')
insert into customer values('y2', 'c2')
insert into customer values('y3', 'c3')
insert into customer values('y4', 'c4')
insert into customer values('y5', 'c5')
declare @ct as custType
insert @ct (ctid, ctName) values(3, 'y33'), (4, 'y44')
exec multiUpdate @ct
create Proc multiUpdate (@ct custType readonly) as begin
update customer set Name = t.ctName from @ct t where t.ctId = customer.id
end
public DataTable UpdateLevels(DataTable dt)
{
DataTable dtRet = new DataTable();
using (SqlConnection con = new SqlConnection(datalayer.bimCS))
{
SqlCommand command = new SqlCommand();
command.CommandText = "UpdateLevels";
command.Parameters.Clear();
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@ct", dt).SqlDbType = SqlDbType.Structured;
command.Connection = con;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.SelectCommand = command;
dataAdapter.Fill(dtRet);
}
}
}
Import jquery first before bootstrap:
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.bundle.js"></script>
Updated NOTE on this solution: Checking with FileAccess.ReadWrite
will fail for Read-Only files so the solution has been modified to check with FileAccess.Read
. While this solution works because trying to check with FileAccess.Read
will fail if the file has a Write or Read lock on it, however, this solution will not work if the file doesn't have a Write or Read lock on it, i.e. it has been opened (for reading or writing) with FileShare.Read or FileShare.Write access.
ORIGINAL: I've used this code for the past several years, and I haven't had any issues with it.
Understand your hesitation about using exceptions, but you can't avoid them all of the time:
protected virtual bool IsFileLocked(FileInfo file)
{
try
{
using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
//file is not locked
return false;
}
My approach:
var temp = { arr : originalArray };
var obj = $.extend(true, {}, temp);
return obj.arr;
gives me a nice, clean, deep clone of the original array - with none of the objects referenced back to the original :-)
Have you tried:
(column LIKE '%this%' and something=else) or (column LIKE '%that%' and something=else)
I developed these 3 useful functions:
def loadModule(moduleName):
module = None
try:
import sys
del sys.modules[moduleName]
except BaseException as err:
pass
try:
import importlib
module = importlib.import_module(moduleName)
except BaseException as err:
serr = str(err)
print("Error to load the module '" + moduleName + "': " + serr)
return module
def reloadModule(moduleName):
module = loadModule(moduleName)
moduleName, modulePath = str(module).replace("' from '", "||").replace("<module '", '').replace("'>", '').split("||")
if (modulePath.endswith(".pyc")):
import os
os.remove(modulePath)
module = loadModule(moduleName)
return module
def getInstance(moduleName, param1, param2, param3):
module = reloadModule(moduleName)
instance = eval("module." + moduleName + "(param1, param2, param3)")
return instance
And everytime I want to reload a new instance I just have to call getInstance() like this:
myInstance = getInstance("MyModule", myParam1, myParam2, myParam3)
Finally I can call all the functions inside the new Instance:
myInstance.aFunction()
The only specificity here is to customize the params list (param1, param2, param3) of your instance.
The simplest way to create a manifest is:
Project Properties -> Security -> Click "enable ClickOnce security settings"
(it will generate default manifest in your project Properties) -> then Click
it again in order to uncheck that Checkbox -> open your app.maifest and edit
it as you wish.
Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using
keytool -list -v -keystore truststore.jks
Since iPhones developer option apply on wifi tethering, you can get an iPhone which has iOS 6
and above (and has been set to use for developments
with the xcode
), set it to emulate the desired network profile, connect your Android device to its hotspot
Assuming you have referenced and correctly integrated your font to your site (presumably using an @font-face kit) it should be alright to just reference yours the way you do. Presumably it is like this so they have fall backs incase some browsers do not render the fonts correctly
This is yet another reason to use Joda Time
new DateMidnight(2010, 3, 5)
DateMidnight is now deprecated but the same effect can be achieved with Joda Time DateTime
DateTime dt = new DateTime(2010, 3, 5, 0, 0);
A very cool util is journalctl
.
For example, to show syslog to console: journalctl -t <syslog-ident>
, where <syslog-ident>
is identity you gave to function openlog
to initialize syslog.
I've found the sticky footer solution a bit painful on responsive sites, given that the height of your nav and footer can differ depending on the device. If you only care about working on modern browsers, you can accomplish your goal using a bit of Javascript.
If this is your HTML:
<div class="nav">
</div>
<div class="wrapper">
</div>
<div class="footer">
</div>
Then use this JQuery on every page:
$(function(){
/* Sets the minimum height of the wrapper div to ensure the footer reaches the bottom */
function setWrapperMinHeight() {
$('.wrapper').css('minHeight', window.innerHeight - $('.nav').height() - $('.footer').height());
}
/* Make sure the main div gets resized on ready */
setWrapperMinHeight();
/* Make sure the wrapper div gets resized whenever the screen gets resized */
window.onresize = function() {
setWrapperMinHeight();
}
});
I had this problem when having multiple versions of Android Studio, it doesn't look like you have multiple versions. But you do use IntelliJ IDEA Community Edition so are you sure you did install the plugins in Android Studio?.
I would have said this in a comment but I dont have enough rep
The second parameter passed to Geolocation.getCurrentPosition()
is the function you want to handle any geolocation errors. The error handler function itself receives a PositionError
object with details about why the geolocation attempt failed. I recommend outputting the error to the console if you have any issues:
var positionOptions = { timeout: 10000 };
navigator.geolocation.getCurrentPosition(updateLocation, errorHandler, positionOptions);
function updateLocation(position) {
// The geolocation succeeded, and the position is available
}
function errorHandler(positionError) {
if (window.console) {
console.log(positionError);
}
}
Doing this in my code revealed the message "Network location provider at 'https://www.googleapis.com/' : Returned error code 400". Turns out Google Chrome uses the Google APIs to get a location on devices that don't have GPS built in (for example, most desktop computers). Google returns an approximate latitude/longitude based on the user's IP address. However, in developer builds of Chrome (such as Chromium on Ubuntu) there is no API access key included in the browser build. This causes the API request to fail silently. See Chromium Issue 179686: Geolocation giving 403 error for details.
The -Wl,xxx
option for gcc passes a comma-separated list of tokens as a space-separated list of arguments to the linker. So
gcc -Wl,aaa,bbb,ccc
eventually becomes a linker call
ld aaa bbb ccc
In your case, you want to say "ld -rpath .
", so you pass this to gcc as -Wl,-rpath,.
Alternatively, you can specify repeat instances of -Wl
:
gcc -Wl,aaa -Wl,bbb -Wl,ccc
Note that there is no comma between aaa
and the second -Wl
.
Or, in your case, -Wl,-rpath -Wl,.
.
You can forget about using JavaScript because the browser controls whether or not it opens in a new tab. Your best option is to do something like the following instead:
<form action="http://www.yoursite.com/dosomething" method="get" target="_blank">
<input name="dynamicParam1" type="text"/>
<input name="dynamicParam2" type="text" />
<input type="submit" value="submit" />
</form>
This will always open in a new tab regardless of which browser a client uses due to the target="_blank"
attribute.
If all you need is to redirect with no dynamic parameters you can use a link with the target="_blank"
attribute as Tim Büthe suggests.
Everything you write in your own stylesheet is overwriting the user agent styles - that's the point of writing your own stylesheet.
Postgres supports next: create table company.monitor2 as select * from company.monitor;
in your action performed method, call:
label1.setText(nameField.getText());
This way, when the button is clicked, label will be updated to the nameField text.
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
Select Eventname,
count(Eventname) as 'Counts'
INTO #TEMPTABLE
FROM tblevent
where Eventname like 'A%'
Group by Eventname
order by count(Eventname)
Here by using the into clause the table is directly created
Here's a pure JavaScript function which will simulate a click (or any mouse event) on a target element:
function simulatedClick(target, options) {
var event = target.ownerDocument.createEvent('MouseEvents'),
options = options || {},
opts = { // These are the default values, set up for un-modified left clicks
type: 'click',
canBubble: true,
cancelable: true,
view: target.ownerDocument.defaultView,
detail: 1,
screenX: 0, //The coordinates within the entire page
screenY: 0,
clientX: 0, //The coordinates within the viewport
clientY: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
button: 0, //0 = left, 1 = middle, 2 = right
relatedTarget: null,
};
//Merge the options with the defaults
for (var key in options) {
if (options.hasOwnProperty(key)) {
opts[key] = options[key];
}
}
//Pass in the options
event.initMouseEvent(
opts.type,
opts.canBubble,
opts.cancelable,
opts.view,
opts.detail,
opts.screenX,
opts.screenY,
opts.clientX,
opts.clientY,
opts.ctrlKey,
opts.altKey,
opts.shiftKey,
opts.metaKey,
opts.button,
opts.relatedTarget
);
//Fire the event
target.dispatchEvent(event);
}
Here's a working example: http://www.spookandpuff.com/examples/clickSimulation.html
You can simulate a click on any element in the DOM. Something like simulatedClick(document.getElementById('yourButtonId'))
would work.
You can pass in an object into options
to override the defaults (to simulate which mouse button you want, whether Shift/Alt/Ctrl are held, etc. The options it accepts are based on the MouseEvents API.
I've tested in Firefox, Safari and Chrome. Internet Explorer might need special treatment, I'm not sure.
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public class DisplayImage {
public static void main(String avg[]) throws IOException
{
DisplayImage abc=new DisplayImage();
}
public DisplayImage() throws IOException
{
BufferedImage img=ImageIO.read(new File("f://images.jpg"));
ImageIcon icon=new ImageIcon(img);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(200,300);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I'd recommend throwing HttpClientErrorException, like this
@RequestMapping(value = "/sample/")
public void sample() {
if (somethingIsWrong()) {
throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
}
}
You must remember that this can be done only before anything is written to servlet output stream.
Recently, I have seen this problem too. Below, you have my solution:
Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart
or fix it up
I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):
ssh -T [email protected]
Upon receiving a successful response, I could fetch/push to the repo with ssh.
I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.
declare
x number;
begin
x := myfunc(myargs);
end;
Alternatively:
select myfunc(myargs) from dual;
As of API 28 at least:
The photos you've dragged in are now available.
I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.
This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.
sub selectVar ()
dim x,y as integer
let srange = "A" & x & ":" & "m" & y
range(srange).select
end sub
I think this is the simplest way.
String[] allfiles = System.IO.Directory.GetFiles("path/to/dir", "*.*", System.IO.SearchOption.AllDirectories);
You can revert by migrating to the previous migration.
For example use below command:
./manage.py migrate example_app one_left_to_the_last_migration
then delete last_migration
file.
if age is int you should use == if it is Integer object then you can use equals(). You also need to implement hashcode method if you override equals. Details of the contract is available in the javadoc of Object and also at various pages in web.
Check permissions of the file, if it is good check parent directories
I had to correct
/home/sravindr/.ssh permissions which worked for me
Or you could use File.AppendAllLines(string, IEnumerable<string>)
File.AppendAllLines(@"C:\Path\file.txt", new[] { "my text content" });
While I agree that in general inline-block
is better, there's one extra thing to take into account if you're using percentage widths to create a responsive grid (or if you want pixel-perfect widths):
If you're using inline-block
for grids that total 100% or near to 100% width, you need to make sure your HTML markup contains no white space between columns.
With floats, this is not something you need to worry about - the columns float over any whitespace or other content between columns. This question's answers have some good tips on ways to remove HTML whitespace without making your code ugly.
If for any reason you can't control the HTML markup (e.g. a restrictive CMS), you can try the tricks described here, or you might need to compromise and use floats instead of inline-block. There are also ugly CSS tricks that should only be used in extreme circumstances, like font-size:0;
on the column container then reapply font size within each column.
For example:
float: left
. It "just works" (but for the wrapper needing to be cleared).inline-block
. The whitespace between blocks creates a fixed-width space which pushes the total width beyond 100%, breaking the layout and causing the last column to drop down a line.inline-block
and no whitespace between columns in the HTML. It "just works" again - but the HTML is uglier and your CMS might force some kind of prettification or indenting to its HTML output making this difficult to achieve in reality.You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance
before trying to spy on the method.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const instance = app.instance()
const spy = jest.spyOn(instance, 'myClickFunc')
instance.forceUpdate();
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html
This is a feature of C# 4.0, but was not possible without using function overload prior to that version.