This is the function I use to modify the exception message in Python 2.7 and 3.x while preserving the original traceback. It requires six
def reraise_modify(caught_exc, append_msg, prepend=False):
"""Append message to exception while preserving attributes.
Preserves exception class, and exception traceback.
Note:
This function needs to be called inside an except because
`sys.exc_info()` requires the exception context.
Args:
caught_exc(Exception): The caught exception object
append_msg(str): The message to append to the caught exception
prepend(bool): If True prepend the message to args instead of appending
Returns:
None
Side Effects:
Re-raises the exception with the preserved data / trace but
modified message
"""
ExceptClass = type(caught_exc)
# Keep old traceback
traceback = sys.exc_info()[2]
if not caught_exc.args:
# If no args, create our own tuple
arg_list = [append_msg]
else:
# Take the last arg
# If it is a string
# append your message.
# Otherwise append it to the
# arg list(Not as pretty)
arg_list = list(caught_exc.args[:-1])
last_arg = caught_exc.args[-1]
if isinstance(last_arg, str):
if prepend:
arg_list.append(append_msg + last_arg)
else:
arg_list.append(last_arg + append_msg)
else:
arg_list += [last_arg, append_msg]
caught_exc.args = tuple(arg_list)
six.reraise(ExceptClass,
caught_exc,
traceback)
Note: starting git1.8.3.2 (July 2013), the following command (mentioned above by Jeremy W Sherman) won't open an editor anymore:
git commit --allow-empty-message -m ''
See commit 25206778aac776fc6cc4887653fdae476c7a9b5a:
If an empty message is specified with the option
-m
of git commit then the editor is started.
That's unexpected and unnecessary.
Instead of using the length of the message string for checking if the user specified one, directly remember if the option-m
was given.
git 2.9 (June 2016) improves the empty message behavior:
See commit 178e814 (06 Apr 2016) by Adam Dinwoodie (me-and
).
See commit 27014cb (07 Apr 2016) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 0709261, 22 Apr 2016)
commit
: do not ignore an empty message given by-m ''
- "
git commit --amend -m '' --allow-empty-message
", even though it looks strange, is a valid request to amend the commit to have no message at all.
Due to the misdetection of the presence of-m
on the command line, we ended up keeping the log messsage from the original commit.- "
git commit -m "$msg" -F file
" should be rejected whether$msg
is an empty string or not, but due to the same bug, was not rejected when$msg
is empty.- "
git -c template=file -m "$msg"
" should ignore the template even when$msg
is empty, but it didn't and instead used the contents from the template file.
Have you tried just going: git commit -m "Message here"
So in your case:
git commit -m "Form validation added"
After you've added your files of course.
The solution below worked for me. It successfully sends an email to multiple recipients, including "CC" and "BCC."
toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n !! Hello... !!"
msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject
s.sendmail(fromaddr, (toaddr+cc+bcc) , message)
You can use .delay()
before an animation, like this:
$("#myElem").show().delay(5000).fadeOut();
If it's not an animation, use setTimeout()
directly, like this:
$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);
You do the second because .hide()
wouldn't normally be on the animation (fx
) queue without a duration, it's just an instant effect.
Or, another option is to use .delay()
and .queue()
yourself, like this:
$("#myElem").show().delay(5000).queue(function(n) {
$(this).hide(); n();
});
You can get access to the WhatsApp data base located on the SD card only as a root user I think. if you open "\data\data\com.whatsapp" you will see that "databases" is linked to "\firstboot\sqlite\com.whatsapp\"
When the user starts making changes to the form, a boolean flag will be set. If the user then tries to navigate away from the page, you check that flag in the window.onunload event. If the flag is set, you show the message by returning it as a string. Returning the message as a string will popup a confirmation dialog containing your message.
If you are using ajax to commit the changes, you can set the flag to false
after the changes have been committed (i.e. in the ajax success event).
Check Following : 1) Package names 2) Import Statements (import every required packages) 3) Proper set of braces ,i.e { } 4) Check Syntax too.. i.e semicolons,commas,etc.
String String_firstNumber = JOptionPane.showInputDialog("Input Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);
Now your Int_firstnumber
contains integer value of String_fristNumber
.
hope it helped
This usually happens to me when I have a using statement but have forgotten to reference the assembly that defines the namespace.
But in your case, as the namespace is defined in a file in your project, you have forgotten to tell the compiler about the snarlnetwork.cs file.
what you want is:
MY_FIELD=
case
when (selectField1 = 1) then Field1
else Field2
end,
in the select
However, y don't you just not show that column in your program?
you can define a custom ScrollView class, & add an interface be called when scrolling like this:
public class ScrollChangeListenerScrollView extends HorizontalScrollView {
private MyScrollListener mMyScrollListener;
public ScrollChangeListenerScrollView(Context context) {
super(context);
}
public ScrollChangeListenerScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ScrollChangeListenerScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setOnMyScrollListener(MyScrollListener myScrollListener){
this.mMyScrollListener = myScrollListener;
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if(mMyScrollListener!=null){
mMyScrollListener.onScrollChange(this,l,t,oldl,oldt);
}
}
public interface MyScrollListener {
void onScrollChange(View view,int scrollX,int scrollY,int oldScrollX, int oldScrollY);
}
}
What database are you on? With MS SQL Server, it's a database-wide setting, or you can over-ride it per-query with the COLLATE keyword.
The key is "argument-less git-pull". When you do a git pull
from a branch, without specifying a source remote or branch, git looks at the branch.<name>.merge
setting to know where to pull from. git push -u
sets this information for the branch you're pushing.
To see the difference, let's use a new empty branch:
$ git checkout -b test
First, we push without -u
:
$ git push origin test
$ git pull
You asked me to pull without telling me which branch you
want to merge with, and 'branch.test.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.
If you often merge with the same branch, you may want to
use something like the following in your configuration file:
[branch "test"]
remote = <nickname>
merge = <remote-ref>
[remote "<nickname>"]
url = <url>
fetch = <refspec>
See git-config(1) for details.
Now if we add -u
:
$ git push -u origin test
Branch test set up to track remote branch test from origin.
Everything up-to-date
$ git pull
Already up-to-date.
Note that tracking information has been set up so that git pull
works as expected without specifying the remote or branch.
Update: Bonus tips:
git pull
this setting also affects default behavior of git push
. If you get in the habit of using -u
to capture the remote branch you intend to track, I recommend setting your push.default
config value to upstream
.git push -u <remote> HEAD
will push the current branch to a branch of the same name on <remote>
(and also set up tracking so you can do git push
after that).ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;
Never mind, I figured it out - I used the Set()
method on Header()
(doh!)
My handler looks like this now:
func saveHandler(w http.ResponseWriter, r *http.Request) {
// allow cross domain AJAX requests
w.Header().Set("Access-Control-Allow-Origin", "*")
}
Maybe this will help someone as caffeine deprived as myself sometime :)
Use:
.content {
background: url('http://www.gransebryan.com/wp-content/uploads/2016/03/bryan-ganzon-granse-who.png') center no-repeat;
}
.displaybg {
text-align: center;
color: #FFF;
}
I found this solution online, and it addressed this pretty well. My only concern is looping through all the pivots and queries might become time consuming if there's a lot of them:
Sub RefreshTables()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim objList As ListObject
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
For Each objList In ws.ListObjects
If objList.SourceType = 3 Then
With objList.QueryTable
.BackgroundQuery = False
.Refresh
End With
End If
Next objList
Next ws
Call UpdateAllPivots
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Sub UpdateAllPivots()
Dim pt As PivotTable
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
For Each pt In ws.PivotTables
pt.RefreshTable
Next pt
Next ws
End Sub
Most browsers don't display the custom message passed to confirm()
.
With this method, you can show a popup with a custom message if your user changed the value of any <input>
field.
You can apply this only to some links, or even other HTML elements in your page. Just add a custom class to all the links that need confirmation and apply use the following code:
$(document).ready(function() {_x000D_
let unsaved = false;_x000D_
// detect changes in all input fields and set the 'unsaved' flag_x000D_
$(":input").change(() => unsaved = true);_x000D_
// trigger popup on click_x000D_
$('.dangerous-link').click(function() {_x000D_
if (unsaved && !window.confirm("Are you sure you want to nuke the world?")) {_x000D_
return; // user didn't confirm_x000D_
}_x000D_
// either there are no unsaved changes or the user confirmed_x000D_
window.location.href = $(this).data('destination');_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<input type="text" placeholder="Nuclear code here" />_x000D_
<a data-destination="https://en.wikipedia.org/wiki/Boom" class="dangerous-link">_x000D_
Launch nuke!_x000D_
</a>
_x000D_
Try changing the input value in the example to get a preview of how it works.
You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)
usually the log file is in
/var/log/apache2/error.log
or
/var/log/httpd/error.log
I think that the best way to stop the execution is the time.sleep() function.
If you need to suspend the execution only in certain cases you can simply implement an if statement like this:
if somethinghappen:
time.sleep(seconds)
You can leave the else branch empty.
This link explains everything in depth, including why those multiplier constants exist before the R, G and B values.
Edit: It has an explanation to one of the answers here too (0.299*R + 0.587*G + 0.114*B)
You need to enable it. Check out the Permission section of the xp_cmdshell MSDN docs:
http://msdn.microsoft.com/en-us/library/ms190693.aspx:
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO
Arrays can't be resized, so you need to allocte a new array that is larger, write the new byte at the beginning of it, and use Buffer.BlockCopy to transfer the contents of the old array across.
My simple solution without regex
int start=Edit1.getSelectionStart();
String sp=Edit1.getText().toString();
sp=sp.replace(",",".");
Double d=Double.valueOf(sp);
String s=String.format("%.2f",d );
if(!Edit1.getText().toString().equals(s))
Edit1.setText(s);
if(start>Edit1.getText().length())start--;
Edit1.setSelection(start);
putting into onTextChange. By deleting the comma, the zeros double because the number becomes an integer.
I thought Activity was deprecated
No.
So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I use both to host the components, and for the components themselves? Are there uses for all of these, or should I be using one or two almost exclusively?
Activity
is the baseline. Every activity inherits from Activity
, directly or indirectly.
FragmentActivity
is for use with the backport of fragments found in the support-v4
and support-v13
libraries. The native implementation of fragments was added in API Level 11, which is lower than your proposed minSdkVersion
values. The only reason why you would need to consider FragmentActivity
specifically is if you want to use nested fragments (a fragment holding another fragment), as that was not supported in native fragments until API Level 17.
AppCompatActivity
is from the appcompat-v7
library. Principally, this offers a backport of the action bar. Since the native action bar was added in API Level 11, you do not need AppCompatActivity
for that. However, current versions of appcompat-v7
also add a limited backport of the Material Design aesthetic, in terms of the action bar and various widgets. There are pros and cons of using appcompat-v7
, well beyond the scope of this specific Stack Overflow answer.
ActionBarActivity
is the old name of the base activity from appcompat-v7
. For various reasons, they wanted to change the name. Unless some third-party library you are using insists upon an ActionBarActivity
, you should prefer AppCompatActivity
over ActionBarActivity
.
So, given your minSdkVersion
in the 15-16 range:
If you want the backported Material Design look, use AppCompatActivity
If not, but you want nested fragments, use FragmentActivity
If not, use Activity
Just adding from comment as note: AppCompatActivity
extends FragmentActivity
, so anyone who needs to use features of FragmentActivity
can use AppCompatActivity
.
These functions are used in stacktrace.js:
/**
* Try XHR methods in order and store XHR factory.
*
* @return <Function> XHR function or equivalent
*/
var createXMLHTTPObject = function() {
var xmlhttp, XMLHttpFactories = [
function() {
return new XMLHttpRequest();
}, function() {
return new ActiveXObject('Msxml2.XMLHTTP');
}, function() {
return new ActiveXObject('Msxml3.XMLHTTP');
}, function() {
return new ActiveXObject('Microsoft.XMLHTTP');
}
];
for (var i = 0; i < XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
// Use memoization to cache the factory
createXMLHTTPObject = XMLHttpFactories[i];
return xmlhttp;
} catch (e) {
}
}
}
/**
* @return the text from a given URL
*/
function ajax(url) {
var req = createXMLHTTPObject();
if (req) {
try {
req.open('GET', url, false);
req.send(null);
return req.responseText;
} catch (e) {
}
}
return '';
}
You can use Javascript URLSearchParams.
var url = new URL(window.location.href);
url.searchParams.set('single','');
window.location.href = url.href;
[UPDATE]: If IE support is a need, check this thread:
SCRIPT5009: 'URLSearchParams' is undefined in IE 11
Thanks @john-m to talk about the IE support
Use %p
, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u
expects an unsigned int
, but what if void*
has a different size or alignment requirement than unsigned int
?)
*) [See Jonathan's fine answer!] Alternatively to %p
, you can use pointer-specific macros from <inttypes.h>
, added in C99.
All object pointers are implicitly convertible to void*
in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):
printf("x lives at %p.\n", (void*)&x);
If you include the following code at the top of your script, matplotlib
will run inline when in an IPython
environment (like jupyter, hydrogen atom plugin...), and it will still work if you launch the script directly via command line (matplotlib
won't run inline, and the charts will open in a pop-ups as usual).
from IPython import get_ipython
ipy = get_ipython()
if ipy is not None:
ipy.run_line_magic('matplotlib', 'inline')
When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.
string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";
Change it to a table-valued function
Please refer to the following link, for example.
This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx
/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */
chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });
Russian Edition
offers CSV
, CSV (Macintosh)
and CSV (DOS)
.
When saving in plain CSV
, it uses windows-1251
.
I just tried to save French word Résumé
along with the Russian text, it saved it in HEX
like 52 3F 73 75 6D 3F
, 3F
being the ASCII
code for question mark
.
When I opened the CSV
file, the word, of course, became unreadable (R?sum?
)
My understanding is that adding r+
opens for both read and write (just like w+
, though as pointed out in the comment, will truncate the file). The b
just opens it in binary mode, which is supposed to be less aware of things like line separators (at least in C++).
You should write in this way
public function up()
{
Schema::create('transactions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->float('amount', 11, 2);
$table->enum('transaction type', ['debit', 'credit']);
$table->bigInteger('customer_id')->unsigned();
$table->timestamps();
});
Schema::table('transactions', function($table) {
$table->foreign('customer_id')
->references('id')->on('customers')
->onDelete('cascade');
});
}
The foreign key field should be unsigned, hope it helps!!
If you need a body in your response, you can call
return StatusCode(StatusCodes.Status500InternalServerError, responseObject);
This will return a 500 with the response object...
What about ordering desc by the desired property,
blah = blah.OrderByDescending(x => x.Property);
And then doing something like
if (!descending)
{
blah = blah.Reverse()
}
else
{
// Already sorted desc ;)
}
Is it Reverse() too slow?
You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:
render: function() {
return (
<span>
// This will go through all the elements in arrayFromJson and
// render each one as a <SomeComponent /> with data from the object
{this.state.arrayFromJson.map(function(object) {
return (
<SomeComponent key={object.id} data={object} />
);
})}
</span>
);
}
I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.
I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.
So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.
I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.
You can check if a element is disabled or not with this:
if($("#slcCausaRechazo").prop('disabled') == false)
{
//your code to realice
}
Application Loader now moved to tools
Since JsonSerializer is deprecated in .Net 4.0+ I used http://www.newtonsoft.com/json to solve this issue.
NuGet- > Install-Package Newtonsoft.Json
The TextBoxFor
is a newer MVC input extension introduced in MVC2.
The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.
See this page.
http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx
<script type="text/javascript">
$("#textFileID").html("Loading...").load("URL TEXT");
</script>
<div id="textFileID"></div>
Here is a simple iterative approach:
public static Node reverse(Node root) {
if (root == null || root.next == null) {
return root;
}
Node curr, prev, next;
curr = root; prev = next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
And here is a recursive approach:
public static Node reverseR(Node node) {
if (node == null || node.next == null) {
return node;
}
Node next = node.next;
node.next = null;
Node remaining = reverseR(next);
next.next = node;
return remaining;
}
If you're actually doing it just because you want to get the user's timezone then all you have to do is change your timezone in you config/applications.rb
.
Like this:
Rails, by default, will save your time record in UTC even if you specify the current timezone.
config.time_zone = "Singapore"
So this is all you have to do and you're good to go.
As an alternative to the other answers, django-devserver outputs SQL to the console.
Smartest tried and tested way of passing data between fragments and activity is to create a variables,example:
class StorageUtil {
public static ArrayList<Employee> employees;
}
Then to pass data from fragment to activity, we do so in the onActivityCreated method:
//a field created in the sending fragment
ArrayList<Employee> employees;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
employees=new ArrayList();
//java 7 and above syntax for arraylist else use employees=new ArrayList<Employee>() for java 6 and below
//Adding first employee
Employee employee=new Employee("1","Andrew","Sam","1984-04-10","Male","Ghanaian");
employees.add(employee);
//Adding second employee
Employee employee=new Employee("1","Akuah","Morrison","1984-02-04","Female","Ghanaian");
employees.add(employee);
StorageUtil.employees=employees;
}
Now you can get the value of StorageUtil.employees from everywhere. Goodluck!
You did not mention what the command was that you were trying to run that produced the error message. However, the bottom line problem is that you are trying to run and/or install 32-bit (i686) packages on a 64-bit (x86_64) system which is not a good idea. For example, if you were trying to run the 32-bit version of Perl on a 64-bit system, the result would be something like
perl: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory
If you still want to use the rpm command to install the 32-bit versions of glibc and glibc-common on your system, then you need to know that you must install both of the packages at the same time and as a single command because they are dependencies of each other. The command to run in your case would be:
rpm -Uvh glibc-2.12-1.80.el6.i686.rpm glibc-common-2.12-1.80.el6.i686.rpm
You're not assigning the parsed float back to your value var:
value = parseFloat(value).toFixed(2);
should fix things up.
Have you considered letting the user of your application select their own color scheme? Without fail you won't be able to please all of your users with your selection but you can allow them to find what pleases them.
/^(([+]{0,1}\d{2})|\d?)[\s-]?[0-9]{2}[\s-]?[0-9]{3}[\s-]?[0-9]{4}$/gm
Tested for
+94 77 531 2412
+94775312412
077 531 2412
0775312412
77 531 2412
// Not matching
77-53-12412
+94-77-53-12412
077 123 12345
77123 12345
If you're dealing with a Java character array (such as password characters that you read from the console), you can convert it to a JRuby string with the following Ruby code:
# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"
jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}
# .. do something with 'password' variable ..
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"
See also "https://stackoverflow.com/a/27628738/4390019" and "https://stackoverflow.com/a/27628756/4390019"
txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\\Tasks";
Put a double backslash instead of a single backslash...
empty
is an operator:
The
empty
operator is a prefix operation that can be used to determine whether a value is null or empty.
<c:if test="${empty myObject.featuresList}">
I also got this problem and found quite simple solution. I have Samsung adb driver installed on my system. I tried "Update driver" -> "Let me pick" -> "Already installed drivers" -> Samsung adb driver. That worked well.
plot "data.txt" using 1:2 with lines
works for me. Do you actually have blank lines in your data file? That will cause an empty plot. Can you see a plot without data? Like plot x*x. If not, then your terminal might not be set up correctly.
It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.
Using _blank
will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).
I think you can normalize the row elements sum to 1 by this:
new_matrix = a / a.sum(axis=1, keepdims=1)
.
And the column normalization can be done with new_matrix = a / a.sum(axis=0, keepdims=1)
. Hope this can hep.
In addition to Norman Ramsey's answer, I'd like to add that you can double-quote the entire string (which may make the statement more readable and less error prone).
So if you want to search for 'foo' and replace it with the content of $BAR, you can enclose the sed command in double-quotes.
sed 's/foo/$BAR/g'
sed "s/foo/$BAR/g"
In the first, $BAR will not expand correctly while in the second $BAR will expand correctly.
You close the second Scanner
which closes the underlying InputStream
, therefore the first Scanner
can no longer read from the same InputStream
and a NoSuchElementException
results.
The solution: For console apps, use a single Scanner
to read from System.in
.
Aside: As stated already, be aware that Scanner#nextInt
does not consume newline characters. Ensure that these are consumed before attempting to call nextLine
again by using Scanner#newLine()
.
See: Do not create multiple buffered wrappers on a single InputStream
Hope this is your structure:
<ul>
<li>
<div ><img.. /><p>text</p></div>
</li>
<li>
<div ><img.. /><p>text</p></div>
</li>
<li>
<div ><img.. /><p>text</p></div>
</li>
</ul>
By default, it will be add one after another row:
-----
-----
-----
if you want to make it vertical, just add float left to li, give width and height, make sure that content will not break the width:
| | |
| | |
li
{
display:block;
float:left;
width:300px; /* adjust */
height:150px; /* adjust */
padding: 5px; /*adjust*/
}
You can use django-ipware which supports Python 2 & 3 and handles IPv4 & IPv6.
Install:
pip install django-ipware
Simple Usage:
# In a view or a middleware where the `request` object is available
from ipware import get_client_ip
ip, is_routable = get_client_ip(request)
if ip is None:
# Unable to get the client's IP address
else:
# We got the client's IP address
if is_routable:
# The client's IP address is publicly routable on the Internet
else:
# The client's IP address is private
# Order of precedence is (Public, Private, Loopback, None)
Advanced Usage:
Custom Header - Custom request header for ipware to look at:
i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR'])
i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR', 'REMOTE_ADDR'])
Proxy Count - Django server is behind a fixed number of proxies:
i, r = get_client_ip(request, proxy_count=1)
Trusted Proxies - Django server is behind one or more known & trusted proxies:
i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2'))
# For multiple proxies, simply add them to the list
i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2', '177.3.3.3'))
# For proxies with fixed sub-domain and dynamic IP addresses, use partial pattern
i, r = get_client_ip(request, proxy_trusted_ips=('177.2.', '177.3.'))
Note: read this notice.
Including the fb:app_id
tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.
The fb:admins
tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.
You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins
is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.
fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>
and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>
This is not supported behavior of the MVC System. If you want to execute an action of another controller you just redirect the user to the page you want (i.e. the controller function that consumes the url).
If you want common functionality, you should build a library to be used in the two different controllers.
I can only assume you want to build up your site a bit modular. (I.e. re-use the output of one controller method in other controller methods.) There's some plugins / extensions for CI that help you build like that. However, the simplest way is to use a library to build up common "controls" (i.e. load the model, render the view into a string). Then you can return that string and pass it along to the other controller's view.
You can load into a string by adding true
at the end of the view call:
$string_view = $this->load->view('someview', array('data'=>'stuff'), true);
if (string.IsNullOrEmpty(myString))
{
. . .
. . .
}
public string RemoveSpecial(string evalstr)
{
StringBuilder finalstr = new StringBuilder();
foreach(char c in evalstr){
int charassci = Convert.ToInt16(c);
if (!(charassci >= 33 && charassci <= 47))// special char ???
finalstr.append(c);
}
return finalstr.ToString();
}
Underneath working solution with normal choice field. my problem was that each user have their own CUSTOM choicefield options based on few conditions.
class SupportForm(BaseForm):
affiliated = ChoiceField(required=False, label='Fieldname', choices=[], widget=Select(attrs={'onchange': 'sysAdminCheck();'}))
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
grid_id = get_user_from_request(self.request)
for l in get_all_choices().filter(user=user_id):
admin = 'y' if l in self.core else 'n'
choice = (('%s_%s' % (l.name, admin)), ('%s' % l.name))
self.affiliated_choices.append(choice)
super(SupportForm, self).__init__(*args, **kwargs)
self.fields['affiliated'].choices = self.affiliated_choice
I had a similar issue and this is how I was able to address it.
Step 1 - Loaded the data from Hive table into another table as follows
DROP TABLE IF EXISTS TestHiveTableCSV;
CREATE TABLE TestHiveTableCSV
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n' AS
SELECT Column List FROM TestHiveTable;
Step 2 - Copied the blob from Hive warehouse to the new location with appropriate extension
Start-AzureStorageBlobCopy
-DestContext $destContext
-SrcContainer "Source Container"
-SrcBlob "hive/warehouse/TestHiveTableCSV/000000_0"
-DestContainer "Destination Container"
-DestBlob "CSV/TestHiveTable.csv"
I had the same issue, while running the couple of scripts. When i execute it manually from task scheduler, The script was executing flawlessly. But it was not executing at the scheduled time automatically.
The following resolution worked for me
Find the location of the powershell exe , Right click and go to security options,Add the "Authenticated users" to the group or user names and give full control.
Once this is done wait for the script to executed.
If you want to do this programmatically you can use some of the options given to you as follows in a PowerShell script:
$processPID = $($(netstat -aon | findstr "9999")[0] -split '\s+')[-1]
taskkill /f /pid $processPID
However; be aware that the more accurate you can be the more precise your PID result will be. If you know which host the port is supposed to be on you can narrow it down a lot. netstat -aon | findstr "0.0.0.0:9999"
will only return one application and most llikely the correct one. Only searching on the port number may cause you to return processes that only happens to have 9999
in it, like this:
TCP 0.0.0.0:9999 0.0.0.0:0 LISTENING 15776
UDP [fe80::81ad:9999:d955:c4ca%2]:1900 *:* 12331
The most likely candidate usually ends up first, but if the process has ended before you run your script you may end up with PID 12331 instead and killing the wrong process.
You could try the following
select case when mydatetime IS NULL THEN '' else convert(varchar(20),@mydatetime,120) end as converted_date from sometable
-- Testing it out could do --
declare @mydatetime datetime
set @mydatetime = GETDATE() -- comment out for null value
--set @mydatetime = GETDATE()
select
case when @mydatetime IS NULL THEN ''
else convert(varchar(20),@mydatetime,120)
end as converted_date
Hope this helps!
def multiples(n,m,starting_from=1,increment_by=1):
"""
# Where n is the number 10 and m is the number 2 from your example.
# In case you want to print the multiples starting from some other number other than 1 then you could use the starting_from parameter
# In case you want to print every 2nd multiple or every 3rd multiple you could change the increment_by
"""
print [ n*x for x in range(starting_from,m+1,increment_by) ]
One thing you could change in your code very easily is the fontsize
you are using for the titles. However, I am going to assume that you don't just want to do that!
Some alternatives to using fig.subplots_adjust(top=0.85)
:
Usually tight_layout()
does a pretty good job at positioning everything in good locations so that they don't overlap. The reason tight_layout()
doesn't help in this case is because tight_layout()
does not take fig.suptitle() into account. There is an open issue about this on GitHub: https://github.com/matplotlib/matplotlib/issues/829 [closed in 2014 due to requiring a full geometry manager - shifted to https://github.com/matplotlib/matplotlib/issues/1109 ].
If you read the thread, there is a solution to your problem involving GridSpec
. The key is to leave some space at the top of the figure when calling tight_layout
, using the rect
kwarg. For your problem, the code becomes:
Using GridSpec
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure(1)
gs1 = gridspec.GridSpec(1, 2)
ax_list = [fig.add_subplot(ss) for ss in gs1]
ax_list[0].plot(f)
ax_list[0].set_title('Very Long Title 1', fontsize=20)
ax_list[1].plot(g)
ax_list[1].set_title('Very Long Title 2', fontsize=20)
fig.suptitle('Long Suptitle', fontsize=24)
gs1.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
plt.show()
The result:
Maybe GridSpec
is a bit overkill for you, or your real problem will involve many more subplots on a much larger canvas, or other complications. A simple hack is to just use annotate()
and lock the coordinates to the 'figure fraction'
to imitate a suptitle
. You may need to make some finer adjustments once you take a look at the output, though. Note that this second solution does not use tight_layout()
.
Simpler solution (though may need to be fine-tuned)
fig = plt.figure(2)
ax1 = plt.subplot(121)
ax1.plot(f)
ax1.set_title('Very Long Title 1', fontsize=20)
ax2 = plt.subplot(122)
ax2.plot(g)
ax2.set_title('Very Long Title 2', fontsize=20)
# fig.suptitle('Long Suptitle', fontsize=24)
# Instead, do a hack by annotating the first axes with the desired
# string and set the positioning to 'figure fraction'.
fig.get_axes()[0].annotate('Long Suptitle', (0.5, 0.95),
xycoords='figure fraction', ha='center',
fontsize=24
)
plt.show()
The result:
[Using Python
2.7.3 (64-bit) and matplotlib
1.2.0]
I've found quite useful, another workaround for that!
If you use asynchronous methods for reading data from the network socket (I mean, use BeginReceive
- EndReceive
methods), whenever a connection is terminated; one of these situations appear: Either a message is sent with no data (you can see it with Socket.Available
- even though BeginReceive
is triggered, its value will be zero) or Socket.Connected
value becomes false in this call (don't try to use EndReceive
then).
I'm posting the function I used, I think you can see what I meant from it better:
private void OnRecieve(IAsyncResult parameter)
{
Socket sock = (Socket)parameter.AsyncState;
if(!sock.Connected || sock.Available == 0)
{
// Connection is terminated, either by force or willingly
return;
}
sock.EndReceive(parameter);
sock.BeginReceive(..., ... , ... , ..., new AsyncCallback(OnRecieve), sock);
// To handle further commands sent by client.
// "..." zones might change in your code.
}
If you want to change only the placeholder style
::-webkit-input-placeholder {
text-align: center;
}
:-moz-placeholder { /* Firefox 18- */
text-align: center;
}
::-moz-placeholder { /* Firefox 19+ */
text-align: center;
}
:-ms-input-placeholder {
text-align: center;
}
Webkit browsers like Safari and Chrome subtract the scroll bar width from the visible page width when calculating width: 100% or 100vw. More at DM Rutherford's Scrolling and Page Width.
Try using overflow-y: overlay
instead.
If you don't want something bloated like jQuery UI, try my custom animations: https://github.com/yckart/jquery-custom-animations
For you, blindLeftToggle
and blindRightToggle
is the appropriate choice.
You can do this method: "IntSummaryStatistics"
IntSummaryStatistics insum = li.stream().filter(v-> v%2==0).mapToInt(mapper->mapper).summaryStatistics();
You might want to consider this answer given by nik on superuser and use "one chmod" for all files/folders like this:
chmod 755 $(find /path/to/base/dir -type d)
chmod 644 $(find /path/to/base/dir -type f)
If id
is the first key in the array, this'll do:
$ids = array_map('current', $users);
You should not necessarily rely on this though. :)
For anyone using entity framework core ending up here. This is how you do it.
# Powershell / Package manager console
Script-Migration
# Cli
dotnet ef migrations script
You can use the -From
and -To
parameter to generate an update script to update a database to a specific version.
Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2
https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts
There are several options to this command.
The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify
0
(this is the default).The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.
An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.
I added my anwer because I have getting the same error while configure ODDO9 source code in local and its need the exe to run while run exe, I got the same error.
From yesterday I was configure oddo 9.0 (section :- "Python dependencies listed in the requirements.txt file.") and its need to run PIP exe as
C:\YourOdooPath> C:\Python27\Scripts\pip.exe install -r requirements.txt
My oddo path is :- D:\Program Files (x86)\Odoo 9.0-20151014 My pip location is :- D:\Program Files (x86)\Python27\Scripts\pip.exe
So I open command prompt and go to above oddo path and try to run pip exe with these combination, but not given always above error.
"D:\Program Files (x86)\Python27\Scripts\pip.exe install -r requirements.txt" Python27\Scripts\pip.exe install -r requirements.txt
"Python27/Scripts/pip.exe install -r requirements.txt"
I resolved my issue by the @user4154243 answer, thanks for that.
Step 1: Add variable(if your path is not comes in variable's path).
Step 2: Go to command prompt, open oddo path where you installed.
Step 3: run this command python -m pip install XXX
will run and installed the things.
This can happen if you forget to return a value from a function: it then returns None. Look at all places where you are assigning to that variable, and see if one of them is a function call where the function lacks a return statement.
You can use dict to convert string to boolean. Change this line flag = bool(reader[0])
to:
flag = {'True': True, 'False': False}.get(reader[0], False) # default is False
Why not this:
rsq <- function(x, y) summary(lm(y~x))$r.squared
rsq(obs, mod)
#[1] 0.8560185
For read a cookie i've made little modifications of the Miquel version that doesn't work for me:
getCookie(name: string) {
let ca: Array<string> = document.cookie.split(';');
let cookieName = name + "=";
let c: string;
for (let i: number = 0; i < ca.length; i += 1) {
if (ca[i].indexOf(name, 0) > -1) {
c = ca[i].substring(cookieName.length +1, ca[i].length);
console.log("valore cookie: " + c);
return c;
}
}
return "";
By far the easiest way is to log in GitHub account:
yourUsername/yourRepository
for example mbaric/zpropertyz
.gitHubUsername/nameOfTheRepository
and click on the button below which says: I understand the consequences, delete the repositoryIn shell, you don't put a $ in front of a variable you're assigning. You only use $IP when you're referring to the variable.
#!/bin/bash
IP=$(curl automation.whatismyip.com/n09230945.asp)
echo "$IP"
sed "s/IP/$IP/" nsupdate.txt | nsupdate
Potential library: https://pypi.org/project/stringcase/
Example:
import stringcase
stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"
Though it's questionable whether it will leave spaces in. (Examples show it removing space, but there is a bug tracker issue noting that it leaves them in.)
Try this:
<?php
/*
Template Name: [contact us]
*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]');
?>
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
I had this problem too, and in my case I found that the color of the font was the same color of the background, so it looked like nothing happened.
An expression is something, while a statement does something.
An expression is a statement as well, but it must have a return.
>>> 2 * 2 #expression
>>> print(2 * 2) #statement
PS:The interpreter always prints out the values of all expressions.
faster way (without pyspark.sql.functions
)
df.filter((df.d<5)&((df.col1 != df.col3) |
(df.col2 != df.col4) &
(df.col1 ==df.col3)))\
.show()
One significant difference between INNER JOIN and NATURAL JOIN is the number of columns returned.
Consider:
TableA TableB
+------------+----------+ +--------------------+
|Column1 | Column2 | |Column1 | Column3 |
+-----------------------+ +--------------------+
| 1 | 2 | | 1 | 3 |
+------------+----------+ +---------+----------+
The INNER JOIN
of TableA and TableB on Column1 will return
SELECT * FROM TableA AS a INNER JOIN TableB AS b USING (Column1);
SELECT * FROM TableA AS a INNER JOIN TableB AS b ON a.Column1 = b.Column1;
+------------+-----------+---------------------+
| a.Column1 | a.Column2 | b.Column1| b.Column3|
+------------------------+---------------------+
| 1 | 2 | 1 | 3 |
+------------+-----------+----------+----------+
The NATURAL JOIN
of TableA and TableB on Column1 will return:
SELECT * FROM TableA NATURAL JOIN TableB
+------------+----------+----------+
|Column1 | Column2 | Column3 |
+-----------------------+----------+
| 1 | 2 | 3 |
+------------+----------+----------+
The repeated column is avoided.
(AFAICT from the standard grammar, you can't specify the joining columns in a natural join; the join is strictly name-based. See also Wikipedia.)
(There's a cheat in the inner join output; the a.
and b.
parts would not be in the column names; you'd just have column1
, column2
, column1
, column3
as the headings.)
This should work with any div
or screen size:
.center-screen {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
text-align: center;_x000D_
min-height: 100vh;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="center-screen">_x000D_
I'm in the center_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
See more details about flex
here. This should work on most of the browsers, see compatibility matrix here.
Update: If you don't want the scroll bar, make min-height
smaller, for example min-height: 95vh;
accuracy_score is a classification metric, you cannot use it for a regression problem.
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
This is a Python 101 type question,
It's a simple question but one where the answer is not so simple.
In python3, a "bytes" object represents a sequence of bytes, a "string" object represents a sequence of unicode code points.
To convert between from "bytes" to "string" and from "string" back to "bytes" you use the bytes.decode and string.encode functions. These functions take two parameters, an encoding and an error handling policy.
Sadly there are an awful lot of cases where sequences of bytes are used to represent text, but it is not necessarily well-defined what encoding is being used. Take for example filenames on unix-like systems, as far as the kernel is concerned they are a sequence of bytes with a handful of special values, on most modern distros most filenames will be UTF-8 but there is no gaurantee that all filenames will be.
If you want to write robust software then you need to think carefully about those parameters. You need to think carefully about what encoding the bytes are supposed to be in and how you will handle the case where they turn out not to be a valid sequence of bytes for the encoding you thought they should be in. Python defaults to UTF-8 and erroring out on any byte sequence that is not valid UTF-8.
print(bytesThing)
Python uses "repr" as a fallback conversion to string. repr attempts to produce python code that will recreate the object. In the case of a bytes object this means among other things escaping bytes outside the printable ascii range.
find section [MySQLi]
in your php.ini
and add line mysqli.default_charset = "UTF-8"
. Similar changes my require for section [Pdo_mysql]
and [mysqlnd]
.
Issue seems to be specifically with MySQL version 8.0, and above solution found working with PHP Version 7.2, and solution didn't work with PHP 7.0
There are two things I think you could try to develop iPhone applications.
You can try the Aptana mobile wep app plugin for eclipse which is nice, although still in early stage. It comes with a emulator for running the applications so this could be helpful
You can try cocoa
(Extra) Here is a nice guide I found of guy who managed to get the iPhone SDK running in ubuntu, hope this help -_-. iPhone on Ubuntu
<style type="text/css">
#nav-ask{ display:none; }
</style>
Here's how you can do it by using loops.
public static int[][] makeCopy(int[][] array){
b=new int[array.length][];
for(int row=0; row<array.length; ++row){
b[row]=new int[array[row].length];
for(int col=0; col<b[row].length; ++col){
b[row][col]=array[row][col];
}
}
return b;
}
Just a slight expansion on the 'angular' solution. I wanted to exclude an item based on it's numeric id, so the ! approach doesn't work. The more general solution which should work for { name: 'ted' } or { id: 42 } is:
mycollection = $filter('filter')(myCollection, { id: theId }, function (obj, test) {
return obj !== test; });
Lets get a visual impression about what was already said. For example you have a table with some tasks:
SELECT a.id,a.status,a.description FROM minicloud_tasks as a ORDER BY random();
id | status | description
----+------------+------------------
4 | processing | work on postgres
6 | deleted | need some rest
3 | pending | garden party
5 | completed | work on html
And you want to order the list of tasks by its status. The status is a list of string values:
(processing, pending, completed, deleted)
The trick is to give each status value an interger and order the list numerical:
SELECT a.id,a.status,a.description FROM minicloud_tasks AS a
JOIN (
VALUES ('processing', 1), ('pending', 2), ('completed', 3), ('deleted', 4)
) AS b (status, id) ON (a.status = b.status)
ORDER BY b.id ASC;
Which leads to:
id | status | description
----+------------+------------------
4 | processing | work on postgres
3 | pending | garden party
5 | completed | work on html
6 | deleted | need some rest
Credit @user80168
String.Format
adds many options in addition to the concatenation operators, including the ability to specify the specific format of each item added into the string.
For details on what is possible, I'd recommend reading the section on MSDN titled Composite Formatting. It explains the advantage of String.Format
(as well as xxx.WriteLine
and other methods that support composite formatting) over normal concatenation operators.
How I would start emulation.
1.Get books based around low level programming, you'll need it for the "pretend" operating system of the Nintendo...game boy...
2.Get books on emulation specifically, and maybe os development. (you won't be making an os, but the closest to it.
3.look at some open source emulators, especially ones of the system you want to make an emulator for.
4.copy snippets of the more complex code into your IDE/compliler. This will save you writing out long code. This is what I do for os development, use a district of linux
.csv field sizes are controlled via [Python 3.Docs]: csv.field_size_limit([new_limit]) (emphasis is mine):
Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit.
It is set by default to 131072 or 0x20000 (128k), which should be enough for any decent .csv:
>>> import csv >>> >>> >>> limit0 = csv.field_size_limit() >>> limit0 131072 >>> "0x{0:016X}".format(limit0) '0x0000000000020000'
However, when dealing with a .csv file (with the correct quoting and delimiter) having (at least) one field longer than this size, the error pops up.
To get rid of the error, the size limit should be increased (to avoid any worries, the maximum possible value is attempted).
Behind the scenes (check [GitHub]: python/cpython - (master) cpython/Modules/_csv.c for implementation details), the variable that holds this value is a C long ([Wikipedia]: C data types), whose size varies depending on CPU architecture and OS (ILP). The classical difference: for a 64bit OS (and Python build), the long type size (in bits) is:
When attempting to set it, the new value is checked to be in the long boundaries, that's why in some cases another exception pops up (because sys.maxsize is typically 64bit wide - encountered on Win):
>>> import sys, ctypes as ct >>> >>> >>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8 ('win32', 9223372036854775807, 64, 32) >>> >>> csv.field_size_limit(sys.maxsize) Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: Python int too large to convert to C long
To avoid running into this problem, set the (maximum possible) limit (LONG_MAX), using an artifice (thanks to [Python 3.Docs]: ctypes - A foreign function library for Python). It should work on Python 3 and Python 2, on any CPU / OS.
>>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2)) 131072 >>> limit1 = csv.field_size_limit() >>> limit1 2147483647 >>> "0x{0:016X}".format(limit1) '0x000000007FFFFFFF'
64bit Python on a Nix like OS:
>>> import sys, csv, ctypes as ct >>> >>> >>> sys.platform, sys.maxsize, ct.sizeof(ct.c_void_p) * 8, ct.sizeof(ct.c_long) * 8 ('linux', 9223372036854775807, 64, 64) >>> >>> csv.field_size_limit() 131072 >>> >>> csv.field_size_limit(int(ct.c_ulong(-1).value // 2)) 131072 >>> limit1 = csv.field_size_limit() >>> limit1 9223372036854775807 >>> "0x{0:016X}".format(limit1) '0x7FFFFFFFFFFFFFFF'
For 32bit Python, things should run smoothly without the artifice (as both sys.maxsize and LONG_MAX are 32bit wide).
If this maximum value is still not enough, then the .csv would need manual intervention in order to be processed from Python.
Check the following resources for more details on:
No, unfortunately this will not be possible because ConverterParameter
is not a DependencyProperty
so you won't be able to use bindings
But perhaps you could cheat and use a MultiBinding
with IMultiValueConverter
to pass in the 2 Tag
properties.
In Firefox, you can use the instanceof Node
. That Node
is defined in DOM1.
But that is not that easy in IE.
You can only ensure it is DOM element by using DOM function and catch if any exception. However, it may have side effect (e.g. change object internal state/performance/memory leak)
I know is a bit later to reply, sorry. But that works for me.
export K8S_public_load_balancer_url="$(kubectl get services -n ${TENANT}-production -o wide | grep "ingress-nginx-internal$" | awk '{print $4}')"
And now I am able to fetch and pass the content of the variable to jq
export TF_VAR_public_load_balancer_url="$(aws elbv2 describe-load-balancers --region eu-west-1 | jq -r '.LoadBalancers[] | select (.DNSName == "'$K8S_public_load_balancer_url'") | .LoadBalancerArn')"
In my case I needed to use double quote and quote to access the variable value.
Cheers.
I tried @knittl's write-tree/commit-tree
approach.
branch-a: the kept branch
branch-b: the abandoned branch
// goto branch-a branch
$ git checkout branch-a
$ git write-tree
6fa6989240d2fc6490f8215682a20c63dac5560a // echo tree id? I guess
$ git commit-tree -p branch-a -p branch-b 6fa6989240d2fc6490f8215682a20c63dac5560a
<type some commit message end with Ctrl-d>
20bc36a2b0f2537ed11328d1aedd9c3cff2e87e9 // echo new commit id
$ git reset --hard 20bc36a2b0f2537ed11328d1aedd9c3cff2e87e9
You can return an object of a Class in Java.
If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.
If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
I can't believe after two years of programming js it never clicked that empty objects and array's aren't falsey, the weirdest thing is it never caught me out.
this will return true
if the input is falsey by default or if it's an empty object or array. the inverse is the trueish
function
http://codepen.io/synthet1c/pen/pjmoWL
function falsish( obj ){
if( (typeof obj === 'number' && obj > 0) || obj === true ){
return false;
}
return !!obj
? !Object.keys( obj ).length
: true;
}
function trueish( obj ){
return !falsish( obj );
}
falsish({}) //=> true
falsish({foo:'bar'}) //=> false
falsish([]) //=> true
falsish(['foo']) //=> false
falsish(false) //=> true
falsish(true) //=> false
// the rest are on codepen
I had it on the Makefile
MAPS+=reverse/db.901:550:2001.ip6.arpa
lastserial: ${MAPS}
./updateser ${MAPS}
It's because of the :
in the file name.
I solved this with
-------- notice / / v v MAPS+=reverse/db.901\:550\:2001.ip6.arpa lastserial: ${MAPS} ./updateser ${MAPS}
By default, gcc selects the language based on the file extension, but you can force gcc to select a different language backend with the -x option thus:
gcc -x c++
More options are detailed in the gcc man page under "Options controlling the kind of output". See e.g. http://linux.die.net/man/1/gcc (search on the page for the text -x language
).
This facility is very useful in cases where gcc can't guess the language using a file extension, for example if you're generating code and feeding it to gcc via stdin.
Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )
I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)
ORA-03113: end-of-file on communication channel
Is the database letting you know that the network connection is no more. This could be because:
For 1) (firewall) search tahiti.oracle.com for SQLNET.EXPIRE_TIME
. This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live.
For 1) (network) speak to your network admin (connection could be unreliable)
For 2) Check the alert.log
for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file.
Support issues can be raised at metalink.oracle.com with a suitable Customer Service Identifier (CSI)
If you have 2 beans of the same class autowired to one class you shoud use @Qualifier
(Spring Autowiring @Qualifier example).
But it seems like your problem comes from incorrect Java Syntax.
Your object should start with lower case letter
SuggestionService suggestion;
Your setter should start with lower case as well and object name should be with Upper case
public void setSuggestion(final Suggestion suggestion) {
this.suggestion = suggestion;
}
@Chaibi Alaa, To make the user able to add only once, and move the marker; You can set the marker on first click and then just change the position on subsequent clicks.
var marker;
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
if (marker == null)
{
marker = new google.maps.Marker({
position: location,
map: map
});
}
else
{
marker.setPosition(location);
}
}
There is no reason not to use exceptions normally in objective C even to signify business rule exceptions. Apple can say use NSError who cares. Obj C has been around a long time and at one time ALL C++ documentation said the same thing. The reason it doesnt matter how expensive throwing and catching an exception is, is the lifetime of an exception is exceedingly short and...its an EXCEPTION to the normal flow. I have never heard anyone say ever in my life, man that exception took a long time to be thrown and caught.
Also, there are people that think that objective C itself is too expensive and code in C or C++ instead. So saying always use NSError is ill-informed and paranoid.
But the question of this thread hasnt yet been answered whats the BEST way to throw an exception. The ways to return NSError are obvious.
So is it: [NSException raise:... @throw [[NSException alloc] initWithName.... or @throw [[MyCustomException... ?
I use the checked/unchecked rule here slightly differently than above.
The real difference between the (using the java metaphor here) checked/unchecked is important --> whether you can recover from the exception. And by recover I mean not just NOT crash.
So I use custom exception classes with @throw for recoverable exceptions, because its likely I will have some app method looking for certain types of failures in multiple @catch blocks. For example if my app is an ATM machine, I would have a @catch block for the "WithdrawalRequestExceedsBalanceException".
I use NSException:raise for runtime exceptions since I have no way to recover from the exception, except to catch it at a higher level and log it. And theres no point in creating a custom class for that.
Anyway thats what I do, but if there's a better, similarly expressive way I would like to know as well. In my own code, since I stopped coding C a hella long time ago I never return an NSError even if I am passed one by an API.
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
the command posted by Milad and Sandy did not work for me with mstsc. i had to add TERMSRV to the /generic switch. i found this information here: https://gist.github.com/jdforsythe/48a022ee22c8ec912b7e
cmdkey /generic:TERMSRV/<server> /user:<username> /pass:<password>
i could then use mstsc /v:<server>
without getting prompted for the login.
I've read all the comments. It's interesting to notice what happens when you print out this:
printf("\nInteger = %d\n", EOF); //OUTPUT = -1
printf("Decimal = %d\n", EOF); //OUTPUT = -1
printf("Octal = %o\n", EOF); //OUTPUT = 37777777777
printf("Hexadecimal = %x\n", EOF); //OUTPUT = ffffffff
printf("Double and float = %f\n", EOF); //OUTPUT = 0.000000
printf("Long double = %Lf\n", EOF); //OUTPUT = 0.000000
printf("Character = %c\n", EOF); //OUTPUT = nothing
As we can see here, EOF is NOT a character (whatsoever).
You can also do what the "Service Reference" generated code does
public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
public ServiceXClient() { }
public ServiceXClient(string endpointConfigurationName) :
base(endpointConfigurationName) { }
public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
base(binding, remoteAddress) { }
public bool ServiceXWork(string data, string otherParam)
{
return base.Channel.ServiceXWork(data, otherParam);
}
}
Where IServiceX is your WCF Service Contract
Then your client code:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
Alternative way sharing:
ASC
List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal::getName)).collect(Collectors.toList());
DESC
List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal::getName).reversed()).collect(Collectors.toList());
Since 2.0 beta :)
import { APP_BASE_HREF } from 'angular2/platform/common';
childClass::customMethod()
has different arguments, or a different access level (public/private/protected) than parentClass::customMethod()
.
I used this below if this is what you are thinking. It it worked well for me.
<?php
include $_SERVER['DOCUMENT_ROOT']."/head_lib.php";
?>
What I was trying to do was pulla file called /head_lib.php from the root folder. It would not pull anything to build the webpage. The header, footer and other key features in sub directories would never show up. Until I did above it worked like a champ.
To avoid blank line skipping (give readability in conf file) I combine aflat and jeb answer (here) to something like this:
@echo off
setlocal enabledelayedexpansion
set INTEXTFILE=test.txt
set OUTTEXTFILE=test_out.txt
set SEARCHTEXT=bath
set REPLACETEXT=hello
set OUTPUTLINE=
for /f "tokens=1,* delims=¶" %%A in ( '"findstr /n ^^ %INTEXTFILE%"') do (
SET string=%%A
for /f "delims=: tokens=1,*" %%a in ("!string!") do set "string=%%b"
if "!string!" == "" (
echo.>>%OUTTEXTFILE%
) else (
SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!
echo !modified! >> %OUTTEXTFILE%
)
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%
You have to add a folder to the Sublime Text window in order to navigate via the sidebar. Go to File -> Open Folder...
and select the highest directory you want to be able to navigate.
Also, 'View -> Sidebar -> Show Sidebar' if it still doesn't show. In the new version, there is only an 'open' menu and no separate option for opening a folder.
DateTime.new(2012, 1, 15).to_time.to_i
Both of them are ways of subsetting. The single bracket will return a subset of the list, which in itself will be a list. ie:It may or may not contain more than one elements. On the other hand a double bracket will return just a single element from the list.
-Single bracket will give us a list. We can also use single bracket if we wish to return multiple elements from the list. consider the following list:-
>r<-list(c(1:10),foo=1,far=2);
Now please note the way the list is returned when I try to display it. I type r and press enter
>r
#the result is:-
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
$foo
[1] 1
$far
[1] 2
Now we will see the magic of single bracket:-
>r[c(1,2,3)]
#the above command will return a list with all three elements of the actual list r as below
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
$foo
[1] 1
$far
[1] 2
which is exactly the same as when we tried to display value of r on screen, which means the usage of single bracket has returned a list, where at index 1 we have a vector of 10 elements, then we have two more elements with names foo and far. We may also choose to give a single index or element name as input to the single bracket. eg:
> r[1]
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
In this example we gave one index "1" and in return got a list with one element(which is an array of 10 numbers)
> r[2]
$foo
[1] 1
In the above example we gave one index "2" and in return got a list with one element
> r["foo"];
$foo
[1] 1
In this example we passed the name of one element and in return a list was returned with one element.
You may also pass a vector of element names like:-
> x<-c("foo","far")
> r[x];
$foo
[1] 1
$far
[1] 2
In this example we passed an vector with two element names "foo" and "far"
In return we got a list with two elements.
In short single bracket will always return you another list with number of elements equal to the number of elements or number of indices you pass into the single bracket.
In contrast, a double bracket will always return only one element.
Before moving to double bracket a note to be kept in mind.
NOTE:THE MAJOR DIFFERENCE BETWEEN THE TWO IS THAT SINGLE BRACKET RETURNS YOU A LIST WITH AS MANY ELEMENTS AS YOU WISH WHILE A DOUBLE BRACKET WILL NEVER RETURN A LIST. RATHER A DOUBLE BRACKET WILL RETURN ONLY A SINGLE ELEMENT FROM THE LIST.
I will site a few examples. Please keep a note of the words in bold and come back to it after you are done with the examples below:
Double bracket will return you the actual value at the index.(It will NOT return a list)
> r[[1]]
[1] 1 2 3 4 5 6 7 8 9 10
>r[["foo"]]
[1] 1
for double brackets if we try to view more than one elements by passing a vector it will result in an error just because it was not built to cater to that need, but just to return a single element.
Consider the following
> r[[c(1:3)]]
Error in r[[c(1:3)]] : recursive indexing failed at level 2
> r[[c(1,2,3)]]
Error in r[[c(1, 2, 3)]] : recursive indexing failed at level 2
> r[[c("foo","far")]]
Error in r[[c("foo", "far")]] : subscript out of bounds
This is an important question. The SSL 3 protocol (1996) is irreparably broken by the Poodle attack published 2014. The IETF have published "SSLv3 MUST NOT be used". Web browsers are ditching it. Mozilla Firefox and Google Chrome have already done so.
Two excellent tools for checking protocol support in browsers are SSL Lab's client test and https://www.howsmyssl.com/ . The latter does not require Javascript, so you can try it from .NET's HttpClient:
// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");
File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);
// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");
The result is damning:
Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.
That's concerning. It's comparable to 2006's Internet Explorer 7.
To list exactly which protocols a HTTP client supports, you can try the version-specific test servers below:
var test_servers = new Dictionary<string, string>();
test_servers["SSL 2"] = "https://www.ssllabs.com:10200";
test_servers["SSL 3"] = "https://www.ssllabs.com:10300";
test_servers["TLS 1.0"] = "https://www.ssllabs.com:10301";
test_servers["TLS 1.1"] = "https://www.ssllabs.com:10302";
test_servers["TLS 1.2"] = "https://www.ssllabs.com:10303";
var supported = new Func<string, bool>(url =>
{
try { return new HttpClient().GetAsync(url).Result.IsSuccessStatusCode; }
catch { return false; }
});
var supported_protocols = test_servers.Where(server => supported(server.Value));
Console.WriteLine(string.Join(", ", supported_protocols.Select(x => x.Key)));
I'm using .NET Framework 4.6.2. I found HttpClient supports only SSL 3 and TLS 1.0. That's concerning. This is comparable to 2006's Internet Explorer 7.
Update: It turns HttpClient does support TLS 1.1 and 1.2, but you have to turn them on manually at System.Net.ServicePointManager.SecurityProtocol
. See https://stackoverflow.com/a/26392698/284795
I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?
UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;
If you look in the source code of the JDK, you can see that for unix systems the property is read at compile time from the paths.h or hard coded. For windows the function GetTempPathW
from win32 returns the tmpdir
name.
For posix systems you might expect the standard TMPDIR
to work, but that is not the case. You can confirm that TMPDIR
is not used by running TMPDIR=/mytmp java -XshowSettings
You need to wait until the image is loaded before you draw it. Try this instead:
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = 'img/base.png';
base_image.onload = function(){
context.drawImage(base_image, 0, 0);
}
}
i.e. draw the image in the onload callback of the image.
I was able to adapt these instructions take a table with an existing non-increment primary key, and add an incrementing primary key to the table and create a new composite primary key with both the old and new keys as a composite primary key using the following code:
DROP TABLE IF EXISTS SAKAI_USER_ID_MAP;
CREATE TABLE SAKAI_USER_ID_MAP (
USER_ID VARCHAR (99) NOT NULL,
EID VARCHAR (255) NOT NULL,
PRIMARY KEY (USER_ID)
);
INSERT INTO SAKAI_USER_ID_MAP VALUES ('admin', 'admin');
INSERT INTO SAKAI_USER_ID_MAP VALUES ('postmaster', 'postmaster');
ALTER TABLE SAKAI_USER_ID_MAP
DROP PRIMARY KEY,
ADD _USER_ID INT AUTO_INCREMENT NOT NULL FIRST,
ADD PRIMARY KEY ( _USER_ID, USER_ID );
When this is done, the _USER_ID field exists and has all number values for the primary key exactly as you would expect. With the "DROP TABLE" at the top, you can run this over and over to experiment with variations.
What I have not been able to get working is the situation where there are incoming FOREIGN KEYs that already point at the USER_ID field. I get this message when I try to do a more complex example with an incoming foreign key from another table.
#1025 - Error on rename of './zap/#sql-da07_6d' to './zap/SAKAI_USER_ID_MAP' (errno: 150)
I am guessing that I need to tear down all foreign keys before doing the ALTER table and then rebuild them afterwards. But for now I wanted to share this solution to a more challenging version of the original question in case others ran into this situation.
You could try count(*)
Integer count = (Integer) session.createQuery("select count(*) from Books").uniqueResult();
Where Books
is the name off the class
- not the table in the database.
Its easy, dont Align it to anything
<Button_x000D_
android:id="@+id/the_button"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content" _x000D_
android:layout_centerInParent="true"_x000D_
android:text="Centered Button"/>
_x000D_
To me, the following is more readable (thus preferable) way to do it:
git reset HEAD~1
Instead of 1
, there could be any number of commits you want to unstage.
The obligatory LINQ one[1]-liner:
var max = anArray.Select((value, index) => new {value, index})
.OrderByDescending(vi => vi.value)
.First();
(The sorting is probably a performance hit over the other solutions.)
[1]: For given values of "one".
You can increase Max Allowed Packet
SET GLOBAL max_allowed_packet=1073741824;
http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_max_allowed_packet
you can use this solution:
items = { 'a', 'b' }
for k,v in pairs(items) do
if v == 'a' then
--do something
else
--do something
end
end
or
items = {'a', 'b'}
for k,v in pairs(items) do
while v do
if v == 'a' then
return found
else
break
end
end
end
return nothing
On Mac OS you can use: CMD + CTRL + G
You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);
example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4));
will merge from B2 to E2. Remember it is zero based indexing (ex. POI version 3.12).
for detail refer BusyDeveloper's Guide
You can simply do
print 2*'hello'
Remove Quote. and use innerText instead of text
function toggleText(button_id)
{ //-----\/ 'button_id' - > button_id
if (document.getElementById(button_id).innerText == "Lock")
{
document.getElementById(button_id).innerText = "Unlock";
}
else
{
document.getElementById(button_id).innerText = "Lock";
}
}
Edit: Unfortunately, as of PHP 8.0, the answer is not "No, not anymore". This RFC was not accepted as I hoped, proposing to change T_PAAMAYIM_NEKUDOTAYIM
to T_DOUBLE_COLON
; but it was declined.
Note: I keep this answer for historical purposes. Actually, because of the creation of the RFC and the votes ratio at some point, I created this answer. Also, I keep this for hoping it to be accepted in the near future.
Though the previou answer are almost similar to what I am going to do, but using the index method does not require using another indexing method .loc(). It can be done in a similar but precise manner as
df.drop(df.index[df['line_race'] == 0], inplace = True)
My way to effectively work with multiple files is to use tmux.
It allows you to split windows vertically and horizontally, as in:
I have it working this way on both my mac and linux machines and I find it better than the native window pane switching mechanism that's provided (on Macs). I find the switching easier and only with tmux have I been able to get the 'new page at the same current directory' working on my mac (despite the fact that there seems to be options to open new panes in the same directory) which is a surprisingly critical piece. An instant new pane at the current location is amazingly useful. A method that does new panes with the same key combos for both OS's is critical for me and a bonus for all for future personal compatibility. Aside from multiple tmux panes, I've also tried using multiple tabs, e.g. and multiple new windows, e.g. and ultimately I've found that multiple tmux panes to be the most useful for me. I am very 'visual' and like to keep my various contexts right in front of me, connected together as panes.
tmux also support horizontal and vertical panes which the older screen
didn't (though mac's iterm2 seems to support it, but again, the current directory setting didn't work for me). tmux 1.8
Yes its possible.
Return a RedirectToAction()
method like this:
return RedirectToAction("ActionOrViewName", "ControllerName");
I would think that one reason could be that the color is applied to things other than font. For example:
div {
border: 1px solid;
color: red;
}
Yields both a red font color and a red border.
Alternatively, it could just be that the W3C's CSS standards are completely backwards and nonsensical as evidenced elsewhere.
Hmm, not quite sure what your question is.
In the title you ask about Databases (DB), whereas in the body of your text you ask about Database Management Systems (DBMS). The two are completely different and require different answers.
A DBMS is a tool that allows you to access a DB.
Other than the data itself, a DB is the concept of how that data is structured.
So just like you can program with Oriented Object methodology with a non-OO powered compiler, or vice-versa, so can you set-up a relational database without an RDBMS or use an RDBMS to store non-relational data.
I'll focus on what Relational Database (RDB) means and leave the discussion about what systems do to others.
A relational database (the concept) is a data structure that allows you to link information from different 'tables', or different types of data buckets. A data bucket must contain what is called a key or index (that allows to uniquely identify any atomic chunk of data within the bucket). Other data buckets may refer to that key so as to create a link between their data atoms and the atom pointed to by the key.
A non-relational database just stores data without explicit and structured mechanisms to link data from different buckets to one another.
As to implementing such a scheme, if you have a paper file with an index and in a different paper file you refer to the index to get at the relevant information, then you have implemented a relational database, albeit quite a simple one. So you see that you do not even need a computer (of course it can become tedious very quickly without one to help), similarly you do not need an RDBMS, though arguably an RDBMS is the right tool for the job. That said there are variations as to what the different tools out there can do so choosing the right tool for the job may not be all that straightforward.
I hope this is layman terms enough and is helpful to your understanding.
You could create a helper function:
def re_match_group(pattern, str, out_groups):
del out_groups[:]
result = re.match(pattern, str)
if result:
out_groups[:len(result.groups())] = result.groups()
return result
And then use it like this:
groups = []
if re_match_group("I love (\w+)", statement, groups):
print "He loves", groups[0]
elif re_match_group("Ich liebe (\w+)", statement, groups):
print "Er liebt", groups[0]
elif re_match_group("Je t'aime (\w+)", statement, groups):
print "Il aime", groups[0]
It's a little clunky, but it gets the job done.
hr
{
background-color: #123455;
}
the background is the one you should try to change
You can also work with the borders color. i am not sure i think there are crossbrowser issues with this. you should test it in differrent browsers
[^\u0000-\u007F]+
for any characters which is not included ASCII characters.
For example:
function isNonLatinCharacters(s) {
return /[^\u0000-\u007F]/.test(s);
}
console.log(isNonLatinCharacters("??"));// Japanese
console.log(isNonLatinCharacters("??"));// Chinese
console.log(isNonLatinCharacters("????"));// Persian
console.log(isNonLatinCharacters("???"));// Korean
console.log(isNonLatinCharacters("???????"));// Hindi
console.log(isNonLatinCharacters("???????"));// Hebrew
_x000D_
Here are some perfect references:
Unicode range RegExp generator
This answer is not yet possible, but I am posting it for "future generations". Hopefully, some day we will be able to do this via the CSS @viewport rule:
@viewport {
orientation: portrait;
}
Here is the "Can I Use" page (as of 2019 only IE and Edge):
https://caniuse.com/#feat=mdn-css_at-rules_viewport_orientation
Spec(in process):
https://drafts.csswg.org/css-device-adapt/#orientation-desc
MDN:
https://developer.mozilla.org/en-US/docs/Web/CSS/@viewport/orientation
Based on the MDN browser compatibility table and the following article, looks like there is some support in certain versions of IE and Opera:
http://menacingcloud.com/?c=cssViewportOrMetaTag
This JS API Spec also looks relevant:
https://w3c.github.io/screen-orientation/
I had assumed that because it was possible with the proposed @viewport
rule, that it would be possible by setting orientation
in the viewport settings in a meta
tag, but I have had no success with this thus far.
Feel free to update this answer as things improve.
Anyway we could use sympy library , also support for multiset permutations
import sympy
from sympy.utilities.iterables import multiset_permutations
t = [1,2,3]
p = list(multiset_permutations(t))
print(p)
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Answer is highly inspired by Get all permutations of a numpy array
@Balamanigandan your Original Post :- PHP Notice: Trying to get property of non-object error
Your are trying to access the Null Object. From AngularJS your are not passing any Objects instead you are passing the $_GET element. Try by using $_GET['uid']
instead of $objData->token
This is fairly simple with the callback syntax of attr
:
$("#product1 :checkbox").click(function(){
$(this)
.closest('tr') // find the parent row
.find(":input[type='text']") // find text elements in that row
.attr('disabled',function(idx, oldAttr) {
return !oldAttr; // invert disabled value
})
.toggleClass('disabled') // enable them
.end() // go back to the row
.siblings() // get its siblings
.find(":input[type='text']") // find text elements in those rows
.attr('disabled',function(idx, oldAttr) {
return !oldAttr; // invert disabled value
})
.removeClass('disabled'); // disable them
});
Assuming that obj
is a pre-constructed object (and not a JSON string), you can achieve this with the following:
Object.keys(obj).forEach(function(key){
console.log(key + '=' + obj[key]);
});
If you use Knockout, then you could use the following custom binding to bind the current viewport breakpoint (xs, sm, md or lg) to an observable in your model. The binding...
divs
with visible-??
class in a div with id detect-viewport
and adds it to the body if it doesn't exist already (so you could reuse this binding without duplicating these divs)ko.bindingHandlers['viewport'] = {_x000D_
init: function(element, valueAccessor) {_x000D_
if (!document.getElementById('detect-viewport')) {_x000D_
let detectViewportWrapper = document.createElement('div');_x000D_
detectViewportWrapper.id = 'detect-viewport';_x000D_
_x000D_
["xs", "sm", "md", "lg"].forEach(function(breakpoint) {_x000D_
let breakpointDiv = document.createElement('div');_x000D_
breakpointDiv.className = 'visible-' + breakpoint;_x000D_
detectViewportWrapper.appendChild(breakpointDiv);_x000D_
});_x000D_
_x000D_
document.body.appendChild(detectViewportWrapper);_x000D_
}_x000D_
_x000D_
let setCurrentBreakpoint = function() {_x000D_
valueAccessor()($('#detect-viewport div:visible')[0].className.substring('visible-'.length));_x000D_
}_x000D_
_x000D_
$(window).resize(setCurrentBreakpoint);_x000D_
setCurrentBreakpoint();_x000D_
}_x000D_
};_x000D_
_x000D_
ko.applyBindings({_x000D_
currentViewPort: ko.observable()_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<div data-bind="viewport: currentViewPort"></div>_x000D_
<div> _x000D_
Current viewport breakpoint: <strong data-bind="text: currentViewPort"></strong>_x000D_
</div>_x000D_
<div>_x000D_
(Click the <em>full page</em> link of this snippet to test the binding with different window sizes)_x000D_
</div>
_x000D_
use this
<div ng-class="{states}[condition]"></div>
for example if the condition is [2 == 2], states are {true: '...', false: '...'}
<div ng-class="{true: 'ClassA', false: 'ClassB'}[condition]"></div>
How about just using
void feedInputToOutput(InputStream in, OutputStream out) {
IOUtils.copy(in, out);
}
and be done with it?
from jakarta apache commons i/o library which is used by a huge amount of projects already so you probably already have the jar in your classpath already.
Or use Series.tolist
or Series.any
:
>>> s = pd.Series(list('abc'))
>>> s
0 a
1 b
2 c
dtype: object
>>> 'a' in s.tolist()
True
>>> (s=='a').any()
True
Series.tolist
makes a list about of a Series
, and the other one i am just getting a boolean Series
from a regular Series
, then checking if there are any True
s in the boolean Series
.
Use the below two commands one by one.
git gc --prune=now
git remote prune origin
This will resolve your issue.
Using boost:
#include <boost/algorithm/hex.hpp>
std::string s("tralalalala");
std::string result;
boost::algorithm::hex(s.begin(), s.end(), std::back_inserter(result));
I use the vimrc in the python repo among other things:
http://svn.python.org/projects/python/trunk/Misc/Vim/vimrc
I also add
set softtabstop=4
Assuming RestTemplate
is configured to use HttpClient 4.x, you can read up on HttpClient's logging documentation here. The loggers are different than those specified in the other answers.
The logging configuration for HttpClient 3.x is available here.
You should override Equals
and GetHashCode
meaningfully, in this case to compare the ID:
public class LinqTest
{
public int id { get; set; }
public string value { get; set; }
public override bool Equals(object obj)
{
LinqTest obj2 = obj as LinqTest;
if (obj2 == null) return false;
return id == obj2.id;
}
public override int GetHashCode()
{
return id;
}
}
Now you can use Distinct
:
List<LinqTest> uniqueIDs = myList.Distinct().ToList();
There isn't any big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data
argument as yadda
, but miss one of the places it is used in the function's body... Now data
refers to the global, and you start having weird behaviour - where you would have a much more obvious NameError
if you didn't have a global name data
.
Also remember that in Python everything is an object (including modules, classes and functions), so there's no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo
at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it - bad luck - foo
.
Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.
None of this is much of a problem if you have short functions, good naming and a decent unit test coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.
Instead of using third party lib, use Java 11 isBlank()
String str1 = "";
String str2 = " ";
Character ch = '\u0020';
String str3 =ch+" "+ch;
System.out.println(str1.isEmpty()); //true
System.out.println(str2.isEmpty()); //false
System.out.println(str3.isEmpty()); //false
System.out.println(str1.isBlank()); //true
System.out.println(str2.isBlank()); //true
System.out.println(str3.isBlank()); //true
Being impatient, I created a new App Pool with the same settings and used that.
The code below will help to consume rest api via Java. URL - end point rest If you dont need any authentication you dont need to write the authStringEnd variable
The method will return a JsonObject with your response
public JSONObject getAllTypes() throws JSONException, IOException {
String url = "/api/atlas/types";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
javax.ws.rs.client.Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(host + url);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON).header("Authorization", "Basic " + authStringEnc);
Response response = invocationBuilder.get();
String output = response.readEntity(String.class
);
System.out.println(response.toString());
JSONObject obj = new JSONObject(output);
return obj;
}
You can find a point on a infinite line that is nearest to circle center by projecting vector AC onto vector AB. Calculate the distance between that point and circle center. If it is greater that R, there is no intersection. If the distance is equal to R, line is a tangent of the circle and the point nearest to circle center is actually the intersection point. If distance less that R, then there are 2 intersection points. They lie at the same distance from the point nearest to circle center. That distance can easily be calculated using Pythagorean theorem. Here's algorithm in pseudocode:
{
dX = bX - aX;
dY = bY - aY;
if ((dX == 0) && (dY == 0))
{
// A and B are the same points, no way to calculate intersection
return;
}
dl = (dX * dX + dY * dY);
t = ((cX - aX) * dX + (cY - aY) * dY) / dl;
// point on a line nearest to circle center
nearestX = aX + t * dX;
nearestY = aY + t * dY;
dist = point_dist(nearestX, nearestY, cX, cY);
if (dist == R)
{
// line segment touches circle; one intersection point
iX = nearestX;
iY = nearestY;
if (t < 0 || t > 1)
{
// intersection point is not actually within line segment
}
}
else if (dist < R)
{
// two possible intersection points
dt = sqrt(R * R - dist * dist) / sqrt(dl);
// intersection point nearest to A
t1 = t - dt;
i1X = aX + t1 * dX;
i1Y = aY + t1 * dY;
if (t1 < 0 || t1 > 1)
{
// intersection point is not actually within line segment
}
// intersection point farthest from A
t2 = t + dt;
i2X = aX + t2 * dX;
i2Y = aY + t2 * dY;
if (t2 < 0 || t2 > 1)
{
// intersection point is not actually within line segment
}
}
else
{
// no intersection
}
}
EDIT: added code to check whether found intersection points actually are within line segment.
Another way to use CASE WHEN
SELECT CASE true
WHEN max(row1) >= max(row2) THEN CASE true WHEN max(row1) >= max(row3) THEN max(row1) ELSE max(row3) end ELSE
CASE true WHEN max(row2) >= max(row3) THEN max(row2) ELSE max(row3) END END
FROM yourTable
Ensure that you have following JARS in place: 1) jackson-core-asl-1.9.13 2) jackson-jaxrs-1.9.13 3) jackson-mapper-asl-1.9.13 4) jackson-xc-1.9.13
Converting an int to a byte in Python 3:
n = 5
bytes( [n] )
>>> b'\x05'
;) guess that'll be better than messing around with strings
source: http://docs.python.org/3/library/stdtypes.html#binaryseq
Agreeing with the answer suggested by @dahlbyk. If you want the diff to be written to a diff file for code reviews use the following command.
git diff branch master -- filepath/filename.extension > filename.diff --cached
It is used to stop the propagation of the event. You see when you have two elements both with a click event handler (for example)
-----------------------------------
| element1 |
| ------------------------- |
| |element2 | |
| ------------------------- |
| |
-----------------------------------
If you click on the inner element (element2) it will trigger a click event in both elements: 1 and 2. It is called "Event bubbling". If you want to handle the event in element2 only, then the event handler has to return false to stop the event propagation.
Another example will be the link onclick handler. If you want to stop a link form working. You can add an onclick handler and return false. To stop the event from propagating to the default handler.
I don't know for sure if the solution is safe, but about the ClassGuard solution, it's interesting to read the article and the comment at: http://www.javaworld.com/community/?q=node/1604#comment-12296
Alert boxes in JavaScript can only display pure text. You could use a JavaScript library like jQuery to display a modal instead?
This might be useful: http://jqueryui.com/dialog/
You can do it like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
body {
font-family: "Trebuchet MS", "Helvetica", "Arial", "Verdana", "sans-serif";
font-size: 62.5%;
}
</script>
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>Image:</p>
<img src="http://placehold.it/50x50" alt="Placeholder Image" />
</div>
</body>
</html>
A quick note: Assume.assumeTrue(condition)
ignores rest of the steps but passes the test.
To fail the test, use org.junit.Assert.fail()
inside the conditional statement. Works same like Assume.assumeTrue()
but fails the test.
Try this, if it helps you
values = ['1', '2', '3']
with open("file.txt", "w") as output:
output.write(str(values))
This works in all browsers including earlier IE versions.
var arr = [];
[].push.apply(arr, htmlCollection);
Since jsperf is still down at the moment, here is a jsfiddle that compares the performance of different methods. https://jsfiddle.net/qw9qf48j/
Another pitfall with this is that command substitution — $()
— strips trailing newlines. Probably not always important, but if you really want to preserve exactly what was output, you'll have to use another line and some quoting:
RESULTX="$(./myscript; echo x)"
RESULT="${RESULTX%x}"
This is especially important if you want to handle all possible filenames (to avoid undefined behavior like operating on the wrong file).
There are probably embedded tabs (CHAR(9)
) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:
DECLARE @var NVARCHAR(255), @i INT;
SET @i = 1;
SELECT @var = AccountType FROM dbo.Account
WHERE AccountNumber = 200
AND AccountType LIKE '%Daily%';
CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));
WHILE @i <= LEN(@var)
BEGIN
INSERT #x
SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));
SET @i = @i + 1;
END
SELECT i,c,a FROM #x ORDER BY i;
You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.
You can use timeit
magic function for that.
%timeit CODE_LINE
Or on the cell
%%timeit
SOME_CELL_CODE
Check more IPython magic functions at https://nbviewer.jupyter.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ipynb
If you want to add magic comments on all the source files of a project easily, you can use the magic_encoding
gem
sudo gem install magic_encoding
then just call magic_encoding
in the terminal from the root of your app.
What I ended up doing is:
internal void LoadExternalData() {
FileStream file;
if (TryOpenRead("filepath/filename", 5, out file)) {
using (file)
using (StreamReader reader = new StreamReader(file)) {
// do something
}
}
}
internal bool TryOpenRead(string path, int timeout, out FileStream file) {
bool isLocked = true;
bool condition = true;
do {
try {
file = File.OpenRead(path);
return true;
}
catch (IOException e) {
var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
isLocked = errorCode == 32 || errorCode == 33;
condition = (isLocked && timeout > 0);
if (condition) {
// we only wait if the file is locked. If the exception is of any other type, there's no point on keep trying. just return false and null;
timeout--;
new System.Threading.ManualResetEvent(false).WaitOne(1000);
}
}
}
while (condition);
file = null;
return false;
}
Since no-one has yet wrote a function to do this with two integers, here's one way:
private long CalculatePower(int number, int powerOf)
{
for (int i = powerOf; i > 1; i--)
number *= number;
return number;
}
CalculatePower(5, 3); // 125
CalculatePower(8, 4); // 4096
CalculatePower(6, 2); // 36
Alternatively in VB.NET:
Private Function CalculatePower(number As Integer, powerOf As Integer) As Long
For i As Integer = powerOf To 2 Step -1
number *= number
Next
Return number
End Function
CalculatePower(5, 3) ' 125
CalculatePower(8, 4) ' 4096
CalculatePower(6, 2) ' 36
if(str.indexOf(",")!=-1) { str = str.replaceAll(",","."); }
or even better
str = str.replace(',', '.');
Status Code 304 Not Modified would also make an acceptable response to a duplicate request. This is similar to processing a header of If-None-Match
using an entity tag.
In my opinion, @Piskvor's answer is the more obvious choice to what I perceive is the intent of the original question, but I have an alternative that is also relevant.
If you want to treat a duplicate request as a warning or notification rather than as an error, a response status code of 304
Not Modified and Content-Location
header identifying the existing resource would be just as valid. When the intent is merely to ensure that a resource exists, a duplicate request would not be an error but a confirmation. The request is not wrong, but is simply redundant, and the client can refer to the existing resource.
In other words, the request is good, but since the resource already exists, the server does not need to perform any further processing.
In my opinion it's a lot easier just to use the UglifyJS tool directly:
npm install --save-dev uglify-js
./dst/bundle.js
file.Add a build
command to your package.json
:
"scripts": {
"build": "webpack && uglifyjs ./dst/bundle.js -c -m -o ./dst/bundle.min.js --source-map ./dst/bundle.min.js.map"
}
npm run build
command.No need to install uglify-js globally, just install it locally for the project.
When it checks id!=2 it returns true and stops further checking
Is adb installed? To check, run the following command in Terminal:
~/Library/Android/sdk/platform-tools/adb
If that prints output, skip these following install steps and go straight to the final Terminal command I list:
Run the following command on your Mac and restart your Terminal session:
echo export "PATH=~/Library/Android/sdk/platform-tools:$PATH" >> ~/.bash_profile
Note: If you've switched to zsh, the above command should use .zshenv
rather than .bash_profile
Here's another solution: http://jsfiddle.net/6WvUY/7/.
HTML:
<div class="container">
<div class="row">
<div class="col-sm-6">
<img src="//placehold.it/600x300" alt="Logo" class="img-responsive"/>
</div>
<div class="col-sm-6">
<h3>Some Text</h3>
</div>
</div>
</div>
CSS:
.row {
display: table;
}
.row > div {
float: none;
display: table-cell;
}
The answers here are outdated, as of today Sep 30 2016. Gmail is currently rolling out support for the style
tag in the head
, as well as media queries. If Gmail is your only concern, you're safe to use classes like a modern developer!
For reference, you can check the official gmail CSS docs.
As a side note, Gmail was the only major client that didn't support style
(reference, until they update anyway). That means you can almost safely stop putting styles inline. Some of the more obscure clients may still need them.
There are some great answers here, here is another great analogy for explaining what mutex is:
Consider single toilet with a key. When someone enters, they take the key and the toilet is occupied. If someone else needs to use the toilet, they need to wait in a queue. When the person in the toilet is done, they pass the key to the next person in queue. Make sense, right?
Convert the toilet in the story to a shared resource, and the key to a mutex. Taking the key to the toilet (acquire a lock) permits you to use it. If there is no key (the lock is locked) you have to wait. When the key is returned by the person (release the lock) you're free to acquire it now.