If you want to print output of anything in Bash without end of line, you echo it with the -n
switch.
If you have it in a variable already, then echo it with the trailing newline cropped:
$ testvar=$(wc -l < log.txt)
$ echo -n $testvar
Or you can do it in one line, instead:
$ echo -n $(wc -l < log.txt)
Set up the text box with placeholder text in a soft color...
public MainWindow ( )
{
InitializeComponent ( );
txtInput.Text = "Type something here...";
txtInput.Foreground = Brushes.DimGray;
}
When the text box gets the focus, clear it and change the text color
private void txtInput_GotFocus ( object sender, EventArgs e )
{
MessageBox.Show ( "got focus" );
txtInput.Text = "";
txtInput.Foreground = Brushes.Red;
}
You cannot open a connection directly to a path on a remote host using fsockopen
. The url www.mydomain.net/1/file.php
contains a path, when the only valid value for that first parameter is the host, www.mydomain.net
.
If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.
If you only want to send an HTTP request and ignore the response, you could use fsockopen()
and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen()
, it might look something like this:
$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1\n");
fputs($fp, "Host: www.mydomain.net\n");
fputs($fp, "Connection: close\n\n");
That leaves any error handling up to you of course, but it would mean that you wouldn't waste time reading the response.
or programatically
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
Screen Size Class
-
Hidden on all .d-none
Hidden only on xs .d-none .d-sm-block
Hidden only on sm .d-sm-none .d-md-block
Hidden only on md .d-md-none .d-lg-block
Hidden only on lg .d-lg-none .d-xl-block
Hidden only on xl .d-xl-none
Visible on all .d-block
Visible only on xs .d-block .d-sm-none
Visible only on sm .d-none .d-sm-block .d-md-none
Visible only on md .d-none .d-md-block .d-lg-none
Visible only on lg .d-none .d-lg-block .d-xl-none
Visible only on xl .d-none .d-xl-block
Refer this link http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements
4.5 link: https://getbootstrap.com/docs/4.5/utilities/display/#hiding-elements
title
is a local variable. They only exists within its scope (current block)
@title
is an instance variable - and is available to all methods within the class.
You can read more here: http://strugglingwithruby.blogspot.dk/2010/03/variables.html
In Ruby on Rails - declaring your variables in your controller as instance variables (@title
) makes them available to your view.
From RFC 5321, section 2.3.11:
The standard mailbox naming convention is defined to be "local-part@domain"; contemporary usage permits a much broader set of applications than simple "user names". Consequently, and due to a long history of problems when intermediate hosts have attempted to optimize transport by modifying them, the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address.
So yes, the part before the "@" could be case-sensitive, since it is entirely under the control of the host system. In practice though, no widely used mail systems distinguish different addresses based on case.
The part after the @ sign however is the domain and according to RFC 1035, section 3.1,
"Name servers and resolvers must compare [domains] in a case-insensitive manner"
In short, you are safe to treat email addresses as case-insensitive.
I recently got this error because the typo, I write 'canavas' instead of 'canvas', hope this could help someone who is searching for this.
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
Yes. First, hook into the column added event:
this.dataGridView1.ColumnAdded += new DataGridViewColumnEventHandler(dataGridView1_ColumnAdded);
Then, in your event handler, just append the text you want to:
private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
e.Column.HeaderText += additionalHeaderText;
}
In my case changing the ~/.zshenv
did not work. I had to make the changes inside ~/.zshrc
.
I just added:
# Include rbenv for ZSH
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
at the top of ~/.zshrc
, restarted the shell and logged out.
Check if it worked:
? ~ rbenv install 2.4.0
? ~ rbenv global 2.4.0
? ~ rbenv global
2.4.0
? ~ ruby -v
ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-darwin16]
.Click() - Perform only click operation as like mouse click.
.Submit() - Perform Enter operation as like keyboard Enter event.
For Example. Consider a login page where it contains username and password and submit button.
On filling password if we want to login without clicking login button. we need to user .submit button on password where .click() operation does not work.[to login into application]
Brif.
driver.get("https:// anyURL");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.id("txtUserId")).sendKeys("[email protected]");
WebElement text = driver.findElement(By.id("txtPassword")); text.sendKeys("password");
Thread.sleep(1000);
text.click(); //This will not work - it will on perform click operation not submit operation
text.submit(); //This will perform submit operation has enter key
I have noticed also that even if you specify your website under secion - Website With Facebook Login -> Site url as e.g. http://example.com, but if your App Domains section is empty, and you open website as www.example.com you will get this error, too. To avoid it in "App Domains" section write example.com, that will allow subdomains, like www.example.com, something.example.com etc
The problem is even if you create a proxy or load the content and inject it as if it's local, any scripts that that content defines will be loaded from the other domain and cause cross-domain problems.
For Linux Mate 17.1 Go to Menu/All applications/Keyboard/Layouts tab/Click Add/Pick out your layout by country or by language/Click Add and a language icon (US, PT and so on) will show at Panel/Close Keyboard Preferences and just click over it at Panel to switch the input language.
Following up on Radmin's excellent answer, there is a little tweak needed for everyone who is using angular-cli version 1.0.0-beta.22 and above.
COMPILER_PROVIDERS
can no longer be imported (for details see angular-cli GitHub).
So the workaround there is to not use COMPILER_PROVIDERS
and JitCompiler
in the providers
section at all, but use JitCompilerFactory
from '@angular/compiler' instead like this inside the type builder class:
private compiler: Compiler = new JitCompilerFactory([{useDebug: false, useJit: true}]).createCompiler();
As you can see, it is not injectable and thus has no dependencies with the DI. This solution should also work for projects not using angular-cli.
This should do it:
<StackPanel>
<TextBox x:Name="TheTextBox" />
<Button Content="Click Me">
<Button.Style>
<Style TargetType="Button">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</StackPanel>
PUSHD and POPD should help in your case.
@echo off
:: Create a temporary drive letter mapped to your UNC root location
:: and effectively CD to that location
pushd \\server\soft
:: Do your work
WP15\setup.exe
robocopy.exe "WP15\Custom" /copyall "C:\Program Files (x86)\WP\Custom Templates"
Regedit.exe /s WPX5\Custom\Migrate.reg
:: Remove the temporary drive letter and return to your original location
popd
Type PUSHD /?
from the command line for more information.
string shortDate = dateTimePicker1.Value.ToShortDateString();
Let's set the terms. The Aggregation is a metaterm in the UML standard, and means BOTH composition and shared aggregation, simply named shared. Too often it is named incorrectly "aggregation". It is BAD, for composition is an aggregation, too. As I understand, you mean "shared".
Further from UML standard:
composite - Indicates that the property is aggregated compositely, i.e., the composite object has responsibility for the existence and storage of the composed objects (parts).
So, University to cathedras association is a composition, because cathedra doesn't exist out of University (IMHO)
Precise semantics of shared aggregation varies by application area and modeler.
I.e., all other associations can be drawn as shared aggregations, if you are only following to some principles of yours or of somebody else. Also look here.
I would be very concerned about putting the load of sending e-mails on my database server (small though it may be). I might suggest one of these alternatives:
log.retention.hours
and add log.retention.ms=1000
. It would keep the record on Kafka Topic for only one second. log.retention.hours
to your desired figure.General answer is:
method
has object context (this, or class instance reference),
function
has none context (null, or global, or static).
But answer to question is dependent on terminology of language you use.
In JavaScript (ES 6) you are free to customising function context (this) for any you desire, which is normally must be link to the (this) object instance context.
In Java world you always hear that "only OOP classes/objects, no functions", but if you watch in detailes to static methods
in Java, they are really in global/null context (or context of classes, whithout instancing), so just functions whithout object. Java teachers could told you, that functions were rudiment of C in C++ and dropped in Java
, but they told you it for simplification of history and avoiding unnecessary questions of newbies. If you see at Java after 7 version, you can find many elements of pure function programming (even not from C, but from older 1988 Lisp) for simplifying parallel computing, and it is not OOP classes style.
In C++ and D world things are stronger, and you have separated functions and objects with methods and fields. But in practice, you again see functions without this
and methods whith this
(with object context).
In FreePascal/Lazarus and Borland Pascal/Delphi things about separation terms of functions and objects (variables and fields) are usually similar to C++.
Objective-C comes from C world, so you must separate C functions and Objective-C objects with methods addon.
C# is very similar to Java, but has many C++ advantages.
You are trying to call DeckOfCards::shuffle
with a deckOfCards
parameter:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck
But the method takes a vector<Card>&
:
void deckOfCards::shuffle(vector<Card>& deck)
The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.
Error:
[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'
Paraphrased:
Hey, pal. You're trying to call a function called
shuffle
which apparently takes a single parameter of type reference-to-deckOfCards
, but there is no such function.
Error:
[Note] candidate is:
In file included from main.cpp
[Note] void deckOfCards::shuffle(std::vector&)
Paraphrased:
I mean, maybe you meant this other function called
shuffle
, but that one takes a reference-tovector<something>
.
Error:
[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'
Which I'd be happy to call if I knew how to convert from a
deckOfCards
to avector
; but I don't. So I won't.
The answer your question is no - @Transactional
will have no effect if used to annotate private methods. The proxy generator will ignore them.
This is documented in Spring Manual chapter 10.5.6:
Method visibility and
@Transactional
When using proxies, you should apply the
@Transactional
annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the@Transactional
annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.
Maybe.
Temporary tables prefixed with one # (#example) are kept on a per session basis. So if your code calls the stored procedure again while another call is running (for example background threads) then the create call will fail because it's already there.
If you're really worried use a table variable instead
DECLARE @MyTempTable TABLE
(
someField int,
someFieldMore nvarchar(50)
)
This will be specific to the "instance" of that stored procedure call.
I would use Winamp to do this. Create a playlist of files you want to merge into one, select Disk Writer output plugin, choose filename and you're done. The file you will get will be correct MP3 file and you can set bitrate etc.
Unset will destroy a particular session variable whereas session_destroy()
will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh
let's use imshow
:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]) # added some commas and array creation code
fig = plt.figure(figsize=(6, 3.2))
ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')
cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()
"
would work in this particular case, as suggested before me, because of the HTML context.
However, if you want your JavaScript code to be independently escaped for any context, you could opt for the native JavaScript encoding:
'
becomes \x27
"
becomes \x22
So your onclick would become:DoEdit('Preliminary Assessment \x22Mini\x22');
This would work for example also when passing a JavaScript string as a parameter to another JavaScript method (alert()
is an easy test method for this).
I am referring you to the duplicate Stack Overflow question, How do I escape a string inside JavaScript code inside an onClick handler?.
sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
on a side note you can make the width variable with *-s
>>> d = "%-*s%-*s"%(25,"apple",30,"something")
>>> d
'apple something '
Year 2020. Now we have element.scrollIntoView()
method to scroll to specific element.
HTML
<div id="my_element">
</div>
JS
var my_element = document.getElementById("my_element");
my_element.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest"
});
Good thing is we can initiate this from any onclick/event and need not be limited to tag.
Because you are passing a string as the second argument to the date function, which should be an integer.
string date ( string $format [, int $timestamp = time() ] )
Try strtotime which will Parse about any English textual datetime description into a Unix timestamp (integer):
date("d", strtotime($_GET['start_date']));
It's not good to keep changing the gulp & npm versions in-order to fix the errors. I was getting several exceptions last days after reinstall my working machine. And wasted tons of minutes to re-install & fixing those.
So, I decided to upgrade all to latest versions:
npm -v : v12.13.0
node -v : 6.13.0
gulp -v : CLI version: 2.2.0 Local version: 4.0.2
This error is getting because of the how it has coded in you gulpfile but not the version mismatch. So, Here you have to change 2 things in the gulpfile to aligned with Gulp version 4. Gulp 4 has changed how initiate the task than Version 3.
gulp.task('serve', ['sass'], function() {..});
But in V4 it should be like:
function serve() {
...
}
gulp.task('serve', gulp.series(sass));
gulp.task('serve', ['sass'], function() { ... });
But in V4, it should be:
gulp.task('serve', gulp.series(sass));
SelectionChange is the event built into the Excel Object model for this. It should do exactly as you want, firing any time the user clicks anywhere...
I'm not sure that I understand your objections to global variables here, you would only need 1 if you use the Application.SelectionChange event. However, you wouldn't need any if you utilize the Workbook class code behind (to trap the Workbook.SelectionChange event) or the Worksheet class code behind (to trap the Worksheet.SelectionChange) event. (Unless your issue is the "global variable reset" problem in VBA, for which there is only one solution: error handling everywhere. Do not allow any unhandled errors, instead log them and/or "soft-report" an error as a message box to the user.)
You might also need to trap the Worksheet.Activate() and Worksheet.Deactivate() events (or the equivalent in the Workbook class) and/or the Workbook.Activate and Workbook.Deactivate() events so that you know when the user has switched worksheets and/or workbooks. The Window activate and deactivate events should make this approach complete. They could all call the same exact procedure, however, they all denote the same thing: the user changed the "focus", if you will.
If you don't like VBA, btw, you can do the same using VB.NET or C#.
[Edit: Dbb makes a very good point about the SelectionChange event not picking up a click when the user clicks within the currently selected cell. If you need to pick that up, then you would need to use subclassing.]
You are wrong about LocalDateTime
: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):
A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.
LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.
The difference between the two is that Instant
represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant
objects created at the same moment in two different places of the Earth will have exactly the same value.
You just need to add three file and two css links. You can either cdn's as well. Links for the js files and css files are as such :-
They are valid if you are using bootstrap in your project.
I hope this will help you. Regards, Vivek Singla
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
You forgot braces around the if block, and a semicolon between the statements in the block.
awk '{if($3 != 0) {a = ($3/$4); print $0, a;} else if($3==0) print $0, "-" }' file > out
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.
Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.
Here's a summary of what we found...
Conclusion
SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.
A less robust approach, but it works.
a = [2, 4, 5].toString();
b = [2, 4, 5].toString();
console.log(a===b);
Java 8 Update
Java 8 introduces the following packages for time and date manipulation.
java.time.*;
java.time.format.*;
java.time.chono.*;
java.time.temporal.*;
java.time.zone.*;
These are more organized and intuitive.
We need only top two packages for the discussion.
There are 3 top level classes - LocalDate
, LocalTime
, LocalDateTime
for describing Date, Time and DateTime respectively. Although, they are formatted properly in toString()
, each class has format method which accepts DateTimeFormatter
to format in customized way.
DateTimeFormatter
can also be used show the date given a day. It has few
import java.time.*;
import java.time.format.*;
class DateTimeDemo{
public static void main(String...args){
LocalDateTime x = LocalDateTime.now();
System.out.println(x.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));//Shows Day and Date.
System.out.println(x.format(DateTimeFormatter.ofPattern("EE")));//Short Form
System.out.println(x.format(DateTimeFormatter.ofPattern("EEEE")));//Long Form
}
}
ofLocalizedTime
accepts FormatStyle
which is an enumeration in java.time.format
ofPattern
accepts String
with restricted pattern characters of restricted length. Here are the characters which can be passed into the toPattern
method.
You can try different number of patterns to see how the output will be.
Check out more about Java 8 DateTime API here
The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.
However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:
document.getElementById('loginSubmit').click();
you cannot set target attribute to div, becacuse div does not know how to handle http requests. instead of you set target attribute for link tag.
$(this).find("a").target = "_blank";
window.location= $(this).find("a").attr("href")
public static Boolean freq[] = new Boolean[Global.iParameter[2]];
Global.iParameter[2]:
It should be const value
As @Malvineous said, It's not professional but a work-around to use the Find/Replace method to remove trailing space (below including tab U+0009 and whitespace U+0020).
Just press Ctrl + F (or command + F)
[\t ][\t ]*$
extra:
For removing leading space, find ^[\t ][\t ]*
instead of [\t ][\t ]*$
For removing blank lines, find ^\s*$\r?\n
uses-permission android:name="android.permission.INTERNET
The JAX-WS dependency library “jaxws-rt.jar” is missing.
Go here http://jax-ws.java.net/. Download JAX-WS RI distribution. Unzip it and copy “jaxws-rt.jar” to Tomcat library folder “{$TOMCAT}/lib“. Restart Tomcat.
A simple solution for selecting 5
random files while avoiding to parse ls. It also works with files containing spaces, newlines and other special characters:
shuf -ezn 5 * | xargs -0 -n1 echo
Replace echo
with the command you want to execute for your files.
for f in `find -depth`; do mv ${f} ${f,,} ; done
find -depth
prints each file and directory, with a directory's contents printed before the directory itself. ${f,,}
lowercases the file name.
To split on a string you need to use the overload that takes an array of strings:
string[] lines = theText.Split(
new[] { Environment.NewLine },
StringSplitOptions.None
);
Edit:
If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:
string[] lines = theText.Split(
new[] { "\r\n", "\r", "\n" },
StringSplitOptions.None
);
threading.get_ident()
works, or threading.current_thread().ident
(or threading.currentThread().ident
for Python < 2.6).
You could do this:
class C
{
public:
template <typename T> C(T*);
};
template <typename T> T* UseType()
{
static_cast<T*>(nullptr);
}
Then to create an object of type C
using int
as the template parameter to the constructor:
C obj(UseType<int>());
Since you can't pass template parameters to a constructor, this solution essentially converts the template parameter to a regular parameter. Using the UseType<T>()
function when calling the constructor makes it clear to someone looking at the code that the purpose of that parameter is to tell the constructor what type to use.
One use case for this would be if the constructor creates a derived class object and assigns it to a member variable that is a base class pointer. (The constructor needs to know which derived class to use, but the class itself doesn't need to be templated since the same base class pointer type is always used.)
If you intend to knowingly keep many plots in memory, but don't want to be warned about it, you can update your options prior to generating figures.
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})
This will prevent the warning from being emitted without changing anything about the way memory is managed.
@martinho as a newbie using Flask and Python myself, I think the previous answers here took for granted that you had a good understanding of the fundamentals. In case you or other viewers don't know the fundamentals, I'll give more context to understand the answer...
... the request.args
is bringing a "dictionary" object for you. The "dictionary" object is similar to other collection-type of objects in Python, in that it can store many elements in one single object. Therefore the answer to your question
And how many parameters
request.args.get()
takes.
It will take only one object, a "dictionary" type of object (as stated in the previous answers). This "dictionary" object, however, can have as many elements as needed... (dictionaries have paired elements called Key, Value).
Other collection-type of objects besides "dictionaries", would be "tuple", and "list"... you can run a google search on those and "data structures" in order to learn other Python fundamentals. This answer is based Python; I don't have an idea if the same applies to other programming languages.
You say that if int(splitLine[0]) > int(lastUnix):
is causing the trouble, but you don't actually show anything which suggests that.
I think this line is the problem instead:
print 'Pulled', + stock
Do you see why this line could cause that error message? You want either
>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA
or
>>> print 'Pulled ' + stock
Pulled AAAA
not
>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
File "<ipython-input-5-7c26bb268609>", line 1, in <module>
print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'
You're asking Python to apply the +
symbol to a string like +23
makes a positive 23, and she's objecting.
The string is basically bounded from the place where it is pointed to (char *ptrChar;
), to the null character (\0
).
The char *ptrChar;
actually points to the beginning of the string (char array), and thus that is the pointer to that string,
so when you do like ptrChar[x]
for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).
Please check this KB article : http://support.microsoft.com/kb/2259709 This issue occurs because Visio 2013 uses new UML and database modeling templates that are not used by Visio 2010 or by earlier versions of Visio. And it applies to both :
"Microsoft Visio Professional 2013" and "Microsoft Visio Standard 2013"
So upgrading to Pro might not help as well.
In my case the issue was due to how I build my Nav bar. I was doing it through a jQuery plugin so I can quickly build Bootstrap components through javascript.
To cut a long story short binding the data elements of the button through jQuery .data() resulted in a collapse button that didn't work, doing it via .attr() fixed the issue.
This doesn't work:
$this.addClass("navbar navbar-default")
.append($("<div />").addClass("container-fluid")
.append($("<div />").addClass("navbar-header")
.append($("<button />").addClass("navbar-toggle collapsed")
.attr("type","button")
.attr("aria-expanded", "false")
.data("target","#" + id)
.data("toggle","collapse")
.html("<span class='sr-only'>Toggle navigation</span>"
+ "<span class='icon-bar'></span>"
+ "<span class='icon-bar'></span>"
+ "<span class='icon-bar'></span>"))
.append($("<a href='#' />").addClass("navbar-brand")
.append(document.createTextNode(settings.label))))
.append($("<div />").addClass("collapse navbar-collapse").attr("id",id)));
But this does (with the changes left in comments):
$this.addClass("navbar navbar-default")
.append($("<div />").addClass("container-fluid")
.append($("<div />").addClass("navbar-header")
.append($("<button />").addClass("navbar-toggle collapsed")
.attr("type","button")
.attr("aria-expanded", "false")
.attr("data-target", "#" + id) //.data("target","#" + id)
.attr("data-toggle", "collapse") // .data("toggle","collapse")
.html("<span class='sr-only'>Toggle navigation</span>"
+ "<span class='icon-bar'></span>"
+ "<span class='icon-bar'></span>"
+ "<span class='icon-bar'></span>"))
.append($("<a href='#' />").addClass("navbar-brand")
.append(document.createTextNode(settings.label))))
.append($("<div />").addClass("collapse navbar-collapse").attr("id",id)));
I can only assume that this is related to the way jQuery binds .data(), it doesn't write the attributes out to the elements, but just attaches them to the jQuery object. Using the .data() version resulted in HTML:
<button class="navbar-toggle collapsed" aria-expanded="false" type="button" >
Where as the .attr() version gives:
<button class="navbar-toggle collapsed" aria-expanded="false" type="button" data-toggle="collapse" data-target="#6a2034fe-8922-4edd-920e-6bd0ea0b2caf">
It seems that Bootstrap needs the data-nnn attribute in the HTML.
Based on Kenton's answer, a simpler yet working solution looks like:
message Foo {
oneof optional_baz { // "optional_" prefix here just serves as an indicator, not keyword in proto2
int32 baz = 1;
}
}
There are a many ways to create your objects in JavaScript. Using a constructer function to create an object or object literal notation is using alot in JavaScript. Also creating an instance of Object and then adding properties and methods to it, there are three common ways to do create objects in JavaScript.
Constructer functions
There are built-in constructer functions that we all may use them time to time, like Date(), Number(), Boolean() etc, all constructer functions start with Capital letter, in the meantime we can create custom constructor function in JavaScript like this:
function Box (Width, Height, fill) {
this.width = Width; // The width of the box
this.height = Height; // The height of the box
this.fill = true; // Is it filled or not?
}
and you can invoke it, simply using new(), to create a new instance of the constructor, create something like below and call the constructor function with filled parameters:
var newBox = new Box(8, 12, true);
Object literals
Using object literals are very used case creating object in JavaScript, this an example of creating a simple object, you can assign anything to your object properties as long as they are defined:
var person = {
name: "Alireza",
surname: "Dezfoolian"
nose: 1,
feet: 2,
hands: 2,
cash: null
};
Prototyping
After creating an Object, you can prototype more members to that, for example adding colour to our Box, we can do this:
Box.prototype.colour = 'red';
Use the string's .replace
method with a regex of \D
, which is a shorthand character class that matches all non-digits:
myString = myString.replace(/\D/g,'');
If the order of the objects is significant, you should revise your JSON schema to store the objects in an array:
[
{"name":"foo", ...},
{"name":"bar", ...},
{"name":"baz", ...}
]
or maybe:
[
["foo", {}],
["bar", {}],
["baz", {}]
]
As Ben Alpert points out, properties of Javascript objects are unordered, and your code is broken if you expect them to enumerate in the same order that they are specified in the object literal—there is no "first" property.
Try jQuery:
$("#banner-contenedor").width();
The reason this puts NaN
into a column is because df.index
and the Index
of your right-hand-side object are different. @zach shows the proper way to assign a new column of zeros. In general, pandas
tries to do as much alignment of indices as possible. One downside is that when indices are not aligned you get NaN
wherever they aren't aligned. Play around with the reindex
and align
methods to gain some intuition for alignment works with objects that have partially, totally, and not-aligned-all aligned indices. For example here's how DataFrame.align()
works with partially aligned indices:
In [7]: from pandas import DataFrame
In [8]: from numpy.random import randint
In [9]: df = DataFrame({'a': randint(3, size=10)})
In [10]:
In [10]: df
Out[10]:
a
0 0
1 2
2 0
3 1
4 0
5 0
6 0
7 0
8 0
9 0
In [11]: s = df.a[:5]
In [12]: dfa, sa = df.align(s, axis=0)
In [13]: dfa
Out[13]:
a
0 0
1 2
2 0
3 1
4 0
5 0
6 0
7 0
8 0
9 0
In [14]: sa
Out[14]:
0 0
1 2
2 0
3 1
4 0
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
Name: a, dtype: float64
On MacOS:
svn upgrade
Can you try this?
Go to Tools> Preferences > Database > NLS and set the Date Format as MM/DD/YYYY HH24:MI:SS
You can get the mouse positions by using this snippet:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
};
}
This code takes into account both changing coordinates to canvas space (evt.clientX - rect.left
) and scaling when canvas logical size differs from its style size (/ (rect.right - rect.left) * canvas.width
see: Canvas width and height in HTML5).
Example: http://jsfiddle.net/sierawski/4xezb7nL/
Source: jerryj comment on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
If i understand what you mean, you have to initialize your controller with that style. Something like:
myTVContoller = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.
PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn()
. There is no need to fetch any data so we will only fetch 1
if the value exists.
<?php
// Connection code.
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);
// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
For more examples see: How to check if email exists in the database?
As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.
<?php
// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');
// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean
if ($exists) {
echo 'Email exists in the database.';
} else {
// email doesn't exist yet
}
Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1)
and read the first item from the first row using fetch_row()[0]
For more examples see: How to check whether a value exists in a database using mysqli prepared statements
mysqli_num_rows()
, don't listen to them. This is a very bad approach and could lead to performance issues if misused.real_escape_string()
. This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.Integer.toString
calls the static method in the class Integer
. It does not need an instance of Integer
.
If you call new Integer(i)
you create an instance of type Integer
, which is a full Java object encapsulating the value of your int. Then you call the toString
method on it to ask it to return a string representation of itself.
If all you want is to print an int
, you'd use the first one because it's lighter, faster and doesn't use extra memory (aside from the returned string).
If you want an object representing an integer value—to put it inside a collection for example—you'd use the second one, since it gives you a full-fledged object to do all sort of things that you cannot do with a bare int
.
You actually need to understand the ApplicationContext
. It is an interface and it will have different implementations based on configuration.
As you are using new ClassPathXmlApplicationContext("applicationContext.xml");
, kindly pay attention to initial right hand-side , it says ClassPathXmlApplicationContext , so the XML must be present in the class path.
So drag your applicationContext.xml wherever it is to the src folder.
Gist: new ClassPathXmlApplicationContext as the name [ClassPathXml]will look for the xml file in the src folder of your project, so drag your xml file there only.
? ClassPathXmlApplicationContext
—Loads a context definition from an XML
file located in the classpath, treating context definition files as classpath
resources.
? FileSystemXmlApplicationContext
—Loads a context definition from an XML
file in the file system.
? XmlWebApplicationContext
—Loads context definitions from an XML file contained
within a web application.
I found that (at least in Visual Studio 2010) you need to set the output verbosity to at least Detailed to be able to spot the problem.
It might be that my problem was a reference that was previously a GAC reference, but that was no longer the case after my machine's reinstall.
Keyboard shortcuts to that are:
For copy: Place cursor on starting of block and press md and then goto end of block and press y'd. This will select the block to paste it press p
For cut: Place cursor on starting of block and press ma and then goto end of block and press d'a. This will select the block to paste it press p
Try this
let path = "/{id}/{name}/{age}";
const paramsPattern = /[^{\}]+(?=})/g;
let extractParams = path.match(paramsPattern);
console.log("extractParams", extractParams) // prints all the names between {} = ["id", "name", "age"]
I'm doing exactly what you're looking for in my rules engine, which uses CS-Script for dynamically compiling, loading, and running C#. It should be easily translatable into what you're looking for, and I'll give an example. First, the code (stripped-down):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using CSScriptLibrary;
namespace RulesEngine
{
/// <summary>
/// Make sure <typeparamref name="T"/> is an interface, not just any type of class.
///
/// Should be enforced by the compiler, but just in case it's not, here's your warning.
/// </summary>
/// <typeparam name="T"></typeparam>
public class RulesEngine<T> where T : class
{
public RulesEngine(string rulesScriptFileName, string classToInstantiate)
: this()
{
if (rulesScriptFileName == null) throw new ArgumentNullException("rulesScriptFileName");
if (classToInstantiate == null) throw new ArgumentNullException("classToInstantiate");
if (!File.Exists(rulesScriptFileName))
{
throw new FileNotFoundException("Unable to find rules script", rulesScriptFileName);
}
RulesScriptFileName = rulesScriptFileName;
ClassToInstantiate = classToInstantiate;
LoadRules();
}
public T @Interface;
public string RulesScriptFileName { get; private set; }
public string ClassToInstantiate { get; private set; }
public DateTime RulesLastModified { get; private set; }
private RulesEngine()
{
@Interface = null;
}
private void LoadRules()
{
if (!File.Exists(RulesScriptFileName))
{
throw new FileNotFoundException("Unable to find rules script", RulesScriptFileName);
}
FileInfo file = new FileInfo(RulesScriptFileName);
DateTime lastModified = file.LastWriteTime;
if (lastModified == RulesLastModified)
{
// No need to load the same rules twice.
return;
}
string rulesScript = File.ReadAllText(RulesScriptFileName);
Assembly compiledAssembly = CSScript.LoadCode(rulesScript, null, true);
@Interface = compiledAssembly.CreateInstance(ClassToInstantiate).AlignToInterface<T>();
RulesLastModified = lastModified;
}
}
}
This will take an interface of type T, compile a .cs file into an assembly, instantiate a class of a given type, and align that instantiated class to the T interface. Basically, you just have to make sure the instantiated class implements that interface. I use properties to setup and access everything, like so:
private RulesEngine<IRulesEngine> rulesEngine;
public RulesEngine<IRulesEngine> RulesEngine
{
get
{
if (null == rulesEngine)
{
string rulesPath = Path.Combine(Application.StartupPath, "Rules.cs");
rulesEngine = new RulesEngine<IRulesEngine>(rulesPath, typeof(Rules).FullName);
}
return rulesEngine;
}
}
public IRulesEngine RulesEngineInterface
{
get { return RulesEngine.Interface; }
}
For your example, you want to call Run(), so I'd make an interface that defines the Run() method, like this:
public interface ITestRunner
{
void Run();
}
Then make a class that implements it, like this:
public class TestRunner : ITestRunner
{
public void Run()
{
// implementation goes here
}
}
Change the name of RulesEngine to something like TestHarness, and set your properties:
private TestHarness<ITestRunner> testHarness;
public TestHarness<ITestRunner> TestHarness
{
get
{
if (null == testHarness)
{
string sourcePath = Path.Combine(Application.StartupPath, "TestRunner.cs");
testHarness = new TestHarness<ITestRunner>(sourcePath , typeof(TestRunner).FullName);
}
return testHarness;
}
}
public ITestRunner TestHarnessInterface
{
get { return TestHarness.Interface; }
}
Then, anywhere you want to call it, you can just run:
ITestRunner testRunner = TestHarnessInterface;
if (null != testRunner)
{
testRunner.Run();
}
It would probably work great for a plugin system, but my code as-is is limited to loading and running one file, since all of our rules are in one C# source file. I would think it'd be pretty easy to modify it to just pass in the type/source file for each one you wanted to run, though. You'd just have to move the code from the getter into a method that took those two parameters.
Also, use your IRunnable in place of ITestRunner.
Most common case of this error happening is using template that is generating the control then changing the way id
and/or name
are being generated by 'overriding' default template with something like
@Html.TextBoxFor(m => m, new {Name = ViewData["Name"], id = ViewData["UniqueId"]} )
and then forgetting to change ValidationMessageFor
to
@Html.ValidationMessageFor(m => m, null, new { data_valmsg_for = ViewData["Name"] })
Hope this saves you some time.
You can use function colSums()
to calculate sum of all values. [,-1]
ensures that first column with names of people is excluded.
colSums(people[,-1])
Height Weight
199 425
Assuming there could be multiple columns that are not numeric, or that your column order is not fixed, a more general approach would be:
colSums(Filter(is.numeric, people))
I've seen this error caused by the combination of good sized viewstate and over aggressive content-filtering devices/firewalls (especially when dealing with K-12 Educational institutions).
We worked around it by storing Viewstate in SQL Server. Before going that route, I would recommend trying to limit your use of viewstate by not storing anything large in it and turning it off for all controls which do not need it.
References for storing ViewState in SQL Server:
MSDN - Overview of PageStatePersister
ASP Alliance - Simple method to store viewstate in SQL Server
Code Project - ViewState Provider Model
Put the following code into head section in your web page programming.
<head>
<style>.carousel-inner > .item > img { width:100%; height:570px; } </style>
</head>
I'd like to add to this the enormously simple, but oh so easily made mistake of writing:
this.state.something = 'changed';
... and then not understanding why it's not rendering and Googling and coming on this page, only to realize that you should have written:
this.setState({something: 'changed'});
React only triggers a re-render if you use setState
to update the state.
There is no way to restrict templates to types, but you can define different actions based on the type. As part of a generic numeric package, I needed a generic class to add two values.
class Something<TCell>
{
internal static TCell Sum(TCell first, TCell second)
{
if (typeof(TCell) == typeof(int))
return (TCell)((object)(((int)((object)first)) + ((int)((object)second))));
if (typeof(TCell) == typeof(double))
return (TCell)((object)(((double)((object)first)) + ((double)((object)second))));
return second;
}
}
Note that the typeofs are evaluated at compile time, so the if statements would be removed by the compiler. The compiler also removes spurious casts. So Something would resolve in the compiler to
internal static int Sum(int first, int second)
{
return first + second;
}
Take a look at JSMPEG project. There is a great idea implemented there — to decode MPEG in the browser using JavaScript. Bytes from encoder (FFMPEG, for example) can be transfered to browser using WebSockets or Flash, for example. If community will catch up, I think, it will be the best HTML5 live video streaming solution for now.
Just a suggestion,in your code instead of using let newData = prevState.data
you could use spread which is introduced in ES6 that is you can uselet newData = ...prevState.data
for copying array
Three dots ... represents Spread Operators or Rest Parameters,
It allows an array expression or string or anything which can be iterating to be expanded in places where zero or more arguments for function calls or elements for array are expected.
Additionally you can delete item from array with following
onRemovePerson: function(index) {
this.setState((prevState) => ({
data: [...prevState.data.slice(0,index), ...prevState.data.slice(index+1)]
}))
}
Hope this contributes!!
If you have Local Values overriding master values, you won't change its values in php.ini take a look for those variables in a .htaccess or in the virtual-host config file.
...
php_admin_value display_errors On
php_admin_value error_reporting E_ALL
</VirtualHost>
If you edit vhost, restart apache,
$ sudo service apache2 restart
.htaccess edits don't need apache to restart
You could use JavaScript and trigger the hidden file input when the button input has been clicked.
http://jsfiddle.net/gregorypratt/dhyzV/ - simple
http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery
Or, you could style a div directly over the file input and set pointer-events
in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events
The mother of all debugger is plain old print screen. Most of the time, you probably only want to inspect some simple objects, a quick and easy way is like this:
@result = fetch_result
p "--------------------------"
p @result
This will print out the contents of @result to STDOUT with a line in front for easy identification.
Bonus if you use a autoload / reload capable framework like Rails, you won't even need to restart your app. (Unless the code you are debugging is not reloaded due to framework specific settings)
I find this works for 90% of the use case for me. You can also use ruby-debug, but I find it overkill most of the time.
You can use Object.assign()
to merge them into a new object:
const response = {_x000D_
lat: -51.3303,_x000D_
lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
id: 'qwenhee-9763ae-lenfya',_x000D_
address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = Object.assign({}, item, { location: response });_x000D_
_x000D_
console.log(newItem );
_x000D_
You can also use object spread, which is a Stage 4 proposal for ECMAScript:
const response = {_x000D_
lat: -51.3303,_x000D_
lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
id: 'qwenhee-9763ae-lenfya',_x000D_
address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well_x000D_
_x000D_
console.log(newItem );
_x000D_
I was using a Dependency Injection - ButterKnife and this problem arised because I had not binded the view.
So inside onCreate() I just inserted this line:
ButterKnife.bind(this);
My RecyclerView declaration with Dependency Injection:
@BindView(R.id.recyclerview)
RecyclerView recyclerView;
Remove new line characters with SQL column data
Update a set a.CityName=Rtrim(Ltrim(REPLACE(REPLACE(a.CityName,CHAR(10),' '),CHAR(13),' ')))
,a.postalZone=Rtrim(Ltrim(REPLACE(REPLACE(a.postalZone,CHAR(10),' '),CHAR(13),' ')))
From tAddress a
inner Join tEmployees p on a.AddressId =p.addressId
Where p.MigratedID is not null and p.AddressId is not null AND
(REPLACE(REPLACE(a.postalZone,CHAR(10),'Y'),CHAR(13),'X') Like 'Y%' OR REPLACE(REPLACE(a.CityName,CHAR(10),'Y'),CHAR(13),'X') Like 'Y%')
Clear repository is one possible solution.
Windows -> delete all subfolders in the maven repository:
C:\Users\YourUserName.m2\repository
Use array notation like name="checkbox[]"
in your input
element. This will give you $_POST['checkbox']
as array. In the query you can utilize it as
$sql = "DELETE FROM links WHERE link_id in ";
$sql.= "('".implode("','",array_values($_POST['checkbox']))."')";
Thats one single query to delete them all.
Note: You need to escape the values passed in $_POST['checkbox']
with mysql_real_escape_string
or similar to prevent SQL Injection.
to make it work in intelliJ, you can also add
<generatedSourcesDirectory>src/main/generated</generatedSourcesDirectory>
to maven-compiler-plugin
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
I'm guessing the question you really care about here is:
Is there a way to force Python to release all the memory that was used (if you know you won't be using that much memory again)?
No, there is not. But there is an easy workaround: child processes.
If you need 500MB of temporary storage for 5 minutes, but after that you need to run for another 2 hours and won't touch that much memory ever again, spawn a child process to do the memory-intensive work. When the child process goes away, the memory gets released.
This isn't completely trivial and free, but it's pretty easy and cheap, which is usually good enough for the trade to be worthwhile.
First, the easiest way to create a child process is with concurrent.futures
(or, for 3.1 and earlier, the futures
backport on PyPI):
with concurrent.futures.ProcessPoolExecutor(max_workers=1) as executor:
result = executor.submit(func, *args, **kwargs).result()
If you need a little more control, use the multiprocessing
module.
The costs are:
mmap
ped or otherwise; the shared-memory APIs in multiprocessing
; etc.).struct
-able or ideally ctypes
-able).Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.
If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.
The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.
So the ultimate difference is:
Use PHP error handling functions to handle errors. How you do it depends on your needs. This system will intercept all errors and forward it however you want it Or supress it if you ask it to do so
This will show only Cart Items Count.
global $woocommerce;
echo $woocommerce->cart->cart_contents_count;
You can use the condition if x is not null then...
. It's not a function. There's also the NVL()
function, a good example of usage here: NVL function ref.
Dir.foreach("/home/mydir") do |fname|
puts fname
end
You can try RuneCountInString
from the utf8 package.
returns the number of runes in p
that, as illustrated in this script: the length of "World" might be 6 (when written in Chinese: "??"), but its rune count is 2:
package main
import "fmt"
import "unicode/utf8"
func main() {
fmt.Println("Hello, ??", len("??"), utf8.RuneCountInString("??"))
}
Phrozen adds in the comments:
Actually you can do len()
over runes by just type casting.
len([]rune("??"))
will print 2
. At leats in Go 1.3.
And with CL 108985 (May 2018, for Go 1.11), len([]rune(string))
is now optimized. (Fixes issue 24923)
The compiler detects len([]rune(string))
pattern automatically, and replaces it with for r := range s call.
Adds a new runtime function to count runes in a string. Modifies the compiler to detect the pattern
len([]rune(string))
and replaces it with the new rune counting runtime function.RuneCount/lenruneslice/ASCII 27.8ns ± 2% 14.5ns ± 3% -47.70% RuneCount/lenruneslice/Japanese 126ns ± 2% 60 ns ± 2% -52.03% RuneCount/lenruneslice/MixedLength 104ns ± 2% 50 ns ± 1% -51.71%
Stefan Steiger points to the blog post "Text normalization in Go"
What is a character?
As was mentioned in the strings blog post, characters can span multiple runes.
For example, an 'e
' and '?´?´' (acute "\u0301") can combine to form 'é' ("e\u0301
" in NFD). Together these two runes are one character.The definition of a character may vary depending on the application.
For normalization we will define it as:
- a sequence of runes that starts with a starter,
- a rune that does not modify or combine backwards with any other rune,
- followed by possibly empty sequence of non-starters, that is, runes that do (typically accents).
The normalization algorithm processes one character at at time.
Using that package and its Iter
type, the actual number of "character" would be:
package main
import "fmt"
import "golang.org/x/text/unicode/norm"
func main() {
var ia norm.Iter
ia.InitString(norm.NFKD, "école")
nc := 0
for !ia.Done() {
nc = nc + 1
ia.Next()
}
fmt.Printf("Number of chars: %d\n", nc)
}
Here, this uses the Unicode Normalization form NFKD "Compatibility Decomposition"
Oliver's answer points to UNICODE TEXT SEGMENTATION as the only way to reliably determining default boundaries between certain significant text elements: user-perceived characters, words, and sentences.
For that, you need an external library like rivo/uniseg, which does Unicode Text Segmentation.
That will actually count "grapheme cluster", where multiple code points may be combined into one user-perceived character.
package uniseg
import (
"fmt"
"github.com/rivo/uniseg"
)
func main() {
gr := uniseg.NewGraphemes("!")
for gr.Next() {
fmt.Printf("%x ", gr.Runes())
}
// Output: [1f44d 1f3fc] [21]
}
Two graphemes, even though there are three runes (Unicode code points).
You can see other examples in "How to manipulate strings in GO to reverse them?"
? alone is one grapheme, but, from unicode to code points converter, 4 runes:
It is a permission error. The way that was most appropriate and secure for me was adding users to a supplementary group that the repo. is owned by (or vice versa):
groupadd git
chgrp -R git .git
chgrp -R git ./
usermod -G -a git $(whoami)
because the dir is not exist.
can use :!mkdir -p /etc/apt/
to make the directory.
then :wq
Return converted image without saving:
from PIL import Image
import cv2
# Take in base64 string and return cv image
def stringToRGB(base64_string):
imgdata = base64.b64decode(str(base64_string))
image = Image.open(io.BytesIO(imgdata))
return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
I have added slashes before inserting into database so on the time of fetching i removed slashes again stripslashes()
and it works for me. I am sharing the code which works for me.
How i inserted into mysql db (blob type)
$db = mysqli_connect("localhost","root","","dName");
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
$query = "INSERT INTO student_img (id,image) VALUES('','$image')";
$query = mysqli_query($db, $query);
Now to access the image
$sqlQuery = "SELECT * FROM student_img WHERE id = $stid";
$rs = $db->query($sqlQuery);
$result=mysqli_fetch_array($rs);
echo '<img src="data:image/jpeg;base64,'.base64_encode( stripslashes($result['image']) ).'"/>';
Hope it will help someone
Thanks.
The connection URL should look like this for SQL Server:
jdbc:sqlserver://serverName[\instanceName][:port][;databaseName=your_db_name]
Examples:
jdbc:sqlserver://localhost
jdbc:sqlserver://127.0.0.1\INGESQL:1433;databaseName=datatest
...
This worked. The first row had column names in it.
COPY wheat FROM 'wheat_crop_data.csv' DELIMITER ';' CSV HEADER
in pure Ruby:
{:a => 1, :b => 2}.tap{|x| x.delete(:a)} # => {:b=>2}
One way to do it is with NumPy transpose. For a list, a:
>>> import numpy as np
>>> np.array(a).T.tolist()
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Or another one without zip:
>>> map(list,map(None,*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
My descriptions for the three:
position: absolute
descendents)position: absolute
ones) without scrolling.Then there is also:
If you mean any letters in any character encoding, then a good approach might be to delete non-letters like spaces \s
, digits \d
, and other special characters like:
[!@#\$%\^&\*\(\)\[\]:;'",\. ...more special chars... ]
Or use negation of above negation to directly describe any letters:
\S \D and [^ ..special chars..]
Pros:
Cons:
I suspect that the xcopy
command is the magic bullet you're looking for.
It can copy files, directories, and even entire drives while preserving the original directory hierarchy. There are also a handful of additional options available, compared to the basic copy
command.
Check out the documentation here.
If your batch file only needs to run on Windows Vista or later, you can use robocopy
instead, which is an even more powerful tool than xcopy
, and is now built into the operating system. It's documentation is available here.
My solution:
Change back to bash
:
source .bashrc
next:
echo $PATH
copy this:
/home/frank/.asdf/shims:/home/frank/....
back to the zsh
:
source .zsh
open .zshrc
:
and paste:
export PATH=/home/frank/.asdf/shims:/home/frank/....
restart terminal
iOS 11
Setting a custom button using constraint:
let buttonWidth = CGFloat(30)
let buttonHeight = CGFloat(30)
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "img name"), for: .normal)
button.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)
button.widthAnchor.constraint(equalToConstant: buttonWidth).isActive = true
button.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: button)
You can refer the below example to understand the working of re.match
and re.search
a = "123abc"
t = re.match("[a-z]+",a)
t = re.search("[a-z]+",a)
re.match
will return none
, but re.search
will return abc
.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD
for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD
is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!or:
YYYY-MM-DDTHH:MM:SS
for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T
as delimiter between the date and time portion of your DATETIME
.This is valid for SQL Server 2000 and newer.
So in your concrete case - use these strings:
insert into table1 values('2012-02-21T18:10:00', '2012-01-01T00:00:00');
and you should be fine (note: you need to use the international 24-hour format rather than 12-hour AM/PM format for this).
Alternatively: if you're on SQL Server 2008 or newer, you could also use the DATETIME2
datatype (instead of plain DATETIME
) and your current INSERT
would just work without any problems! :-) DATETIME2
is a lot better and a lot less picky on conversions - and it's the recommend date/time data types for SQL Server 2008 or newer anyway.
SELECT
CAST('02-21-2012 6:10:00 PM' AS DATETIME2), -- works just fine
CAST('01-01-2012 12:00:00 AM' AS DATETIME2) -- works just fine
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD
format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful
library(dplyr)
iris %>%
mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))
you can combine them using LINQ:
list = list1.Concat(list2).Concat(list3).ToList();
the more traditional approach of using List.AddRange()
might be more efficient though.
Using the wildcard * selector in CSS to override inheritance for all attributes of an element (by setting these back to their initial state).
An example of its use:
li * {
display: initial;
}
If you know how many lines you want, create an array of String with that many members (e.g. myStringArray). Then use myListBox.Lines = myStringArray;
LocalDateTime.parse(
"2018-01-23 01:23:45".replace( " " , "T" )
).plusHours( 2 )
The modern approach uses the java.time classes added to Java 8, Java 9, and later.
user enters in the format YYYY-MM-DD HH:MM:SS
Parse that input string into a date-time object. Your format is close to complying with standard ISO 8601 format, used by default in the java.time classes for parsing/generating strings. To fully comply, replace the SPACE in the middle with a T
.
String input = "2018-01-23 01:23:45".replace( " " , "T" ) ; // Yields: 2018-01-23T01:23:45
Parse as a LocalDateTime
given that your input lacks any indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
add two hours
The java.time classes can do the math for you.
LocalDateTime twoHoursLater = ldt.plusHours( 2 ) ;
Be aware that a LocalDateTime
does not represent a moment, a point on the timeline. Without the context of a time zone or offset-from-UTC, it has no real meaning. The “Local” part of the name means any locality or no locality, rather than any one particular locality. Just saying "noon on Jan 21st" could mean noon in Auckland, New Zealand which happens several hours earlier than noon in Paris France.
To define an actual moment, you must specify a zone or offset.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Define an actual moment, a point on the timeline by giving a context with time zone.
If you know the intended time zone for certain, apply it before adding the two hours. The LocalDateTime
class assumes simple generic 24-hour days when doing the math. But in various time zones on various dates, days may be 23 or 25 hours long, or may be other lengths. So, for correct results in a zoned context, add the hours to your ZonedDateTime
rather than LocalDateTime
.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Why not just:
IF object_id('YourFunctionName', 'FN') IS NOT NULL
BEGIN
DROP FUNCTION [dbo].[YourFunctionName]
END
GO
The second argument of object_id
is optional, but can help to identify the correct object. There are numerous possible values for this type argument, particularly:
try this:
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
public class JsonParsing {
public static void main(String[] args) throws Exception {
InputStream is =
JsonParsing.class.getResourceAsStream( "sample-json.txt");
String jsonTxt = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");
System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );
}
}
and this is your sample-json.txt , should be in json format
{
'foo':'bar',
'coolness':2.0,
'altitude':39000,
'pilot':
{
'firstName':'Buzz',
'lastName':'Aldrin'
},
'mission':'apollo 11'
}
If you want to test the logic just don´t test it asynchronously.
For example to test this code which works on results of an asynchronous method.
public class Example {
private Dependency dependency;
public Example(Dependency dependency) {
this.dependency = dependency;
}
public CompletableFuture<String> someAsyncMethod(){
return dependency.asyncMethod()
.handle((r,ex) -> {
if(ex != null) {
return "got exception";
} else {
return r.toString();
}
});
}
}
public class Dependency {
public CompletableFuture<Integer> asyncMethod() {
// do some async stuff
}
}
In the test mock the dependency with synchronous implementation. The unit test is completely synchronous and runs in 150ms.
public class DependencyTest {
private Example sut;
private Dependency dependency;
public void setup() {
dependency = Mockito.mock(Dependency.class);;
sut = new Example(dependency);
}
@Test public void success() throws InterruptedException, ExecutionException {
when(dependency.asyncMethod()).thenReturn(CompletableFuture.completedFuture(5));
// When
CompletableFuture<String> result = sut.someAsyncMethod();
// Then
assertThat(result.isCompletedExceptionally(), is(equalTo(false)));
String value = result.get();
assertThat(value, is(equalTo("5")));
}
@Test public void failed() throws InterruptedException, ExecutionException {
// Given
CompletableFuture<Integer> c = new CompletableFuture<Integer>();
c.completeExceptionally(new RuntimeException("failed"));
when(dependency.asyncMethod()).thenReturn(c);
// When
CompletableFuture<String> result = sut.someAsyncMethod();
// Then
assertThat(result.isCompletedExceptionally(), is(equalTo(false)));
String value = result.get();
assertThat(value, is(equalTo("got exception")));
}
}
You don´t test the async behaviour but you can test if the logic is correct.
Say suppose, you have
File f = new File("SomeFile");
f.length();
You need not close the File
s, because its just the representation of a path.
You should always consider to close only reader/writers and in fact streams.
You can replace the src/main/resources/
directly by classpath:
So for your example you will replace this line:
new BufferedReader(new FileReader(new File("src/main/resources/config.txt")));
By this line:
new BufferedReader(new FileReader(new File("classpath:config.txt")));
I know this is an old post, but this worked for me:
open -a Terminal "`pwd`"
To run a command as requested below takes some jiggery:
echo /sbin/ping 8.8.8.8 > /tmp/tmp.sh;chmod a+x /tmp/tmp.sh;open -a Terminal /tmp/tmp.sh
WAR stands for Web application ARchive
JAR stands for Java ARchive
your div looks like this:
<div class="readonly_label" id="field-function_purpose">Other</div>
With jquery you can easily get inner content:
Use .html()
: HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
var text = $('#field-function_purpose').html();
Read more about jquery .html()
or
Use .text()
: Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
var text = $('#field-function_purpose').text();
I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C
). Now a program can use SIG_IGN
to ignore all signals or SIG_DFL
to restore the default action.
Now if you do $ command &
then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.
You can use the Test-Path
cmd-let. So something like...
if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
Write-Host "$file doesn't exist in both locations."
}
Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy
It seems that ssh is not installed on your computer.
You can install openssh from here : http://openssh.en.softonic.com/download
Than you will have to geneate your ssh-key. There's a good tutorial about this here:
https://help.github.com/articles/generating-ssh-keys#platform-windows
To deploy, you just have to push your code over git. Something like this:
git push fort master
If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.
The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication
The Request.Form.Keys collection will be empty if none of your html inputs have NAMEs. It's easy to forget to put them there after you've been doing .NET for a while. Just name them and you'll be good to go.
Checking if something is promise unnecessarily complicates the code, just use Promise.resolve
Promise.resolve(valueOrPromiseItDoesntMatter).then(function(value) {
})
This code mouse cursor “jtextfield” “Jcombobox” location focused
try {
Robot robot = new Robot();
int x = Jtextfield.getLocationOnScreen().x;
int y= Jtextfield.getLocationOnScreen().y;
JOptionPane.showMessageDialog(null, x+"x< - y>"+y);// for I location see
robot.mouseMove(x, y);
} catch (AWTException ex) {
ex.printStackTrace();
}
You might be needed to restart
the process if app.get
not
working. Press ctl+c
and then restart node app
.
For a new project select the home directory of the jdk
eg C:\Java\jdk1.7.0_99
or C:\Program Files\Java\jdk1.7.0_99
For an existing project.
1) You need to have a jdk
installed on the system.
for instance in
C:\Java\jdk1.7.0_99
2) go to project structure
under File
menu ctrl+alt+shift+S
3) SDKs
is located under Platform Settings
. Select it.
4) click the green +
up the top of the window.
5) select JDK
(I have to use keyboard to select it do not know why).
select the home directory for your jdk installation.
should be good to go.
Push down the whole button. I suggest this it is looking nice in button.
#button:active {
position: relative;
top: 1px;
}
if you only want to push text increase top-padding and decrease bottom padding. You can also use line-height.
you should return three different values from this method and get these three in a single variable like this.
func getTime()-> (hour:Int,min:Int,sec:Int){
//your code
return (hour,min,sec)
}
get the value in single variable
let getTime = getTime()
now you can access the hour,min and seconds simply by "." ie.
print("hour:\(getTime.hour) min:\(getTime.min) sec:\(getTime.sec)")
Use Linq, it is a very quick and easy way.
string mystring = "0, 10, 20, 30, 100, 200";
var query = from val in mystring.Split(',')
select int.Parse(val);
foreach (int num in query)
{
Console.WriteLine(num);
}
use this one i think this help...
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 0.005f;// set this according to that you want...
}
Excel 2013 can do Count distinct in pivots. If no access to 2013, and it's a smaller amount of data, I make two copies of the raw data, and in copy b, select both columns and remove duplicates. Then make the pivot and count your column b.
Looking at the code always helps too. That is, you can actually take a look at the generated partial class (that calls LoadComponent) by doing the following:
The YourClass.g.cs ... is the code for generated partial class. Again, if you open that up you can see the InitializeComponent method and how it calls LoadComponent ... and much more.
My modern variant:
function blob2file(blobData) {
const fd = new FormData();
fd.set('a', blobData);
return fd.get('a');
}
Throwing exceptions in a constructor is not bad practice. In fact, it is the only reasonable way for a constructor to indicate that there is a problem; e.g. that the parameters are invalid.
I also think that throwing checked exceptions can be OK1, assuming that the checked exception is 1) declared, 2) specific to the problem you are reporting, and 3) it is reasonable to expect the caller to deal with a checked exception for this2.
However explicitly declaring or throwing java.lang.Exception
is almost always bad practice.
You should pick an exception class that matches the exceptional condition that has occurred. If you throw Exception
it is difficult for the caller to separate this exception from any number of other possible declared and undeclared exceptions. This makes error recovery difficult, and if the caller chooses to propagate the Exception, the problem just spreads.
1 - Some people may disagree, but IMO there is no substantive difference between this case and the case of throwing exceptions in methods. The standard checked vs unchecked advice applies equally to both cases.
2 - For example, the existing FileInputStream
constructors will throw FileNotFoundException
if you try to open a file that does not exist. Assuming that it is reasonable for FileNotFoundException
to be a checked exception3, then the constructor is the most appropriate place for that exception to be thrown. If we threw the FileNotFoundException
the first time that (say) a read
or write
call was made, that is liable to make application logic more complicated.
3 - Given that this is one of the motivating examples for checked exceptions, if you don't accept this you are basically saying that all exceptions should be unchecked. That is not practical ... if you are going to use Java.
Someone suggested using assert
for checking arguments. The problem with this is that checking of assert
assertions can be turned on and off via a JVM command-line setting. Using assertions to check internal invariants is OK, but using them to implement argument checking that is specified in your javadoc is not a good idea ... because it means your method will only strictly implement the specification when assertion checking is enabled.
The second problem with assert
is that if an assertion fails, then AssertionError
will be thrown, and received wisdom is that it is a bad idea to attempt to catch Error
and any of its subtypes.
It's an excellent question, I had the same question yesterday. I thought about this problem, specifically SEARCHED if existed something like "ON UPDATE CASCADE" and fortunately the designers of SQL had also thought about that. I agree with Ted.strauss, and I also commented Noran's case.
When did I use it? Like Ted pointed out, when you are treating several databases at one time, and the modification in one of them, in one table, has any kind of reproduction in what Ted calls "satellite database", can't be kept with the very original ID, and for any reason you have to create a new one, in case you can't update the data on the old one (for example due to permissions, or in case you are searching for fastness in a case that is so ephemeral that doesn't deserve the absolute and utter respect for the total rules of normalization, simply because will be a very short-lived utility)
So, I agree in two points:
(A.) Yes, in many times a better design can avoid it; BUT
(B.) In cases of migrations, replicating databases, or solving emergencies, it's a GREAT TOOL that fortunately was there when I went to search if it existed.
The version of JBoss should also be visible in the boot log file. Standard install would have that (for linux) in
/var/log/jboss/boot.log
$ head boot.log
08:30:07,477 INFO [Server] Starting JBoss (MX MicroKernel)...
08:30:07,478 INFO [Server] Release ID: JBoss [Trinity] 4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)
08:30:07,478 DEBUG [Server] Using config: org.jboss.system.server.ServerConfigImpl@4277158a
08:30:07,478 DEBUG [Server] Server type: class org.jboss.system.server.ServerImpl
08:30:07,478 DEBUG [Server] Server loaded through: org.jboss.system.server.NoAnnotationURLClassLoader
08:30:07,478 DEBUG [Server] Boot URLs:
so required info int the above case is
Release ID: JBoss [Trinity] 4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)
I am using Oracle Database and i had same problem. Eventually i found ORACLE DB is converting all the metadata (table/sp/view/trigger) in upper case.
And i was trying how i wrote table name (myTempTable) in sql whereas it expect how it store table name in databsae (MYTEMPTABLE). Also same applicable on column name.
It is quite common problem with developer whoever used sql and now jumped into ORACLE DB.
There's the IOUtils.toString(..)
utility from Apache Commons.
If you're using Guava
there's also Files.readLines(..)
and Files.toString(..)
.
the perfect solution is to Using UICollectionViewDelegateFlowLayout but you can easily so calculate the cell width and divided on the wanted number of columns you want
the tricky is to make the width with no fraction
(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat screenWidth = self.view.frame.size.width;
CGFloat marginWidth = (screenWidth - collectionView.frame.size.width);
CGFloat cellWith = (collectionView.frame.size.width - marginWidth )/3;
cellWith= floorf(cellWith);
CGSize retval = CGSizeMake(cellWith,cellWith);
return retval;}
The inconvenience of typing 10 < x && x < 20
is minimal compared to the increase in language complexity if one would allow 10 < x < 20
, so the designers of the Java language decided against supporting it.
You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button
, but also for other widgets and non-gui objects such as StringVar
.
Quick fix: add the frame new
as the first argument to your Button
in Demo2
.
Possibly better: Currently you have Demo2
inheriting from tk.Frame
but I think this makes more sense if you change Demo2
to be something like this,
class Demo2(tk.Toplevel):
def __init__(self):
tk.Toplevel.__init__(self)
self.title("Demo 2")
self.button = tk.Button(self, text="Button 2", # specified self as master
width=25, command=self.close_window)
self.button.pack()
def close_window(self):
self.destroy()
Just as a suggestion, you should only import tkinter
once. Pick one of your first two import statements.
With Java 11 you won't have to go through this rigmarole anymore!
Instead, you can do this:
> java MyApp.java
You don't have to compile beforehand, as it's all done in one step.
You can get the Java 11 JDK here: JDK 11 GA Release
Add your controllers in your folders:
controllers\
---- folder1
---- folder2
Create your route not specifying the folder:
Route::get('/product/dashboard', 'MakeDashboardController@showDashboard');
Run
composer dump-autoload
And try again
Rand() does generate a uniform distribution of random numbers between 0 and 1, but the norminv (or norm.inv) function is taking the uniform distributed Rand() as an input to generate the normally distributed sample set.
I had the same problem and not any of the above mentioned solutions worked.
Until I updated conda packages:
conda update conda
conda update anaconda
and ... Voila! It all works!
To convert any JSON to array, use the below code:
const usersJson: any[] = Array.of(res.json());
To use the push function of an Array your var needs to be an Array.
Change data{"name":"ananta","age":"15"}
to following:
var data = [
{
"name": "ananta",
"age": "15",
"country": "Atlanta"
}
];
data.push({"name": "Tony Montana", "age": "99"});
data.push({"country": "IN"});
..
The containing Array Items will be typeof Object and you can do following:
var text = "You are " + data[0]->age + " old and come from " + data[0]->country;
Notice: Try to be consistent. In my example, one array contained object properties name
and age
while the other only contains country
. If I iterate this with for
or forEach
then I can't always check for one property, because my example contains Items that changing.
Perfect would be: data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );
So you can iterate and always can get the properties, even if they are empty, null or undefined.
edit
Cool stuff to know:
var array = new Array();
is similar to:
var array = [];
Also:
var object = new Object();
is similar to:
var object = {};
You also can combine them:
var objectArray = [{}, {}, {}];
Please try selecting the password field like this.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement passwordElement = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#Passwd")));
passwordElement.click();
passwordElement.clear();
passwordElement.sendKeys("123");
If you want to try it without the try catch block, can use the following method, Create a intent and set the package of the app which you want to verify
val intent = Intent(Intent.ACTION_VIEW)
intent.data = uri
intent.setPackage("com.example.packageofapp")
and the call the following method to check if the app is installed
fun isInstalled(intent:Intent) :Boolean{
val list = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
return list.isNotEmpty()
}
One other cause may be using lombok.
@Builder
- causes to save Collections.emptyList()
even if you say .myCollection(new ArrayList());
@Singular
- ignores the class level defaults and leaves field null
even if the class field was declared as myCollection = new ArrayList()
My 2 cents, just spent 2 hours with the same :)
function_that_needs_strings(*my_list) # works!
Merge this:
private long previousItemId = 0;
@Override
public long getItemId(int position) {
long nextItemId = random.nextInt(Integer.MAX_VALUE);
while(previousItemId == nextItemId) {
nextItemId = random.nextInt(Integer.MAX_VALUE);
}
previousItemId = nextItemId;
return nextItemId;
}
With this answer:
public class SpinnerInteractionListener
implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
private AdapterView.OnItemSelectedListener onItemSelectedListener;
public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
this.onItemSelectedListener = selectedListener;
}
boolean userSelect = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(userSelect) {
onItemSelectedListener.onItemSelected(parent, view, pos, id);
userSelect = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
if(userSelect) {
onItemSelectedListener.onNothingSelected(parent);
userSelect = false;
}
}
}
In spherical geometry shapes are defined by points, lines and angles between those lines. You have only those rudimentary values to work with.
Therefore a circle (in terms of a a shape projected onto a sphere) is something that must be approximated using points. The more points, the more it'll look like a circle.
Having said that, realize that google maps is projecting the earth onto a flat surface (think "unrolling" the earth and stretching+flattening until it looks "square"). And if you have a flat coordinate system you can draw 2D objects on it all you want.
In other words you can draw a scaled vector circle on a google map. The catch is, google maps doesn't give it to you out of the box (they want to stay as close to GIS values as is pragmatically possible). They only give you GPolygon which they want you to use to approximate a circle. However, this guy did it using vml for IE and svg for other browsers (see "SCALED CIRCLES" section).
Now, going back to your question about Google Latitude using a scaled circle image (and this is probably the most useful to you): if you know the radius of your circle will never change (eg it's always 10 miles around some point), then the easiest solution would be to use a GGroundOverlay, which is just an image url + the GLatLngBounds the image represents. The only work you need to do then is cacluate the GLatLngBounds representing your 10 mile radius. Once you have that, the google maps api handles scaling your image as the user zooms in and out.
echo $bool_val ? 'true' : 'false';
Or if you only want output when it's false:
echo !$bool_val ? 'false' : '';
In my case this was fixed when I set up 'Enable 32 Bit applications'=True for Application pool in IIS server.
$('a[href$="ABC"]')...
Selector documentation can be found at http://docs.jquery.com/Selectors
For attributes:
= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")
Sometimes offsetHeight will return zero because the element you've created has not been rendered in the Dom yet. I wrote this function for such circumstances:
function getHeight(element)
{
var e = element.cloneNode(true);
e.style.visibility = "hidden";
document.body.appendChild(e);
var height = e.offsetHeight + 0;
document.body.removeChild(e);
e.style.visibility = "visible";
return height;
}
Try this regex:
^(\+?\d{1,4}[\s-])?(?!0+\s+,?$)\d{10}\s*,?$
Explanation of the regex using Perl's YAPE is as below:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1 (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\+? '+' (optional (matching the most amount
possible))
----------------------------------------------------------------------
\d{1,4} digits (0-9) (between 1 and 4 times
(matching the most amount possible))
----------------------------------------------------------------------
[\s-] any character of: whitespace (\n, \r,
\t, \f, and " "), '-'
----------------------------------------------------------------------
)? end of \1 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
0+ '0' (1 or more times (matching the most
amount possible))
----------------------------------------------------------------------
\s+ whitespace (\n, \r, \t, \f, and " ") (1
or more times (matching the most amount
possible))
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of
the string
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
\d{10} digits (0-9) (10 times)
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
These are questions which, in my opionion, requires different knowledge from different domains.
That said, maybe you want to read some books, personally I've used this book in my datbase university course (and found a decent one, but I've not read other books in this field, so my advice is to check out for some good books in database design).
I would like to give you also the idea to disable an <option>
with a given defined value (not innerhtml
). I recommend to it with jQuery
to get the simplest way. See my sample below.
HTML
Status:
<div id="option">
<select class="status">
<option value="hand" selected>Hand</option>
<option value="simple">Typed</option>
<option value="printed">Printed</option>
</select>
</div>
Javascript
The idea here is how to disable Printed
option when current Status
is Hand
var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;
You may see how it works here:
JFrame.setVisible(true);
You can either use setVisible(false)
or dispose()
method to disappear current form.
Perhaps you don't have a recent enough version of Greasemonkey. It was version 0.8 that added @require
.
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
If you don't have 0.8, then use the technique Joan Piedra describes for manually adding a script
element to the page.
Between version 0.8 and 0.9, @require
is only processed when the script is first installed. If you change the list of required scripts, you need to uninstall your script and reinstall it; Greasemonkey downloads the required script once at installation and uses a cached copy thereafter.
As of 0.9, Greasemonkey behavior has changed (to address a tangentially related issue) so that it now loads the required scripts after every edit; reinstalling the script is no longer necessary.
To resolve all conflicts with the version in a particular branch:
git diff --name-only --diff-filter=U | xargs git checkout ${branchName}
So, if you are already in the merging state, and you want to keep the master version of the conflicting files:
git diff --name-only --diff-filter=U | xargs git checkout master
You can do the same for method parameters as well:
Method method = someClass.getDeclaredMethod("someMethod");
Type[] types = method.getGenericParameterTypes();
//Now assuming that the first parameter to the method is of type List<Integer>
ParameterizedType pType = (ParameterizedType) types[0];
Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[0];
System.out.println(clazz); //prints out java.lang.Integer
Surprised that nobody mentioned that zoom: 1;
is useful for IE6-7, to solve most IE-only bugs by triggering hasLayout.
I have now tried your suggestions and found that it kinda works,
Se my "new" script below:
$('a.cancel').click(function() {
var a = this;
$("#dialog").dialog({
autoOpen: false,
buttons: {
"Ja": function() {
$.post(a.href);
},
"Nej": function() { $(this).dialog("close"); }
},
modal: true,
overlay: {
opacity: 0.5,
background: "black"
}
});
$("#dialog").dialog('open');
return false;
});
});
Any clues?
oh and my Action link now looks like this:
<%= Html.ActionLink("Cancel", "Cancel", new { id = v.BookingId }, new { @class = "cancel" })%>
It's part of C99 and defined in POSIX definition stdbool.h.
You can also have a look at the method findText(const QString & text) from QComboBox; it returns the index of the element which contains the given text, (-1 if not found). The advantage of using this method is that you don't need to set the second parameter when you add an item.
Here is a little example :
/* Create the comboBox */
QComboBox *_comboBox = new QComboBox;
/* Create the ComboBox elements list (here we use QString) */
QList<QString> stringsList;
stringsList.append("Text1");
stringsList.append("Text3");
stringsList.append("Text4");
stringsList.append("Text2");
stringsList.append("Text5");
/* Populate the comboBox */
_comboBox->addItems(stringsList);
/* Create the label */
QLabel *label = new QLabel;
/* Search for "Text2" text */
int index = _comboBox->findText("Text2");
if( index == -1 )
label->setText("Text2 not found !");
else
label->setText(QString("Text2's index is ")
.append(QString::number(_comboBox->findText("Text2"))));
/* setup layout */
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(_comboBox);
layout->addWidget(label);
This was already in a comment, but deserves its own answer: Without editing the config files: in mysql, as root, do
SET global general_log_file='/tmp/mysql.log';
SET global log_output = 'file';
SET global general_log = on;
Don't forget to turn it off afterwards:
SET global general_log = off;
These do the same thing:
window.location.assign(url);
window.location = url;
window.location.href = url;
They simply navigate to the new URL. The replace
method on the other hand navigates to the URL without adding a new record to the history.
So, what you have read in those many forums is not correct. The assign
method does add a new record to the history.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location
function createOfferUrlArray($Offer) {
$offerArray = array();
foreach ($Offer as $key => $value) {
$offerArray[$key] = $value[4];
}
return $offerArray;
}
or
function createOfferUrlArray($offer) {
foreach ( $offer as &$value ) {
$value = $value[4];
}
unset($value);
return $offer;
}
How about writing some color-based class in a global sass file, thus we don't need to care where variables are. Just like the following:
// base.scss
@import "./_variables.scss";
.background-color{
background: $bg-color;
}
and then, we can use the background-color
class in any file.
My point is that I don't need to import variable.scss
in any file, just use it.
Have a look at the Requests exception docs. In short:
In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a
ConnectionError
exception.In the event of the rare invalid HTTP response, Requests will raise an
HTTPError
exception.If a request times out, a
Timeout
exception is raised.If a request exceeds the configured number of maximum redirections, a
TooManyRedirects
exception is raised.All exceptions that Requests explicitly raises inherit from
requests.exceptions.RequestException
.
To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.
What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit
).
You can either catch the base-class exception, which will handle all cases:
try:
r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e: # This is the correct syntax
raise SystemExit(e)
Or you can catch them separately and do different things.
try:
r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
# Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
# Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
raise SystemExit(e)
As Christian pointed out:
If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call
Response.raise_for_status
. That will raise anHTTPError
, if the response was an http error.
An example:
try:
r = requests.get('http://www.google.com/nothere')
r.raise_for_status()
except requests.exceptions.HTTPError as err:
raise SystemExit(err)
Will print:
404 Client Error: Not Found for url: http://www.google.com/nothere
You're misinterpreting what the onchange event does when applied to a textarea. It won't fire until it loses focus or you hit enter. Why not fire the function from an onchange on the select that fills in the text area?
Check out here for more on the onchange event: w3schools
E.g : "abcd: efg: 1006746" "bhddy: nshhf36: 1006754" "hfquv: nd: 5894254"
-Step 1: String firstString = "abcd: efg: 1006746";
-Step 2: String lastSevenNumber = firstString.substring(firstString.lastIndexOf(':'), firstString.length()).trim();
You could try to use anchorScroll.
So the controller would be:
app.controller('MainCtrl', function($scope, $location, $anchorScroll, $routeParams) {
$scope.scrollTo = function(id) {
$location.hash(id);
$anchorScroll();
}
});
And the view:
<a href="" ng-click="scrollTo('foo')">Scroll to #foo</a>
...and no secret for the anchor id:
<div id="foo">
This is #foo
</div>
i have never done this, but it would be done like this:
var script = $('#google').attr("onclick")
Try this:
$(document).ready(function() {
// When the document is ready
// Do something
});
To avoid that issue, when incrementing time you should convert back to UTC and then add or subtract.
This way you will be able to walk through any periods where hours or minutes happen twice.
If you converted to UTC, add each second, and convert to local time for display. You would go through 11:54:08 p.m. LMT - 11:59:59 p.m. LMT and then 11:54:08 p.m. CST - 11:59:59 p.m. CST.
Try this, working fine -
$array = json_decode(json_encode($array), true);
Yes you can use SQL Server 2008 itself but you need to install SQL Server Management Studio Express (if not installed ) . Just right Click on Database Diagrams and create new diagram. Select the exisiting tables and if you have specified the references in your tables properly. You will be able to see the complete diagram of selected tables. For further reference see Getting started with SQL Server database diagrams
Use the below:
var regEx = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regEx);
The error is from this:
def playSound(myList):
for i in range(myList): # <= myList is a list, not an integer
You cannot pass a list to range
which expects an integer. Most likely, you meant to do:
def playSound(myList):
for list_item in myList:
OR
def playSound(myList):
for i in range(len(myList)):
OR
def playSound(myList):
for i, list_item in enumerate(myList):
The default configuration of most SMTP servers is not to relay from an untrusted source to outside domains. For example, imagine that you contact the SMTP server for foo.com and ask it to send a message to [email protected]. Because the SMTP server doesn't really know who you are, it will refuse to relay the message. If the server did do that for you, it would be considered an open relay, which is how spammers often do their thing.
If you contact the foo.com mail server and ask it to send mail to [email protected], it might let you do it. It depends on if they trust that you're who you say you are. Often, the server will try to do a reverse DNS lookup, and refuse to send mail if the IP you're sending from doesn't match the IP address of the MX record in DNS. So if you say that you're the bar.com mail server but your IP address doesn't match the MX record for bar.com, then it will refuse to deliver the message.
You'll need to talk to the administrator of that SMTP server to get the authentication information so that it will allow relay for you. You'll need to present those credentials when you contact the SMTP server. Usually it's either a user name/password, or it can use Windows permissions. Depends on the server and how it's configured.
See Unable to send emails to external domain using SMTP for an example of how to send the credentials.
Comparing non-primitives (aka Objects) in Java with ==
compares their reference instead of their values. Long
is a class and thus Long
values are Objects.
The problem is that the Java Developers wanted people to use Long
like they used long
to provide compatibility, which led to the concept of autoboxing, which is essentially the feature, that long
-values will be changed to Long
-Objects and vice versa as needed. The behaviour of autoboxing is not exactly predictable all the time though, as it is not completely specified.
So to be safe and to have predictable results always use .equals()
to compare objects and do not rely on autoboxing in this case:
Long num1 = 127, num2 = 127;
if(num1.equals(num2)) { iWillBeExecutedAlways(); }