Breaking down your code example (Explanations are under the line of code.)
import cv2
imports openCV for usage
camera = cv2.VideoCapture(0)
creates an object called camera, of type openCV video capture, using the first camera in the list of cameras connected to the computer.
for i in range(10):
tells the program to loop the following indented code 10 times
return_value, image = camera.read()
read values from the camera object, using it's read method. it resonds with 2 values save the 2 data values into two temporary variables called "return_value" and "image"
cv2.imwrite('opencv'+str(i)+'.png', image)
use the openCV method imwrite (that writes an image to a disk) and write an image using the data in the temporary data variable
fewer indents means that the loop has now ended...
del(camera)
deletes the camrea object, we no longer needs it.
you can what you request in many ways, one could be to replace the for loop with a while loop, (running forever, instead of 10 times), and then wait for a keypress (like answered by danidee while I was typing)
or create a much more evil service that hides in the background and captures an image everytime someone presses the keyboard...
Transparent background will help you see what behind the element, in this case what behind your td
is in fact the parent table. So we have no way to achieve what you want using pure CSS. Even using script can't solve it in a direct way. We can just have a workaround using script based on the idea of using the same background for both the body and the td
. However we have to update the background-position
accordingly whenver the window is resized. Here is the code you can use with the default background position of body
(which is left top
, otherwise you have to change the code to update the background-position
of the td
correctly):
HTML:
<table id = "MainTable">
<tr>
<td width = "20%"></td>
<td width = "80%" id='test'>
<table>
<tr><td>something interesting here</td></tr>
<tr><td>another thing also interesting out there</td></tr>
</table>
</td>
</tr>
</table>
CSS:
/* use the same background for the td #test and the body */
#test {
padding:40px;
background:url('http://placekitten.com/800/500');
}
body {
background:url('http://placekitten.com/800/500');
}
JS (better use jQuery):
//code placed in onload event handler
function updateBackgroundPos(){
var pos = $('#test').offset();
$('#test').css('background-position',
-pos.left + 'px' + " " + (-pos.top + 'px'));
};
updateBackgroundPos();
$(window).resize(updateBackgroundPos);
Try resizing the viewport, you'll see the background-position
updated correctly, which will make an effect looking like the background of the td
is transparent to the body.
I recommended an experimental new attribute CSS I tested on latest browser and it's good:
image-rendering: optimizeSpeed; /* */
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: -o-crisp-edges; /* Opera */
image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */
image-rendering: optimize-contrast; /* CSS3 Proposed */
-ms-interpolation-mode: nearest-neighbor; /* IE8+ */
With this the browser will know the algorithm for rendering
In your manifest use:-
android:theme="@style/AppTheme" >
in styles.xml:-
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
Surprisingly this works as yo desire, Using the same parent of AppBaseTheme in AppTheme does not.
I fixed my case by adding:
transform: perspective(-1px)
Cocos2d-x within uikit tutorial http://jpsarda.tumblr.com/post/24983791554/mixing-cocos2d-x-uikit
Building off of Nike's answer. Its straightforward to implement the laplacian based method with opencv:
short GetSharpness(char* data, unsigned int width, unsigned int height)
{
// assumes that your image is already in planner yuv or 8 bit greyscale
IplImage* in = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,1);
IplImage* out = cvCreateImage(cvSize(width,height),IPL_DEPTH_16S,1);
memcpy(in->imageData,data,width*height);
// aperture size of 1 corresponds to the correct matrix
cvLaplace(in, out, 1);
short maxLap = -32767;
short* imgData = (short*)out->imageData;
for(int i =0;i<(out->imageSize/2);i++)
{
if(imgData[i] > maxLap) maxLap = imgData[i];
}
cvReleaseImage(&in);
cvReleaseImage(&out);
return maxLap;
}
Will return a short indicating the maximum sharpness detected, which based on my tests on real world samples, is a pretty good indicator of if a camera is in focus or not. Not surprisingly, normal values are scene dependent but much less so than the FFT method which has to high of a false positive rate to be useful in my application.
Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.
extension UIView {
func getSnapshotImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
drawHierarchy(in: bounds, afterScreenUpdates: false)
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return snapshotImage
}
}
You should be able to do it using the text-shadow, erm somethink like this:
.inner_text_shadow
{
text-shadow: 1px 1px white, -1px -1px #444;
}
here's an example: http://jsfiddle.net/ekDNq/
great answer by @Rarw. Try using a bundle to pass information from one fragment to another
$rootScope.$broadcast is a convenient way to raise a "global" event which all child scopes can listen for. You only need to use $rootScope
to broadcast the message, since all the descendant scopes can listen for it.
The root scope broadcasts the event:
$rootScope.$broadcast("myEvent");
Any child Scope can listen for the event:
$scope.$on("myEvent",function () {console.log('my event occurred');} );
Why we use $rootScope.$broadcast? You can use $watch
to listen for variable changes and execute functions when the variable state changes. However, in some cases, you simply want to raise an event that other parts of the application can listen for, regardless of any change in scope variable state. This is when $broadcast
is helpful.
I did it many times. To bypass the JavaScript warning, I add two parens:
if ((result = get_something())) { }
You should avoid it, if you really want to use it, write a comment above it saying what you are doing.
While this isn't possible with the video itself, you could use a canvas to draw the frames of the video except for pixels in a color range or whatever. It would take some javascript and such of course. See Video Puzzle (apparently broken at the moment), Exploding Video, and Realtime Video -> ASCII
http://rreddy.blogspot.com/2009/07/vncviewer-clipboard-operations-like.html
Many times you must have observed that clipboard operations like copy/cut and paste suddenly stops workings with the vncviewer. The main reason for this there is a program called as vncconfig responsible for these clipboard transfers. Some times the program may get closed because of some bug in vnc or some other reasons like you closed that window.
To get those clipboard operations back you need to run the program "vncconfig &".
After this your clipboard actions should work fine with out any problems.
Run "vncconfig &" on the client.
In .net VB - you could achieve control over columns and rows with the following in your razor file:
@Html.EditorFor(Function(model) model.generalNotes, New With {.htmlAttributes = New With {.class = "someClassIfYouWant", .rows = 5,.cols=6}})
In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
When using setAttribute
and getRequestDispatcher
on doGet
, make sure that you are accessing your pages with the urlPatterns ("/login" for example) defined for your servlet. If you do it with "/login.jsp" your doGet
won't get called so none of your attributes will be available.
I believe you can create a unix style datestamp accurate to a second using the following
//Find unix timestamp (seconds since 01/01/1970)
long ticks = DateTime.UtcNow.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;
ticks /= 10000000; //Convert windows ticks to seconds
timestamp = ticks.ToString();
Adjusting the denominator allows you to choose your level of precision
Try the out-of-the-box solution (ASP.NET MVC 4 or later):
@{
var bundle = BundleTable.Bundles.GetRegisteredBundles().First(b => b.Path == "~/js");
bundle.Include("~/Scripts/myFile.js");
}
Actually, I just noticed that the shell syntax somewhat has a behavior built-in that allows for easy reconstruction of the array when, as posed in the question, an item should be removed.
# let's set up an array of items to consume:
x=()
for (( i=0; i<10; i++ )); do
x+=("$i")
done
# here, we consume that array:
while (( ${#x[@]} )); do
i=$(( $RANDOM % ${#x[@]} ))
echo "${x[i]} / ${x[@]}"
x=("${x[@]:0:i}" "${x[@]:i+1}")
done
Notice how we constructed the array using bash's x+=()
syntax?
You could actually add more than one item with that, the content of a whole other array at once.
(first post - so it may not be clean)
This is my fix for OS X 11.6, Maven-based Netbeans 8.2 program. Up to now my app is 100% Netbeans - no tweaking (just a few shell escapes for the impossible!).
Having tried most all of the answers here and elsewhere to no avail, I returned to the art of "use what works".
The top answer here (olivier-refalo thanx) looked like the right place to start but didn't help.
Looking at other projects which did work, I noticed some minor differences in the manifest lines:
Not sure why (I am only 3 months into java) or how, but can only say this worked.
Here is just the modified manifest block used:
<manifest>
<mainClass>mypackage.MyClass</mainClass>
</manifest>
I haven't played with these settings myself so this is just speculation but if we think about this issue as normal cores and threads in a distributed system then in your cluster you can use up to 12 cores (4 * 3 machines) and 24 threads (8 * 3 machines). In your first two examples you are giving your job a fair number of cores (potential computation space) but the number of threads (jobs) to run on those cores is so limited that you aren't able to use much of the processing power allocated and thus the job is slower even though there is more computation resources allocated.
you mention that your concern was in the shuffle step - while it is nice to limit the overhead in the shuffle step it is generally much more important to utilize the parallelization of the cluster. Think about the extreme case - a single threaded program with zero shuffle.
Boot strapping the dictionary meaning is to start up with minimum resources. In the Context of an OS the OS should be able to swiftly load once the Power On Self Test (POST) determines that its safe to wake up the CPU. The boot strap code will be run from the BIOS. BIOS is a small sized ROM. Generally it is a jump instruction to the set of instructions which will load the Operating system to the RAM. The destination of the Jump is the Boot sector in the Hard Disk. Once the bios program checks it is a valid Boot sector which contains the starting address of the stored OS, ie whether it is a valid MBR (Master Boot Record) or not. If its a valid MBR the OS will be copied to the memory (RAM)from there on the OS takes care of Memory and Process management.
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
BalusC said:
Update: to clarify a conceptual misunderstanding, the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep().
But if you replace Thread.sleep(4000);
with for (int i = 0; i < 5E8; i++) {}
then it doesn't compile, because the empty loop doesn't throw an InterruptedException
.
And for the thread to be interruptible, it needs to throw an InterruptedException
.
This seems like a serious problem to me. I can't see how to adapt this answer to work with a general long-running task.
Edited to add: I reasked this as a new question: [ interrupting a thread after fixed time, does it have to throw InterruptedException? ]
Alternative
If your console is not empty, right click on the Console area > Preferences... > change the value for the Console buffer size (characters) (recommended) or uncheck the Limit console output (not recommended):
Look at here: http://blog-mstechnology.blogspot.de/2010/06/throw-vs-throw-ex.html
Throw:
try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw;
}
It preserve the Stack information with Exception
This is called as "Rethrow"
If want to throw new exception,
throw new ApplicationException("operation failed!");
Throw Ex:
try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw ex;
}
It Won't Send Stack information with Exception
This is called as "Breaking the Stack"
If want to throw new exception,
throw new ApplicationException("operation failed!",ex);
You should put a padding in each object. For example, you want a space between images, you can use the following:
img{
padding: 5px;
}
That means 5px paddin for ALL sides. Read more at http://www.w3schools.com/css/css_padding.asp. By the way, studying a lot before attempting to program will make things easier for you (and for us).
You forgot @Service annotation in your service class.
You've tried alot. And I feel for you. Here is an idea. I kinda followed everything you tried. The mental note I have in my head goes like this: "When Sql Server won't connect when you've tried everything, wire up your firewall rules by the program, not the port"
I know you said you disabled the firewall. But something is telling me to give this a try anyways.
I think you have to open the firewall "by program", and not by port.
http://technet.microsoft.com/en-us/library/cc646023.aspx
To add a program exception to the firewall using the Windows Firewall item in Control Panel.
On the Exceptions tab of the Windows Firewall item in Control Panel, click Add a program.
Browse to the location of the instance of SQL Server that you want to allow through the firewall, for example C:\Program Files\Microsoft SQL Server\MSSQL11.<instance_name>\MSSQL\Binn, select sqlservr.exe, and then click Open.
Click OK.
EDIT..........
http://msdn.microsoft.com/en-us/library/ms190479.aspx
I'm a little cloudy on which "program" you're trying to use on SQLB?
Is it SSMS on SQLB? Or a client program on SQLB ?
EDIT...........
No idea if this will help. But I use this to ping "ports" ... and something that is outside of the SSMS world.
http://www.microsoft.com/en-us/download/details.aspx?id=24009
well the only thing that will work is
python -m pip install pip==
you can and should run it under IDE terminal (mine was pycharm)
When using matplotlib.pyplot
, you must first save your plot and then close it using these 2 lines:
fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window
This code worked for me, it kills all existing connections of a database. All you have to do is change the line Set @dbname = 'databaseName' so it has your database name.
Use Master
Go
Declare @dbname sysname
Set @dbname = 'databaseName'
Declare @spid int
Select @spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(@dbname)
While @spid Is Not Null
Begin
Execute ('Kill ' + @spid)
Select @spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(@dbname) and spid > @spid
End
after this I was able to restore it
If you are simply looking for the occurrence of "Miami" or "Florida" inside a string (since you put * at both ends), it's probably better to use the InStr function instead of Like. Not only are the results more predictable, but I believe you'll get better performance.
Also, VBA is not short-circuited so when you use the AND keyword, it will test both sides of the AND, regardless if the first test failed or not. In VBA, it is more optimal to use 2 if-statements in these cases, that way you aren't checking for "Florida" if you don't find "Miami".
The other advice I have is that a for-each loop is faster than a for-loop. Using .offset, you can achieve the same thing, but with better effeciency. Of course there are even better ways (like variant arrays), but those will add a layer of complexity not needed in this example.
Here is some sample code:
Sub test()
Application.ScreenUpdating = False
Dim lastRow As Long
Dim cell As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
For Each cell In Range("A1:A" & lastRow)
If InStr(1, cell.Value, "Miami") <> 0 Then
If InStr(1, cell.Offset(, 3).Value, "Florida") <> 0 Then
cell.Offset(, 2).Value = "BA"
End If
End If
Next
Application.ScreenUpdating = True
End Sub
I hope you find some of this helpful, and keep at it with VBA! ^^
Short answer (valid as of 2015-04-16): removeAtIndex(myString.endIndex.predecessor())
Example:
var howToBeHappy = "Practice compassion, attention and gratitude. And smile!!"
howToBeHappy.removeAtIndex(howToBeHappy.endIndex.predecessor())
println(howToBeHappy)
// "Practice compassion, attention and gratitude. And smile!"
Meta:
The language continues its rapid evolution, making the half-life for many formerly-good S.O. answers dangerously brief. It's always best to learn the language and refer to real documentation.
Follow these steps:
1. Generate an APNs Auth Key
Open the APNs Auth Key page in your Developer Center and click the + button to create a new APNs Auth Key.
In the next page, select Apple Push Notification Authentication Key (Sandbox & Production) and click Continue at the bottom of the page.
Apple will then generate a .p8
key file containing your APNs Auth Key.
Download the .p8
key file to your computer and save it for later. Also, be sure to write down the Key ID somewhere, as you'll need it later when connecting to APNs.
2. Send Push Notifications
Ref: APNS (Configure push notifications)
Important: Save a back up of your key in a secure place. It will not be presented again and cannot be retrieved later.
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
Is the best one to use. Using sleep(15); will cause the user unable to perform any other actions. With the following function, you would replace goToSecondButton with the appropriate selector or command, which can also be from the frameworks.
I would recommend you google 'Read objects in folder'. You might need to create a reader and a list and let the reader read all the object names in the folder and add them to the list in n loops.
I just figured it out! What I did was I created the batch file like I had it originally:
net use P: "\\server\foldername\foldername"
I then saved it to the desktop and right clicked the properties and checked run as administrator. I then copied the file to C:\Users\"TheUser"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Where "TheUser" was the desired user I wanted to add it to.
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
~/.matplotlib
. ~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
when you paste into Word, the formating/formula of excel still exists. Simply click the clip board and select the option "keep text only."
You can use this www.npmjs.com/package/sleep
var sleep = require('sleep');
sleep.sleep(10); // sleep for ten seconds
public static bool CompareDateTimes(this DateTime firstDate, DateTime secondDate)
{
return firstDate.Day == secondDate.Day && firstDate.Month == secondDate.Month && firstDate.Year == secondDate.Year;
}
$("#search").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("tbody tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
Assumption there is a one table with a tbody. you can also search with find or if the table has an ID you can use the id
The easiest way is probably just to split on your target word
my_string="hello python world , i'm a beginner "
print my_string.split("world",1)[1]
split takes the word(or character) to split on and optionally a limit to the number of splits.
In this example split on "world" and limit it to only one split.
If using jQuery and have a handle to any form element, you need to get(0) the element before using .form
var my_form = $('input[name=first_name]').get(0).form;
The following codes should give you the fastest speed for big data as long as you have many cores on your computer:
if (!require("pacman")) install.packages("pacman")
pacman::p_load(doParallel, data.table, stringr)
# get the file name
dir() %>% str_subset("\\.csv$") -> fn
# use parallel setting
(cl <- detectCores() %>%
makeCluster()) %>%
registerDoParallel()
# read and bind all files together
system.time({
big_df <- foreach(
i = fn,
.packages = "data.table"
) %dopar%
{
fread(i, colClasses = "character")
} %>%
rbindlist(fill = TRUE)
})
# end of parallel work
stopImplicitCluster(cl)
Updated in 2020/04/16: As I find a new package available for parallel computation, an alternative solution is provided using the following codes.
if (!require("pacman")) install.packages("pacman")
pacman::p_load(future.apply, data.table, stringr)
# get the file name
dir() %>% str_subset("\\.csv$") -> fn
plan(multiprocess)
future_lapply(fn,fread,colClasses = "character") %>%
rbindlist(fill = TRUE) -> res
# res is the merged data.table
I eventually figured it out. Place:
import warnings
warnings.filterwarnings('ignore')
inside ~/.ipython/profile_default/startup/disable-warnings.py
. I'm leaving this question and answer for the record in case anyone else comes across the same issue.
Quite often it is useful to see a warning once. This can be set by:
warnings.filterwarnings(action='once')
You could use the bootstrap grid system :
<div class="col-md-6 form-group">
<label for="textbox1">Label1</label>
<input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
<label for="textbox2">Label2</label>
<input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">
http://getbootstrap.com/css/#grid
Is that what you want to achieve?
The # is an id selector. It matches only elements with a matching id. Next style rule will match the element that has an id attribute with a value of "green":
#green {color: green}
See http://www.w3schools.com/css/css_syntax.asp for more information
I had installed CUDA 10.1 and CUDNN 7.6 by mistake. You can use following configurations (This worked for me - as of 9/10). :
But I had to create symlinks for it to work as tensorflow originally works with CUDA 10.
sudo ln -s /opt/cuda/targets/x86_64-linux/lib/libcublas.so /opt/cuda/targets/x86_64-linux/lib/libcublas.so.10.0
sudo cp /usr/lib/x86_64-linux-gnu/libcublas.so.10 /usr/local/cuda-10.1/lib64/
sudo ln -s /usr/local/cuda-10.1/lib64/libcublas.so.10 /usr/local/cuda-10.1/lib64/libcublas.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcusolver.so.10 /usr/local/cuda/lib64/libcusolver.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcurand.so.10 /usr/local/cuda/lib64/libcurand.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcufft.so.10 /usr/local/cuda/lib64/libcufft.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcudart.so /usr/local/cuda/lib64/libcudart.so.10.0
sudo ln -s /usr/local/cuda/targets/x86_64-linux/lib/libcusparse.so.10 /usr/local/cuda/lib64/libcusparse.so.10.0
And add the following to my ~/.bashrc -
export PATH=/usr/local/cuda/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
export PATH=/usr/local/cuda-10.1/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.1/lib64:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/cuda/targets/x86_64-linux/lib/
Tried most of the above and nothing worked. Then turned off the VPN software (NordVPN) and everything was fine.
For my Debian Jessie box, I also included:
sudo apt-get build-dep libxml2-dev
Hint: The r-tool console output is pretty verbose so I would check for any other dependencies.
Then, I finally got it:
> find_rtools()
[1] TRUE
I needed the same concept to compress sequentially several directories or files from a certain folder. I have solved using awk to parsel the list from ls and to avoid the problem of blank space in the name.
source="/xxx/xxx"
dest="/yyy/yyy"
n_max=`ls . | wc -l`
echo "Loop over items..."
i=1
while [ $i -le $n_max ];do
item=`ls . | awk 'NR=='$i'' `
echo "File selected for compression: $item"
tar -cvzf $dest/"$item".tar.gz "$item"
i=$(( i + 1 ))
done
echo "Done!!!"
what do you think?
function waitforme(ms) {
return new Promise( resolve => {
setTimeout(()=> {resolve('')} ,ms );
})
}
async function printy() {
for (let i= 0; i < 10 ; ++i) {
await waitforme(1000);
//wait for 500 milisecond
console.log(i);
}
console.log("I Ran after the loop finished :)");
}
printy();
_x000D_
Further to this, the return type is determined by
What the HTTP Request says it wants - in its Accept header. Try looking at the initial request as see what Accept is set to.
What HttpMessageConverters Spring sets up. Spring MVC will setup converters for XML (using JAXB) and JSON if Jackson libraries are on he classpath.
If there is a choice it picks one - in this example, it happens to be JSON.
This is covered in the course notes. Look for the notes on Message Convertors and Content Negotiation.
I prefer using a separate file for ie rules, as described earlier.
<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->
And inside it you can set up rules for different versions of ie using this:
.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */
$(window).on("touchstart", function(ev) {
var e = ev.originalEvent;
console.log(e.touches);
});
I know it been asked a long time ago, but I thought a concrete example might help.
You've already stated why np.maximum
is different - it returns an array that is the element-wise maximum between two arrays.
As for np.amax
and np.max
: they both call the same function - np.max
is just an alias for np.amax
, and they compute the maximum of all elements in an array, or along an axis of an array.
In [1]: import numpy as np
In [2]: np.amax
Out[2]: <function numpy.core.fromnumeric.amax>
In [3]: np.max
Out[3]: <function numpy.core.fromnumeric.amax>
Rather going for pop up,I personally liked this solution, mentioned on this Question thread JavaScript: location.href to open in new window/tab?
$(document).on('click','span.external-link',function(){
var t = $(this),
URL = t.attr('data-href');
$('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();
});
Working example.
From Windows 10 version 1607, the limitation has been removed by setting a registry key
Platform.runLater
: If you need to update a GUI component from a non-GUI thread, you can use that to put your update in a queue and it will be handled by the GUI thread as soon as possible.Task
implements the Worker
interface which is used when you need to run a long task outside the GUI thread (to avoid freezing your application) but still need to interact with the GUI at some stage.If you are familiar with Swing, the former is equivalent to SwingUtilities.invokeLater
and the latter to the concept of SwingWorker
.
The javadoc of Task gives many examples which should clarify how they can be used. You can also refer to the tutorial on concurrency.
Another way to phrase the same idea:
If speeding up the CPU doesn't speed up your program, it may be I/O bound.
If speeding up the I/O (e.g. using a faster disk) doesn't help, your program may be CPU bound.
(I used "may be" because you need to take other resources into account. Memory is one example.)
If your elements are glitching this is probably because when you change the position to relative
the Y position of the footer increases which tries to send the item back to fixed
which creates a loop. You can avoid this by setting two different cases when scrolling up and down. You don't even need to reference the fixed element, just the footer, and window size.
const footer = document.querySelector('footer');
document.addEventListener("scroll", checkScroll);
let prevY = window.scrollY + window.innerHeight;
function checkScroll() {
let footerTop = getRectTop(footer) + window.scrollY;
let windowBottomY = window.scrollY + window.innerHeight;
if (prevY < windowBottomY) { // Scroll Down
if (windowBottomY > footerTop)
setScrolledToFooter(true) // using React state. Change class or change style in JS.
} else { // Scroll Up
if (windowBottomY <= footerTop)
setScrolledToFooter(false)
}
prevY = windowBottomY
};
function getRectTop(el) {
var rect = el.getBoundingClientRect();
return rect.top;
}
and the position of the element in the style object as follows:
position: scrolledToFooter ? 'relative' : 'fixed'
countDecimals = value => {
if (Math.floor(value) === value) return 0;
let stringValue = value.toString().split(".")[1];
if (stringValue) {
return value.toString().split(".")[1].length
? value.toString().split(".")[1].length
: 0;
} else {
return 0;
}
};
formatNumber=(ans)=>{
let decimalPlaces = this.countDecimals(ans);
ans = 1 * ans;
if (decimalPlaces !== 0) {
let onePlusAns = ans + 1;
let decimalOnePlus = this.countDecimals(onePlusAns);
if (decimalOnePlus < decimalPlaces) {
ans = ans.toFixed(decimalPlaces - 1).replace(/\.?0*$/, "");
} else {
let tenMulAns = ans * 10;
let decimalTenMul = this.countDecimals(tenMulAns);
if (decimalTenMul + 1 < decimalPlaces) {
ans = ans.toFixed(decimalPlaces - 1).replace(/\.?0*$/, "");
}
}
}
}
_x000D_
I just add 1 to the value and count the decimal digits present in the original value and the added value. If I find the decimal digits after adding one less than the original decimal digits, I just call the toFixed() with (original decimals - 1). I also check by multiplying the original value by 10 and follow the same logic in case adding one doesn't reduce redundant decimal places. A simple workaround to handle floating-point number rounding in JS. Works in most cases I tried.
Most answers already cover getContext()
and getApplicationContext()
but getBaseContext() is rarely explained.
The method getBaseContext()
is only relevant when you have a ContextWrapper
.
Android provides a ContextWrapper
class that is created around an existing Context
using:
ContextWrapper wrapper = new ContextWrapper(context);
The benefit of using a ContextWrapper
is that it lets you “modify behavior without changing the original Context”. For example, if you have an activity called myActivity
then can create a View
with a different theme than myActivity
:
ContextWrapper customTheme = new ContextWrapper(myActivity) {
@Override
public Resources.Theme getTheme() {
return someTheme;
}
}
View myView = new MyView(customTheme);
ContextWrapper
is really powerful because it lets you override most functions provided by Context
including code to access resources (e.g. openFileInput()
, getString()
), interact with other components (e.g. sendBroadcast()
, registerReceiver()
), requests permissions (e.g. checkCallingOrSelfPermission()
) and resolving file system locations (e.g. getFilesDir()
). ContextWrapper
is really useful to work around device/version specific problems or to apply one-off customizations to components such as Views that require a context.
The method getBaseContext() can be used to access the “base” Context that the ContextWrapper
wraps around. You might need to access the “base” context if you need to, for example, check whether it’s a Service
, Activity
or Application
:
public class CustomToast {
public void makeText(Context context, int resId, int duration) {
while (context instanceof ContextWrapper) {
context = context.baseContext();
}
if (context instanceof Service)) {
throw new RuntimeException("Cannot call this from a service");
}
...
}
}
Or if you need to call the “unwrapped” version of a method:
class MyCustomWrapper extends ContextWrapper {
@Override
public Drawable getWallpaper() {
if (BuildInfo.DEBUG) {
return mDebugBackground;
} else {
return getBaseContext().getWallpaper();
}
}
}
You can consider using numpy.putmask:
np.putmask(arr, arr>=T, 255.0)
Here is a performance comparison with the Numpy's builtin indexing:
In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit np.putmask(A, A>0.5, 5)
1000 loops, best of 3: 1.34 ms per loop
In [4]: timeit A[A > 0.5] = 5
1000 loops, best of 3: 1.82 ms per loop
have you visited this links? http://groups.google.com/group/android-developers/browse_thread/thread/dcaf8b2fdd8a90c4/62d5e2ffef31ebdb
http://moazzam-khan.com/blog/?tag=android-upload-file
http://evgenyg.wordpress.com/2010/05/01/uploading-files-multipart-post-apache/
Concise example of file upload via Java lib Apache Commons
i think you will get help from this
Nowadays, this is possible to achieve using CSS only with position: sticky
property.
Here goes a snippet:
(jsFiddle: https://jsfiddle.net/hbqzdzdt/5/)
.grid-container {_x000D_
display: grid; /* This is a (hacky) way to make the .grid element size to fit its content */_x000D_
overflow: auto;_x000D_
height: 300px;_x000D_
width: 600px;_x000D_
}_x000D_
.grid {_x000D_
display: flex;_x000D_
flex-wrap: nowrap;_x000D_
}_x000D_
.grid-col {_x000D_
width: 150px;_x000D_
min-width: 150px;_x000D_
}_x000D_
_x000D_
.grid-item--header {_x000D_
height: 100px;_x000D_
min-height: 100px;_x000D_
position: sticky;_x000D_
position: -webkit-sticky;_x000D_
background: white;_x000D_
top: 0;_x000D_
}_x000D_
_x000D_
.grid-col--fixed-left {_x000D_
position: sticky;_x000D_
left: 0;_x000D_
z-index: 9998;_x000D_
background: white;_x000D_
}_x000D_
.grid-col--fixed-right {_x000D_
position: sticky;_x000D_
right: 0;_x000D_
z-index: 9998;_x000D_
background: white;_x000D_
}_x000D_
_x000D_
.grid-item {_x000D_
height: 50px;_x000D_
border: 1px solid gray;_x000D_
}
_x000D_
<div class="grid-container">_x000D_
<div class="grid">_x000D_
<div class="grid-col grid-col--fixed-left">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>P</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="grid-col grid-col--fixed-right">_x000D_
<div class="grid-item grid-item--header">_x000D_
<p>HEAD</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>9</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>9</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>9</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>9</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>9</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>9</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>9</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>9</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>9</p>_x000D_
</div>_x000D_
<div class="grid-item">_x000D_
<p>9</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>
_x000D_
Regarding compatibility. It works in all major browsers, but not in IE. There is a polyfill for position: sticky
but I never tried it.
In my case, a message appeared as follow.
Command CompileSwiftSources failed with a nonzero exit code.
I changed toolchain Xcode->Toolchain->Xcode 10.1
This was happened right after I update to Xcode10.1. I hope it will work.
I also attach a link more about manage toolchain.
Building on @danfolkes' answer, this worked for me in IE 8 and ASP.NET MVC3.
In our _Layout.cshtml
<body style="min-width: 800px">
<div id="progress">
<div style="min-height: 200px">
</div>
<div id="throbber">
<img src="..\..\Content\ajax-loader.gif" alt="Progress" style="display: block;
margin-left: auto; margin-right: auto" />
</div>
</div>
<div id="main">
<<< content here >>> ...
<script type="text/javascript" language="javascript">
function ShowThrobber() {
$('#main').hide();
$('#progress').show();
// Work around IE bug which freezes gifs
if (navigator.appName == 'Microsoft Internet Explorer') {
// Work around IE bug which freezes gifs
$("#throbber").html('<img src="../../Content/ajax-loader.gif" alt="Progress" style="display: block; margin-left: auto; margin-right: auto"/>');
}
</script>
<script type="text/javascript" language="javascript">
function HideThrobber() {
$('#main').show();
$('#progress').hide();
}
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
HideThrobber();
});
</script>
And in our navigation links:
<input type="submit" value="Finish" class="submit-link" onclick="ShowThrobber()"/>
or
@Html.ActionLink("DoSometthing", "MyController", new { Model.SomeProperty }, new { onclick = "ShowThrobber()" })
I find the -e
flag elegant and straight forward
bash$ STR="Hello\nWorld"
bash$ echo -e $STR
Hello
World
If the string is the output of another command, I just use quotes
indexes_diff=$(git diff index.yaml)
echo "$indexes_diff"
You could not iterate or store more data than the length of your array. In this case you could do like this:
for (int i = 0; i <= name.length - 1; i++) {
// ....
}
Or this:
for (int i = 0; i < name.length; i++) {
// ...
}
To set all FormGroup values use, setValue:
this.myFormGroup.setValue({
formControlName1: myValue1,
formControlName2: myValue2
});
To set only some values, use patchValue:
this.myFormGroup.patchValue({
formControlName1: myValue1,
// formControlName2: myValue2 (can be omitted)
});
With this second technique, not all values need to be supplied and fields whos values were not set will not be affected.
Depending on the version, do:
version <2.3.0
Kill a hadoop job:
hadoop job -kill $jobId
You can get a list of all jobId's doing:
hadoop job -list
version >=2.3.0
Kill a hadoop job:
yarn application -kill $ApplicationId
You can get a list of all ApplicationId's doing:
yarn application -list
yourTable.ImportRow(dataRow);
It's because the row you're copying doesn't have the same TableName
:
For example, try:
Table1.TableName = "Table1";
Table2.TableName = "Table2";
have you tried:
.image_block{
text-align: center;
vertical-align: bottom;
}
This worked for me. But it didn't list in alphabetical order.
find "$(pwd)" -maxdepth 1
This command lists alphabetically as well as lists hidden files too.
ls -d -1 "$PWD/".*; ls -d -1 "$PWD/"*;
I find this, simple and efficient:
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
// default options
app.use(fileUpload());
app.post('/upload', function(req, res) {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file somewhere on your server
sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
To solve this problem in Excel, usually I would just type in the literal row number of the cell above, e.g., if I'm typing in Cell A7
, I would use the formula =A6
. Then if I copied that formula to other cells, they would also use the row of the previous cell.
Another option is to use Indirect()
, which resolves the literal statement inside to be a formula. You could use something like:
=INDIRECT("A" & ROW() - 1)
The above formula will resolve to the value of the cell in column A
and the row that is one less than that of the cell which contains the formula.
In SQL 2005, this is simple: 1. Open SQL Server management studio and copy the sql statement you need into the TSQL , such as exec sp_whatever 2. Query->Results to Grid 3. Highlight the sql statement and run it 4. Highlight the data results (left-click on upper left area of results grid) 5. Now right-click and select Save Results As 6. Select CSV in the Save as type, enter a file name, select a location and click Save.
Easy!
Here is how to do it:
#!/bin/sh
abort()
{
echo >&2 '
***************
*** ABORTED ***
***************
'
echo "An error occurred. Exiting..." >&2
exit 1
}
trap 'abort' 0
set -e
# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0
echo >&2 '
************
*** DONE ***
************
'
The @ symbol denotes an annotation type definition.
That means it is not really an interface, but rather a new annotation type -- to be used as a function modifier, such as @override.
See this javadocs entry on the subject.
&& x.DateTimeValueColumn <= DateTime.Now
This is supported so long as your schema is correct
&& x.DateTimeValueColumn.Value.Date <=DateTime.Now
It would probably be easier to just fake it by using a div. Just make sure you set the height if its empty so that it can actually appear. Say for instance you want it to be 50px tall set the div height to 50px.
<div id="rightflower">
<div id="divImg"></div>
</div>
And in your style sheet just add the background and its properties, height and width, and what ever positioning you had in mind.
Here's a variation on this theme. I want to uninstall Cisco Amp, wait, and get the exit code. But the uninstall program starts a second program called "un_a" and exits. With this code, I can wait for un_a to finish and get the exit code of it, which is 3010 for "needs reboot". This is actually inside a .bat file.
If you've ever wanted to uninstall folding@home, it works in a similar way.
rem uninstall cisco amp, probably needs a reboot after
rem runs Un_A.exe and exits
rem start /wait isn't useful
"c:\program files\Cisco\AMP\6.2.19\uninstall.exe" /S
powershell while (! ($proc = get-process Un_A -ea 0)) { sleep 1 }; $handle = $proc.handle; 'waiting'; wait-process Un_A; exit $proc.exitcode
For me, the problem was trying to pass a filename in a url, with a dot. For example
"http://localhost:8080/something/asdf.jpg" //causes error because of '.jpg'
It could be solved by not passing the .jpg extension, or sending it all in a request body.
If you wont to forward your ref
, in Props interface you need to use RefObject<CmpType>
type from import React, { RefObject } from 'react';
For Unity, use Mathf.RoundToInt.
using UnityEngine;
public class ExampleScript : MonoBehaviour
{
void Start()
{
// Prints 10
Debug.Log(Mathf.RoundToInt(10.0f));
// Prints 10
Debug.Log(Mathf.RoundToInt(10.2f));
// Prints 11
Debug.Log(Mathf.RoundToInt(10.7f));
// Prints 10
Debug.Log(Mathf.RoundToInt(10.5f));
// Prints 12
Debug.Log(Mathf.RoundToInt(11.5f));
// Prints -10
Debug.Log(Mathf.RoundToInt(-10.0f));
// Prints -10
Debug.Log(Mathf.RoundToInt(-10.2f));
// Prints -11
Debug.Log(Mathf.RoundToInt(-10.7f));
// Prints -10
Debug.Log(Mathf.RoundToInt(-10.5f));
// Prints -12
Debug.Log(Mathf.RoundToInt(-11.5f));
}
}
public static int RoundToInt(float f) { return (int)Math.Round(f); }
pip is the package installer for python, update it first, then download what you need
python -m pip install --upgrade pip
Then:
python -m pip install <package_name>
If you prefer to use Guice and you don't want to declare all the bindings, you can also try this adapter:
Try this out:
<script type="text/javascript">
function test
{
alert("hello world"); //write your logic here like ajax
}
</script>
<form action="javascript:test();" >
firstName : <input type="text" name="firstName" id="firstName" required/><br/>
lastName : <input type="text" name="lastName" id="lastName" required/><br/>
email : <input type="email" name="email" id="email"/><br/>
<input type="submit" value="Get It!" name="submit" id="submit"/>
</form>
Maybe a bit late, but hope it hellps:
@echo off
if %ERRORLEVEL% == 0 (
msg * 1st line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue1
)
:Continue1
If exist "C:\Python31" (
msg * 2nd line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue2
)
:Continue2
If exist "C:\Python31\Lib\site-packages\PyQt4" (
msg * 3th line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue3
)
:Continue3
msg * 4th line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue4
)
:Continue4
msg * "Tutto a posto" rem You can relpace msg * with any othe operation...
pause
For example,
package verbose
import (
"fmt"
"testing"
)
func TestPrintSomething(t *testing.T) {
fmt.Println("Say hi")
t.Log("Say bye")
}
go test -v
=== RUN TestPrintSomething
Say hi
--- PASS: TestPrintSomething (0.00 seconds)
v_test.go:10: Say bye
PASS
ok so/v 0.002s
-v Verbose output: log all tests as they are run. Also print all text from Log and Logf calls even if the test succeeds.
func (c *T) Log(args ...interface{})
Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.
Note that if the object you are talking about has a custom property model (such as DataRowView
etc for DataTable
), then you need to use TypeDescriptor
; the good news is that this still works fine for regular classes (and can even be much quicker than reflection):
foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}
This also provides easy access to things like TypeConverter
for formatting:
string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));
The onkeypress event works for all the keys except ALT, CTRL, SHIFT, ESC in all browsers where as onkeydown event works for all keys. Means onkeydown event captures all the keys.
ORDER BY: sort the data in ascending or descending order.
Consider the CUSTOMERS table:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would sort the result in ascending order by NAME:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME;
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
GROUP BY: arrange identical data into groups.
Now, CUSTOMERS table has the following records with duplicate names:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
if you want to group identical names into single name, then GROUP BY query would be as follows:
SQL> SELECT * FROM CUSTOMERS
GROUP BY NAME;
This would produce the following result: (for identical names it would pick the last one and finally sort the column in ascending order)
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
+----+----------+-----+-----------+----------+
as you have inferred that it is of no use without SQL functions like sum,avg etc..
so go through this definition to understand the proper use of GROUP BY:
A GROUP BY clause works on the rows returned by a query by summarizing identical rows into a single/distinct group and returns a single row with the summary for each group, by using appropriate Aggregate function in the SELECT list, like COUNT(), SUM(), MIN(), MAX(), AVG(), etc.
Now, if you want to know the total amount of salary on each customer(name), then GROUP BY query would be as follows:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;
This would produce the following result: (sum of the salaries of identical names and sort the NAME column after removing identical names)
+---------+-------------+
| NAME | SUM(SALARY) |
+---------+-------------+
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+---------+-------------+
One main reason we went with Workstation over Player at my job is because we need to run VMs that use a physical disk as their hard drive instead of a virtual disk. Workstation supports using physical disks while Player does not.
Doing some testing with a Raspberry Pi 3B+ (I'm using an overlay file system, and need to sync periodically), I ran a comparison of my own for diff -q and cmp -s; note that this is a log from inside /dev/shm, so disk access speeds are a non-issue:
[root@mypi shm]# dd if=/dev/urandom of=test.file bs=1M count=100 ; time diff -q test.file test.copy && echo diff true || echo diff false ; time cmp -s test.file test.copy && echo cmp true || echo cmp false ; cp -a test.file test.copy ; time diff -q test.file test.copy && echo diff true || echo diff false; time cmp -s test.file test.copy && echo cmp true || echo cmp false
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 6.2564 s, 16.8 MB/s
Files test.file and test.copy differ
real 0m0.008s
user 0m0.008s
sys 0m0.000s
diff false
real 0m0.009s
user 0m0.007s
sys 0m0.001s
cmp false
cp: overwrite âtest.copyâ? y
real 0m0.966s
user 0m0.447s
sys 0m0.518s
diff true
real 0m0.785s
user 0m0.211s
sys 0m0.573s
cmp true
[root@mypi shm]# pico /root/rwbscripts/utils/squish.sh
I ran it a couple of times. cmp -s consistently had slightly shorter times on the test box I was using. So if you want to use cmp -s to do things between two files....
identical (){
echo "$1" and "$2" are the same.
echo This is a function, you can put whatever you want in here.
}
different () {
echo "$1" and "$2" are different.
echo This is a function, you can put whatever you want in here, too.
}
cmp -s "$FILEA" "$FILEB" && identical "$FILEA" "$FILEB" || different "$FILEA" "$FILEB"
//Create File object for Parent Directory
File wallpaperDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +File.separator + "wallpaper");
if (!wallpaperDir.exists()) {
wallpaperDir.mkdir();
}
File out = new File(wallpaperDir, wallpaperfile);
FileOutputStream outputStream = new FileOutputStream(out);
Use typeof for elements checks.
if(typeof(element) === 'undefined')
{
// then field does not exist
}
Unicode is a fairly complex standard. Don’t be too afraid, but be prepared for some work! [2]
Because a credible resource is always needed, but the official report is massive, I suggest reading the following:
A brief explanation:
Computers read bytes and people read characters, so we use encoding standards to map characters to bytes. ASCII was the first widely used standard, but covers only Latin (7 bits/character can represent 128 different characters). Unicode is a standard with the goal to cover all possible characters in the world (can hold up to 1,114,112 characters, meaning 21 bits/character max. Current Unicode 8.0 specifies 120,737 characters in total, and that's all).
The main difference is that an ASCII character can fit to a byte (8 bits), but most Unicode characters cannot. So encoding forms/schemes (like UTF-8 and UTF-16) are used, and the character model goes like this:
Every character holds an enumerated position from 0 to 1,114,111 (hex: 0-10FFFF) called code point.
An encoding form maps a code point to a code unit sequence. A code unit is the way you want characters to be organized in memory, 8-bit units, 16-bit units and so on. UTF-8 uses 1 to 4 units of 8 bits, and UTF-16 uses 1 or 2 units of 16 bits, to cover the entire Unicode of 21 bits max. Units use prefixes so that character boundaries can be spotted, and more units mean more prefixes that occupy bits. So, although UTF-8 uses 1 byte for the Latin script it needs 3 bytes for later scripts inside Basic Multilingual Plane, while UTF-16 uses 2 bytes for all these. And that's their main difference.
Lastly, an encoding scheme (like UTF-16BE or UTF-16LE) maps (serializes) a code unit sequence to a byte sequence.
character: p
code point: U+03C0
encoding forms (code units):
UTF-8: CF 80
UTF-16: 03C0
encoding schemes (bytes):
UTF-8: CF 80
UTF-16BE: 03 C0
UTF-16LE: C0 03
Tip: a hex digit represents 4 bits, so a two-digit hex number represents a byte
Also take a look at Plane maps in Wikipedia to get a feeling of the character set layout
You can't search a text field without converting it from text to varchar.
declare @table table (a text)
insert into @table values ('a')
insert into @table values ('a')
insert into @table values ('b')
insert into @table values ('c')
insert into @table values ('d')
select *
from @table
where a ='a'
This give an error:
The data types text and varchar are incompatible in the equal to operator.
Wheras this does not:
declare @table table (a varchar(max))
Interestingly, LIKE
still works, i.e.
where a like '%a%'
The jQuery blog, jQuery 3.1.1 Released!, says,
Slim build
Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for all your web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code. The size of jQuery is very rarely a load performance concern these days, but the slim build is about 6k gzipped bytes smaller than the regular version – 23.6k vs 30k.
Another solution is to use stat_count()
when dealing with discrete variables (and stat_bin()
with continuous ones).
ggplot(data = df, aes(x = x)) +
geom_bar(stat = "count") +
stat_count(geom = "text", colour = "white", size = 3.5,
aes(label = ..count..),position=position_stack(vjust=0.5))
You can use it with your local variables, like this:
@animal = "Dog"
@action = "licks"
@second_animal = "Bird"
"The #{@animal} #{@action} the #{@second_animal}"
the output would be: "The Dog licks the Bird"
I know this is an old question, with quite a few answers, but I was surprised to find that no one was suggesting the naming convention used in the official documentation:
$ docker build -f dockerfiles/Dockerfile.debug -t myapp_debug . $ docker build -f dockerfiles/Dockerfile.prod -t myapp_prod .
The above commands will build the current build context (as specified by the
.
) twice, once using a debug version of aDockerfile
and once using a production version.
In summary, if you have a file called Dockerfile
in the root of your build context it will be automatically picked up. If you need more than one Dockerfile
for the same build context, the suggested naming convention is:
Dockerfile.<purpose>
These dockerfiles could be in the root of your build context or in a subdirectory to keep your root directory more tidy.
Replace (.*")\d+(")
With $1x$2
Where x
is your "value inside scopes".
Node.js is a runtime that compiles and executes javaScript. It can be used to develop application that runs end-to-end in JavaScript i..e both client side and server side uses javascript code unlike most of todays' application with rich client framework (angularJs, extJs) and RESTful server side APIs
I believe pwdencrypt is using a hash so you cannot really reverse the hashed string - the algorithm is designed so it's impossible.
If you are verifying the password that a user entered the usual technique is to hash it and then compare it to the hashed version in the database.
This is how you could verify a usered entered table
SELECT password_field FROM mytable WHERE password_field=pwdencrypt(userEnteredValue)
Replace userEnteredValue with (big surprise) the value that the user entered :)
From pandas version 0.18+ filtering a series can also be done as below
test = {
383: 3.000000,
663: 1.000000,
726: 1.000000,
737: 9.000000,
833: 8.166667
}
pd.Series(test).where(lambda x : x!=1).dropna()
Checkout: http://pandas.pydata.org/pandas-docs/version/0.18.1/whatsnew.html#method-chaininng-improvements
you cant set the iframe height in % because your parent body height is not 100% so make the parent height as 100% and then apply iframe height 100%
For eg.
<html>
<head>
<style>
html,body{height:100%}
</style>
</head>
<body>
<iframe src="http://www.quasarinfosystem.com" height="100%" width="100%" ></iframe>
</body>
</html>
you can do something like this
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
Reference is https://laravel.com/docs/5.1/collections#method-toarray
Originally from Laracasts website https://laracasts.com/discuss/channels/laravel/how-to-convert-this-collection-to-an-array
Proximity Sensor Dial
*#*#7378423#*#*
1) Service Tests - (If present)
2) Proximity Switch
3) Test on sensor (Next to logo(top) of mobile)
4) Yes if works, then u can keep on and proximity switch forever which gives beep all the time and consumes lot of battery
OR
4) No it doesn't work - Then simply clean the mobile screen or screen guard and clear the blocked screen from sensor. It works charm.
Technically, Its not any software solution, but hardware solution will work.
Just a note in case others have the same problem.
I had the same problem and found a different answer. I found that getting the height of a div that's height is determined by its contents needs to be initiated on window.load, or window.scroll not document.ready otherwise i get odd heights/smaller heights, i.e before the images have loaded. I also used outerHeight().
var currentHeight = 0;
$(window).load(function() {
//get the natural page height -set it in variable above.
currentHeight = $('#js_content_container').outerHeight();
console.log("set current height on load = " + currentHeight)
console.log("content height function (should be 374) = " + contentHeight());
});
Using CliWrap:
var result = await Cli.Wrap("foobar.bat").ExecuteBufferedAsync();
var exitCode = result.ExitCode;
var stdOut = result.StandardOutput;
The easiest way to compute the correct mouse click or mouse move position on a canvas event is to use this little equation:
canvas.addEventListener('click', event =>
{
let bound = canvas.getBoundingClientRect();
let x = event.clientX - bound.left - canvas.clientLeft;
let y = event.clientY - bound.top - canvas.clientTop;
context.fillRect(x, y, 16, 16);
});
If the canvas has padding-left or padding-top, subtract x and y via:
x -= parseFloat(style['padding-left'].replace('px'));
y -= parseFloat(style['padding-top'].replace('px'));
i am using centos
and getting same error when run mvn
command with goal, install
. After some googling i have found the solution to run following command.
sudo yum install java-1.8.0-openjdk-devel
So, let's say you have this table:
CREATE TABLE YourTable(Col1 VARCHAR(10))
And you want to change Col1
to VARCHAR(20)
. What you need to do is this:
ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)
That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5)
, then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE
will fail.
All one need is to go into MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window g = getWindow();
g.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
setContentView(R.layout.activity_main);
}
Another option to include_once or require_once is to use class autoloading. http://php.net/manual/en/language.oop5.autoload.php
Use the P
format string. This will vary by culture:
String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)
I created an insecure but simple text cipher/decipher util. No dependencies with any external library.
These are the functions
const cipher = salt => {
const textToChars = text => text.split('').map(c => c.charCodeAt(0));
const byteHex = n => ("0" + Number(n).toString(16)).substr(-2);
const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
return text => text.split('')
.map(textToChars)
.map(applySaltToChar)
.map(byteHex)
.join('');
}
const decipher = salt => {
const textToChars = text => text.split('').map(c => c.charCodeAt(0));
const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
return encoded => encoded.match(/.{1,2}/g)
.map(hex => parseInt(hex, 16))
.map(applySaltToChar)
.map(charCode => String.fromCharCode(charCode))
.join('');
}
And you can use them as follows:
// To create a cipher
const myCipher = cipher('mySecretSalt')
//Then cipher any text:
myCipher('the secret string') // --> "7c606d287b6d6b7a6d7c287b7c7a61666f"
//To decipher, you need to create a decipher and use it:
const myDecipher = decipher('mySecretSalt')
myDecipher("7c606d287b6d6b7a6d7c287b7c7a61666f") // --> 'the secret string'
In Node.js, you could use:
console.log('Current directory: ' + process.cwd());
I get get the same minicom error, "cannot open /dev/ttyUSB0: No such file or directory"
Three notes:
I get the error when the device attached to the serial port end of my Prolific Technology PL2303 USB/Serial adapter is turned off. After turning on the device (an embedded controller running Linux) minicom connected fine.
I have to run as super user (i.e. sudo minicom
)
Sometimes I have to unplug and plug back in the USB-to-serial adapter to get minicom to connect to it.
I am running Ubuntu 10.04 LTS (Lucid Lynx) under VMware (running on Windows 7). In this situation, make sure the device is attached to VM operating system by right clicking on the USB/Serial USB icon in the lower right of the VMware window and select Connect (Disconnect from Host).
Remember to press Ctrl + A to get minicom's prompt, and type X to exit the program. Just exiting the terminal session running minicom will leave the process running.
This is quote from the book "Programming in Go: Creating Applications for the 21st Century":
Using a simple linear search like this is the only option for unsorted data and is fine for small slices (up to hundreds of items). But for larger slices—especially if we are performing searches repeatedly—the linear search is very inefficient, on average requiring half the items to be compared each time.
Go provides a sort.Search() method which uses the binary search algorithm: This requires the comparison of only log2(n) items (where n is the number of items) each time. To put this in perspective, a linear search of 1000000 items requires 500000 comparisons on average, with a worst case of 1000000 comparisons; a binary search needs at most 20 comparisons, even in the worst case.
files := []string{"Test.conf", "util.go", "Makefile", "misc.go", "main.go"}
target := "Makefile"
sort.Strings(files)
i := sort.Search(len(files),
func(i int) bool { return files[i] >= target })
if i < len(files) && files[i] == target {
fmt.Printf("found \"%s\" at files[%d]\n", files[i], i)
}
With Python 3.2 and later, you can use int.to_bytes
and int.from_bytes
: https://docs.python.org/3/library/stdtypes.html#int.to_bytes
One common error is leaving a space before the class names. Even if this was the correct syntax:
.menu a:hover .main-nav-item
it never would have worked.
Therefore, you would not write
.menu a .main-nav-item:hover
it would be
.menu a.main-nav-item:hover
Like timber said - "Java 8 Collection has a nice method called removeIf that makes things easier and safer"
Here is the code that solve your problem:
set.removeIf((Integer element) -> {
return (element % 2 == 0);
});
Now your set contains only odd values.
for large data set and multiple value drop down it is better to use ng-options
rather than ng-repeat
.
ng-repeat
is slow because it loops over all coming values but ng-options
simply display to the select option.
ng-options='state.StateCode as state.StateName for state in States'>
much much faster than
<option ng-repeat="state in States" value="{{state.StateCode}}">
{{state.StateName }}
</option>
yes you can by using static class. like this:
static class Global
{
private static string _globalVar = "";
public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
}
and for using any where you can write:
GlobalClass.GlobalVar = "any string value"
Unless you're looking for something specific, you can already do Regular Expression matching using regular Javascript with strings.
For example, you can do matching using a string by something like this...
var phrase = "This is a phrase";
phrase = phrase.replace(/is/i, "is not");
alert(phrase);
Is there something you're looking for other than just Regular Expression matching in general?
On the off chance anyone else ever runs into this extremely specific issue..
Something inside PyTorch breaks DLL loading. Once you run import torch
, any further DLL loads will fail. So if you're using PyTorch and loading your own DLLs you'll have to rearrange your code to import all DLLs first. Confirmed w/ PyTorch 1.5.0 on Python 3.7
A better solution without if-else:
$(document).ready(function() {
$("#chkdwn2").click(function() {
$("#dropdown").prop("disabled", this.checked);
});
});
$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor
This is documented in the Shell Parameter Expansion section of the manual:
${parameter#word}
${parameter##word}
The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the
#
case) or the longest matching pattern (the##
case) deleted. […]
${parameter%word}
${parameter%%word}
The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the
%
case) or the longest matching pattern (the%%
case) deleted. […]
On a SpringBoot project using IntelliJ and Gradle, I got the warning "Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0" when running my integration test. What solved the problem was: - Going to: File > Settings > Build, Execution, Deployment - Selecting for "Build and run using": Intellij IDEA (instead of "Gradle") - Same for "Run tests using" That did not explain why Gradle is displaying the warning, but that let me perform the test and progress in my work.
Go to the .project file of your project make sure it display the same name as displayed in project folder. if not change the name. it will work.
I've had the same exact problem in that I installed Anaconda because a python script I want to use relies on pandas, and that after so doing, python still returned the same comment that "pandas module is missing" or something to that effect.
When I typed "python" to see which python was being called, I found it was still accessing the older version of python 2.7, even though when I installed Anaconda the installer asked (and I agreed) that it would make its python the default python on my machine (PC running Windows 7).
I tried to find if there is a CONFIG.SYS file on the PC, but gave up after searching in various places (If anyone knows, please tell me). I got around the problem by writing a one-line batch script named python2.bat that called the Anaconda2 version of python, which then worked. However, it would clearly be better to change the CONFIG.SYS or whatever the PC uses to decide which version of python to call.
I assume X
and Y
are arrays? If so, there's a very simple way to do this:
x = [1, 1, 2, 4]
y = [1, 2, 2, 2]
# intersection
x & y # => [1, 2]
# union
x | y # => [1, 2, 4]
# difference
x - y # => [4]
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.
I created an abstraction layer over FPDI (might accommodate other engines). I published it as a Symfony2 bundle depending on a library, and as the library itself.
usage:
public function handlePdfChanges(Document $document, array $formRawData)
{
$oldPath = $document->getUploadRootDir($this->kernel) . $document->getOldPath();
$newTmpPath = $document->getFile()->getRealPath();
switch ($formRawData['insertOptions']['insertPosition']) {
case PdfInsertType::POSITION_BEGINNING:
// prepend
$newPdf = $this->pdfManager->insert($oldPath, $newTmpPath);
break;
case PdfInsertType::POSITION_END:
// Append
$newPdf = $this->pdfManager->append($oldPath, $newTmpPath);
break;
case PdfInsertType::POSITION_PAGE:
// insert at page n: PdfA={p1; p2; p3}, PdfB={pA; pB; pC}
// insert(PdfA, PdfB, 2) will render {p1; pA; pB; pC; p2; p3}
$newPdf = $this->pdfManager->insert(
$oldPath, $newTmpPath, $formRawData['insertOptions']['pageNumber']
);
break;
case PdfInsertType::POSITION_REPLACE:
// does nothing. overrides old file.
return;
break;
}
$pageCount = $newPdf->getPageCount();
$newPdf->renderFile($mergedPdfPath = "$newTmpPath.merged");
$document->setFile(new File($mergedPdfPath, true));
return $pageCount;
}
Here is another way of doing it
public DataSet CreateTable(string source)
{
using (var connection = new OleDbConnection(GetConnectionString(source, true)))
{
var dataSet = new DataSet();
connection.Open();
var schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (schemaTable == null)
return dataSet;
var sheetName = "";
foreach (DataRow row in schemaTable.Rows)
{
sheetName = row["TABLE_NAME"].ToString();
break;
}
var command = string.Format("SELECT * FROM [{0}$]", sheetName);
var adapter = new OleDbDataAdapter(command, connection);
adapter.TableMappings.Add("TABLE", "TestTable");
adapter.Fill(dataSet);
connection.Close();
return dataSet;
}
}
//
private string GetConnectionString(string source, bool hasHeader)
{
return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
Extended Properties=\"Excel 12.0;HDR={1};IMEX=1\"", source, (hasHeader ? "YES" : "NO"));
}
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
The difference comes in when you use the struct
.
The first way you have to do:
struct myStruct aName;
The second way allows you to remove the keyword struct
.
myStruct aName;
Python's power operator is **
and Euler's number is math.e
, so:
from math import e
x.append(1-e**(-value1**2/2*value2**2))
My use case was to save range to variable and then select it later on
Dim targetRange As Range
Set targetRange = Sheets("Sheet").Range("Name")
Application.Goto targetRange
Set targetRangeQ = Nothing ' reset
Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
// Your Extended Properties
public long? OrganizationId { get; set; }
}
Then what you need is to create an extension method like so (I create mine in an new Extensions folder):
namespace App.Extensions
{
public static class IdentityExtensions
{
public static string GetOrganizationId(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
}
When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here => this.OrganizationId is a value stored in database against the user
userIdentity.AddClaim(new Claim("OrganizationId", this.OrganizationId.ToString()));
return userIdentity;
}
Once you added the claim and have your extension method in place, to make it available as a property on your User.Identity, add a using statement on the page/file you want to access it:
in my case: using App.Extensions;
within a Controller and @using. App.Extensions
withing a .cshtml View file.
EDIT:
What you can also do to avoid adding a using statement in every View is to go to the Views folder, and locate the Web.config file in there.
Now look for the <namespaces>
tag and add your extension namespace there like so:
<add namespace="App.Extensions" />
Save your file and you're done. Now every View will know of your extensions.
You can access the Extension Method:
var orgId = User.Identity.GetOrganizationId();
When you install your python version (in this case it is python2.6) then issue this command to create your virtualenv
:
virtualenv -p /usr/bin/python2.6 /your/virtualenv/path/here/
first you run the command mongod and check weather the port 27017 has started or not if yes then hit the command mongo....and database will start.
s3cmd can show you this by running s3cmd du
, optionally passing the bucket name as an argument.
I used the command
ansible -i inventory example -m ping -u <your_user_name> --ask-pass
And it will ask for your password.
For anyone who gets the error:
to use the 'ssh' connection type with passwords, you must install the sshpass program
On MacOS, you can follow below instructions to install sshpass:
For me this approach works:
The dialog may be closed by clicking the X on the dialog or by clicking 'Bewaren'. I'm adding an (arbitrary) id because I need to be sure every bit of html added to the dom is removed afterwards.
$('<div id="dossier_edit_form_tmp_id">').html(data.form)
.data('dossier_id',dossier_id)
.dialog({
title: 'Opdracht wijzigen',
show: 'clip',
hide: 'clip',
minWidth: 520,
width: 520,
modal: true,
buttons: { 'Bewaren': dossier_edit_form_opslaan },
close: function(event, ui){
$(this).dialog('destroy');
$('#dossier_edit_form_tmp_id').remove();
}
});
During testing I found that foreach loop after break go to the loop beging and not out of the loop. So I changed foreach into for and break in this case work correctly- after break program flow goes out of the loop.
You can either pass the parameter in the task constructor or when you call execute:
AsyncTask<Object, Void, MyTaskResult>
The first parameter (Object) is passed in doInBackground. The third parameter (MyTaskResult) is returned by doInBackground. You can change them to the types you want. The three dots mean that zero or more objects (or an array of them) may be passed as the argument(s).
public class MyActivity extends AppCompatActivity {
TextView textView1;
TextView textView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textView1 = (TextView) findViewById(R.id.textView1);
textView2 = (TextView) findViewById(R.id.textView2);
String input1 = "test";
boolean input2 = true;
int input3 = 100;
long input4 = 100000000;
new MyTask(input3, input4).execute(input1, input2);
}
private class MyTaskResult {
String text1;
String text2;
}
private class MyTask extends AsyncTask<Object, Void, MyTaskResult> {
private String val1;
private boolean val2;
private int val3;
private long val4;
public MyTask(int in3, long in4) {
this.val3 = in3;
this.val4 = in4;
// Do something ...
}
protected void onPreExecute() {
// Do something ...
}
@Override
protected MyTaskResult doInBackground(Object... params) {
MyTaskResult res = new MyTaskResult();
val1 = (String) params[0];
val2 = (boolean) params[1];
//Do some lengthy operation
res.text1 = RunProc1(val1);
res.text2 = RunProc2(val2);
return res;
}
@Override
protected void onPostExecute(MyTaskResult res) {
textView1.setText(res.text1);
textView2.setText(res.text2);
}
}
}
For just copying (possibly long) texts to the Windows clipboard, I have found that just piping the output to clip.exe
(including the .exe
file extension) works fine for me. So:
$ echo "Hello World" | clip.exe
lets me paste Hello World
using Ctrl-V anywhere else.
Now that I have posted this, I notice that related question Pipe from clipboard in linux subsytem for windows includes this and a command solution for pasting from the Windows clipboard as well.
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
Try to remove any trace of cocoapods pods using pod deintegrate
then
Run pod install
simplejson
and json
don't work with django objects well.
Django's built-in serializers can only serialize querysets filled with django objects:
data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")
In your case, self.get_queryset()
contains a mix of django objects and dicts inside.
One option is to get rid of model instances in the self.get_queryset()
and replace them with dicts using model_to_dict
:
from django.forms.models import model_to_dict
data = self.get_queryset()
for item in data:
item['product'] = model_to_dict(item['product'])
return HttpResponse(json.simplejson.dumps(data), mimetype="application/json")
Hope that helps.
The list.append
function does not return any value(but None
), it just adds the value to the list you are using to call that method.
In the first loop round you will assign None
(because the no-return of append
) to a
, then in the second round it will try to call a.append
, as a is None
it will raise the Exception you are seeing
You just need to change it to:
a=[]
for i in range(5):
a.append(i)
print(a)
# [0, 1, 2, 3, 4]
list.append
is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).
If you would like to create a new list based in one list without destroying or mutating it you can do something like this:
a=['a', 'b', 'c']
result = a + ['d']
print result
# ['a', 'b', 'c', 'd']
print a
# ['a', 'b', 'c']
As a corollary only, you can mimic the append
method by doing the following:
a=['a', 'b', 'c']
a = a + ['d']
print a
# ['a', 'b', 'c', 'd']
Because static methods cannot be overridden in subclasses, and hence they cannot be abstract. And all methods in an interface are, de facto, abstract.
If your strings are in Unicode you should use preg_split
with /u
modifier
From comments in php documentation:
function mb_str_split( $string ) {
# Split at all position not after the start: ^
# and not before the end: $
return preg_split('/(?<!^)(?!$)/u', $string );
}
My understanding is that interfaces are not that necessary in dynamic languages like Python. In Java (or C++ with its abstract base class) interfaces are means for ensuring that e.g. you're passing the right parameter, able to perform set of tasks.
E.g. if you have observer and observable, observable is interested in subscribing objects that supports IObserver interface, which in turn has notify
action. This is checked at compile time.
In Python, there is no such thing as compile time
and method lookups are performed at runtime. Moreover, one can override lookup with __getattr__() or __getattribute__() magic methods. In other words, you can pass, as observer, any object that can return callable on accessing notify
attribute.
This leads me to the conclusion, that interfaces in Python do exist - it's just their enforcement is postponed to the moment in which they are actually used
IE trick for dynamic forms:
$('#someform').find('input,select,textarea').serialize();
This just allow positive integers.
^[0-9]*[1-9][0-9]*$
Easy way
As described here, there is an existing method in the matplotlib.pyplot
figure
class that automatically rotates dates appropriately for you figure.
You can call it after you plot your data (i.e.ax.plot(dates,ydata)
:
fig.autofmt_xdate()
If you need to format the labels further, checkout the above link.
Non-datetime objects
As per languitar's comment, the method I suggested for non-datetime xticks
would not update correctly when zooming, etc. If it's not a datetime
object used as your x-axis data, you should follow Tommy's answer:
for tick in ax.get_xticklabels():
tick.set_rotation(45)
What I suggest for now is to create symlinks in a folder, since VSCode isn't supporting that feature.
First, make a folder called whatever you'd like it to be.
$ mkdir random_project_folder
$ cd random_project_folder
$ ln -s /path/to/folder1/you/want/to/open folder1
$ ln -s /path/to/folder2/you/want/to/open folder2
$ ln -s /path/to/folder3/you/want/to/open folder3
$ code .
And you'll see your folders in the same VSCode window.
Identify the hash of the commit, using git log
, then use git revert <commit>
to create a new commit that removes these changes. In a way, git revert
is the converse of git cherry-pick
-- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.
I use the following:
Date.prototype.getUTCTime = function(){
return this.getTime()-(this.getTimezoneOffset()*60000);
};
Once defined this method you can do:
var utcTime = new Date().getUTCTime();
You either need to keep creating new objects, or clone the existing one. See What is the most efficient way to deep clone an object in JavaScript? for how to clone.
Set up a flux container
simple example
import alt from './../../alt.js';
class PostActions {
constructor(){
this.generateActions('setMessages');
}
setMessages(indexArray){
this.actions.setMessages(indexArray);
}
}
export default alt.createActions(PostActions);
store looks like this
class PostStore{
constructor(){
this.messages = [];
this.bindActions(MessageActions);
}
setMessages(messages){
this.messages = messages;
}
}
export default alt.createStore(PostStore);
Then every component that listens to the store can share this variable In your constructor is where you should grab it
constructor(props){
super(props);
//here is your data you get from the store, do what you want with it
var messageStore = MessageStore.getState();
}
componentDidMount() {
MessageStore.listen(this.onMessageChange.bind(this));
}
componentWillUnmount() {
MessageStore.unlisten(this.onMessageChange.bind(this));
}
onMessageChange(state){
//if the data ever changes each component listining will be notified and can do the proper processing.
}
This way, you can share you data across the app without every component having to communicate with each other.
End of the user session means when the browser is shut down.
Read this: http://en.wikipedia.org/wiki/HTTP_cookie#Expires_and_Max-Age
You can use the flip commands numpy.flipud()
or numpy.fliplr()
to get the indexes in descending order after sorting using the argsort
command. Thats what I usually do.
- have names, unlike constructors, which can clarify code.
- do not need to create a new object upon each invocation - objects can be cached and reused, if necessary.
- can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller. This is a very valuable and widely used feature in many frameworks which use interfaces as the return type of static factory methods.
1.
Type t = typeof(obj1);
if (t == typeof(int))
This is illegal, because typeof
only works on types, not on variables. I assume obj1 is a variable. So, in this way typeof
is static, and does its work at compile time instead of runtime.
2.
if (obj1.GetType() == typeof(int))
This is true
if obj1
is exactly of type int
. If obj1
derives from int
, the if condition will be false
.
3.
if (obj1 is int)
This is true
if obj1
is an int
, or if it derives from a class called int
, or if it implements an interface called int
.
While debugging System.Diagnostics.Debug.WriteLine
will display in the output window (Ctrl+Alt+O), you can also add a TraceListener
to the Debug.Listeners
collection to specify Debug.WriteLine
calls to output in other locations.
Note: Debug.WriteLine
calls may not display in the output window if you have the Visual Studio option "Redirect all Output Window text to the Immediate Window" checked under the menu Tools ? Options ? Debugging ? General. To display "Tools ? Options ? Debugging", check the box next to "Tools ? Options ? Show All Settings".
Each time the same will be generated:
if let uuid = UIDevice.current.identifierForVendor?.uuidString {
print(uuid)
}
Each time a new one will be generated:
let uuid = UUID().uuidString
print(uuid)
It seems to me that simply: ls -lt mydirectory
does the job...
Well if you know the order of your words.. you can use:
SELECT `name` FROM `table` WHERE `name` REGEXP 'Stylus.+2100'
Also you can use:
SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%' AND `name` LIKE '%2100%'
an exapansion on Gala's answer that will also include the causes for the exception:
private String extrapolateStackTrace(Exception ex) {
Throwable e = ex;
String trace = e.toString() + "\n";
for (StackTraceElement e1 : e.getStackTrace()) {
trace += "\t at " + e1.toString() + "\n";
}
while (e.getCause() != null) {
e = e.getCause();
trace += "Cause by: " + e.toString() + "\n";
for (StackTraceElement e1 : e.getStackTrace()) {
trace += "\t at " + e1.toString() + "\n";
}
}
return trace;
}
Add reference > Browse > C: > Windows > assembly > GAC > Microsoft.Office.Interop.Excel > 12.0.0.0_wasd.. > Microsoft.Office.Interop.Excel.dll
Try this:
// I suppose you have already set your JFrame
Icon imgIcon = new ImageIcon(this.getClass().getResource("ajax-loader.gif"));
JLabel label = new JLabel(imgIcon);
label.setBounds(668, 43, 46, 14); // for example, you can use your own values
frame.getContentPane().add(label);
Found on this tutorial on how to display animated gif in java
Or live on youtube : https://youtu.be/_NEnhm9mgdE
You can use Array.push()
for appending elements to an array.
For deleting, it is best to use this.$delete(array, index)
for reactive objects.
Vue.delete( target, key )
: Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:
http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/
I added the snippet below as a tl;dr
#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
case $OPTION in
h)
usage
exit 1
;;
t)
TEST=$OPTARG
;;
r)
SERVER=$OPTARG
;;
p)
PASSWD=$OPTARG
;;
v)
VERBOSE=1
;;
?)
usage
exit
;;
esac
done
if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
usage
exit 1
fi
./script.sh -t test -r server -p password -v
In navigateExtra we can pass only some specific name as argument otherwise it showing error like below: For Ex- Here I want to pass customer key in router navigate and I pass like this-
this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});
but it showing some error like below:
Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'
.
Solution: we have to write like this:
this.Router.navigate(['componentname'],{state: {customerkey:response.key}});
To do this in any ES5-compatible environment, such as Node, Chrome, IE 9+, Firefox 4+, or Safari 5+:
Object.keys(obj).length
almost a decade passed but the issue still valid with Asp.Net Core 2.2 as well.
I managed it by adding data-val-number
to the input field the use localization on the message:
<input asp-for="Age" data-val-number="@_localize["Please enter a valid number."]"/>
As Jose answered, screen -d -r
should do the trick. This is a combination of two commands, as taken from the man page.
screen -d
detaches the already-running screen session, and screen -r
reattaches the existing session. By running screen -d -r
, you force screen to detach it and then resume the session.
If you use the capital -D -RR
, I quote the man page because it's too good to pass up.
Attach here and now. Whatever that means, just do it.
Note: It is always a good idea to check the status of your sessions by means of "screen -list".
I think you can change your query and try it like :
$res=User::where('id',$id)->delete();
strSearch in this case is probably null (not simply empty).
Try using
String.IsNullOrEmpty(strSearch)
if you are just trying to determine if the string doesn't have any contents.
To turn line numbers on by default in all cells at startup I recommend this link. I quote:
Navigate to your jupyter config directory, which you can find by typing the following at the command line:
jupyter --config-dir
From there, open or create the
custom
folder.In that folder, you should find a
custom.js
file. If there isn’t one, you should be able to create one. Open it in a text editor and add this code:define([ 'base/js/namespace', 'base/js/events' ], function(IPython, events) { events.on("app_initialized.NotebookApp", function () { IPython.Cell.options_default.cm_config.lineNumbers = true; } ); } );
Have you tried HttpServerUtility.UrlDecode
or HttpUtility.UrlDecode
?
If your script always requires an Administrator's privileges then:
runas /user:Administrator "python your_script.py"
Use the "has attribute" selector:
$('p[MyTag]')
Or to select one where that attribute has a specific value:
$('p[MyTag="Sara"]')
There are other selectors for "attribute value starts with", "attribute value contains", etc.
Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.
Diamond inheritance runnable usage example
This example shows how to use a virtual base class in the typical scenario: to solve diamond inheritance problems.
Consider the following working example:
main.cpp
#include <cassert>
class A {
public:
A(){}
A(int i) : i(i) {}
int i;
virtual int f() = 0;
virtual int g() = 0;
virtual int h() = 0;
};
class B : public virtual A {
public:
B(int j) : j(j) {}
int j;
virtual int f() { return this->i + this->j; }
};
class C : public virtual A {
public:
C(int k) : k(k) {}
int k;
virtual int g() { return this->i + this->k; }
};
class D : public B, public C {
public:
D(int i, int j, int k) : A(i), B(j), C(k) {}
virtual int h() { return this->i + this->j + this->k; }
};
int main() {
D d = D(1, 2, 4);
assert(d.f() == 3);
assert(d.g() == 5);
assert(d.h() == 7);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
If we remove the virtual
into:
class B : public virtual A
we would get a wall of errors about GCC being unable to resolve D members and methods that were inherited twice via A:
main.cpp:27:7: warning: virtual base ‘A’ inaccessible in ‘D’ due to ambiguity [-Wextra]
27 | class D : public B, public C {
| ^
main.cpp: In member function ‘virtual int D::h()’:
main.cpp:30:40: error: request for member ‘i’ is ambiguous
30 | virtual int h() { return this->i + this->j + this->k; }
| ^
main.cpp:7:13: note: candidates are: ‘int A::i’
7 | int i;
| ^
main.cpp:7:13: note: ‘int A::i’
main.cpp: In function ‘int main()’:
main.cpp:34:20: error: invalid cast to abstract class type ‘D’
34 | D d = D(1, 2, 4);
| ^
main.cpp:27:7: note: because the following virtual functions are pure within ‘D’:
27 | class D : public B, public C {
| ^
main.cpp:8:21: note: ‘virtual int A::f()’
8 | virtual int f() = 0;
| ^
main.cpp:9:21: note: ‘virtual int A::g()’
9 | virtual int g() = 0;
| ^
main.cpp:34:7: error: cannot declare variable ‘d’ to be of abstract type ‘D’
34 | D d = D(1, 2, 4);
| ^
In file included from /usr/include/c++/9/cassert:44,
from main.cpp:1:
main.cpp:35:14: error: request for member ‘f’ is ambiguous
35 | assert(d.f() == 3);
| ^
main.cpp:8:21: note: candidates are: ‘virtual int A::f()’
8 | virtual int f() = 0;
| ^
main.cpp:17:21: note: ‘virtual int B::f()’
17 | virtual int f() { return this->i + this->j; }
| ^
In file included from /usr/include/c++/9/cassert:44,
from main.cpp:1:
main.cpp:36:14: error: request for member ‘g’ is ambiguous
36 | assert(d.g() == 5);
| ^
main.cpp:9:21: note: candidates are: ‘virtual int A::g()’
9 | virtual int g() = 0;
| ^
main.cpp:24:21: note: ‘virtual int C::g()’
24 | virtual int g() { return this->i + this->k; }
| ^
main.cpp:9:21: note: ‘virtual int A::g()’
9 | virtual int g() = 0;
| ^
./main.out
Tested on GCC 9.3.0, Ubuntu 20.04.
A bit shorter answer since PHP >= 5.3.0:
$csvFile = file('../somefile.csv');
$data = [];
foreach ($csvFile as $line) {
$data[] = str_getcsv($line);
}
I had this issue when I was accidentally using the WRONG "uuid" in my child record. When that happens the constraint looks from the child to the parent record to ensure that the link is correct. I was generating it manually, when I had already rigged my Model to do it automatically. So my fix was:
$parent = Parent:create($recData); // asssigning autogenerated uuid into $parent
Then when I called my child class to insert children, I passed this var value:
$parent->uuid
Hope that helps.
All the fixes currently mentioned here basically enable the security hole all over again.
What I ended up doing is adding the following lines to my PHP-FPM configuration file.
listen.owner = www-data
listen.group = www-data
Make sure that www-data is actually the user the nginx worker is running as. For debian it's www-data by default.
Doing it this way does not enable the security problem that this change was supposed to fix.
My best guess is that they ran out of brackets and didn't think it would be useful enough to warrent adding an "ugly" syntax ...
When is a Boolean neither True nor False?
Bill discovered that you can hack a boolean so that if A is True and B is True, (A and B) is False.
Another cause might be the fact that you're pointing to the wrong port.
Make sure you are actually pointing to the right SQL server. You may have a default installation of MySQL running on 3306 but you may actually be needing a different MySQL instance.
Check the ports and run some query against the db.
If you don't like using multi-inheritance, use extends
and implements
together to stay safe.
class C extends B implements A {
// implements A here
}