I had to use strcpy_s and it worked.
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
struct student
{
char name[30];
int age;
};
int main()
{
struct student s1;
char myname[30] = "John";
strcpy_s (s1.name, strlen(myname) + 1 ,myname );
s1.age = 21;
cout << " Name: " << s1.name << " age: " << s1.age << endl;
return 0;
}
Async HTTP client loopj vs. Volley
The specifics of my project are small HTTP REST requests, every 1-5 minutes.
I using an async HTTP client (1.4.1) for a long time. The performance is better than using the vanilla Apache httpClient or an HTTP URL connection. Anyway, the new version of the library is not working for me: library inter exception cut chain of callbacks.
Reading all answers motivated me to try something new. I have chosen the Volley HTTP library.
After using it for some time, even without tests, I see clearly that the response time is down to 1.5x, 2x Volley.
Maybe Retrofit is better than an async HTTP client? I need to try it. But I'm sure that Volley is not for me.
Have you tried using the JQuery
change event?
$("#g01-01").change(function() {
if(this.checked) {
//Do stuff
}
});
Then you can also remove onchange="doalert(this.id)"
from your checkbox :)
Edit:
I don't know if you are using JQuery
, but if you're not yet using it, you will need to put the following script in your page so you can use it:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Here's the jQuery way to do it:
$('#calendar').attr('src', loc);
I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
For more details see:
One notable difference in Python 2 is that if you're using ensure_ascii=False
, dump
will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):
dumps
on the other hand, with ensure_ascii=False
can produce a str
or unicode
just depending on what types you used for strings:
Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a
unicode
instance.
(emphasis mine). Note that it may still be a str
instance as well.
Thus you cannot use its return value to save the structure into file without checking which
format was returned and possibly playing with unicode.encode
.
This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.
As for load
vs loads
, load
considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.
You can use the expect
utility to drive all programs that read from a tty (as opposed to stdin, which is what passwd does). Expect comes with ready to run examples for all sorts of interactive problems, like passwd entry.
Yes, I understood your problem. If is difficult to identify cell has Numeric or Data value.
If you want data in format that shows in Excel, you just need to format cell using DataFormatter class.
DataFormatter dataFormatter = new DataFormatter();
String cellStringValue = dataFormatter.formatCellValue(row.getCell(0));
System.out.println ("Is shows data as show in Excel file" + cellStringValue); // Here it automcatically format data based on that cell format.
// No need for extra efforts
My solution was to insert <packaging>pom</packaging>
between artifactId
and version
<groupId>com.onlinechat</groupId>
<artifactId>chat-online</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>server</module>
<module>client</module>
<module>network</module>
</modules>
I have recently written a plugin that does exactly that - jquery.initialize
You use it the same way as .each
function
$(".some-element").initialize( function(){
$(this).css("color", "blue");
});
The difference from .each
is - it takes your selector, in this case .some-element
and wait for new elements with this selector in the future, if such element will be added, it will be initialized too.
In our case initialize function just change element color to blue. So if we'll add new element (no matter if with ajax or even F12 inspector or anything) like:
$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!
Plugin will init it instantly. Also plugin makes sure one element is initialized only once. So if you add element, then .detach()
it from body and then add it again, it will not be initialized again.
$("<div/>").addClass('some-element').appendTo("body").detach()
.appendTo(".some-container");
//initialized only once
Plugin is based on MutationObserver
- it will work on IE9 and 10 with dependencies as detailed on the readme page.
you can also try something like this as well
<input type="button" value="text" name="text" onClick="{action}; return false" class="fwm_button">
and CSS class
.fwm_button {
color: white;
font-weight: bold;
background-color: #6699cc;
border: 2px outset;
border-top-color: #aaccff;
border-left-color: #aaccff;
border-right-color: #003366;
border-bottom-color: #003366;
}
An example is given here
Using round
:
>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'
It will/may be empty when the enduser
First check the list contains some values:
if (list.isEmpty()) {
listview.setVisibility(View.GONE);
}
If it is then OK, otherwise use:
else {
listview.setVisibility(View.VISIBLE);
}
Starting in Python 3.9
, you can use removesuffix
instead:
'abcdc.com'.removesuffix('.com')
# 'abcdc'
For version v2.2.2 and newer
In version v2.2.2 and up, name property no longer exists and it shouldn't be used to define the route. path should be used instead of name and no leading slash is needed on the path. In this case use path: '404'
instead of path: '/404'
:
{path: '404', component: NotFoundComponent},
{path: '**', redirectTo: '/404'}
For versions older than v2.2.2
you can use {path: '/*path', redirectTo: ['redirectPathName']}
:
{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},
{path: '/*path', redirectTo: ['NotFound']}
if no path matches then redirect to NotFound
path
MOD() function exists in both Oracle and MySQL, but not in SQL Server.
In SQL Server, try this:
SELECT * FROM Orders where OrderID % 2 = 0;
I had this issue with an image gallery that I wanted to rerender due to changes made on a different tab. So tab1 = imageGallery, tab2 = favoriteImages
tab @change="updateGallery()" -> this forces my v-for directive to process the filteredImages function every time I switch tabs.
<script>
export default {
data() {
return {
currentTab: 0,
tab: null,
colorFilter: "",
colors: ["None", "Beige", "Black"],
items: ["Image Gallery", "Favorite Images"]
};
},
methods: {
filteredImages: function() {
return this.$store.getters.getImageDatabase.filter(img => {
if (img.color.match(this.colorFilter)) return true;
});
},
updateGallery: async function() {
// instance is responsive to changes
// change is made and forces filteredImages to do its thing
// async await forces the browser to slow down and allows changes to take effect
await this.$nextTick(function() {
this.colorFilter = "Black";
});
await this.$nextTick(function() {
// Doesnt hurt to zero out filters on change
this.colorFilter = "";
});
}
}
};
</script>
Try this more succinct code:
Sub LoopOverEachColumn()
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
ResizeColumns WS
Next WS
End Sub
Private Sub ResizeColumns(WS As Worksheet)
Dim StrSize As String
Dim ColIter As Long
StrSize = "20.14;9.71;35.86;30.57;23.57;21.43;18.43;23.86;27.43;36.71;30.29;31.14;31;41.14;33.86"
For ColIter = 1 To 15
WS.Columns(ColIter).ColumnWidth = Split(StrSize, ";")(ColIter - 1)
Next ColIter
End Sub
If you want additional columns, just change 1 to 15
to 1 to X
where X
is the column index of the column you want, and append the column size you want to StrSize
.
For example, if you want P:P
to have a width of 25
, just add ;25
to StrSize
and change ColIter...
to ColIter = 1 to 16
.
Hope this helps.
The output of dpkg -s ...
demonstrates that docker-compose
is not installed from a package. Without more information from you there are at least two possibilities:
docker-compose simply isn't installed at all, and you need to install it.
The solution here is simple: install docker-compose
.
docker-compose is installed in your $HOME
directory (or other location not on root's $PATH
).
There are several solution in this case. The easiest is probably to replace:
sudo docker-compose ...
With:
sudo `which docker-compose` ...
This will call sudo
with the full path to docker-compose
.
You could alternatively install docker-compose
into a system-wide directory, such as /usr/local/bin
.
Just add to the CommandArgument
parameter and read it out on the Click
handler:
<asp:LinkButton ID="ENameLinkBtn" runat="server"
style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere"
OnClick="ENameLinkBtn_Click" >
Then in your click event:
protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string yourValue = btn.CommandArgument;
// do what you need here
}
Also you can set the CommandArgument
argument when binding if you are using the LinkButton
in any bindable controls by doing:
CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'
Import System.Web Or call the System.Web.HttpUtility which contains it
You will need to add the reference to the DLL if it isn't there already
string TestString = "This is a <Test String>.";
string EncodedString = System.Web.HttpUtility.HtmlEncode(TestString);
I would wrap your rows in labels
<form action="doit" id="doit" method="post">
<label>
Name
<input id="name" name="name" type="text" />
</label>
<label>
Phone number
<input id="phone" name="phone" type="text" />
</label>
<label>
Year
<input id="year" name="year" type="text" />
</label>
</form>
And use
label, input {
display: block;
}
label {
margin-bottom: 20px;
}
Don't use br
s for spacing!
There are a number of ways you can do this:
How to implement Idea #5? Well, one way is to first create an interface:
public interface ThreadCompleteListener {
void notifyOfThreadComplete(final Thread thread);
}
then create the following class:
public abstract class NotifyingThread extends Thread {
private final Set<ThreadCompleteListener> listeners
= new CopyOnWriteArraySet<ThreadCompleteListener>();
public final void addListener(final ThreadCompleteListener listener) {
listeners.add(listener);
}
public final void removeListener(final ThreadCompleteListener listener) {
listeners.remove(listener);
}
private final void notifyListeners() {
for (ThreadCompleteListener listener : listeners) {
listener.notifyOfThreadComplete(this);
}
}
@Override
public final void run() {
try {
doRun();
} finally {
notifyListeners();
}
}
public abstract void doRun();
}
and then each of your Threads will extend NotifyingThread
and instead of implementing run()
it will implement doRun()
. Thus when they complete, they will automatically notify anyone waiting for notification.
Finally, in your main class -- the one that starts all the Threads (or at least the object waiting for notification) -- modify that class to implement ThreadCompleteListener
and immediately after creating each Thread add itself to the list of listeners:
NotifyingThread thread1 = new OneOfYourThreads();
thread1.addListener(this); // add ourselves as a listener
thread1.start(); // Start the Thread
then, as each Thread exits, your notifyOfThreadComplete
method will be invoked with the Thread instance that just completed (or crashed).
Note that better would be to implements Runnable
rather than extends Thread
for NotifyingThread
as extending Thread is usually discouraged in new code. But I'm coding to your question. If you change the NotifyingThread
class to implement Runnable
then you have to change some of your code that manages Threads, which is pretty straightforward to do.
As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang
package is automatically imported, as is everything in the current package.
The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.
By the way, if you are using lots of static methods (from Math
, for example), you could also write
import static java.lang.Math.*;
and then use
sqrt(x)
directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)
For me, I ran into this issue after switching over from bash to zsh so I could get my console to look all awesome fantastic-ish with Hyper and the snazzy theme. I was trying to run my react-native application using react-native run-android
and running into the op's issue. Adding the following into my ~.zshrc
file solved the issue for me:
export ANDROID_HOME=~/Library/Android/sdk
export PATH=${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools
you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]
css
.even{background: red; color:white;}
.odd{background: darkred; color:white;}
html
<div class="container">
<ul class="list-unstyled">
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
</ul>
</div>
You would use a Shape Drawable as the layout's background and set its cornerRadius. Check this blog for a detailed tutorial
Using INSTR:
SELECT *
FROM TABLE a
JOIN TABLE b ON INSTR(b.column, a.column) > 0
Using LIKE:
SELECT *
FROM TABLE a
JOIN TABLE b ON b.column LIKE '%'+ a.column +'%'
Using LIKE, with CONCAT:
SELECT *
FROM TABLE a
JOIN TABLE b ON b.column LIKE CONCAT('%', a.column ,'%')
Mind that in all options, you'll probably want to drive the column values to uppercase BEFORE comparing to ensure you are getting matches without concern for case sensitivity:
SELECT *
FROM (SELECT UPPER(a.column) 'ua'
TABLE a) a
JOIN (SELECT UPPER(b.column) 'ub'
TABLE b) b ON INSTR(b.ub, a.ua) > 0
The most efficient will depend ultimately on the EXPLAIN plan output.
JOIN
clauses are identical to writing WHERE
clauses. The JOIN
syntax is also referred to as ANSI JOINs because they were standardized. Non-ANSI JOINs look like:
SELECT *
FROM TABLE a,
TABLE b
WHERE INSTR(b.column, a.column) > 0
I'm not going to bother with a Non-ANSI LEFT JOIN example. The benefit of the ANSI JOIN syntax is that it separates what is joining tables together from what is actually happening in the WHERE
clause.
Do not use more than one style attribute. Just seperate styles in the style attribute with ;
It is a block of inline CSS, so think of this as you would do CSS in a separate stylesheet.
So in this case its:
style="height:100px;width:100px;"
You can use this for any CSS style, so if you wanted to change the colour of the text to white:
style="height:100px;width:100px;color:#ffffff"
and so on.
However, it is worth using inline CSS sparingly, as it can make code less manageable in future. Using an external stylesheet may be a better option for this. It depends really on your requirements. Inline CSS does make for quicker coding.
Try:
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
To improve James' excellent answer:
It's better to put BINARY
in front of the constant instead:
SELECT * FROM `table` WHERE `column` = BINARY 'value'
Putting BINARY
in front of column
will prevent the use of any index on that column.
All answers are based on anonymous inner class. We have one more way for adding click event for buttons as well as other components too.
An activity needs to implement View.OnClickListener interface and we need to override the onClick function. I think this is best approach compared to using anonymous class.
package com.pointerunits.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button)findViewById(R.id.loginbutton);
login.setOnClickListener((OnClickListener) this);
Log.i(DISPLAY_SERVICE, "Activity is created");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
Log.i(DISPLAY_SERVICE, "Button clicked : " + v.getId());
}
}
My tomcat7 implementation is accepting strings as ISO-8859-1; despite the content-type of the HTTP request. The following solution worked for me when trying to correctly interpret characters like 'é' .
byte[] b1 = szP1.getBytes("ISO-8859-1");
System.out.println(b1.toString());
String szUT8 = new String(b1, "UTF-8");
System.out.println(szUT8);
When trying to interpret the string as US-ASCII, the byte info wasn't correctly interpreted.
b1 = szP1.getBytes("US-ASCII");
System.out.println(b1.toString());
If you have a huge number of objects, this can (at times) be much faster:
try:
orgs[0]
# If you get here, it exists...
except IndexError:
# Doesn't exist!
On a project I'm working on with a huge database, not orgs
is 400+ ms and orgs.count()
is 250ms. In my most common use cases (those where there are results), this technique often gets that down to under 20ms. (One case I found, it was 6.)
Could be much longer, of course, depending on how far the database has to look to find a result. Or even faster, if it finds one quickly; YMMV.
EDIT: This will often be slower than orgs.count()
if the result isn't found, particularly if the condition you're filtering on is a rare one; as a result, it's particularly useful in view functions where you need to make sure the view exists or throw Http404. (Where, one would hope, people are asking for URLs that exist more often than not.)
You may also need to make database containing table active
use [dbname]
otherwise you may get error (even if you specify database i.e. dbname.table )
FAILED Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter partition. Unable to alter partitions because table or database does not exist.
Just to be clear, you need to go to the controlpanel\System\Advanced system settings\Environment Variables\Path
,
then hit edit and add:
C:Users\user.user\Anaconda3\Scripts
to the end and restart the cmd line
Hypothetically, if search landed you on this question then you probably want this:
doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));
Why? Because like me you value time and you are not going to implement .equals
just for the sake of the single test scenario.
And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null
at all costs, use Optional
or move to Kotlin. This implies that verify
does not need to be used that often and ArgumentCaptors are just too tedious to write.
Add these helper classes to the stylesheet.less (you can use http://less2css.org/ to compile them to CSS )
.row.gutter-0 {
margin-left: 0;
margin-right: 0;
[class*="col-"] {
padding-left: 0;
padding-right: 0;
}
}
.row.gutter-10 {
margin-left: -5px;
margin-right: -5px;
[class*="col-"] {
padding-left: 5px;
padding-right: 5px;
}
}
.row.gutter-20 {
margin-left: -10px;
margin-right: -10px;
[class*="col-"] {
padding-left: 10px;
padding-right: 10px;
}
}
And here’s how you can use it in your HTML:
<div class="row gutter-0">
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
</div>
<div class="row gutter-10">
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
</div>
<div class="row gutter-20">
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-sm-3 col-md-3 col-lg-3">
</div>
</div>
To download a file please use the following code ... Store the File name with location in $file variable. It supports all mime type
$file = "location of file to download"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
To know about Mime types please refer to this link: http://php.net/manual/en/function.mime-content-type.php
You can take a look at the source code .
DataFrame
has a private function _slice()
to slice the DataFrame
, and it allows the parameter axis
to determine which axis to slice. The __getitem__()
for DataFrame
doesn't set the axis while invoking _slice()
. So the _slice()
slice it by default axis 0.
You can take a simple experiment, that might help you:
print df._slice(slice(0, 2))
print df._slice(slice(0, 2), 0)
print df._slice(slice(0, 2), 1)
I simply do it in the data frame kind of way:
DT$col = NULL
Works fast and as far as I could see doesn't cause any problems.
UPDATE: not the best method if your DT is very large, as using the $<-
operator will lead to object copying. So better use:
DT[, col:=NULL]
This should work
background: url("youimage.png") no-repeat center center fixed;
-webkit-background-size: 100% auto;
-moz-background-size: 100% auto;
-o-background-size: 100% auto;
background-size: 100% auto;
I needed to do something similar and came across the same issues. I used the AfterSelect event to make sure I wasn't getting the previously selected node.
It's actually really easy to reference the correct node to receive the new child node.
private void TreeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
//show dialogbox to let user name the new node
frmDialogInput f = new frmDialogInput();
f.ShowDialog();
//find the node that was selected
TreeNode myNode = TreeView1.SelectedNode;
//create the new node to add
TreeNode newNode = new TreeNode(f.EnteredText);
//add the new child to the selected node
myNode.Nodes.Add(newNode);
}
To keep the migration consistency across platforms (macOS/Windows/Linux), try:
path = r'%s' % os.getcwd().replace('\\','/')
If we want output like 'string0123456789'
then we can use map function
and join
method of string.
>>> 'string'+"".join(map(str,xrange(10)))
'string0123456789'
If we want List of string values then use list comprehension
method.
>>> ['string'+i for i in map(str,xrange(10))]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9']
Note:
Use xrange()
for Python 2.x
USe range()
for Python 3.x
One option is to chain the -replace
operations together. The `
at the end of each line escapes the newline, causing PowerShell to continue parsing the expression on the next line:
$original_file = 'path\filename.abc'
$destination_file = 'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
$_ -replace 'something1', 'something1aa' `
-replace 'something2', 'something2bb' `
-replace 'something3', 'something3cc' `
-replace 'something4', 'something4dd' `
-replace 'something5', 'something5dsf' `
-replace 'something6', 'something6dfsfds'
} | Set-Content $destination_file
Another option would be to assign an intermediate variable:
$x = $_ -replace 'something1', 'something1aa'
$x = $x -replace 'something2', 'something2bb'
...
$x
You should have to look at StringBuilder/StringBuffer
which allow you to delete, insert, replace char(s) at specified offset.
{% url 'polls:create' poll.id %}
You may also use this to delete a folder that contains subfolders and files.
Fist, create a recursive function.
private void recursiveDelete(File file){
if(file.list().length > 0){
String[] list = file.list();
for(String is: list){
File currentFile = new File(file.getPath(),is);
if(currentFile.isDirectory()){
recursiveDelete(currentFile);
}else{
currentFile.delete();
}
}
}else {
file.delete();
}
}
then, from your initial function use a while loop to call the recursive.
private boolean deleteFolderContainingSubFoldersAndFiles(){
boolean deleted = false;
File folderToDelete = new File("C:/mainFolderDirectoryHere");
while(folderToDelete != null && folderToDelete.isDirectory()){
recursiveDelete(folderToDelete);
}
return deleted;
}
I know I'm am very late on this, but here some usefull samples:
'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select
or
'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
.value = .value
end with
To find the last used row in column, never rely on LastCell, which is unreliable (it is not reset after deleting data). Instead, I use someting like
lngLast = cells(rows.count,3).end(xlUp).row
the mobile solution suggested by Sumit works perfectly for AS3 Air:
html.location = "http://m.facebook.com/logout.php?confirm=1&next=http://yoursitename.com"
string foo;
... foo.length() ...
.length and .size are synonymous, I just think that "length" is a slightly clearer word.
mkdir ~/bin
PATH=~/bin:$PATH
ln -s /usr/bin/python2 ~/bin/python
To stop using python2, exit
or rm ~/bin/python
.
This property will register an OpenEntityManagerInViewInterceptor
, which registers an EntityManager
to the current thread, so you will have the same EntityManager
until the web request is finished. It has nothing to do with a Hibernate SessionFactory
etc.
A standard button is not supposed to be used at full width which is why you experience this.
If you have a look at the Material Design - Button Style you will see that a button has a 48dp height click area, but will be displayed as 36dp of height for...some reason.
This is the background outline you see, which will not cover the whole area of the button itself.
It has rounded corners and some padding and is supposed to be clickable by itself, wrap its content, and not span the whole width at the bottom of your screen.
As mentioned above, what you want is a different background. Not a standard button, but a background for a selectable item with this nice ripple effect.
For this use case there is the ?selectableItemBackground
theme attribute which you can use for your backgrounds (especially in lists).
It will add a platform standard ripple (or some color state list on < 21) and will use your current theme colors.
For your usecase you might just use the following:
<Button
android:id="@+id/sign_in_button"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:background="?attr/selectableItemBackground" />
<!-- /\ that's all -->
There is also no need to add layout weights if your view is the only one and spans the whole screen
If you have some different idea on what your background should look like you have to create a custom drawable yourself, and manage color and state there.
This answer copied from Question: How to properly remove padding (or margin?) around buttons in Android?
In your project settings.py file,set ALLOWED_HOSTS like this :
ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']
and then restart your apache. in ubuntu:
/etc/init.d/apache2 restart
Just add click event by jquery in $(document).ready() like :
$(document).ready(function(){
$('#YourControlID').click(function(){
if(Check your condtion)
{
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
}
});
});
Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.
import java.sql.*;
public class UserLogin
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "username", "password");
System.out.println("Connection Succesfull");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
use Below command in terminal
php artisan cache:clear
php artisan route:cache
php artisan config:cache
php artisan view:clear
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
In a microservice infrastructure (does not fit the problem, I know ;)) you must not use:
server:
ssl:
trust-store: path-to-truststore...
trust-store-password: my-secret-password...
Instead the ribbon loadbalancer can be configuered:
ribbon:
TrustStore: keystore.jks
TrustStorePassword : example
ReadTimeout: 60000
IsSecure: true
MaxAutoRetries: 1
Here https://github.com/rajaramkushwaha/https-zuul-proxy-spring-boot-app you can find a working sample. There was also a github discussion about that, but I didn't find it anymore.
Let me clarify two points here :
(a = 'b',c)
in function.
The correct order of defining parameter in function are :(a,b,c)
(a = 'b',r= 'j')
(*args)
(**kwargs)
def example(a, b, c=None, r="w" , d=[], *ae, **ab):
(a,b)
are positional parameter
(c=none)
is optional parameter
(r="w")
is keyword parameter
(d=[])
is list parameter
(*ae)
is keyword-only
(*ab)
is var-keyword parameter
so first re-arrange your parameters
so second remove this "len1 = hgt"
it's not allowed in python.
keep in mind the difference between argument and parameters.
If I understand clearly, you want to do this programatically. Then, you could use the onTouchEvent method of View
, and create a MotionEvent
with the coordinates you need.
To pass/use the variables, first create parameters in the configure section of Jenkins. Parameters that you use can be of type text, String, file, etc.
After creating them, use the variable reference in the fields you want to.
For example: I have configured/created two variables for Email-subject
and Email-recipentList
, and I have used their reference in the EMail-ext
plugin (attached screenshot).
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT
function on the nvarchar field.
Example: Left(Field,4)
Basically, the query will look like:
Select convert(float,left(Field,4)) from TABLE
Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.
var cumulativeOffset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)
You can reference is that way if you wrap the query, like this:
SELECT P
FROM (SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts) innertable
WHERE P LIKE 'NW101%'
Be sure to give the wrapped select an alias, even unused (SQL Server doesn't allow it without one IIRC)
getline()
is what you're looking for. You use strings in C++, and you don't need to know the size ahead of time.
Assuming std namespace:
ifstream file1("myfile.txt");
string stuff;
while (getline(file1, stuff, '\n')) {
cout << stuff << endl;
}
file1.close();
A good option is Node-supervisor and Node.js Restart on File Change is good article on how to use it, typically:
npm install supervisor -g
and after migrating to the root of your application use the following
supervisor app.js
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email.Have a look at the example:
<?php
//define the receiver of the email
$to = '[email protected]';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: [email protected]\r\nReply-To: [email protected]";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Hello World!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64, split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.
Taken from here.
Include an Setup Project (New Project > Other Project Types > Setup and Deployment > Visual Studio Installer
) in your solution. It has options to include the framework installer. Check out this Deployment Guide MSDN post.
Anaconda does not use the PYTHONPATH
. One should however note that if the PYTHONPATH
is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a
unset PYTHONPATH
For instance this PYTHONPATH points to an incorrect pandas lib:
export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
unsetting the PYTHONPATH
prevents the wrong pandas lib from being loaded:
unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>
my OS is ubuntu, XAMPP installed in /opt/lampp
, and I found php.ini in /opt/lampp/etc/php.ini
Do you have anything in machine.config that might be taking effect? Setting the session timeout in web.config should override any settings in IIS or machine.config, however, if you have a web.config file somewhere in a subfolder in your application, that setting will override the one in the root of your application.
Also, if I remember correctly, the timeout in IIS only affects .asp pages, not .aspx. Are you sure your session code in web.config is correct? It should look something like:
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="60"
sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
cookieless="false"
timeout="60"
/>
You probably mean heap memory, not memory heap.
Heap memory is essentially a large pool of memory (typically per process) from which the running program can request chunks. This is typically called dynamic allocation.
It is different from the Stack, where "automatic variables" are allocated. So, for example, when you define in a C function a pointer variable, enough space to hold a memory address is allocated on the stack. However, you will often need to dynamically allocate space (With malloc) on the heap and then provide the address where this memory chunk starts to the pointer.
To overcome the issue of Win7 32bit VB6, try copying from Windows Server 2003 C:\Windows\system32\
the files mscomctl.ocx
and mscomcctl.oba
.
I am using asp.net WCF webservices with angular js and below code worked:
$http({
contentType: "application/json; charset=utf-8",//required
method: "POST",
url: '../../operation/Service.svc/user_forget',
dataType: "json",//optional
data:{ "uid_or_phone": $scope.forgettel, "user_email": $scope.forgetemail },
async: "isAsync"//optional
}).success( function (response) {
$scope.userforgeterror = response.d;
})
Hope it helps.
This worked for me:
src="{0}" width=30 height=30 style="border:0;"
Nothing else has worked so far.
To eliminate the need to repeatedly press F5 in an IE tab while developing a website, use ReloadIt.
For each webpage displayed in IE, you can configure a filename, a directory, or a set of them. If any change occurs in any of those configured paths, ReloadIt refreshes the IE tab. A simple tool. It just works.
This will reload everything, not just javascript.
If you are in Android Studio Open Terminal
adb kill-server
press enter and again
adb start-server
press enter
Otherwise
Open Command prompt and got android
sdk>platform-tools> adb kill-server
press enter
and again
adb start-server
press enter
For slow queries on version < 5.1, the following configuration worked for me:
log_slow_queries=/var/log/mysql/slow-query.log
long_query_time=20
log_queries_not_using_indexes=YES
Also note to place it under [mysqld]
part of the config file and restart mysqld
.
Try phoneNumber.setVisibility(View.GONE);
If you are new to Active Directory, I suggest you should understand how Active Directory stores data first.
Active Directory is actually a LDAP server. Objects stored in LDAP server are stored hierarchically. It's very similar to you store your files in your file system. That's why it got the name Directory server and Active Directory
The containers and objects on Active Directory can be specified by a distinguished name
. The distinguished name is like this CN=SomeName,CN=SomeDirectory,DC=yourdomain,DC=com
. Like a traditional relational database, you can run query against a LDAP server. It's called LDAP query.
There are a number of ways to run a LDAP query in .NET. You can use DirectorySearcher from System.DirectoryServices
or SearchRequest from System.DirectoryServices.Protocol
.
For your question, since you are asking to find user principal object specifically, I think the most intuitive way is to use PrincipalSearcher from System.DirectoryServices.AccountManagement
. You can easily find a lot of different examples from google. Here is a sample that is doing exactly what you are asking for.
using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
Console.WriteLine("SAM account name : " + de.Properties["samAccountName"].Value);
Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
Console.WriteLine();
}
}
}
Console.ReadLine();
Note that on the AD user object, there are a number of attributes. In particular, givenName
will give you the First Name
and sn
will give you the Last Name
. About the user name. I think you meant the user logon name. Note that there are two logon names on AD user object. One is samAccountName
, which is also known as pre-Windows 2000 user logon name. userPrincipalName
is generally used after Windows 2000.
If you need the transition to run infinitely, try the below example:
#box {_x000D_
position: relative;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: gray;_x000D_
border: 5px solid black;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#box:hover {_x000D_
border-color: red;_x000D_
animation-name: flash_border;_x000D_
animation-duration: 2s;_x000D_
animation-timing-function: linear;_x000D_
animation-iteration-count: infinite;_x000D_
-webkit-animation-name: flash_border;_x000D_
-webkit-animation-duration: 2s;_x000D_
-webkit-animation-timing-function: linear;_x000D_
-webkit-animation-iteration-count: infinite;_x000D_
-moz-animation-name: flash_border;_x000D_
-moz-animation-duration: 2s;_x000D_
-moz-animation-timing-function: linear;_x000D_
-moz-animation-iteration-count: infinite;_x000D_
}_x000D_
_x000D_
@keyframes flash_border {_x000D_
0% {_x000D_
border-color: red;_x000D_
}_x000D_
50% {_x000D_
border-color: black;_x000D_
}_x000D_
100% {_x000D_
border-color: red;_x000D_
}_x000D_
}_x000D_
_x000D_
@-webkit-keyframes flash_border {_x000D_
0% {_x000D_
border-color: red;_x000D_
}_x000D_
50% {_x000D_
border-color: black;_x000D_
}_x000D_
100% {_x000D_
border-color: red;_x000D_
}_x000D_
}_x000D_
_x000D_
@-moz-keyframes flash_border {_x000D_
0% {_x000D_
border-color: red;_x000D_
}_x000D_
50% {_x000D_
border-color: black;_x000D_
}_x000D_
100% {_x000D_
border-color: red;_x000D_
}_x000D_
}
_x000D_
<div id="box">roll over me</div>
_x000D_
"user.dir" is the current working directory, not the home directory It is all described here.
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
Also, by using \\
instead of File.separator, you will lose portability with *nix system which uses /
for file separator.
Try the following snippet, using a dictionary comprehension:
value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }
In the above code we find the difference of the keys and then rebuild a dict
taking the corresponding values.
ng-if if false will remove elements from DOM. This means that all your events, directives attached to those elements will be lost. For example, ng-click to one of child elements, when ng-if evaluates to false, that element will be removed from DOM and again when it is true it is recreated.
ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles (.ng-hide) to hide/show elements .This way your events, directives that were attached to children will not be lost.
ng-if creates a child scope while ng-show/ng-hide does not.
A keystore contains private keys. You only need this if you are a server, or if the server requires client authentication.
A truststore contains CA certificates to trust. If your server’s certificate is signed by a recognized CA, the default truststore that ships with the JRE will already trust it (because it already trusts trustworthy CAs), so you don’t need to build your own, or to add anything to the one from the JRE.
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
Your problem is that you're not closing your HEREDOC correctly. The line containing END;
must not contain any whitespace afterwards.
In .Net Core (as of v2.2) it should be:
new Process
{
StartInfo = new ProcessStartInfo(@"file path")
{
UseShellExecute = true
}
}.Start();
Related github issue can be found here
They're both inner joins that do the same thing, one simply uses the newer ANSI syntax.
Just an update with Java Generics.
You could create an utility method to retrieve an optional value of any Java type from a given ResultSet, previously casted.
Unfortunately, getObject(columnName, Class) does not return null, but the default value for given Java type, so 2 calls are required
public <T> T getOptionalValue(final ResultSet rs, final String columnName, final Class<T> clazz) throws SQLException {
final T value = rs.getObject(columnName, clazz);
return rs.wasNull() ? null : value;
}
In this example, your code could look like below:
final Integer columnValue = getOptionalValue(rs, Integer.class);
if (columnValue == null) {
//null handling
} else {
//use int value of columnValue with autoboxing
}
Happy to get feedback
Subtract from another date object
var d = new Date();
d.setHours(d.getHours() - 2);
I have a suggestion to properly handle rejects in a novel approach, without having multiple try-catch blocks.
import to from './to';
async foo(id: string): Promise<A> {
let err, result;
[err, result] = await to(someAsyncPromise()); // notice the to() here
if (err) {
return 400;
}
return 200;
}
Where the to.ts function should be imported from:
export default function to(promise: Promise<any>): Promise<any> {
return promise.then(data => {
return [null, data];
}).catch(err => [err]);
}
Credits go to Dima Grossman in the following link.
To remove specific key and element from hashmap use
hashmap.remove(key)
full source code is like
import java.util.HashMap;
public class RemoveMapping {
public static void main(String a[]){
HashMap hashMap = new HashMap();
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
System.out.println("Original HashMap : "+hashMap);
hashMap.remove(3);
System.out.println("Changed HashMap : "+hashMap);
}
}
Since your files are not yet committed in branch1
:
git stash
git checkout branch2
git stash pop
or
git stash
git checkout branch2
git stash list # to check the various stash made in different branch
git stash apply x # to select the right one
As commented by benjohn (see git stash
man page):
To also stash currently untracked (newly added) files, add the argument
-u
, so:
git stash -u
Try this one:
public void deleteEntry(long rowId) {
database.delete(DATABASE_TABLE , KEY_ROWID
+ " = " + rowId, null);}
I followed most, if not all, of Gunnar Bernstein's suggestions mentioned above and it still didn't work. However, it started to work after I followed his suggestions AND the following:
I created a new MapActivity by using Android Studio's right click list of options: New -> Google -> Google Maps Activity
I then opened the google_maps_api.xml file that automatically gets generated and used the stated link to create a new API KEY. I did all the steps and saved my new key under my current project. I then removed my old registered API KEY as it was no longer required.
Under the Manifest file I replaced the old API KEY value with the
string shortcut created by this new XML file:
android:value="@string/google_maps_key
", instead of stating the KEY
directly.
Finally, remove the new MapActivity, but keep the xml file that was created in that process.
Note: By creating the API KEY in this way the Restrictions column, under Credentials, now stated "Android apps". Earlier, when it didn't work the column stated "Android apps, 1 API" or something similar. I do not know if this makes a difference or not. Note: No, that just means that I do not have a specific API selected for this API key (Console -> API key -> Key restrictions -> API restrictions).
Note: It looks like the meta-data tag under the Manifest file:
android:name="com.google.android.maps.v2.API_KEY
has been replaced by:
android:name="com.google.android.geo.API_KEY"
I guess that both can be used but it's better from the start using the latter.
Note: The value stated, in the build.gradle file, under android -> defaultConfig -> applicationId has to match the Package name text under the Credentials page.
Please check if the dll in application is of the same version as that in the sys32 or wow64 folder depending on your version of windows.
You can check that from the filesize of the dlls.
Eg: I faced this issue because my libeay32.dll and ssleay32.dll file in system32 had a different dll than my libeay32.dll and ssleay32.dll file in openssl application.
I copied the one in sys32 into openssl and everything worked well.
While this is a wild guess and may not be applicable in your specific situation, this could've saved me an hour or so.
In case you have "converted" a plain project into Java project (by editing .project file and adding appropriate tag), make sure you also have a proper specified - my project didn't get built even though Eclipse attempted to and run no builders (success!):
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
Given an array you can use the Array.ConvertAll
method:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:
int[] myInts = Array.ConvertAll(arr, int.Parse);
A LINQ solution is similar, except you would need the extra ToArray
call to get an array:
int[] myInts = arr.Select(int.Parse).ToArray();
You can use either $().jquery;
or $.fn.jquery
which will return a string containing the version number, e.g. 1.6.2
.
This is my approach. Iterate over characters in the string until a match is found. On a larger array of needles this will outperform the accepted answer because it doesn't need to check every needle to determine that a match has been found.
function strpos_array($haystack, $needles = [], $offset = 0) {
for ($i = $offset, $len = strlen($haystack); $i < $len; $i++){
if (in_array($haystack[$i],$needles)) {
return $i;
}
}
return false;
}
I benchmarked this against the accepted answer and with an array of more than 7 $needles
this was dramatically faster.
Yes, I got the answer.. just simply edit the manifest
file as:
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysVisible" />
and set EditText.requestFocus()
in onCreate()
..
Thanks..
All of the answers so far ignore a dangerous problem with ===. It has been noted in passing, but not stressed, that integer and double are different types, so the following code:
$n = 1000;
$d = $n + 0.0e0;
echo '<br/>'. ( ($n == $d)?'equal' :'not equal' );
echo '<br/>'. ( ($n === $d)?'equal' :'not equal' );
gives:
equal
not equal
Note that this is NOT a case of a "rounding error". The two numbers are exactly equal down to the last bit, but they have different types.
This is a nasty problem because a program using === can run happily for years if all of the numbers are small enough (where "small enough" depends on the hardware and OS you are running on). However, if by chance, an integer happens to be large enough to be converted to a double, its type is changed "forever" even though a subsequent operation, or many operations, might bring it back to a small integer in value. And, it gets worse. It can spread - double-ness infection can be passed along to anything it touches, one calculation at a time.
In the real world, this is likely to be a problem in programs that handle dates beyond the year 2038, for example. At this time, UNIX timestamps (number of seconds since 1970-01-01 00:00:00 UTC) will require more than 32-bits, so their representation will "magically" switch to double on some systems. Therefore, if you calculate the difference between two times you might end up with a couple of seconds, but as a double, rather than the integer result that occurs in the year 2017.
I think this is much worse than conversions between strings and numbers because it is subtle. I find it easy to keep track of what is a string and what is a number, but keeping track of the number of bits in a number is beyond me.
So, in the above answers there are some nice tables, but no distinction between 1 (as an integer) and 1 (subtle double) and 1.0 (obvious double). Also, advice that you should always use === and never == is not great because === will sometimes fail where == works properly. Also, JavaScript is not equivalent in this regard because it has only one number type (internally it may have different bit-wise representations, but it does not cause problems for ===).
My advice - use neither. You need to write your own comparison function to really fix this mess.
Nobody has explained the difference between ExceptionDispatchInfo.Capture( ex ).Throw()
and a plain throw
, so here it is. However, some people have noticed the problem with throw
.
The complete way to rethrow a caught exception is to use ExceptionDispatchInfo.Capture( ex ).Throw()
(only available from .Net 4.5).
Below there are the cases necessary to test this:
1.
void CallingMethod()
{
//try
{
throw new Exception( "TEST" );
}
//catch
{
// throw;
}
}
2.
void CallingMethod()
{
try
{
throw new Exception( "TEST" );
}
catch( Exception ex )
{
ExceptionDispatchInfo.Capture( ex ).Throw();
throw; // So the compiler doesn't complain about methods which don't either return or throw.
}
}
3.
void CallingMethod()
{
try
{
throw new Exception( "TEST" );
}
catch
{
throw;
}
}
4.
void CallingMethod()
{
try
{
throw new Exception( "TEST" );
}
catch( Exception ex )
{
throw new Exception( "RETHROW", ex );
}
}
Case 1 and case 2 will give you a stack trace where the source code line number for the CallingMethod
method is the line number of the throw new Exception( "TEST" )
line.
However, case 3 will give you a stack trace where the source code line number for the CallingMethod
method is the line number of the throw
call. This means that if the throw new Exception( "TEST" )
line is surrounded by other operations, you have no idea at which line number the exception was actually thrown.
Case 4 is similar with case 2 because the line number of the original exception is preserved, but is not a real rethrow because it changes the type of the original exception.
you can use :
git clone <url> --branch <branch>
to clone/download only the contents of the branch.
This was helpful to me especially, since the contents of my branch were entirely different from the master branch (though this is not usually the case). Hence, the suggestions listed by others above didn't help me and I would end up getting a copy of the master even after I checked out the branch and did a git pull.
This command would directly give you the contents of the branch. It worked for me.
Its better to access the count with the laravels count method
$count = Model::where('status','=','1')->count();
or
$count = Model::count();
Look at this method to see which fields are supported. You will find for LocalDateTime
:
•NANO_OF_SECOND
•NANO_OF_DAY
•MICRO_OF_SECOND
•MICRO_OF_DAY
•MILLI_OF_SECOND
•MILLI_OF_DAY
•SECOND_OF_MINUTE
•SECOND_OF_DAY
•MINUTE_OF_HOUR
•MINUTE_OF_DAY
•HOUR_OF_AMPM
•CLOCK_HOUR_OF_AMPM
•HOUR_OF_DAY
•CLOCK_HOUR_OF_DAY
•AMPM_OF_DAY
•DAY_OF_WEEK
•ALIGNED_DAY_OF_WEEK_IN_MONTH
•ALIGNED_DAY_OF_WEEK_IN_YEAR
•DAY_OF_MONTH
•DAY_OF_YEAR
•EPOCH_DAY
•ALIGNED_WEEK_OF_MONTH
•ALIGNED_WEEK_OF_YEAR
•MONTH_OF_YEAR
•PROLEPTIC_MONTH
•YEAR_OF_ERA
•YEAR
•ERA
The field INSTANT_SECONDS is - of course - not supported because a LocalDateTime
cannot refer to any absolute (global) timestamp. But what is helpful is the field EPOCH_DAY which counts the elapsed days since 1970-01-01. Similar thoughts are valid for the type LocalDate
(with even less supported fields).
If you intend to get the non-existing millis-since-unix-epoch field you also need the timezone for converting from a local to a global type. This conversion can be done much simpler, see other SO-posts.
Coming back to your question and the numbers in your code:
The result 1605 is correct
=> (2014 - 1970) * 365 + 11 (leap days) + 31 (in january 2014) + 3 (in february 2014)
The result 71461 is also correct => 19 * 3600 + 51 * 60 + 1
16105L * 86400 + 71461 = 1391543461 seconds since 1970-01-01T00:00:00 (attention, no timezone) Then you can subtract the timezone offset (watch out for possible multiplication by 1000 if in milliseconds).
UPDATE after given timezone info:
local time = 1391543461 secs
offset = 3600 secs (Europe/Oslo, winter time in february)
utc = 1391543461 - 3600 = 1391539861
As JSR-310-code with two equivalent approaches:
long secondsSinceUnixEpoch1 =
LocalDateTime.of(2014, 2, 4, 19, 51, 1).atZone(ZoneId.of("Europe/Oslo")).toEpochSecond();
long secondsSinceUnixEpoch2 =
LocalDate
.of(2014, 2, 4)
.atTime(19, 51, 1)
.atZone(ZoneId.of("Europe/Oslo"))
.toEpochSecond();
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}})
Table or record locking is available in Access during data writes. You can control the Default record locking through Tools | Options | Advanced tab:
You can set this on a form's Record Locks or in your DAO/ADO code for specific needs.
Transactions shouldn't be a problem if you use them correctly.
Best practice: Separate your tables from All your other code. Give each user their own copy of the code file and then share the data file on a network server. Work on a 'test' copy of the code (and a link to a test data file) and then update user's individual code files separately. If you need to make data file changes (add tables, columns, etc), you will have to have all users get out of the application to make the changes.
See other answers for Oracle comparison.
df.insert(0, 'New_ID', range(880, 880 + len(df)))
df
@echo off
title Test
echo Select a language. (de/en)
set /p language=
IF /i "%language%"=="de" goto languageDE
IF /i "%language%"=="en" goto languageEN
echo Not found.
goto commonexit
:languageDE
echo German
goto commonexit
:languageEN
echo English
goto commonexit
:commonexit
pause
The point is that batch simply continues through instructions, line by line until it reaches a goto
, exit
or end-of-file. It has no concept of sections
to control flow.
Hence, entering de
would jump to :languagede
then simply continue executing instructions until the file ends, showing de
then en
then not found
.
The extended configuration section in a previous response with
...
...
<rollingStyle value="Composite" />
...
...
listed works but I did not have to use
<staticLogFileName value="false" />
. I think the RollingAppender must (logically) ignore that setting since by definition the file gets rebuilt each day when the application restarts/reused. Perhaps it does matter for immediate rollover EVERY time the application starts.
Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use ✓
for ✓ and ✗
for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.
As mentioned in the comments, ✓
and ✗
are not supported in HTML4, so you may be better off using the more cryptic ✓
and ✗
if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.
By the way it is written, clean rule is invoked only if it is explicitly called:
make clean
I think it is better, than make clean every time. If you want to do this by your way, try this:
CXX = g++ -O2 -Wall all: clean code1 code2 code1: code1.cc utilities.cc $(CXX) $^ -o $@ code2: code2.cc utilities.cc $(CXX) $^ -o $@ clean: rm ... echo Clean done
Update in 2018: I just got some points for this old answer, and just wanted to add that the best solution would be to make the operation idempotent so that duplicate submissions are harmless.
Eg, if the form creates an order, put a unique ID in the form. The first time the server sees an order creation request with that id, it should create it and respond "success". Subsequent submissions should also respond "success" (in case the client didn't get the first response) but shouldn't change anything.
Duplicates should be detected via a uniqueness check in the database to prevent race conditions.
I think that your problem is this line:
$('input').attr('disabled','disabled');
You're disabling ALL the inputs, including, I'd guess, the ones whose data the form is supposed to submit.
To disable just the submit button(s), you could do this:
$('button[type=submit], input[type=submit]').prop('disabled',true);
However, I don't think IE will submit the form if even those buttons are disabled. I'd suggest a different approach.
We just solved this problem with the following code. The trick here is using jQuery's data()
to mark the form as already submitted or not. That way, we don't have to mess with the submit buttons, which freaks IE out.
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).on('submit',function(e){
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
Use it like this:
$('form').preventDoubleSubmission();
If there are AJAX forms that should be allowed to submit multiple times per page load, you can give them a class indicating that, then exclude them from your selector like this:
$('form:not(.js-allow-double-submission)').preventDoubleSubmission();
In spring pre-3.0 it doesn't matter which one.
In spring 3.0 there's support for the standard (JSR-330) annotation @javax.inject.Inject
- use it, with a combination of @Qualifier
. Note that spring now also supports the @javax.inject.Qualifier
meta-annotation:
@Qualifier
@Retention(RUNTIME)
public @interface YourQualifier {}
So you can have
<bean class="com.pkg.SomeBean">
<qualifier type="YourQualifier"/>
</bean>
or
@YourQualifier
@Component
public class SomeBean implements Foo { .. }
And then:
@Inject @YourQualifier private Foo foo;
This makes less use of String-names, which can be misspelled and are harder to maintain.
As for the original question: both, without specifying any attributes of the annotation, perform injection by type. The difference is:
@Resource
allows you to specify a name of the injected bean@Autowired
allows you to mark it as non-mandatory.Try this one it will work
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.add("Nokia");
adapter.notifyDataSetChanged();
}
}
#include <iostream>
#include <type_traits>
using namespace std;
enum class A {
a = 1,
b = 69,
c= 666
};
std::ostream& operator << (std::ostream& os, const A& obj)
{
os << static_cast<std::underlying_type<A>::type>(obj);
return os;
}
int main () {
A a = A::c;
cout << a << endl;
}
Variables declared inside a function are local to that function. For instance:
foo <- function() {
bar <- 1
}
foo()
bar
gives the following error: Error: object 'bar' not found
.
If you want to make bar
a global variable, you should do:
foo <- function() {
bar <<- 1
}
foo()
bar
In this case bar
is accessible from outside the function.
However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:
if (x > 10) {
y <- 0
}
else {
y <- 1
}
y
remains accessible after the if-else
statement.
As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:
Here you have a small example:
test.env <- new.env()
assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100
get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found
A new way to do this. iOS 8
let string: NSString = "Café"
let substring: NSString = "É"
string.localizedCaseInsensitiveContainsString(substring) // true
I'm a friend of keeping the original files, so that you can still use the archived original ones and do new encodes from these fresh ones when the old transcodes are out of date. eg. migrating them from previously transocded mpeg2-hd to mpeg4-hd (and perhaps from mpeg4-hd to its successor in sometime). but all of these should be done from the original. any compression step will followed by a loss of quality. it will need some time to redo this again, but in my opinion it's worth the effort.
so, if you want to keep the originals, you can use the running time in seconds of you tapes times the maximum datarate of hdv (constants 27mbit/s I think) to get your needed storage capacity
There is exactly one reason why the following is preferred:
with open('filename.txt') as fp:
for line in fp:
print line
We are all spoiled by CPython's relatively deterministic reference-counting scheme for garbage collection. Other, hypothetical implementations of Python will not necessarily close the file "quickly enough" without the with
block if they use some other scheme to reclaim memory.
In such an implementation, you might get a "too many files open" error from the OS if your code opens files faster than the garbage collector calls finalizers on orphaned file handles. The usual workaround is to trigger the GC immediately, but this is a nasty hack and it has to be done by every function that could encounter the error, including those in libraries. What a nightmare.
Or you could just use the with
block.
(Stop reading now if are only interested in the objective aspects of the question.)
Why isn't that included in the iterator protocol for file objects?
This is a subjective question about API design, so I have a subjective answer in two parts.
On a gut level, this feels wrong, because it makes iterator protocol do two separate things—iterate over lines and close the file handle—and it's often a bad idea to make a simple-looking function do two actions. In this case, it feels especially bad because iterators relate in a quasi-functional, value-based way to the contents of a file, but managing file handles is a completely separate task. Squashing both, invisibly, into one action, is surprising to humans who read the code and makes it more difficult to reason about program behavior.
Other languages have essentially come to the same conclusion. Haskell briefly flirted with so-called "lazy IO" which allows you to iterate over a file and have it automatically closed when you get to the end of the stream, but it's almost universally discouraged to use lazy IO in Haskell these days, and Haskell users have mostly moved to more explicit resource management like Conduit which behaves more like the with
block in Python.
On a technical level, there are some things you may want to do with a file handle in Python which would not work as well if iteration closed the file handle. For example, suppose I need to iterate over the file twice:
with open('filename.txt') as fp:
for line in fp:
...
fp.seek(0)
for line in fp:
...
While this is a less common use case, consider the fact that I might have just added the three lines of code at the bottom to an existing code base which originally had the top three lines. If iteration closed the file, I wouldn't be able to do that. So keeping iteration and resource management separate makes it easier to compose chunks of code into a larger, working Python program.
Composability is one of the most important usability features of a language or API.
I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
<a href="#test100">Test link</a>
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?
read
without any parameters will only continue if you press enter.
The DOS pause
command will continue if you press any key. Use read –n1
if you want this behaviour.
I ran this code to see if the checked answer worked, and had to try swapping around the dates to get it right. This worked--
Day.where(:reference_date => 3.months.ago..Time.now).count
#=> 721
If you're thinking the output should have been 36, consider this, Sir, how many days is 3 days to 3 people?
You mention PHP and Javascript in your question, but not in the tags. I reached this question with the intention of passing an array to an MVC.Net action.
I found the answer to my question here: the expected format is the one you proposed in your question, with multiple parameters having the same name.
Here's my solution to the issue. Tried to keep it straight and simple.
#include <iostream>
using namespace std;
class Game{
public:
void init(){
cout << "Hi" << endl;
}
}g;
class b : Game{ //class b uses/imports class Game
public:
void h(){
init(); //Use function from class Game
}
}A;
int main()
{
A.h();
return 0;
}
You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/
IE Driver is also available in the following site:
The way to do this using the Extention Methods, instead of the linq query syntax would be like this:
var results = workOrders.Join(plans,
wo => wo.WorkOrderNumber,
p => p.WorkOrderNumber,
(order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);
Below code worked for me to generate and download a text file.
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDownloadData() throws Exception {
String regData = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
byte[] output = regData.getBytes();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("charset", "utf-8");
responseHeaders.setContentType(MediaType.valueOf("text/html"));
responseHeaders.setContentLength(output.length);
responseHeaders.set("Content-disposition", "attachment; filename=filename.txt");
return new ResponseEntity<byte[]>(output, responseHeaders, HttpStatus.OK);
}
get radio buttons value and matches with each if it is 3 then disabled checkbox and textbox
.
$("#radiobutt input[type=radio]").click(function () {_x000D_
$(this).each(function(index){_x000D_
//console.log($(this).val());_x000D_
if($(this).val()==3) { //get radio buttons value and matched if 3 then disabled._x000D_
$("#textbox_field").attr("disabled", "disabled"); _x000D_
$("#checkbox_field").attr("disabled", "disabled"); _x000D_
}_x000D_
else {_x000D_
$("#textbox_field").removeAttr("disabled"); _x000D_
$("#checkbox_field").removeAttr("disabled"); _x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<span id="radiobutt">_x000D_
<input type="radio" name="groupname" value="1" />_x000D_
<input type="radio" name="groupname" value="2" />_x000D_
<input type="radio" name="groupname" value="3" />_x000D_
</span>_x000D_
<div>_x000D_
<input type="text" id="textbox_field" />_x000D_
<input type="checkbox" id="checkbox_field" />_x000D_
</div>
_x000D_
They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.
If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.
The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.
But in general, use the activity context unless you have a good reason not to.
You can remove in two ways
var output = from x in authorsList
where x.firstname != "Bob"
select x;
or
var authors = from x in authorsList
where x.firstname == "Bob"
select x;
var output = from x in authorsList
where !authors.Contains(x)
select x;
I had same issue, if you want simple output based on your where condition , then first solution is better.
I had this and looked over everything and didn't see any problems, but eventually remembered to try Clean and clear Derived Data and that solved it!
You can generate scripts to a file via SQL Server Management Studio, here are the steps:
When generating the scripts, there is an area that will allow you to script, constraints, keys, etc. From SQL Server 2008 R2 there is an Advanced Option under scripting:
a) extract in yourfolder
b) create file.php in yourfolder
and insert such code:
<?php
include('../mpdf.php');
$mpdf=new mPDF();
$mpdf->WriteHTML('<p style="color:red;">Hallo World<br/>Fisrt sentencee</p>');
$mpdf->Output(); exit;
?>
c) open file.php from your browser
1) extract pdftohtml.exe to your root folder:
2) inside that folder, in anyfile.php file, put this code (assuming, there is a source example.pdf too):
<?php
$source="example.pdf";
$output_fold="FinalFolder";
if (!file_exists($output_fold)) { mkdir($output_fold, 0777, true);}
$result= passthru("pdftohtml $source $output_fold/new_filename",$log);
//var_dump($result); var_dump($log);
?>
3) enter FinalFolder, and there will be the converted files (as many pages, as the source PDF had..)
You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.
function form($scope){_x000D_
$scope.onSubmit = function(){_x000D_
alert("form submitted");_x000D_
}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>_x000D_
<div ng-app ng-controller="form">_x000D_
<form name="myForm" ng-submit="onSubmit()">_x000D_
<input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>_x000D_
<span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>_x000D_
<input type="submit" value="submit"/>_x000D_
</form>_x000D_
</div>
_x000D_
static_cast
vs dynamic_cast
vs reinterpret_cast
internals view on a downcast/upcast
In this answer, I want to compare these three mechanisms on a concrete upcast/downcast example and analyze what happens to the underlying pointers/memory/assembly to give a concrete understanding of how they compare.
I believe that this will give a good intuition on how those casts are different:
static_cast
: does one address offset at runtime (low runtime impact) and no safety checks that a downcast is correct.
dyanamic_cast
: does the same address offset at runtime like static_cast
, but also and an expensive safety check that a downcast is correct using RTTI.
This safety check allows you to query if a base class pointer is of a given type at runtime by checking a return of nullptr
which indicates an invalid downcast.
Therefore, if your code is not able to check for that nullptr
and take a valid non-abort action, you should just use static_cast
instead of dynamic cast.
If an abort is the only action your code can take, maybe you only want to enable the dynamic_cast
in debug builds (-NDEBUG
), and use static_cast
otherwise, e.g. as done here, to not slow down your fast runs.
reinterpret_cast
: does nothing at runtime, not even the address offset. The pointer must point exactly to the correct type, not even a base class works. You generally don't want this unless raw byte streams are involved.
Consider the following code example:
main.cpp
#include <iostream>
struct B1 {
B1(int int_in_b1) : int_in_b1(int_in_b1) {}
virtual ~B1() {}
void f0() {}
virtual int f1() { return 1; }
int int_in_b1;
};
struct B2 {
B2(int int_in_b2) : int_in_b2(int_in_b2) {}
virtual ~B2() {}
virtual int f2() { return 2; }
int int_in_b2;
};
struct D : public B1, public B2 {
D(int int_in_b1, int int_in_b2, int int_in_d)
: B1(int_in_b1), B2(int_in_b2), int_in_d(int_in_d) {}
void d() {}
int f2() { return 3; }
int int_in_d;
};
int main() {
B2 *b2s[2];
B2 b2{11};
D *dp;
D d{1, 2, 3};
// The memory layout must support the virtual method call use case.
b2s[0] = &b2;
// An upcast is an implicit static_cast<>().
b2s[1] = &d;
std::cout << "&d " << &d << std::endl;
std::cout << "b2s[0] " << b2s[0] << std::endl;
std::cout << "b2s[1] " << b2s[1] << std::endl;
std::cout << "b2s[0]->f2() " << b2s[0]->f2() << std::endl;
std::cout << "b2s[1]->f2() " << b2s[1]->f2() << std::endl;
// Now for some downcasts.
// Cannot be done implicitly
// error: invalid conversion from ‘B2*’ to ‘D*’ [-fpermissive]
// dp = (b2s[0]);
// Undefined behaviour to an unrelated memory address because this is a B2, not D.
dp = static_cast<D*>(b2s[0]);
std::cout << "static_cast<D*>(b2s[0]) " << dp << std::endl;
std::cout << "static_cast<D*>(b2s[0])->int_in_d " << dp->int_in_d << std::endl;
// OK
dp = static_cast<D*>(b2s[1]);
std::cout << "static_cast<D*>(b2s[1]) " << dp << std::endl;
std::cout << "static_cast<D*>(b2s[1])->int_in_d " << dp->int_in_d << std::endl;
// Segfault because dp is nullptr.
dp = dynamic_cast<D*>(b2s[0]);
std::cout << "dynamic_cast<D*>(b2s[0]) " << dp << std::endl;
//std::cout << "dynamic_cast<D*>(b2s[0])->int_in_d " << dp->int_in_d << std::endl;
// OK
dp = dynamic_cast<D*>(b2s[1]);
std::cout << "dynamic_cast<D*>(b2s[1]) " << dp << std::endl;
std::cout << "dynamic_cast<D*>(b2s[1])->int_in_d " << dp->int_in_d << std::endl;
// Undefined behaviour to an unrelated memory address because this
// did not calculate the offset to get from B2* to D*.
dp = reinterpret_cast<D*>(b2s[1]);
std::cout << "reinterpret_cast<D*>(b2s[1]) " << dp << std::endl;
std::cout << "reinterpret_cast<D*>(b2s[1])->int_in_d " << dp->int_in_d << std::endl;
}
Compile, run and disassemble with:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
setarch `uname -m` -R ./main.out
gdb -batch -ex "disassemble/rs main" main.out
where setarch
is used to disable ASLR to make it easier to compare runs.
Possible output:
&d 0x7fffffffc930
b2s[0] 0x7fffffffc920
b2s[1] 0x7fffffffc940
b2s[0]->f2() 2
b2s[1]->f2() 3
static_cast<D*>(b2s[0]) 0x7fffffffc910
static_cast<D*>(b2s[0])->int_in_d 1
static_cast<D*>(b2s[1]) 0x7fffffffc930
static_cast<D*>(b2s[1])->int_in_d 3
dynamic_cast<D*>(b2s[0]) 0
dynamic_cast<D*>(b2s[1]) 0x7fffffffc930
dynamic_cast<D*>(b2s[1])->int_in_d 3
reinterpret_cast<D*>(b2s[1]) 0x7fffffffc940
reinterpret_cast<D*>(b2s[1])->int_in_d 32767
Now, as mentioned at: https://en.wikipedia.org/wiki/Virtual_method_table in order to support the virtual method calls efficiently, the memory data structure of D
has to look something like:
B1:
+0: pointer to virtual method table of B1
+4: value of int_in_b1
B2:
+0: pointer to virtual method table of B2
+4: value of int_in_b2
D:
+0: pointer to virtual method table of D (for B1)
+4: value of int_in_b1
+8: pointer to virtual method table of D (for B2)
+12: value of int_in_b2
+16: value of int_in_d
The key fact is that the memory data structure of D
contains inside it memory structure compatible with that of B1
and that of B2
internally.
Therefore we reach the critical conclusion:
an upcast or downcast only needs to shift the pointer value by a value known at compile time
This way, when D
gets passed to the base type array, the type cast actually calculates that offset and points something that looks exactly like a valid B2
in memory:
b2s[1] = &d;
except that this one has the vtable for D
instead of B2
, and therefore all virtual calls work transparently.
Now, we can finally get back to type casting and the analysis of our concrete example.
From the stdout output we see:
&d 0x7fffffffc930
b2s[1] 0x7fffffffc940
Therefore, the implicit static_cast
done there did correctly calculate the offset from the full D
data structure at 0x7fffffffc930 to the B2
like one which is at 0x7fffffffc940. We also infer that what lies between 0x7fffffffc930 and 0x7fffffffc940 is likely be the B1
data and vtable.
Then, on the downcast sections, it is now easy to understand how the invalid ones fail and why:
static_cast<D*>(b2s[0]) 0x7fffffffc910
: the compiler just went up 0x10 at compile time bytes to try and go from a B2
to the containing D
But because b2s[0]
was not a D
, it now points to an undefined memory region.
The disassembly is:
49 dp = static_cast<D*>(b2s[0]);
0x0000000000000fc8 <+414>: 48 8b 45 d0 mov -0x30(%rbp),%rax
0x0000000000000fcc <+418>: 48 85 c0 test %rax,%rax
0x0000000000000fcf <+421>: 74 0a je 0xfdb <main()+433>
0x0000000000000fd1 <+423>: 48 8b 45 d0 mov -0x30(%rbp),%rax
0x0000000000000fd5 <+427>: 48 83 e8 10 sub $0x10,%rax
0x0000000000000fd9 <+431>: eb 05 jmp 0xfe0 <main()+438>
0x0000000000000fdb <+433>: b8 00 00 00 00 mov $0x0,%eax
0x0000000000000fe0 <+438>: 48 89 45 98 mov %rax,-0x68(%rbp)
so we see that GCC does:
D
which does not existdynamic_cast<D*>(b2s[0]) 0
: C++ actually found that the cast was invalid and returned nullptr
!
There is no way this can be done at compile time, and we will confirm that from the disassembly:
59 dp = dynamic_cast<D*>(b2s[0]);
0x00000000000010ec <+706>: 48 8b 45 d0 mov -0x30(%rbp),%rax
0x00000000000010f0 <+710>: 48 85 c0 test %rax,%rax
0x00000000000010f3 <+713>: 74 1d je 0x1112 <main()+744>
0x00000000000010f5 <+715>: b9 10 00 00 00 mov $0x10,%ecx
0x00000000000010fa <+720>: 48 8d 15 f7 0b 20 00 lea 0x200bf7(%rip),%rdx # 0x201cf8 <_ZTI1D>
0x0000000000001101 <+727>: 48 8d 35 28 0c 20 00 lea 0x200c28(%rip),%rsi # 0x201d30 <_ZTI2B2>
0x0000000000001108 <+734>: 48 89 c7 mov %rax,%rdi
0x000000000000110b <+737>: e8 c0 fb ff ff callq 0xcd0 <__dynamic_cast@plt>
0x0000000000001110 <+742>: eb 05 jmp 0x1117 <main()+749>
0x0000000000001112 <+744>: b8 00 00 00 00 mov $0x0,%eax
0x0000000000001117 <+749>: 48 89 45 98 mov %rax,-0x68(%rbp)
First there is a NULL check, and it returns NULL if th einput is NULL.
Otherwise, it sets up some arguments in the RDX, RSI and RDI and calls __dynamic_cast
.
I don't have the patience to analyze this further now, but as others said, the only way for this to work is for __dynamic_cast
to access some extra RTTI in-memory data structures that represent the class hierarchy.
It must therefore start from the B2
entry for that table, then walk this class hierarchy until it finds that the vtable for a D
typecast from b2s[0]
.
This is why reinterpret cast is potentially expensive! Here is an example where a one liner patch converting a dynamic_cast
to a static_cast
in a complex project reduced runtime by 33%!.
reinterpret_cast<D*>(b2s[1]) 0x7fffffffc940
this one just believes us blindly: we said there is a D
at address b2s[1]
, and the compiler does no offset calculations.
But this is wrong, because D is actually at 0x7fffffffc930, what is at 0x7fffffffc940 is the B2-like structure inside D! So trash gets accessed.
We can confirm this from the horrendous -O0
assembly that just moves the value around:
70 dp = reinterpret_cast<D*>(b2s[1]);
0x00000000000011fa <+976>: 48 8b 45 d8 mov -0x28(%rbp),%rax
0x00000000000011fe <+980>: 48 89 45 98 mov %rax,-0x68(%rbp)
Related questions:
Tested on Ubuntu 18.04 amd64, GCC 7.4.0.
if you are using sometimes playerID.stopVideo(); doesnot work, here is a trick,
function stopVideo() {
playerID.seekTo(0);
playerID.stopVideo();
}
No, they both have their uses:
Use xrange()
when iterating, as it saves memory. Say:
for x in xrange(1, one_zillion):
rather than:
for x in range(1, one_zillion):
On the other hand, use range()
if you actually want a list of numbers.
multiples_of_seven = range(7,100,7)
print "Multiples of seven < 100: ", multiples_of_seven
Action normally specifies the file/page that the form is submitted to (using the method described in the method paramater (post, get etc.))
An action of #
indicates that the form stays on the same page, simply suffixing the url with a #
. Similar use occurs in anchors. <a href=#">Link</a>
for example, will stay on the same page.
Thus, the form is submitted to the same page, which then processes the data etc.
You can also use rdp/specific_install gem:
gem install specific_install
gem specific_install https://github.com/capistrano/drupal-deploy.git
The simplest way is to map over the DataFrame's RDD and use mkString:
df.rdd.map(x=>x.mkString(","))
As of Spark 1.5 (or even before that)
df.map(r=>r.mkString(","))
would do the same
if you want CSV escaping you can use apache commons lang for that. e.g. here's the code we're using
def DfToTextFile(path: String,
df: DataFrame,
delimiter: String = ",",
csvEscape: Boolean = true,
partitions: Int = 1,
compress: Boolean = true,
header: Option[String] = None,
maxColumnLength: Option[Int] = None) = {
def trimColumnLength(c: String) = {
val col = maxColumnLength match {
case None => c
case Some(len: Int) => c.take(len)
}
if (csvEscape) StringEscapeUtils.escapeCsv(col) else col
}
def rowToString(r: Row) = {
val st = r.mkString("~-~").replaceAll("[\\p{C}|\\uFFFD]", "") //remove control characters
st.split("~-~").map(trimColumnLength).mkString(delimiter)
}
def addHeader(r: RDD[String]) = {
val rdd = for (h <- header;
if partitions == 1; //headers only supported for single partitions
tmpRdd = sc.parallelize(Array(h))) yield tmpRdd.union(r).coalesce(1)
rdd.getOrElse(r)
}
val rdd = df.map(rowToString).repartition(partitions)
val headerRdd = addHeader(rdd)
if (compress)
headerRdd.saveAsTextFile(path, classOf[GzipCodec])
else
headerRdd.saveAsTextFile(path)
}
The date.js library is handy for these things. It makes all JS date-related scriping a lot easier.
How about using spread operator as a parameter? The same block can be called with Multiple parameters. All the parameters are added into an array and inside the method you can loop in based on the length.
function mName(...opt){
console.log(opt);
}
mName(1,2,3,4); //[1,2,3,4]
mName(1,2,3); //[1,2,3]
Easyest way to do that is simply
IEnumerable<T> items = new T[]{new T("msg")};
List<string> itemsList = new List<string>();
itemsList.AddRange(items.Select(y => y.ToString()));
itemsList.Add("msg2");
Then you can return list as IEnumerable also because it implements IEnumerable interface
Well, I have tried something I hope it helps ..
They changed the schema a little bit ..
Use the following :
1- Change the AccessDataSource to SQLDataSource in the toolbox.
2- In the drop down menu choose your access database (xxxx.accdb or xxxx.mdb)
3- Next -> Next -> Test Query -> Finish.
Worked for me.
If you create an object, you get a more readable output and also gain an object with properties you can access:
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework'
$obj = New-Object -TypeName psobject
Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
$command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_)
$value = Invoke-Expression -Command $command
$obj | Add-Member -MemberType NoteProperty -Name $_ -Value $value}
Write-Output $obj | fl
Sample output: InstallRoot : C:\Windows\Microsoft.NET\Framework\
And the object: $obj.InstallRoot = C:\Windows\Microsoft.NET\Framework\
The truth of the matter is this is way more complicated than it needs to be. Here is a much better example, and much simpler:
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework'
$objReg = Get-ItemProperty -Path $path | Select -Property *
$objReg is now a custom object where each registry entry is a property name. You can view the formatted list via:
write-output $objReg
InstallRoot : C:\Windows\Microsoft.NET\Framework\
DbgManagedDebugger : "C:\windows\system32\vsjitdebugger.exe"
And you have access to the object itself:
$objReg.InstallRoot
C:\Windows\Microsoft.NET\Framework\
It can also happen if your password policy or something else have changed your password in case your appPools are using the the user with changed password.
So, you should update the user password from the advanced settings of your appPool throught "Identity" property.
The reference is here
Ex1:
Reading a single CSV file. Provide complete file path:
val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\tmp\\cars1.csv")
Ex2:
Reading multiple CSV files passing names:
val df=spark.read.option("header","true").csv("C:spark\\sample_data\\tmp\\cars1.csv", "C:spark\\sample_data\\tmp\\cars2.csv")
Ex3:
Reading multiple CSV files passing list of names:
val paths = List("C:spark\\sample_data\\tmp\\cars1.csv", "C:spark\\sample_data\\tmp\\cars2.csv")
val df = spark.read.option("header", "true").csv(paths: _*)
Ex4:
Reading multiple CSV files in a folder ignoring other files:
val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\tmp\\*.csv")
Ex5:
Reading multiple CSV files from multiple folders:
val folders = List("C:spark\\sample_data\\tmp", "C:spark\\sample_data\\tmp1")
val df = spark.read.option("header", "true").csv(folders: _*)
let cloneObj = Object.assign({}, this.form.getRawValue(), someClass);
this.form.complexForm.patchValue(cloneObj);
If you don't want manually set each field.
I found that the above answer caused me an exception when I tried to instantiate the parser. I found the following code that resolved this at http://docstore.mik.ua/orelly/xml/sax2/ch03_02.htm.
import org.xml.sax.*;
import javax.xml.parsers.*;
XMLReader parser;
try {
SAXParserFactory factory;
factory = SAXParserFactory.newInstance ();
factory.setNamespaceAware (true);
parser = factory.newSAXParser ().getXMLReader ();
// success!
} catch (FactoryConfigurationError err) {
System.err.println ("can't create JAXP SAXParserFactory, "
+ err.getMessage ());
} catch (ParserConfigurationException err) {
System.err.println ("can't create XMLReader with namespaces, "
+ err.getMessage ());
} catch (SAXException err) {
System.err.println ("Hmm, SAXException, " + err.getMessage ());
}
Select
Count(Distinct user_id) As countUsers
, Count(site_id) As countVisits
, site_id As site
From cp_visits
Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Group By site_id
Just to augment this for anyone looking, you are also able to just:
$("#selectBox option[value='option1']").hide();
and
$("#selectBox option[value='option1']").show();
If you are happy to use an external library, the org.apache.commons.codec.binary.Hex
class has an encodeHex
method which takes a byte[]
and returns a char[]
. This methods is MUCH faster than the format option, and encapsulates the details of the conversion. Also comes with a decodeHex
method for the opposite conversion.
The accepted answer does not work when you have multiple items to copy, and each with a separate "copy to clipboard" button. After clicking one button, the others will not work.
To make them work, I added some code to the accepted answer's function to clear text selections before doing a new one:
function CopyToClipboard(containerid) {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select().createTextRange();
document.execCommand("copy");
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
document.execCommand("copy");
}
}
You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.
Rows("52:55").EntireRow.Hidden = False
becomes
activesheet.Rows("52:55").EntireRow.Hidden = False
i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,
Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub
That's it. Anytime you change something, it will run the macro test1.
I think this answer is quite readable:
def month_delta(dt, delta):
year_delta, month = divmod(dt.month + delta, 12)
if month == 0:
# convert a 0 to december
month = 12
if delta < 0:
# if moving backwards, then it's december of last year
year_delta -= 1
year = dt.year + year_delta
return dt.replace(month=month, year=year)
for delta in range(-20, 21):
print(delta, "->", month_delta(datetime(2011, 1, 1), delta))
-20 -> 2009-05-01 00:00:00
-19 -> 2009-06-01 00:00:00
-18 -> 2009-07-01 00:00:00
-17 -> 2009-08-01 00:00:00
-16 -> 2009-09-01 00:00:00
-15 -> 2009-10-01 00:00:00
-14 -> 2009-11-01 00:00:00
-13 -> 2009-12-01 00:00:00
-12 -> 2010-01-01 00:00:00
-11 -> 2010-02-01 00:00:00
-10 -> 2010-03-01 00:00:00
-9 -> 2010-04-01 00:00:00
-8 -> 2010-05-01 00:00:00
-7 -> 2010-06-01 00:00:00
-6 -> 2010-07-01 00:00:00
-5 -> 2010-08-01 00:00:00
-4 -> 2010-09-01 00:00:00
-3 -> 2010-10-01 00:00:00
-2 -> 2010-11-01 00:00:00
-1 -> 2010-12-01 00:00:00
0 -> 2011-01-01 00:00:00
1 -> 2011-02-01 00:00:00
2 -> 2011-03-01 00:00:00
3 -> 2011-04-01 00:00:00
4 -> 2011-05-01 00:00:00
5 -> 2011-06-01 00:00:00
6 -> 2011-07-01 00:00:00
7 -> 2011-08-01 00:00:00
8 -> 2011-09-01 00:00:00
9 -> 2011-10-01 00:00:00
10 -> 2011-11-01 00:00:00
11 -> 2012-12-01 00:00:00
12 -> 2012-01-01 00:00:00
13 -> 2012-02-01 00:00:00
14 -> 2012-03-01 00:00:00
15 -> 2012-04-01 00:00:00
16 -> 2012-05-01 00:00:00
17 -> 2012-06-01 00:00:00
18 -> 2012-07-01 00:00:00
19 -> 2012-08-01 00:00:00
20 -> 2012-09-01 00:00:00
The reason Herb said what he said is because of cases like this.
Let's say I have function A
which calls function B
, which calls function C
. And A
passes a string through B
and into C
. A
does not know or care about C
; all A
knows about is B
. That is, C
is an implementation detail of B
.
Let's say that A is defined as follows:
void A()
{
B("value");
}
If B and C take the string by const&
, then it looks something like this:
void B(const std::string &str)
{
C(str);
}
void C(const std::string &str)
{
//Do something with `str`. Does not store it.
}
All well and good. You're just passing pointers around, no copying, no moving, everyone's happy. C
takes a const&
because it doesn't store the string. It simply uses it.
Now, I want to make one simple change: C
needs to store the string somewhere.
void C(const std::string &str)
{
//Do something with `str`.
m_str = str;
}
Hello, copy constructor and potential memory allocation (ignore the Short String Optimization (SSO)). C++11's move semantics are supposed to make it possible to remove needless copy-constructing, right? And A
passes a temporary; there's no reason why C
should have to copy the data. It should just abscond with what was given to it.
Except it can't. Because it takes a const&
.
If I change C
to take its parameter by value, that just causes B
to do the copy into that parameter; I gain nothing.
So if I had just passed str
by value through all of the functions, relying on std::move
to shuffle the data around, we wouldn't have this problem. If someone wants to hold on to it, they can. If they don't, oh well.
Is it more expensive? Yes; moving into a value is more expensive than using references. Is it less expensive than the copy? Not for small strings with SSO. Is it worth doing?
It depends on your use case. How much do you hate memory allocations?
Even though it is an older post but as I came across it while looking for same problem so I thought I will add my two cents as well. Here is my version of Spinner's background with DropDown arrow. Just the complete background, not only the arrow.
Apply on spinner like...
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/spinner_bg" />
spinner_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<color android:color="@color/InputBg" />
</item>
<item android:gravity="center_vertical|right" android:right="8dp">
<layer-list>
<item android:width="12dp" android:height="12dp" android:gravity="center" android:bottom="10dp">
<rotate
android:fromDegrees="45"
android:toDegrees="45">
<shape android:shape="rectangle">
<solid android:color="#666666" />
<stroke android:color="#aaaaaa" android:width="1dp"/>
</shape>
</rotate>
</item>
<item android:width="30dp" android:height="10dp" android:bottom="21dp" android:gravity="center">
<shape android:shape="rectangle">
<solid android:color="@color/InputBg"/>
</shape>
</item>
</layer-list>
</item>
</layer-list>
@color/InputBg
should be replaced by the color you want as your background.
First it fills the background with desired color. Then a child layer-list makes a square and rotates it by 45 degrees and then a second Rectangle with background color covers the top part of rotated square making it look like a down arrow. (There is an extra stroke in rotated rectangle with is not really required)
HTML Code
<div class="rCol">
<div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
</div>
<div class="rCol" style="clear:both;">
<label > Upload Photo : </label>
<input type="file" id="file" name='file' onChange=" return submitForm();">
<input type="hidden" id="filecount" value='0'>
Here is Ajax Code:
function submitForm() {
var fcnt = $('#filecount').val();
var fname = $('#filename').val();
var imgclean = $('#file');
if(fcnt<=5)
{
data = new FormData();
data.append('file', $('#file')[0].files[0]);
var imgname = $('input[type=file]').val();
var size = $('#file')[0].files[0].size;
var ext = imgname.substr( (imgname.lastIndexOf('.') +1) );
if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG')
{
if(size<=1000000)
{
$.ajax({
url: "<?php echo base_url() ?>/upload.php",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' )
{
fcnt = parseInt(fcnt)+1;
$('#filecount').val(fcnt);
var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"><a href="#" id="rmv_'+fcnt+'" onclick="return removeit('+fcnt+')" class="close-classic"></a></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
$('#prv').append(img);
if(fname!=='')
{
fname = fname+','+data;
}else
{
fname = data;
}
$('#filename').val(fname);
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
}
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('SORRY SIZE AND TYPE ISSUE');
}
});
return false;
}//end size
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
alert('Sorry File size exceeding from 1 Mb');
}
}//end FILETYPE
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
}
}//end filecount
else
{ imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('You Can not Upload more than 6 Photos');
}
}
Here is PHP code :
$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG');
foreach ($_FILES as $key )
{
$name =time().$key['name'];
$path='local_cdn/'.$name;
$file_ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array(strtolower($file_ext), $filetype))
{
if($key['name']<1000000)
{
@move_uploaded_file($key['tmp_name'],$path);
echo $name;
}
else
{
echo "FILE_SIZE_ERROR";
}
}
else
{
echo "FILE_TYPE_ERROR";
}// Its simple code.Its not with proper validation.
Here upload and preview part done.Now if you want to delete and remove image from page and folder both then code is here for deletion. Ajax Part:
function removeit (arg) {
var id = arg;
// GET FILE VALUE
var fname = $('#filename').val();
var fcnt = $('#filecount').val();
// GET FILE VALUE
$('#img_'+id).remove();
$('#rmv_'+id).remove();
$('#img_'+id).css('display','none');
var dname = $('#name_'+id).val();
fcnt = parseInt(fcnt)-1;
$('#filecount').val(fcnt);
var fname = fname.replace(dname, "");
var fname = fname.replace(",,", "");
$('#filename').val(fname);
$.ajax({
url: 'delete.php',
type: 'POST',
data:{'name':dname},
success:function(a){
console.log(a);
}
});
}
Here is PHP part(delete.php):
$path='local_cdn/'.$_POST['name'];
if(@unlink($path))
{
echo "Success";
}
else
{
echo "Failed";
}
I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.
package local.test.servlet;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;
@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
// /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
System.out.println(templateFileUrl.getPath());
String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
String outputFileDir = "MasatoExcelHorizontalOutput";
ReportProcessor reportProcessor = new ReportProcessor();
ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);
ReportSheet outputSheet = new ReportSheet("MySheet");
outputBook.addReportSheet(outputSheet);
reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
System.out.println("wtf???");
reportProcessor.process(outputBook);
System.out.println("done!!");
}
catch(Exception e) {
System.out.println(e);
}
} //end doGet()
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}//end class
class OutputStreamExporter extends ReportBookExporter {
private HttpServletResponse response;
public OutputStreamExporter(HttpServletResponse response) {
this.response = response;
}
@Override
public String getExtention() {
return null;
}
@Override
public String getFormatType() {
return ExcelExporter.FORMAT_TYPE;
}
@Override
public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {
System.out.println(book.getFirstVisibleTab());
System.out.println(book.getSheetName(0));
//TODO write to stream
try {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
book.write(response.getOutputStream());
response.getOutputStream().close();
System.out.println("booya!!");
}
catch(Exception e) {
System.out.println(e);
}
}
}//end class
If these are elements naturally in the tab order like buttons and anchors, removing them from the tab order with tabindex="-1"
is kind of an accessibility smell. If they're providing duplicate functionality removing them from the tab order is ok, and consider adding aria-hidden="true"
to these elements so assistive technologies will ignore them.
The following way has helped me (includes react-hot, babel loaders and es2015, react presets):
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react']
}
]
After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:
10
but you want it to return a String and not a Fixnum, write '10'
or "10"
.:
, {
, }
, [
, ]
, ,
, &
, *
, #
, ?
, |
, -
, <
, >
, =
, !
, %
, @
, \
).'\n'
would be returned as the string \n
."\n"
would be returned as a line feed character.!ruby/sym
to return a Ruby symbol.Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.
Update
"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:
en:
yesno:
'yes': 'Yes'
'no': 'No'
In Swift 4, just as simple as Swift 3:
self.view.backgroundColor = UIColor.brown
SQL Server uses the TCP port 1433. This is probably blocked either by the VPN tunnel or by a firewall on the server.
For percent increase and decrease, using 2 different methods:
const a = 541
const b = 394
// Percent increase
console.log(
`Increase (from ${b} to ${a}) => `,
(((a/b)-1) * 100).toFixed(2) + "%",
)
// Percent decrease
console.log(
`Decrease (from ${a} to ${b}) => `,
(((b/a)-1) * 100).toFixed(2) + "%",
)
// Alternatives, using .toLocaleString()
console.log(
`Increase (from ${b} to ${a}) => `,
((a/b)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)
console.log(
`Decrease (from ${a} to ${b}) => `,
((b/a)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)
_x000D_
I found that "phpseclib" should help you with this (SFTP and many more features). http://phpseclib.sourceforge.net/
To Put the file to the server, simply call (Code example from http://phpseclib.sourceforge.net/sftp/examples.html#put)
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE);
Here is a VB.Net example if you are trying to retrieve the value of a variable from within a page loaded in a WebBrowser control.
Step 1) Add a COM reference in your project to Microsoft HTML Object Library
Step 2) Next, add this VB.Net code to your Form1 to import the mshtml library:
Imports mshtml
Step 3) Add this VB.Net code above your "Public Class Form1" line:
<System.Runtime.InteropServices.ComVisibleAttribute(True)>
Step 4) Add a WebBrowser control to your project
Step 5) Add this VB.Net code to your Form1_Load function:
WebBrowser1.ObjectForScripting = Me
Step 6) Add this VB.Net sub which will inject a function "CallbackGetVar" into the web page's Javascript:
Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser)
Dim head As HtmlElement
Dim script As HtmlElement
Dim domElement As IHTMLScriptElement
head = wb.Document.GetElementsByTagName("head")(0)
script = wb.Document.CreateElement("script")
domElement = script.DomElement
domElement.type = "text/javascript"
domElement.text = "function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }"
head.AppendChild(script)
End Sub
Step 7) Add the following VB.Net sub which the Javascript will then look for when invoked:
Public Sub Callback_GetVar(ByVal vVar As String)
Debug.Print(vVar)
End Sub
Step 8) Finally, to invoke the Javascript callback, add this VB.Net code when a button is pressed, or wherever you like:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
WebBrowser1.Document.InvokeScript("CallbackGetVar", New Object() {"NameOfVarToRetrieve"})
End Sub
Step 9) If it surprises you that this works, you may want to read up on the Javascript "eval" function, used in Step 6, which is what makes this possible. It will take a string and determine whether a variable exists with that name and, if so, returns the value of that variable.
In the latest version of the SDK, you would use the setBackgroundResource
method.
public void onClick(View v) {
if(v == ButtonName) {
ButtonName.setBackgroundResource(R.drawable.ImageResource);
}
}
My cause was different I referenced a web service then I got this message.
Then I changed my target .Net Framework 4.0 to .Net Framework 2.0 and re-refer my webservice. After a few changes problem solved. There is no error worked fine.
hope this helps!
This one is tricky problem, i set margin to textview in a row of a table layout. see the below:
TableLayout tl = new TableLayout(this);
tl.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
TableRow tr = new TableRow(this);
tr.setBackgroundResource(R.color.rowColor);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(4, 4, 4, 4);
TextView tv = new TextView(this);
tv.setBackgroundResource(R.color.textviewColor);
tv.setText("hello");
tr.addView(tv, params);
TextView tv2 = new TextView(this);
tv2.setBackgroundResource(R.color.textviewColor);
tv2.setText("hi");
tr.addView(tv2, params);
tl.addView(tr);
setContentView(tl);
the class needed to import for LayoutParams for use in a table row is :
import android.widget.**TableRow**.LayoutParams;
important to note that i added the class for table row. similarly many other classes are available to use LayoutParams like:
import android.widget.**RelativeLayout**.LayoutParams;
import android.widget.LinearLayout.LayoutParams;
so use accordingly.
I had the same issue and eventually chose to use a Rectangle element:
<Rectangle HorizontalAlignment="Stretch" Fill="Blue" Height="4"/>
In my opinion it's somewhat easier to modify/shape than a separator.
Of course the Separator
is a very easy and neat solution for simple separations :)
Based on https://github.com/SonarSource/sonar-examples/blob/master/projects/tycho/pom.xml, the following POM works for me:
<properties>
<sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.0.201403182114</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
<configuration>
<destFile>${sonar.jacoco.reportPath}</destFile>
</configuration>
</plugin>
</plugins>
</build>
reuseReports
setting prevents the deletion of the JaCoCo report file before it is read! (Since 4.3, this is the default and is deprecated.)Then I just run
mvn clean install
mvn sonar:sonar
This worked for me on Windows Server 2012 - I needed to export a non-exportable certificate to setup another ADFS server and this did the trick. Remember to use the jailbreak instructions above i.e.:
crypto::certificates /export /systemstore:CERT_SYSTEM_STORE_LOCAL_MACHINE
Range("$A$1").Value = "'01/01/13 00:00"
will do it.
Note the single quote; this will defeat automatic conversion to a number type. But is that what you really want? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.
In order to read a file chosen by the user, using a file open dialog, you can use the <input type="file">
tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.
function onFileLoad(elementId, event) {_x000D_
document.getElementById(elementId).innerText = event.target.result;_x000D_
}_x000D_
_x000D_
function onChooseFile(event, onLoadFileHandler) {_x000D_
if (typeof window.FileReader !== 'function')_x000D_
throw ("The file API isn't supported on this browser.");_x000D_
let input = event.target;_x000D_
if (!input)_x000D_
throw ("The browser does not properly implement the event object");_x000D_
if (!input.files)_x000D_
throw ("This browser does not support the `files` property of the file input.");_x000D_
if (!input.files[0])_x000D_
return undefined;_x000D_
let file = input.files[0];_x000D_
let fr = new FileReader();_x000D_
fr.onload = onLoadFileHandler;_x000D_
fr.readAsText(file);_x000D_
}
_x000D_
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />_x000D_
<p id="contents"></p>
_x000D_
As of IE6 I believe you cannot customize the scroll bar using those properties. The Chris Coyier article linked to above goes into nice detail about the options for webkit proprietary css for customizing the scroll bar.
If you really want a cross browser solution that you can fully customize you're going to have to use some JS. Here is a link to a nice plugin for it called FaceScroll: http://www.dynamicdrive.com/dynamicindex11/facescroll/index.htm
Resolved by saving dependent object before the next.
This was happened to me because I was not setting Id (which was not auto generated). and trying to save with relation @ManytoOne
ISO C states what the differences are.
The int
data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h
as INT_MIN
and INT_MAX
respectively.
An unsigned int
has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX
from that same header file.
Beyond that, the standard does not mandate twos complement notation for encoding the values, that's just one of the possibilities. The three allowed types would have encodings of the following for 5 and -5 (using 16-bit data types):
two's complement | ones' complement | sign/magnitude
+---------------------+---------------------+---------------------+
5 | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101 |
-5 | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101 |
+---------------------+---------------------+---------------------+
Note that positive values have the same encoding for all representations, only the negative values are different.
Note further that, for unsigned values, you do not need to use one of the bits for a sign. That means you get more range on the positive side (at the cost of no negative encodings, of course).
And no, 5
and -5
cannot have the same encoding regardless of which representation you use. Otherwise, there'd be no way to tell the difference.
As an aside, there are currently moves underway, in both C and C++ standards, to nominate two's complement as the only encoding for negative integers.
Just check the string against this regex:
if(mystring.match(/^\s+$/) === null) {
alert("String is good");
} else {
alert("String contains only whitespace");
}
In my case i had some problem with opacity transition so this one fix it:
#dropdown {
transition:.6s opacity;
}
#dropdown.ns {
opacity:0;
transition:.6s all;
}
#dropdown.fade {
opacity:1;
}
Mouse Enter
$('#dropdown').removeClass('ns').addClass('fade');
Mouse Leave
$('#dropdown').addClass('ns').removeClass('fade');
It's possible to pass multiple parameters as a single model as vijay suggested. This works for GET when you use the FromUri parameter attribute. This tells WebAPI to fill the model from the query parameters.
The result is a cleaner controller action with just a single parameter. For more information see: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
public class BooksController : ApiController
{
// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query)
{
// ...
}
}
public class BookQuery
{
public string Author { get; set; }
public string Title { get; set; }
public string ISBN { get; set; }
public string SomethingElse { get; set; }
public DateTime? Date { get; set; }
}
It even supports multiple parameters, as long as the properties don't conflict.
// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query, [FromUri]Paging paging)
{
// ...
}
public class Paging
{
public string Sort { get; set; }
public int Skip { get; set; }
public int Take { get; set; }
}
Update:
In order to ensure the values are optional make sure to use reference types or nullables (ex. int?) for the models properties.
Fetch vs Pull
Git fetch just updates your repo data, but a git pull will basically perform a fetch and then merge the branch pulled
What is the difference between 'git pull' and 'git fetch'?
Merge vs Rebase
from Atlassian SourceTree Blog, Merge or Rebase:
Merging brings two lines of development together while preserving the ancestry of each commit history.
In contrast, rebasing unifies the lines of development by re-writing changes from the source branch so that they appear as children of the destination branch – effectively pretending that those commits were written on top of the destination branch all along.
Also, check out Learn Git Branching, which is a nice game that has just been posted to HackerNews (link to post) and teaches a lot of branching and merging tricks. I believe it will be very helpful in this matter.
In my case, I was developing a Windows CE app, that tested against an emulator. The problem was that the executable wasn't deployed to the emulator, so the .pdb (in the development environment) was out of sync with the .exe (in the emulator), because the new .exe was never copied to the emulator. I had to delete the .exe in the emulator to force a new deployment. Then it worked.
You are setting the extra with an array. You are then trying to get a single int.
Your code should be:
int[] arrayB = extras.getIntArray("numbers");
You should use @input
:
<input @input="handleInput" />
@input
fires when user changes input value.
@change
fires when user changed value and unfocus input (for example clicked somewhere outside)
You can see the difference here: https://jsfiddle.net/posva/oqe9e8pb/
The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:
var array = db.CollectionName.find({}).sort({ _id: -1 }).limit(1).toArray(); var max = max.length?max[0]+1:1;
Even if an User ID is deleted, this wont create duplicate