Well the following worked for me...
workspace
)bin
folderA great way of handling this is with regular expressions.
string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");
This will replace any of the 3 legal types of newline with the html tag.
I'm sticking with DbVisualizer Free until something better comes along.
EDIT/UPDATE: been using https://dbeaver.io/ lately, really enjoying this
Based on Haim's answer I created a PHP code to test and display all the differences between two databases. This will also display if a table is present in source or test databases. You have to change with your details the <> variables content.
<?php
$User = "<DatabaseUser>";
$Pass = "<DatabasePassword>";
$SourceDB = "<SourceDatabase>";
$TestDB = "<DatabaseToTest>";
$link = new mysqli( "p:". "localhost", $User, $Pass, "" );
if ( mysqli_connect_error() ) {
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
mysqli_set_charset( $link, "utf8" );
mb_language( "uni" );
mb_internal_encoding( "UTF-8" );
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $SourceDB .'";';
$SourceDB_Content = query( $link, $sQuery );
if ( !is_array( $SourceDB_Content) ) {
echo "Table $SourceDB cannot be accessed";
exit(0);
}
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $TestDB .'";';
$TestDB_Content = query( $link, $sQuery );
if ( !is_array( $TestDB_Content) ) {
echo "Table $TestDB cannot be accessed";
exit(0);
}
$SourceDB_Tables = array();
foreach( $SourceDB_Content as $item ) {
$SourceDB_Tables[] = $item["TABLE_NAME"];
}
$TestDB_Tables = array();
foreach( $TestDB_Content as $item ) {
$TestDB_Tables[] = $item["TABLE_NAME"];
}
//var_dump( $SourceDB_Tables, $TestDB_Tables );
$LookupTables = array_merge( $SourceDB_Tables, $TestDB_Tables );
$NoOfDiscrepancies = 0;
echo "
<table border='1' width='100%'>
<tr>
<td>Table</td>
<td>Found in $SourceDB (". count( $SourceDB_Tables ) .")</td>
<td>Found in $TestDB (". count( $TestDB_Tables ) .")</td>
<td>Test result</td>
<tr>
";
foreach( $LookupTables as $table ) {
$FoundInSourceDB = in_array( $table, $SourceDB_Tables ) ? 1 : 0;
$FoundInTestDB = in_array( $table, $TestDB_Tables ) ? 1 : 0;
echo "
<tr>
<td>$table</td>
<td><input type='checkbox' ". ($FoundInSourceDB == 1 ? "checked" : "") ."></td>
<td><input type='checkbox' ". ($FoundInTestDB == 1 ? "checked" : "") ."></td>
<td>". compareTables( $SourceDB, $TestDB, $table ) ."</td>
</tr>
";
}
echo "
</table>
<br><br>
No of discrepancies found: $NoOfDiscrepancies
";
function query( $link, $q ) {
$result = mysqli_query( $link, $q );
$errors = mysqli_error($link);
if ( $errors > "" ) {
echo $errors;
exit(0);
}
if( $result == false ) return false;
else if ( $result === true ) return true;
else {
$rset = array();
while ( $row = mysqli_fetch_assoc( $result ) ) {
$rset[] = $row;
}
return $rset;
}
}
function compareTables( $source, $test, $table ) {
global $link;
global $NoOfDiscrepancies;
$sQuery = "
SELECT column_name,ordinal_position,data_type,column_type FROM
(
SELECT
column_name,ordinal_position,
data_type,column_type,COUNT(1) rowcount
FROM information_schema.columns
WHERE
(
(table_schema='$source' AND table_name='$table') OR
(table_schema='$test' AND table_name='$table')
)
AND table_name IN ('$table')
GROUP BY
column_name,ordinal_position,
data_type,column_type
HAVING COUNT(1)=1
) A;
";
$result = query( $link, $sQuery );
$data = "";
if( is_array( $result ) && count( $result ) > 0 ) {
$NoOfDiscrepancies++;
$data = "<table><tr><td>column_name</td><td>ordinal_position</td><td>data_type</td><td>column_type</td></tr>";
foreach( $result as $item ) {
$data .= "<tr><td>". $item["column_name"] ."</td><td>". $item["ordinal_position"] ."</td><td>". $item["data_type"] ."</td><td>". $item["column_type"] ."</td></tr>";
}
$data .= "</table>";
return $data;
}
else {
return "Checked but no discrepancies found!";
}
}
?>
When a function call is invoked by a Java application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method.
The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM).
The most common case that can possibly exhaust a Java application’s stack is recursion.
Please Have a look
In R the equivalent function is seq
and you can use it with the option by
:
seq(from = 5, to = 100, by = 5)
# [1] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
In addition to by
you can also have other options such as length.out
and along.with
.
length.out: If you want to get a total of 10 numbers between 0 and 1, for example:
seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1
along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).
seq(along.with=c(10,20,30))
# [1] 1 2 3
Although, instead of using the along.with
option, it is recommended to use seq_along
in this case. From the documentation for ?seq
seq
is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to useseq_along
in that case.
seq_along: Instead of seq(along.with(.))
seq_along(c(10,20,30))
# [1] 1 2 3
Hope this helps.
In a nutshell, sys.argv
is a list of the words that appear in the command used to run the program. The first word (first element of the list) is the name of the program, and the rest of the elements of the list are any arguments provided. In most computer languages (including Python), lists are indexed from zero, meaning that the first element in the list (in this case, the program name) is sys.argv[0]
, and the second element (first argument, if there is one) is sys.argv[1]
, etc.
The test len(sys.argv) >= 2
simply checks wither the list has a length greater than or equal to 2, which will be the case if there was at least one argument provided to the program.
Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:
echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"
you could use an onchange event to trigger a validation and then you can display a toast if this is enough for you
You can reset your branch to the state it was in just before the merge if you find the commit it was on then.
One way is to use git reflog
, it will list all the HEADs you've had.
I find that git reflog --relative-date
is very useful as it shows how long ago each change happened.
Once you find that commit just do a git reset --hard <commit id>
and your branch will be as it was before.
If you have SourceTree, you can look up the <commit id>
there if git reflog
is too overwhelming.
I had the same issue, unable to resize the image when adjusting browser dimensions.
Bad Code:
html {
background-color: white;
background-image: url("example.png");
background-repeat: no-repeat;
background-attachment: scroll;
background-position: 0% 0%;
}
Good Code:
html {
background-color: white;
background-image: url("example.png");
background-repeat: no-repeat;
background-attachment: scroll;
background-position: 0% 0%;
background-size: contain;
}
The key here is the addition of this element -> background-size: contain;
Here is a solution that worked for me.
function calduedate(ndays){
var newdt = new Date(); var chrday; var chrmnth;
newdt.setDate(newdt.getDate() + parseInt(ndays));
var newdate = newdt.getFullYear();
if(newdt.getMonth() < 10){
newdate = newdate+'-'+'0'+newdt.getMonth();
}else{
newdate = newdate+'-'+newdt.getMonth();
}
if(newdt.getDate() < 10){
newdate = newdate+'-'+'0'+newdt.getDate();
}else{
newdate = newdate+'-'+newdt.getDate();
}
alert("newdate="+newdate);
}
Wow so many complicated/confusing answers here.
This is as of v3.4.
1) Start MongoDB without access control.
mongod --dbpath /data/db
2) Connect to the instance.
mongo
3) Create the user.
use some_db
db.createUser(
{
user: "myNormalUser",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "some_db" },
{ role: "read", db: "some_other_db" } ]
}
)
4) Stop the MongoDB instance and start it again with access control.
mongod --auth --dbpath /data/db
5) Connect and authenticate as the user.
use some_db
db.auth("myNormalUser", "xyz123")
db.foo.insert({x:1})
use some_other_db
db.foo.find({})
It's really simple. I'll dumb the following down https://docs.mongodb.com/manual/tutorial/enable-authentication/
If you want to learn more about what the roles actually do read more here: https://docs.mongodb.com/manual/reference/built-in-roles/
1) Start MongoDB without access control.
mongod --dbpath /data/db
2) Connect to the instance.
mongo
3) Create the user administrator. The following creates a user administrator in the admin
authentication database. The user is a dbOwner
over the some_db
database and NOT over the admin
database, this is important to remember.
use admin
db.createUser(
{
user: "myDbOwner",
pwd: "abc123",
roles: [ { role: "dbOwner", db: "some_db" } ]
}
)
Or if you want to create an admin which is admin over any database:
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
4) Stop the MongoDB instance and start it again with access control.
mongod --auth --dbpath /data/db
5) Connect and authenticate as the user administrator towards the admin
authentication database, NOT towards the some_db
authentication database. The user administrator was created in the admin
authentication database, the user does not exist in the some_db
authentication database.
use admin
db.auth("myDbOwner", "abc123")
You are now authenticated as a dbOwner
over the some_db
database. So now if you wish to read/write/do stuff directly towards the some_db
database you can change to it.
use some_db
//...do stuff like db.foo.insert({x:1})
// remember that the user administrator had dbOwner rights so the user may write/read, if you create a user with userAdmin they will not be able to read/write for example.
More on roles: https://docs.mongodb.com/manual/reference/built-in-roles/
If you wish to make additional users which aren't user administrators and which are just normal users continue reading below.
6) Create a normal user. This user will be created in the some_db
authentication database down below.
use some_db
db.createUser(
{
user: "myNormalUser",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "some_db" },
{ role: "read", db: "some_other_db" } ]
}
)
7) Exit the mongo shell, re-connect, authenticate as the user.
use some_db
db.auth("myNormalUser", "xyz123")
db.foo.insert({x:1})
use some_other_db
db.foo.find({})
Comparaison of the different methods:
> CGI::escapeHTML("quote ' double quotes \"")
=> "quote ' double quotes ""
> Rack::Utils.escape_html("quote ' double quotes \"")
=> "quote ' double quotes ""
> ERB::Util.html_escape("quote ' double quotes \"")
=> "quote ' double quotes ""
I wrote my own to be compatible with Rails ActiveMailer escaping:
def escape_html(str)
CGI.escapeHTML(str).gsub("'", "'")
end
Here's a code snippet to split a string by n characters separated over lines:
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let str = String(charsPerLine: 5, "Hello World!")
print(str) // "Hello\n Worl\nd!\n"
}
}
extension String {
init(charsPerLine:Int, _ str:String){
self = ""
var idx = 0
for char in str {
self += "\(char)"
idx = idx + 1
if idx == charsPerLine {
self += "\n"
idx = 0
}
}
}
}
If you want to Use SmartCSV
all_data = SmarterCSV.process(
params[:file].tempfile,
{
:col_sep => "\t",
:row_sep => "\n"
}
)
This represents tab delimited data in each row "\t"
with rows separated by new lines "\n"
if you want the original style of your Ui to remain and the title bar to be removed with no effect on that, you have to remove the title bar in your activity rather than the manifest. leave the original theme style that you had in the manifest and in each activity that you want no title bar use this.requestWindowFeature(Window.FEATURE_NO_TITLE);
in the oncreate()
method before setcontentview()
like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_signup);
...
}
What is that BasePagerAdapter
? You should use one of the standard pager adapters -- either FragmentPagerAdapter
or FragmentStatePagerAdapter
, depending on whether you want Fragments that are no longer needed by the ViewPager
to either be kept around (the former) or have their state saved (the latter) and re-created if needed again.
Sample code for using ViewPager
can be found here
It is true that the management of fragments in a view pager across activity instances is a little complicated, because the FragmentManager
in the framework takes care of saving the state and restoring any active fragments that the pager has made. All this really means is that the adapter when initializing needs to make sure it re-connects with whatever restored fragments there are. You can look at the code for FragmentPagerAdapter
or FragmentStatePagerAdapter
to see how this is done.
You're missing a GROUP BY clause:
SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.
try this code to format as used in Brazil:
DecimalFormat df = new DecimalFormat(
"#,##0.00",
new DecimalFormatSymbols(new Locale("pt", "BR")));
BigDecimal value = new BigDecimal(123456.00);
System.out.println(df.format(value.floatValue()));
// results: "123.456,00"
One thing to watch out for though, particularly if you are using a framework, is to check if the application is regenerating session ids between requests - anything that depends explicitly on the session id will run into problems, although obviously the rest of the data in the session will unaffected.
If the application is regenerating session ids like this then you can end up with a situation where an ajax request in effect invalidates / replaces the session id in the requesting page.
Get the path of running Apache
$ ps -ef | grep apache
apache 12846 14590 0 Oct20 ? 00:00:00 /usr/sbin/apache2
Append -V
argument to the path
$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"
Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location
Try this , old school way ;)
public static void openit(string x)
{
System.Diagnostics.Process.Start("cmd", "/C start" + " " + x);
}
using : openit("www.google.com");
You can manually upload the artifact's by clicking on upload artifacts button in the Nexus server and provide the necessary GAV properties for uploading(it's generally the file structure for storing the artifact)
I am using Rails REE (2.3.4) for a legacy system we have. After upgrading to El Capitan, running script/console enerated an error and my app would no longer start (using pow):
$ script/console
Loading development environment (Rails 2.3.4)
/blah-blah/gems/activerecord-2.3.4/lib/active_record/connection_adapters/abstract/connection_specification.rb:76:in establish_connection:RuntimeError: Please install the mysql2 adapter: gem install activerecord-mysql2-adapter (dlopen(/blah-blah/gems/mysql2-0.2.19b4/lib/mysql2/mysql2.bundle, 9): Library not loaded: libmysqlclient.18.dylib
Referenced from: /blah-blah/gems/mysql2-0.2.19b4/lib/mysql2/mysql2.bundle
Reason: image not found - /blah-blah/gems/mysql2-0.2.19b4/lib/mysql2/mysql2.bundle)
From this very thread, above, I determined that I needed to issue this command in terminal:sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
This command produced an error: "ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted". I have never seen that error before.
After quite a bit of digging, I found this article: http://www.macworld.com/article/2986118/security/how-to-modify-system-integrity-protection-in-el-capitan.html and followed the instructions to turn SIP (El Capitan's new System Integrity Protection) off. After turning SIP off, and after rebooting, the ln command worked fine. Then I turned SIP off. Now all is fine. My app runs again using pow and no error running script/console. I hope this helps you.
From the oracle documentation, the below query explains it better
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
You can read this link
Your query would be as follows
//just the concept
INSERT INTO quotedb
(COLUMN_NAMES) //seperated by comma
SELECT COLUMN_NAMES FROM tickerdb,quotedb WHERE quotedb.ticker = tickerdb.ticker
Note: Make sure the columns in insert and select are in right position as per your requirement
Hope this helps!
Total Commander also has a binary compare option:
go to: File \\Compare by content
ps. I guess some people may alredy be using this tool and may not be aware of the built-in feature.
Try to replace the
padding: 2px 30px 2px 2px;
with
padding: 2px 2px 2px 2px;
It should work.
Plain JavaScript escaping example:
function escapeHtml(text) {
var div = document.createElement('div');
div.innerText = text;
return div.innerHTML;
}
escapeHtml("<script>alert('hi!');</script>")
// "<script>alert('hi!');</script>"
Not exactly sure this is what you are asking but you can do something like:
new Thread() {
public void run() {
System.out.println("blah");
}
}.start();
Notice the start()
method at the end of the anonymous class. You create the thread object but you need to start it to actually get another running thread.
Better than creating an anonymous Thread
class is to create an anonymous Runnable
class:
new Thread(new Runnable() {
public void run() {
System.out.println("blah");
}
}).start();
Instead overriding the run()
method in the Thread
you inject a target Runnable
to be run by the new thread. This is a better pattern.
Not every jar file is executable.
Now, you need to import the classes, which are there under the jar, in your java file. For example,
import org.xml.sax.SAXException;
If you are working on an IDE, then you should refer its documentation. Or at least specify which one you are using here in this thread. It would definitely enable us to help you further.
And if you are not using any IDE, then please look at javac -cp option. However, it's much better idea to package your program in a jar
file, and include all the required jar
s within that. Then, in order to execute your jar
, like,
java -jar my_program.jar
you should have a META-INF/MANIFEST.MF
file in your jar
. See here, for how-to.
If the data set contains many rows it might be more efficient to join with a lookup table using data.table
instead of nested ifelse()
.
Provided the lookup table below
lookup
idnat idbp idnat2 1: french mainland mainland 2: french colony overseas 3: french overseas overseas 4: foreign foreign foreign
and a sample data set
library(data.table)
n_row <- 10L
set.seed(1L)
DT <- data.table(idnat = "french",
idbp = sample(c("mainland", "colony", "overseas", "foreign"), n_row, replace = TRUE))
DT[idbp == "foreign", idnat := "foreign"][]
idnat idbp 1: french colony 2: french colony 3: french overseas 4: foreign foreign 5: french mainland 6: foreign foreign 7: foreign foreign 8: french overseas 9: french overseas 10: french mainland
then we can do an update while joining:
DT[lookup, on = .(idnat, idbp), idnat2 := i.idnat2][]
idnat idbp idnat2 1: french colony overseas 2: french colony overseas 3: french overseas overseas 4: foreign foreign foreign 5: french mainland mainland 6: foreign foreign foreign 7: foreign foreign foreign 8: french overseas overseas 9: french overseas overseas 10: french mainland mainland
select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual
As the name suggests, Layout weight specifies what amount or percentage of space a particular field or widget should occupy the screen space.
If we specify weight in horizontal orientation, then we must specify layout_width = 0px
.
Similarly, If we specify weight in vertical orientation, then we must specify layout_height = 0px
.
make sure you have same / higher API level installed on SDK packages with your devices.
example :
I have Android 2.3.4 on my Xperia Play. ADB wouldn't detect my device if theres only API 10 (Android 2.3.3) installed on my Mac. When i installed SDK 11 (Android 3.0) -- since I didn't found any SDK package for 2.3.4, the ADB working fine.
hope this help you.
If the XML module is not installed, install it.
Current version 5.6 on ubuntu 14.04:
sudo apt-get install php5.6-xml
And don't forget to run sudo service apache2 restart command after it
Zulhilmi Zainudi
My project should use the 'latest' for the submodule. On Mac OSX 10.11, git version 2.7.1, I did not need to go 'into' my submodule folder in order to collect its commits. I merely did a regular
git pull --rebase
at the top level, and it correctly updated my submodule.
To start the port correctly in your desired port use:
npm start -- --port 8000
From the command run:
sudo docker build -t myrepo/redis
there are no "arguments" passed to the docker build
command, only a single flag -t
and a value for that flag. After docker parses all of the flags for the command, there should be one argument left when you're running a build.
That argument is the build context. The standard command includes a trailing dot for the context:
sudo docker build -t myrepo/redis .
Every docker build sends a directory to the build server. Docker is a client/server application, and the build runs on the server which isn't necessarily where the docker command is run. Docker uses the build context as the source for files used in COPY
and ADD
steps. When you are in the current directory to run the build, you would pass a .
for the context, aka the current directory. You could pass a completely different directory, even a git repo, and docker will perform the build using that as the context, e.g.:
docker build -t sudobmitch/base:alpine --target alpine-base \
'https://github.com/sudo-bmitch/docker-base.git#main'
For more details on these options to the build command, see the docker build documentation.
If you are including the value for the build context (typically the .
) and still see this error message, you have likely passed more than one argument. Typically this is from failing to parse a flag, or passing a string with spaces without quotes. Possible causes for docker to see more than one argument include:
Missing quotes around a path or argument with spaces (take note using variables that may have spaces in them)
Incorrect dashes in the command: make sure to type these manually rather than copy and pasting
Incorrect quotes: smart quotes don't work on the command line, type them manually rather than copy and pasting.
Whitespace that isn't white space, or that doesn't appear to be a space.
Most all of these come from either a typo or copy and pasting from a source that modified the text to look pretty, breaking it for using as a command.
The easiest way I have to debug this, run the command without any other flags:
docker build .
Once that works, add flags back in until you get the error, and then you'll know what flag is broken and needs the quotes to be fixed/added or dashes corrected, etc.
jQuery's .show() and .hide() functions are probably your best bet.
There's also the QueryString module's parse()
method:
var http = require('http'),
queryString = require('querystring');
http.createServer(function (oRequest, oResponse) {
var oQueryParams;
// get query params as object
if (oRequest.url.indexOf('?') >= 0) {
oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));
// do stuff
console.log(oQueryParams);
}
oResponse.writeHead(200, {'Content-Type': 'text/plain'});
oResponse.end('Hello world.');
}).listen(1337, '127.0.0.1');
You could build a Column/Row with Flexible or Expanded children that have flex values that add up to the percentages you want.
You may also find the AspectRatio widget useful.
Always encode from unicode to bytes.
In this direction, you get to choose the encoding.
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print _
??
The other way is to decode from bytes to unicode.
In this direction, you have to know what the encoding is.
>>> bytes = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print bytes
??
>>> bytes.decode('utf-8')
u'\u4f60\u597d'
>>> print _
??
This point can't be stressed enough. If you want to avoid playing unicode "whack-a-mole", it's important to understand what's happening at the data level. Here it is explained another way:
decode
on it.encode
on it.Now, on seeing .encode
on a byte string, Python 2 first tries to implicitly convert it to text (a unicode
object). Similarly, on seeing .decode
on a unicode string, Python 2 implicitly tries to convert it to bytes (a str
object).
These implicit conversions are why you can get Unicode
Decode
Error
when you've called encode
. It's because encoding usually accepts a parameter of type unicode
; when receiving a str
parameter, there's an implicit decoding into an object of type unicode
before re-encoding it with another encoding. This conversion chooses a default 'ascii' decoder†, giving you the decoding error inside an encoder.
In fact, in Python 3 the methods str.decode
and bytes.encode
don't even exist. Their removal was a [controversial] attempt to avoid this common confusion.
† ...or whatever coding sys.getdefaultencoding()
mentions; usually this is 'ascii'
The problem described here was solved by me quite a long time ago but I don't really remember what was the main reason that uploads weren't working. There were multiple things that needed fixing so the upload could work. I have created checklist that might help others having similar problems and I will edit it to make it as helpful as possible. As I said before on chat, I was working on embedded system, so some points may be skipped on non-embedded systems.
Check upload_tmp_dir
in php.ini. This is directory where PHP stores temporary files while uploading.
Check open_basedir
in php.ini. If defined it limits PHP read/write rights to specified path and its subdirectories. Ensure that upload_tmp_dir
is inside this path.
Check post_max_size
in php.ini. If you want to upload 20 Mbyte files, try something a little bigger, like post_max_size = 21M
. This defines largest size of POST message which you are probably using during upload.
Check upload_max_filesize
in php.ini. This specifies biggest file that can be uploaded.
Check memory_limit
in php.ini. That's the maximum amount of memory a script may consume. It's quite obvious that it can't be lower than upload size (to be honest I'm not quite sure about it-PHP is probably buffering while copying temporary files).
Ensure that you're checking the right php.ini file that is one used by PHP on your webserver. The best solution is to execute script with directive described here http://php.net/manual/en/function.php-ini-loaded-file.php (php_ini_loaded_file
function)
Check what user php runs as (See here how to do it: How to check what user php is running as? ). I have worked on different distros and servers. Sometimes it is apache
, but sometimes it can be root
. Anyway, check that this user has rights for reading and writing in the temporary directory and directory that you're uploading into. Check all directories in the path in case you're uploading into subdirectory (for example /dir1/dir2/
-check both dir1
and dir2
.
On embedded platforms you sometimes need to restrict writing to root filesystem because it is stored on flash card and this helps to extend life of this card. If you are using scripts to enable/disable file writes, ensure that you enable writing before uploading.
I had serious problems with PHP >5.4 upload monitoring based on sessions (as described here http://phpmaster.com/tracking-upload-progress-with-php-and-javascript/ ) on some platforms. Try something simple at first (like here: http://www.dzone.com/snippets/very-simple-php-file-upload ). If it works, you can try more sophisticated mechanisms.
If you make any changes in php.ini remember to restart server so the configuration will be reloaded.
Take a look at google ndk group it looks promising, first version of the NDK will be available in 1H2009.
Update: And it is released http://android-developers.blogspot.com/2009/06/introducing-android-15-ndk-release-1.html
You need to read and write document.cookie
if (document.cookie.indexOf("visited=") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
Most browsers will pick up favicon.ico
from the root directory of the site without needing to be told; but they don't always update it with a new one right away.
However, I usually go for the second of your examples:
<link rel='shortcut icon' type='image/x-icon' href='/favicon.ico' />
C:/blah/blah/foldercontainJava
javac javafile.java
You can append the text to $0
in awk if it matches the condition:
awk '/^all:/ {$0=$0" anotherthing"} 1' file
/patt/ {...}
if the line matches the pattern given by patt
, then perform the actions described within {}
./^all:/ {$0=$0" anotherthing"}
if the line starts (represented by ^
) with all:
, then append anotherthing
to the line.1
as a true condition, triggers the default action of awk
: print the current line (print $0
). This will happen always, so it will either print the original line or the modified one.For your given input it returns:
somestuff...
all: thing otherthing anotherthing
some other stuff
Note you could also provide the text to append in a variable:
$ awk -v mytext=" EXTRA TEXT" '/^all:/ {$0=$0mytext} 1' file
somestuff...
all: thing otherthing EXTRA TEXT
some other stuff
I like to do this witch i think is cleaner :
1 - Add the model to namespace:
use App\Employee;
2 - then you can do :
$employees = Employee::get();
or maybe somthing like this:
$employee = Employee::where('name', 'John')->first();
If you are using jQuery, following code will work for you.
$('input[name=radioName]:checked').val();
Using pathlib and preserving full path:
from pathlib import Path
p = Path('/User/my/path')
new_p = Path(p.parent.as_posix() + '/' + p.stem + '.aln')
The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA
) values. Here's an example:
> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
In your example this means that in your line plot(costs,pseudor2,type="l")
, costs
is completely NA
. You have to figure out why this is, but that's the explanation of your error.
From comments:
Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.
stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x)
)
Just for the record, here is the difference between If and IIf:
IIf(condition, true-part, false-part):
If(condition, true-part, false-part):
It works for me:
=SUMPRODUCT(NOT(ISBLANK(F2:F)))
Count of all non-empty cells from F2 to the end of the column
Just
android:buttonTint="@color/primary"
push is an Array method, for json object you may need to define it
this should do it:
library[title] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};
To supplement Muhamed Riyas M's top voted answer:
Faster rotation
android:toDegrees="1080"
Thinner ring
android:thicknessRatio="16"
Light white
android:endColor="#80ffffff"
I was having a similar issue with my button. I included line-height: 0;
and it appears to have worked. Also mentioned by @anddero.
button[type=submit] {
background-color: #4056A1;
border-radius: 12px;
border: 1px solid #4056A1;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 2px 1px;
cursor: pointer;
display: inline-block;
font-size: 16px;
height: 20px;
line-height: 0;
}
use std::map< std::string, std::map<std::string, std::string> >::const_iterator
when map is const.
Load data into a table in MySQL and specify columns:
LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE t1
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
(@col1,@col2,@col3,@col4) set name=@col4,id=@col2 ;
@col1,2,3,4 are variables to hold the csv file columns (assume 4 ) name,id are table columns.
It was giving 415 Http response Code as error,
So I added
httppost.addHeader("Content-Type", "text/xml; charset=utf-8");
Everything alright now, Http: 200
Like this
sleep(no_of_seconds)
Or you may pass other possible arguments like:
sleep(5.seconds)
sleep(5.minutes)
sleep(5.hours)
sleep(5.days)
About the window.location.hash
property:
Return the anchor part of a URL.
//Assume that the current URL is
var URL = "http://www.example.com/test.htm#part2";
var x = window.location.hash;
//The result of x will be:
x = "#part2"
Exmaple 2:
$(function(){
setTimeout(function(){
var id = document.location.hash;
$(id).click().blur();
}, 200);
})
Example 3:
var hash = "#search" || window.location.hash;
window.location.hash = hash;
switch(hash){
case "#search":
selectPanel("pnlSearch");
break;
case "#advsearch":
case "#admin":
}
The modern answer:
if your app support split view on iPad, this problem becomes a little complicated. You need window's size, not the screen's, which may contain 2 apps. Window's size may also vary while running.
Use app's main window's size:
UIApplication.shared.delegate?.window??.bounds.size ?? .zero
Note: The method above may get wrong value before window becoming key window when starting up. if you only need width, method below is very recommended:
UIApplication.shared.statusBarFrame.width
The old solution using UIScreen.main.bounds
will return the device's bounds. If your app running in split view mode, it get the wrong dimensions.
self.view.window
in the hottest answer may get wrong size when app contains 2 or more windows and the window have small size.
You can cut off the milliseconds using a Calendar
:
java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));
Output:
2014-04-04 10:10:17.78
2014-04-04 10:10:17.0
Instead of AudioManager.STREAM_RING
you shoul use AudioManager.STREAM_MUSIC
This question has already discussed here.
In my case the below method works.
sed -i 's/playstation/PS4/' input.txt
Can be written as:
sed -i 's/playstation/PS4\nplaystation/' input.txt
PS4
playstation
Consider using \\n while using it in a string literal.
sed : is stream editor
-i : Allows to edit the source file
+: Is delimiter.
I hope the above information works for you .
I just figured out interesting solution:
public class DepthAware<T> : IEnumerable<T>
{
private readonly IEnumerable<T> source;
public DepthAware(IEnumerable<T> source)
{
this.source = source;
this.Depth = 0;
}
public int Depth { get; private set; }
private IEnumerable<T> GetItems()
{
foreach (var item in source)
{
yield return item;
++this.Depth;
}
}
public IEnumerator<T> GetEnumerator()
{
return GetItems().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
// Generic type leverage and extension invoking
public static class DepthAware
{
public static DepthAware<T> AsDepthAware<T>(this IEnumerable<T> source)
{
return new DepthAware<T>(source);
}
public static DepthAware<T> New<T>(IEnumerable<T> source)
{
return new DepthAware<T>(source);
}
}
Usage:
var chars = new[] {'a', 'b', 'c', 'd', 'e', 'f', 'g'}.AsDepthAware();
foreach (var item in chars)
{
Console.WriteLine("Char: {0}, depth: {1}", item, chars.Depth);
}
suppressWarnings()
has already been mentioned. An alternative is to manually convert the problematic characters to NA first. For your particular problem, taRifx::destring
does just that. This way if you get some other, unexpected warning out of your function, it won't be suppressed.
> library(taRifx)
> x <- as.numeric(c("1", "2", "X"))
Warning message:
NAs introduced by coercion
> y <- destring(c("1", "2", "X"))
> y
[1] 1 2 NA
> x
[1] 1 2 NA
The easiest way to do this is to use jQuery : jQuery UI combobox/autocomplete
The withColumn function in pyspark enables you to make a new variable with conditions, add in the when and otherwise functions and you have a properly working if then else structure. For all of this you would need to import the sparksql functions, as you will see that the following bit of code will not work without the col() function. In the first bit, we declare a new column -'new column', and then give the condition enclosed in when function (i.e. fruit1==fruit2) then give 1 if the condition is true, if untrue the control goes to the otherwise which then takes care of the second condition (fruit1 or fruit2 is Null) with the isNull() function and if true 3 is returned and if false, the otherwise is checked again giving 0 as the answer.
from pyspark.sql import functions as F
df=df.withColumn('new_column',
F.when(F.col('fruit1')==F.col('fruit2'), 1)
.otherwise(F.when((F.col('fruit1').isNull()) | (F.col('fruit2').isNull()), 3))
.otherwise(0))
For people who are using AppCompatActivity with Toolbar as white background. Do use this code.
Updated: December, 2017
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="@style/ThemeOverlay.AppCompat.Light">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_edit"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.AppBarOverlay"
app:title="Edit Your Profile"/>
</android.support.design.widget.AppBarLayout>
The he library is the only 100% reliable solution that I know of!
He is written by Mathias Bynens - one of the world's most renowned JavaScript gurus - and has the following features :
he.encode('foo © bar ? baz qux');
// Output : 'foo © bar ≠ baz 𝌆 qux'
he.decode('foo © bar ≠ baz 𝌆 qux');
// Output : 'foo © bar ? baz qux'
Here '~' refers to the root directory ,where Home is controller and Download_Excel_File is actionmethod
<a href="~/Home/Download_Excel_File" />
After placing the jar file in desired location, you need to add the jar file by right click on
Project --> properties --> Java Build Path --> Libraries --> Add Jar.
You are attempting to call
List<EmailData>.Add(string,string,string). Try this:
lstemail.add(new EmailData{ FirstName="John", LastName="Smith", Location="Los Angeles"});
Try DataGridView.CurrentCellAddress.
Returns: A Point that represents the row and column indexes of the currently active cell.
E.G. Select the first column and the fifth row, and you'll get back: Point( X=1, Y=5 )
If "ReferenceError: Model is not defined" error is raised, then you might try to use the following method:
$(document).ready(function () {
@{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(Model);
}
var model = @Html.Raw(json);
if(model != null && @Html.Raw(json) != "undefined")
{
var id= model.Id;
var mainFloorPlanId = model.MainFloorPlanId ;
var imageDirectory = model.ImageDirectory ;
var iconsDirectory = model.IconsDirectory ;
}
});
Hope this helps...
This answer does not fully deal with the OP, but there are have been several times I have had a similar problem and searched for the answer.
If you can recreate the formula or the data if needed (and from your description it looks as if you can), then when you are ready to run the portion that requires the blank cells to be actually empty, then you can select the region and run the following vba macro.
Sub clearBlanks()
Dim r As Range
For Each r In Selection.Cells
If Len(r.Text) = 0 Then
r.Clear
End If
Next r
End Sub
this will wipe out off of the contents of any cell which is currently showing ""
or has only a formula
This is probably the most elegant way to do it.
Right in the PDO constructor call, but avoiding the buggy charset option (as mentioned above):
$connect = new PDO(
"mysql:host=$host;dbname=$db",
$user,
$pass,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
)
);
Works great for me.
To set the credentials for the entire day that is 24 hours.
git config --global credential.helper 'cache --timeout 86400'
Else for 1 hour replace the 86400 secs to 3600.
OR
all configuration options for the 'cache' authentication helper:
git help credential-cache
Just for yumers,
yum install php-mcrypt
service httpd restart
chown -R apache:apache apppath
Maybe you need install remi repo
mystring = mystring.replace(/["']/g, "");
As of laravel 5.5 if the file is stored on a remote storage
return Storage::response($path_to_file);
or if it's locally stored you can also use
return response()->file($path_to_file);
I would recommend using the Storage facade.
I have encountered problem installing numpy package to pycharm and finally figured out. I hope it would be helpful for someone having the same problem in installing numpy and other packages on pycharm.
Pycharm Setting :
Go to File => Setting => Project => Project Interpreter. On this window select the appropriate project interpreter. After this, a list of packages under the selected project interpreter will be shown. From the list select pip and check if the version column and the latest version column are the same. If different upgrade the version to the latest version by selecting the pip and using the upward triangle sign on the right side of the lists. Once the upgrading completed successfully, you can now add new packages from the plus sign.
I hope this would be clear and useful for someone.
Anonymous function:
(function(n) { while(n-- && this.push(0)); return this; }).call([], 5);
// => [0, 0, 0, 0, 0]
A bit shorter with for-loop:
(function(n) { for(;n--;this.push(0)); return this; }).call([], 5);
// => [0, 0, 0, 0, 0]
Works with any Object
, just change what's inside this.push()
.
You can even save the function:
function fill(size, content) {
for(;size--;this.push(content));
return this;
}
Call it using:
var helloArray = fill.call([], 5, 'hello');
// => ['hello', 'hello', 'hello', 'hello', 'hello']
Adding elements to an already existing array:
var helloWorldArray = fill.call(helloArray, 5, 'world');
// => ['hello', 'hello', 'hello', 'hello', 'hello', 'world', 'world', 'world', 'world', 'world']
Performance: http://jsperf.com/zero-filled-array-creation/25
RewriteEngine On
RewriteRule ^(wordpress)($|/) - [L]
I had the same problem, with a slightly different fix: REBUILDING GIT WITH HTTP SUPPORT
The git:
protocol did not work through my corporate firewall.
For example, this timed out:
git clone git://github.com/miksago/node-websocket-server.git
curl github.com
works just fine, though, so I know my http_proxy
environment variable is correct.
I tried using http
, like below, but got an immediate error.
git clone http://github.com/miksago/node-websocket-server.git
->>> fatal: Unable to find remote helper for 'http' <<<-
I tried recompiling git like so:
./configure --with-curl --with-expat
but still got the fatal error.
Finally, after several frustrating hours, I read the configure file, and saw this:
# Define CURLDIR=/foo/bar if your curl header and library files are in
# /foo/bar/include and /foo/bar/lib directories.
I remembered then, that I had not complied curl
from source, and so went
looking for the header files. Sure enough, they were not installed. That was the problem. Make did not complain about the missing header files. So
I did not realize that the --with-curl
option did nothing (it is, in fact the default in my version of git
).
I did the following to fix it:
Added the headers needed for make:
yum install curl-devel
(expat-devel-1.95.8-8.3.el5_5.3.i386 was already installed).
Removed git
from /usr/local
(as I want the new install to live there).
I simply removed git*
from /usr/local/share
and /usr/local/libexec
Searched for the include dirs containing the curl
and expat
header files, and then (because I had read through configure
) added these to the environment like so:
export CURLDIR=/usr/include
export EXPATDIR=/usr/include
Ran configure
with the following options, which, again, were described in the configure
file itself, and were also the defaults but what the heck:
./configure --with-curl --with-expat
And now http
works with git
through my corporate firewall:
git clone http://github.com/miksago/node-websocket-server.git
Cloning into 'node-websocket-server'...
* Couldn't find host github.com in the .netrc file, using defaults
* About to connect() to proxy proxy.entp.attws.com port 8080
* Trying 135.214.40.30... * connected
...
I prefer elegant solutions
In Template
<td>Total: {{ totalSum }}</td>
In Controller
$scope.totalSum = Object.keys(cart.products).map(function(k){
return +cart.products[k].price;
}).reduce(function(a,b){ return a + b },0);
If you're using ES2015 (aka ES6)
$scope.totalSum = Object.keys(cart.products)
.map(k => +cart.products[k].price)
.reduce((a, b) => a + b);
Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>
It's a ton more portable, easier to use and more feature packed too.
In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on http://ssllabs.com or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.
This error raised up because you trying to update dict
object by using a wrong sequence (list
or tuple
) structure.
cash_id.create(cr, uid, lines,context=None)
trying to convert lines
into dict object:
(0, 0, {
'name': l.name,
'date': l.date,
'amount': l.amount,
'type': l.type,
'statement_id': exp.statement_id.id,
'account_id': l.account_id.id,
'account_analytic_id': l.analytic_account_id.id,
'ref': l.ref,
'note': l.note,
'company_id': l.company_id.id
})
Remove the second zero from this tuple to properly convert it into a dict object.
To test it your self, try this into python shell:
>>> l=[(0,0,{'h':88})]
>>> a={}
>>> a.update(l)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
a.update(l)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
>>> l=[(0,{'h':88})]
>>> a.update(l)
Clever use of find
method for collection will do the trick for you.
var largest = 0
lazy val ij =
for (i <- 999 to 1 by -1; j <- i to 1 by -1) yield (i, j)
val largest_ij = ij.find { case(i,j) =>
val product = i * j
if (product.toString == product.toString.reverse)
largest = largest max product
largest > product
}
println(largest_ij.get)
println(largest)
Simpler way:
if grep "$filename" my_list.txt > /dev/null
then
... found
else
... not found
fi
Tip: send to /dev/null
if you want command's exit status, but not outputs.
The accepted answer fails when trying to repeat deleting words, try this solution instead:
" delete current word, insert and normal modes
inoremap <C-BS> <C-O>b<C-O>dw
noremap <C-BS> bdw
It maps CTRL-BackSpace, also working in normal mode.
This can be done with MySQL, although it's highly unintuitive:
CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
DECLARE a,b INT;
DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET b = 1;
OPEN cur_1;
REPEAT
FETCH cur_1 INTO a;
UNTIL b = 1
END REPEAT;
CLOSE cur_1;
SET return_val = a;
END;//
Check out this guide: mysql-storedprocedures.pdf
As addition to the answers above:
If you would like to delete those files
find $dir -size 0 -type f -delete
To add to Rob's answer, since iOS 10.0, Apple has introduced an entirely new "Unified Logging" system that supersedes existing logging systems (including ASL and Syslog, NSLog), and also surpasses existing logging approaches in performance, thanks to its new techniques including log data compression and deferred data collection.
From Apple:
The unified logging system provides a single, efficient, performant API for capturing messaging across all levels of the system. This unified system centralizes the storage of log data in memory and in a data store on disk.
Apple highly recommends using os_log
going forward to log all kinds of messages, including info, debug, error messages because of its much improved performance compared to previous logging systems, and its centralized data collection allowing convenient log and activity inspection for developers. In fact, the new system is likely so low-footprint that it won't cause the "observer effect" where your bug disappears if you insert a logging command, interfering the timing of the bug to happen.
You can learn more about this in details here.
To sum it up: use print()
for your personal debugging for convenience (but the message won't be logged when deployed on user devices). Then, use Unified Logging (os_log
) as much as possible for everything else.
This should work:
txtfarmersize = Convert.ToInt32(reader["farmsize"]);
I think the approach to using UITableViewController might be a little bit different from what you have done before. It has worked for me, but you might not be a fan of it. What I have done is have a view controller with a container view that points to my UItableViewController. This way I am able to use the TopLayoutGuide provided to my in storyboard. Just add the constraint to the container view and you should be taken care of for both iOS7 and iOS6.
For those using the Symfony framework, the phpseclib can also be used to connect via SSH. It can be installed using composer:
composer require phpseclib/phpseclib
Next, simply use it as follows:
use phpseclib\Net\SSH2;
// Within a controller for example:
$ssh = new SSH2('hostname or ip');
if (!$ssh->login('username', 'password')) {
// Login failed, do something
}
$return_value = $ssh->exec('command');
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
Is the best one to use. Using sleep(15); will cause the user unable to perform any other actions. With the following function, you would replace goToSecondButton with the appropriate selector or command, which can also be from the frameworks.
Additionally, if you set a layout_weight
, this supersedes the numStars
attribute.
The :before
pseudo element isn't needed for the clearfix hack itself.
It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.
display:table
is being used because display:block
doesn't do the trick. Using display:block
margins will collapse even with a :before
element.
There is one caveat: if vertical-align:baseline
is used in table cells with clearfixed <div>
elements, Firefox won't align well. Then you might prefer using display:block
despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.
see this page Entity Framework and AsNoTracking
Entity Framework exposes a number of performance tuning options to help you optimise the performance of your applications. One of these tuning options is .AsNoTracking()
. This optimisation allows you to tell Entity Framework
not to track the results of a query. This means that Entity Framework
performs no additional processing or storage of the entities which are returned by the query. However, it also means that you can't update these entities without reattaching them to the tracking graph.
there are significant performance gains to be had by using AsNoTracking
What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:
p = [q.index(v) if v in q else 99999 for v in vm]
When using a list comprehension, you do not call list.append
because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for
keyword, which in this case is q.index(v) if v in q else 99999
. Incidentially, if you do use list.append
inside a comprehension, then you will get a list of None
values because that is what the append
method always returns.
response.writeHead(301,
{Location: 'http://whateverhostthiswillbe:8675/'+newRoom}
);
response.end();
DBNull.Value is what the .NET Database providers return to represent a null entry in the database. DBNull.Value is not null and comparissons to null for column values retrieved from a database row will not work, you should always compare to DBNull.Value.
http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx
+1 to @MartinNuc, you can run the mysql
client in batch mode and then you won't see the long stream of "OK" lines.
The amount of time it takes to import a given SQL file depends on a lot of things. Not only the size of the file, but the type of statements in it, how powerful your server server is, and how many other things are running at the same time.
@MartinNuc says he can load 4GB of SQL in 4-5 minutes, but I have run 0.5 GB SQL files and had it take 45 minutes on a smaller server.
We can't really guess how long it will take to run your SQL script on your server.
Re your comment,
@MartinNuc is correct you can choose to make the mysql client print every statement. Or you could open a second session and run mysql> SHOW PROCESSLIST
to see what's running. But you probably are more interested in a "percentage done" figure or an estimate for how long it will take to complete the remaining statements.
Sorry, there is no such feature. The mysql client doesn't know how long it will take to run later statements, or even how many there are. So it can't give a meaningful estimate for how much time it will take to complete.
http://www.mail-archive.com/[email protected]/msg03998.html says:
...and .removeClass() would remove all classes...
It works for me ;)
cheers
namespace FileUpload
{
public partial class Form1 : Form
{
string fileName = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = "";
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Attach customer proposal document";
fDialog.Filter = "Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf";
fDialog.InitialDirectory = @"C:\";
if (fDialog.ShowDialog() == DialogResult.OK)
{
fileName = System.IO.Path.GetFileName(fDialog.FileName);
path = Path.GetDirectoryName(fDialog.FileName);
textBox1.Text = path + "\\" + fileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential("erandika1986", "123");
Uri addy = new Uri(@"\\192.168.2.4\UploadDocs\"+fileName);
client.Credentials = nc;
byte[] arrReturn = client.UploadFile(addy, textBox1.Text);
MessageBox.Show(arrReturn.ToString());
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}
}
}
}
Browsing the registry for guids or using paths, which method is best. If browsing the registry is no longer necessary, won't it be the better way to use guids? Office is not always installed in the same directory. The installation path can be manually altered. Also the version number is a part of the path. I could have never predicted that Microsoft would ever add '(x86)' to 'Program Files' before the introduction of 64 bits processors. If possible I would try to avoid using a path.
The code below is derived from Siddharth Rout's answer, with an additional function to list all the references that are used in the active workbook. What if I open my workbook in a later version of Excel? Will the workbook still work without adapting the VBA code? I have already checked that the guids for office 2003 and 2010 are identical. Let's hope that Microsoft doesn't change guids in future versions.
The arguments 0,0 (from .AddFromGuid) should use the latest version of a reference (which I have not been able to test).
What are your thoughts? Of course we cannot predict the future but what can we do to make our code version proof?
Sub AddReferences(wbk As Workbook)
' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub
Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
Dim i As Integer
On Error GoTo EH
With wbk.VBProject.References
For i = 1 To .Count
If .Item(i).Name = sRefName Then
Exit For
End If
Next i
If i > .Count Then
.AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
End If
End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
Resume EX
Resume ' debug code
End Sub
Public Sub DebugPrintExistingRefs()
Dim i As Integer
With Application.ThisWorkbook.VBProject.References
For i = 1 To .Count
Debug.Print " AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
Next i
End With
End Sub
The code above does not need the reference to the "Microsoft Visual Basic for Applications Extensibility" object anymore.
If you want to just auto focus any modal that was open you can put in you patterns or lib functions this snippet that will focus on the first input:
$('.modal').on('shown.bs.modal', function () {
$(this).find('input:first').focus();
})
in my case just removing background-image
from nav-bar
item solved the problem
.navbar-default .navbar-nav > .active > a:focus {
.
.
.
background-image: none;
}
Excel is not designed to be programmed via C++ or C#. The COM API is specifically designed to work with Visual Basic, VB.NET, and VBA.
Also all the code samples on this page are not optimal for the simple reason that each call must cross a managed/unmanaged boundary and further ignore the fact that the Excel COM API is free to fail any call with a cryptic HRESULT indicating the RPC server is busy.
The best way to automate Excel in my opinion is to collect your data into as big an array as possible / feasible and send this across to a VBA function or sub (via Application.Run
) which then performs any required processing. Furthermore - when calling Application.Run
- be sure to watch for exceptions indicating excel is busy and retry calling Application.Run
.
Take a look at this example. This query should work:
var leftFinal = from left in lefts
join right in rights on left equals right.Left into leftRights
from leftRight in leftRights.DefaultIfEmpty()
select new { LeftId = left.Id, RightId = left.Key==leftRight.Key ? leftRight.Id : 0 };
Generally on Android, if you simply display the phone number, and the user taps on it, it will pull it up in the dialer. So, you could simply do
For more information, call us at <b>416-555-1234</b>
When the user taps on the bold part, since it's formatted like a phone number, the dialer will pop up, and show 4165551234
in the phone number field. The user then just has to hit the call button.
You might be able to do
For more information, call us at <a href='tel:416-555-1234'>416-555-1234</a>
to cover both devices, but I'm not sure how well this would work. I'll give it a try shortly and let you know.
EDIT: I just gave this a try on my HTC Magic running a rooted Rogers 1.5 with SenseUI:
For more information, call us at <a href='tel:416-555-1234'>416-555-1234</a><br />
<br />
Call at <a href='tel:416-555-1234'>our number</a>
<br />
<br />
<a href='416-555-1234'>Blah</a>
<br />
<br />
For more info, call <b>416-555-1234</b>
The first one, surrounding with the link and printing the phone number, worked perfectly. Pulled up the dialer with the hyphens and all. The second, saying our number
with the link, worked exactly the same. This means that using <a href='tel:xxx-xxx-xxxx'>
should work across the board, but I wouldn't suggest taking my one test as conclusive.
Linking straight to the number did the expected: Tried to pull up the nonexistent file from the server.
The last one did as I mentioned above, and pulled up the dialer, but without the nice formatting hyphens.
auto
keyword is intended to use in such situation, it is absolutely safe. But unfortunately it available only in C++0x so you will have portability issues with it.
select constraint_name,constraint_type
from user_constraints
where table_name = 'YOUR TABLE NAME';
note: table name should be in caps.
In case you don't know the name of the table then,
select constraint_name,constraint_type,table_name
from user_constraints;
In Controller
$hostname = $_ENV['IMAP_HOSTNAME_TEST']; (or) $hostname = env('IMAP_HOSTNAME_TEST');
In blade.view
{{$_ENV['IMAP_HOSTNAME_TEST']}}
Yes. Click on the object (textbox, shape, etc.) to select the object and in the Drawing Tools | Format tab, click on Selection Pane in the Arrange group. From there, you'll see names of objects - you can double click (or press F2) on any name and rename it. By deselecting it, it becomes renamed. You can also get to this from the Home tab -> Drawing group -> Arrange drop-down -> Selection pane or by pressing ALT + F10.
Did you try D3.js? Here is a good example.
In the local searchbox (ctrl + f) you can insert newlines by pressing ctrl + enter.
If you use the global search (ctrl + shift + f) you can insert newlines by pressing shift + enter.
If you want to search for multilines by the character literal, remember to check the rightmost regex icon.
In previous versions of Visual Studio code this was difficult or impossible. Older versions require you to use the regex mode, older versions yet did not support newline search whatsoever.
Per the Android docs SystemClock.elapsedRealtime()
is the recommend basis for general purpose interval timing. This is because, per the documentation, elapsedRealtime() is guaranteed to be monotonic, [...], so is the recommend basis for general purpose interval timing.
The SystemClock documentation has a nice overview of the various time methods and the applicable use cases for them.
SystemClock.elapsedRealtime()
and SystemClock.elapsedRealtimeNanos()
are the best bet for calculating general purpose elapsed time.SystemClock.uptimeMillis()
and System.nanoTime()
are another possibility, but unlike the recommended methods, they don't include time in deep sleep. If this is your desired behavior then they are fine to use. Otherwise stick with elapsedRealtime()
.System.currentTimeMillis()
as this will return "wall" clock time. Which is unsuitable for calculating elapsed time as the wall clock time may jump forward or backwards. Many things like NTP clients can cause wall clock time to jump and skew. This will cause elapsed time calculations based on currentTimeMillis()
to not always be accurate.When the game starts:
long startTime = SystemClock.elapsedRealtime();
When the game ends:
long endTime = SystemClock.elapsedRealtime();
long elapsedMilliSeconds = endTime - startTime;
double elapsedSeconds = elapsedMilliSeconds / 1000.0;
Also, Timer() is a best effort timer and will not always be accurate. So there will be an accumulation of timing errors over the duration of the game. To more accurately display interim time, use periodic checks to System.currentTimeMillis()
as the basis of the time sent to setText(...)
.
Also, instead of using Timer
, you might want to look into using TimerTask
, this class is designed for what you want to do. The only problem is that it counts down instead of up, but that can be solved with simple subtraction.
This should work for you:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public static void main(String[] args) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("abc.java")));
}
I hope you find this helpful.
HTML :
<html>
<head>
<link rel = "stylesheet" href = "test.css">
<body>
</body>
<script src = "test.js"></script>
</head>
</html>
JAVASCRIPT :
var tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div');
for (row = 1; row < 101; row += 1) {
tableString += "<tr>";
for (col = 1; col < 11; col += 1) {
tableString += "<td>" + "row [" + row + "]" + "col [" + col + "]" + "</td>";
}
tableString += "</tr>";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
You are missing an include :
#include <stdlib.h>
, so GCC creates an implicit declaration of atof
and atod
, leading to garbage values.
And the format specifier for double is %f
, not %d
(that is for integers).
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;
}
/* Output */
price: 12.110000, 12.110000
You can use np.where
to get indices and np.logical_and
to set two conditions:
import numpy as np
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.where(np.logical_and(a>=6, a<=10))
# returns (array([3, 4, 5]),)
Like the other answers you can do theTypeIs = Object.keys(myVar)[0];
to get the first key. If you are expecting more keys, you can use
Object.keys(myVar).forEach(function(k) {
if(k === "typeA") {
// do stuff
}
else if (k === "typeB") {
// do more stuff
}
else {
// do something
}
});
As others have already said, parameters passed through the command line can be accessed in batch files with the notation %1
to %9
. There are also two other tokens that you can use:
%0
is the executable (batch file) name as specified in the command line.%*
is all parameters specified in the command line -- this is very useful if you want to forward the parameters to another program.There are also lots of important techniques to be aware of in addition to simply how to access the parameters.
This is done with constructs like IF "%~1"==""
, which is true if and only if no arguments were passed at all. Note the tilde character which causes any surrounding quotes to be removed from the value of %1
; without a tilde you will get unexpected results if that value includes double quotes, including the possibility of syntax errors.
If you need to access more than 9 arguments you have to use the command SHIFT
. This command shifts the values of all arguments one place, so that %0
takes the value of %1
, %1
takes the value of %2
, etc. %9
takes the value of the tenth argument (if one is present), which was not available through any variable before calling SHIFT
(enter command SHIFT /?
for more options).
SHIFT
is also useful when you want to easily process parameters without requiring that they are presented in a specific order. For example, a script may recognize the flags -a
and -b
in any order. A good way to parse the command line in such cases is
:parse
IF "%~1"=="" GOTO endparse
IF "%~1"=="-a" REM do something
IF "%~1"=="-b" REM do something else
SHIFT
GOTO parse
:endparse
REM ready for action!
This scheme allows you to parse pretty complex command lines without going insane.
For parameters that represent file names the shell provides lots of functionality related to working with files that is not accessible in any other way. This functionality is accessed with constructs that begin with %~
.
For example, to get the size of the file passed in as an argument use
ECHO %~z1
To get the path of the directory where the batch file was launched from (very useful!) you can use
ECHO %~dp0
You can view the full range of these capabilities by typing CALL /?
in the command prompt.
I stopped using DECODE
several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN
.
However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.
select a, b, decode(a, b, 'true', 'false') as same
from t;
A B SAME
------ ------ -----
1 1 true
1 0 false
1 false
null null true
x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
> names(summary(fit))
[1] "call" "terms"
[3] "residuals" "coefficients"
[5] "aliased" "sigma"
[7] "df" "r.squared"
[9] "adj.r.squared" "fstatistic"
[11] "cov.unscaled"
summary(fit)$r.squared
To get a negative version of a number in JavaScript you can always use the ~
bitwise operator.
For example, if you have a = 1000
and you need to convert it to a negative, you could do the following:
a = ~a + 1;
Which would result in a
being -1000
.
I want to give a different view of MONEY vs. NUMERICAL, largely based my own expertise and experience... My point of view here is MONEY, because I have worked with it for a considerable long time and never really used NUMERICAL much...
MONEY Pro:
Native Data Type. It uses a native data type (integer) as the same as a CPU register (32 or 64 bit), so the calculation doesn't need unnecessary overhead so it's smaller and faster... MONEY needs 8 bytes and NUMERICAL(19, 4) needs 9 bytes (12.5% bigger)...
MONEY is faster as long as it is used for it was meant to be (as money). How fast? My simple SUM
test on 1 million data shows that MONEY is 275 ms and NUMERIC 517 ms... That is almost twice as fast... Why SUM test? See next Pro point
MONEY Con:
money
doesn't need to be so precise and is meant to be used as money, not just a number...But... Big, but here is even your application involved real-money, but do not use it in lots of SUM operations, like in accounting. If you use lots of divisions and multiplications instead then you should not use MONEY...
The R method will work reliably, and it requires little knowledge of R. Note that the conversion using the foreign package will preserve data, but may introduce differences. For example, when converting a table without a primary key, the primary key and associated columns will be inserted during the conversion.
From http://www.r-bloggers.com/using-r-for-stata-to-csv-conversion/ I recommend:
library(foreign)
write.table(read.dta(file.choose()), file=file.choose(), quote = FALSE, sep = ",")
I had the same problem. Check out the comment in https://gist.github.com/khernyo/4226923#comment-812526
It says:
for gradle android plugin v0.3 use "com.android.build.gradle.tasks.PackageApplication"
That should fix your problem.
Start pgAdmin, connect to the server, click on the database name, and select the statistics tab. You will see the size of the database at the bottom of the list.
Then if you click on another database, it stays on the statistics tab so you can easily see many database sizes without much effort. If you open the table list, it shows all tables and their sizes.
List<string> animals= new List<string>();
animals.Add("dog");
animals.Add("tiger");
import array
integerValue = array.array("I", 'y\xcc\xa6\xbb')[0]
Warning: the above is strongly platform-specific. Both the "I" specifier and the endianness of the string->int conversion are dependent on your particular Python implementation. But if you want to convert many integers/strings at once, then the array module does it quickly.
Open up Settings (By default is Alt + Ctrl + S) and search for Live Templates. In the upper part there's an option that says "By default expand with TAB" (TAB is the default), choose "Custom" and then hit "change" and add the keymap "ctrl+spacebar" to the option "Expand Live Template/Emmet Abbreviation".
Now you can hit ctrl + spacebar and expand the live templates. Now, to change it to "syso" instead of "sout", in the Live Templates option, theres a list of tons of options checked, go to "other" and expand it, there you wil find "sout", just rename it to "syso" and hit aply.
Hope this can help you.
MacPorts will install ant for you in MacOSX 10.9. Just use
$ sudo port install apache-ant
and it will install.
since you followed the tutorial, I presume you have a screen that says Hello World.
that means you have some code in your layout xml that looks like this
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
you want to display an image, so instead of TextView you want to have ImageView. and instead of a text attribute you want an src attribute, that links to your drawable resource
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cool_pic"
/>
Edit!: Please be sure that you should have both Python installed on your computer.
Maybe my answer is late for you but I can help someone who has the same problem!
You don't have to download both Anaconda
.
If you are using Spyder
and Jupyter
in Anaconda environmen and,
If you have already Anaconda 2 type in Terminal:
python3 -m pip install ipykernel
python3 -m ipykernel install --user
If you have already Anaconda 3 then type in terminal:
python2 -m pip install ipykernel
python2 -m ipykernel install --user
Then before use Spyder
you can choose Python environment like below!
Sometimes only you can see root and your new Python environment, so root is your first anaconda environment!
Also this is Jupyter. You can choose python version like this!
I hope it will help.
You can use StringBuffer
or StringBuilder
for this. Both are for dynamic string manipulation. StringBuffer
is thread-safe where as StringBuilder
is not.
Use StringBuffer
in a multi-thread environment. But if it is single threaded StringBuilder
is recommended and it is much faster than StringBuffer
.
From WWDC 2015 there is a session on Implementing UI Designs in Interface Builder. Around the 32min mark he says that you always want to make your @IBOutlet
strong.
What you've got (according to the debug image) is an object array containing a string array. So you need something like:
Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];
You haven't shown the type of values
- if this is already Object[]
then you could just use (String[])values[0]
.
Of course even with the cast to Object[]
you could still do it in one statement, but it's ugly:
String[] strings = (String[]) ((Object[])values)[0];
By the way, Jsoup has method that takes file: http://jsoup.org/apidocs/org/jsoup/Jsoup.html#parse(java.io.File,%20java.lang.String)
Well... its quite simple to get a SQL min date
DateTime sqlMinDateAsNetDateTime = System.Data.SqlTypes.SqlDateTime.MinValue.Value;
To break a loop, use break
instead of return
.
Or put the loop or control construct into a function, only functions can return values.
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
And it works, thanks @trichetriche. The problem was in my RequestOptions
, apparently, you can not pass params
or body
to the RequestOptions
while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.
public post(cmd: string, data: string): Observable<any> {
const options = new RequestOptions({
headers: this.getAuthorizedHeaders(),
responseType: ResponseContentType.Json,
withCredentials: false
});
console.log('Options: ' + JSON.stringify(options));
return this.http.post(this.BASE_URL, JSON.stringify({
cmd: cmd,
data: data}), options)
.map(this.handleData)
.catch(this.handleError);
}
I not expert in MySQL but you probably should look on triggers e.g. BEFORE INSERT. In the trigger you can run select query on your original table and if it found something just update the row 'logins' instead of inserting new values. But all this depends on version of MySQL you running.
After you get from Eclipse the ugly CheckoutConflictException, the Eclipse-Merge Tool button is disabled.
Git need alle your files added to the Index for enable Merging.
So, to merge your Changes and commit them you need to add your files first to the index "Add to Index" and "Commit" them without "Push". Then you should see one pending pull and one pending push request in Eclipse. You see that in one up arrow and one down arrow.
If all conflict Files are in the commit, you can "pull" again. Then you will see something like:
\< < < < < < < HEAD Server Version \======= Local Version > > > > > > > branch 'master' of ....git
Then you either change it by the Merge-Tool, which is now enable or just do the merge by hand direct in the file. In the last step, you have to add the modified files again to the index and "Commit and Push" them.
Checking done!
Banengusk was putting me on the right track. For further reference, I want to post the steps I took to fix my repository corruption. I was lucky enough to find all needed objects either in older packs or in repository backups.
# Unpack last non-corrupted pack
$ mv .git/objects/pack .git/objects/pack.old
$ git unpack-objects -r < .git/objects/pack.old/pack-012066c998b2d171913aeb5bf0719fd4655fa7d0.pack
$ git log
fatal: bad object HEAD
$ cat .git/HEAD
ref: refs/heads/master
$ ls .git/refs/heads/
$ cat .git/packed-refs
# pack-refs with: peeled
aa268a069add6d71e162c4e2455c1b690079c8c1 refs/heads/master
$ git fsck --full
error: HEAD: invalid sha1 pointer aa268a069add6d71e162c4e2455c1b690079c8c1
error: refs/heads/master does not point to a valid object!
missing blob 75405ef0e6f66e48c1ff836786ff110efa33a919
missing blob 27c4611ffbc3c32712a395910a96052a3de67c9b
dangling tree 30473f109d87f4bcde612a2b9a204c3e322cb0dc
# Copy HEAD object from backup of repository
$ cp repobackup/.git/objects/aa/268a069add6d71e162c4e2455c1b690079c8c1 .git/objects/aa
# Now copy all missing objects from backup of repository and run "git fsck --full" afterwards
# Repeat until git fsck --full only reports dangling objects
# Now garbage collect repo
$ git gc
warning: reflog of 'HEAD' references pruned commits
warning: reflog of 'refs/heads/master' references pruned commits
Counting objects: 3992, done.
Delta compression using 2 threads.
fatal: object bf1c4953c0ea4a045bf0975a916b53d247e7ca94 inconsistent object length (6093 vs 415232)
error: failed to run repack
# Check reflogs...
$ git reflog
# ...then clean
$ git reflog expire --expire=0 --all
# Now garbage collect again
$ git gc
Counting objects: 3992, done.
Delta compression using 2 threads.
Compressing objects: 100% (3970/3970), done.
Writing objects: 100% (3992/3992), done.
Total 3992 (delta 2060), reused 0 (delta 0)
Removing duplicate objects: 100% (256/256), done.
# Done!
Thank you all. I did find a way to do what I wanted.
UIView
with the IBOutlet
s you need.UIViewController
(No custom subclass, but the "real" one). The File Owner's view is connected to the main view and its class is declared as the one from step 1).IBOutlet
s.The DynamicViewController
can run its logic to decide what view/xib to load. Once its made the decission, in the loadView
method put something like this:
NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"QPickOneView"
owner:self
options:nil];
QPickOneView* myView = [ nibViews objectAtIndex: 1];
myView.question = question;
That's it!
The main bundle's loadNibNamed
method will take care of initializing the view and creating the connections.
Now the ViewController can display a view or another depending on the data in memory, and the "parent" screen doesn't need to bother with this logic.
For those who still might be facing issue adding jsx to test fixed it for me
test: /\.jsx?$/,
You can check your eav_attributes table to find the relevant attribute IDs for each image role, such as;
Then you can use those to set whichever role to any other role for all products like so;
UPDATE catalog_product_entity_varchar AS `v` INNER JOIN (SELECT `value`,`entity_id` FROM `catalog_product_entity_varchar` WHERE `attribute_id`=86) AS `j` ON `j`.`entity_id`=`v`.entity_id SET `v`.`value`=j.`value` WHERE `v`.attribute_id = 85 AND `v`.`entity_id`=`j`.`entity_id`
The above will set all your 'base' roles to the 'small' image of the same product.
Those who are facing this problem: Don't panic.
Short answer:
Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)
Long answer: Let's learn how to restart the router.
telnet 192.168.1.1
Run these commands:
mount_root ## this remounts your partitions from read-only to read/write mode
firstboot ## This will reset your router after reboot
reboot -f ## And force reboot
Log in the web interface using web browser.
link to see the official failsafe mode.
Use
jQuery(document).
instead of
$(document).
or
Within the function, $ points to jQuery as you would expect
(function ($) {
$(document).
}(jQuery));
Mongoose maintainer here. You need to set the new
option to true
(or, equivalently, returnOriginal
to false
)
await User.findOneAndUpdate(filter, update, { new: true });
// Equivalent
await User.findOneAndUpdate(filter, update, { returnOriginal: false });
See Mongoose findOneAndUpdate()
docs and this tutorial on updating documents in Mongoose.
Try this one -
CREATE PROCEDURE sp_ADD_USER_EXTRANET_CLIENT_INDEX_PHY
AS
BEGIN
DECLARE @ParLngId INT
SELECT TOP 1 @ParLngId = ParLngId
FROM dbo.T_Param
WHERE ParStrNom = 'Extranet Client'
IF (@ParLngId = 0)
BEGIN
INSERT INTO dbo.T_Param
VALUES ('PHY', 'Extranet Client', NULL, NULL, 'T', 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL)
RETURN SCOPE_IDENTITY()
END
ELSE BEGIN
RETURN @ParLngId
END
END
Getter functions in module operator
The functions attrgetter()
and itemgetter()
in module operator
can be used to generate fast access functions for use in sorting and search objects and dictionaries
Chapter 6.7 in the Python Library Docs
Use CURRENT_TIMESTAMP (or GETDATE() on archaic versions of SQL Server).
To get one cell value based on entire row selection:
if (dataGridView1.SelectedRows.Count > 0)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
TextBox1.Text = row.Cells["ColumnName"].Value.ToString();
}
}
else
{
MessageBox.Show("Please select item!");
}
}
Blog post Serial RS232 connections in Python
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyUSB1',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(input + '\r\n')
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
I use .bat file with this commad to do that.
for /f %%F in ('dir /b /ad /s ^| findstr /iles "Bin"') do RMDIR /s /q "%%F"
for /f %%F in ('dir /b /ad /s ^| findstr /iles "Obj"') do RMDIR /s /q "%%F"
Easy way for older C++, or C:
#include <time.h> // includes clock_t and CLOCKS_PER_SEC
int main() {
clock_t start, end;
start = clock();
// ...code to measure...
end = clock();
double duration_sec = double(end-start)/CLOCKS_PER_SEC;
return 0;
}
Timing precision in seconds is 1.0/CLOCKS_PER_SEC
Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?
If you don't mind including the underscore as an allowed character, you could try simply:
result = subject.replace(/\W+/g, "");
If the underscore must be excluded also, then
result = subject.replace(/[^A-Z0-9]+/ig, "");
(Note the case insensitive flag)
You can refer this following link for using strptime
function from datetime.datetime
, to convert date from any format along with time zone.
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
In Java 8 this can be made a little cleaner, assuming you have a static import for org.mockito.Mockito.doAnswer
:
doAnswer(i -> {
// Do stuff with i.getArguments() here
return null;
}).when(*mock*).*method*(*methodArguments*);
The return null;
is important and without it the compile will fail with some fairly obscure errors as it won't be able to find a suitable override for doAnswer
.
For example an ExecutorService
that just immediately executes any Runnable
passed to execute()
could be implemented using:
doAnswer(i -> {
((Runnable) i.getArguments()[0]).run();
return null;
}).when(executor).execute(any());
Old question; but I always try to use fastest code!
I had a huge list with 69 millions of uint64. np.array() was fastest for me.
df['hashes'] = hashes
Time spent: 17.034842014312744
df['hashes'] = pd.Series(hashes).values
Time spent: 17.141014337539673
df['key'] = np.array(hashes)
Time spent: 10.724546194076538
I believe the browser is looking for those assets FROM the root of the webserver. This is difficult because it is easy to start developing on your machine WITHOUT actually using a webserver ( just by loading local files through your browser)
You could start by packaging your html and css/js together?
a directory structure something like:
-yourapp
- index.html
- assets
- css
- js
- myPage.js
Then your script tag (from index.html) could look like
<script src="assets/js/myPage.js"></script>
An added benifit of packaging your html and assets in one directory is that you can copy the directory and give it to someone else or put it on another machine and it will work great.
I tested for JS with Node 4.0.0 if anyone is interested. Declaring outside the loop resulted in a ~.5 ms performance improvement on average over 1000 trials with 100 million loop iterations per trial. So I'm gonna say go ahead and write it in the most readable / maintainable way which is B, imo. I would put my code in a fiddle, but I used the performance-now Node module. Here's the code:
var now = require("../node_modules/performance-now")
// declare vars inside loop
function varInside(){
for(var i = 0; i < 100000000; i++){
var temp = i;
var temp2 = i + 1;
var temp3 = i + 2;
}
}
// declare vars outside loop
function varOutside(){
var temp;
var temp2;
var temp3;
for(var i = 0; i < 100000000; i++){
temp = i
temp2 = i + 1
temp3 = i + 2
}
}
// for computing average execution times
var insideAvg = 0;
var outsideAvg = 0;
// run varInside a million times and average execution times
for(var i = 0; i < 1000; i++){
var start = now()
varInside()
var end = now()
insideAvg = (insideAvg + (end-start)) / 2
}
// run varOutside a million times and average execution times
for(var i = 0; i < 1000; i++){
var start = now()
varOutside()
var end = now()
outsideAvg = (outsideAvg + (end-start)) / 2
}
console.log('declared inside loop', insideAvg)
console.log('declared outside loop', outsideAvg)
Steveha's answer was helpful to me, but omits an important point (one that I think wisty was getting at). The global keyword is not necessary if you only access but do not assign the variable in the function.
If you assign the variable without the global keyword then Python creates a new local var -- the module variable's value will now be hidden inside the function. Use the global keyword to assign the module var inside a function.
Pylint 1.3.1 under Python 2.7 enforces NOT using global if you don't assign the var.
module_var = '/dev/hello'
def readonly_access():
connect(module_var)
def readwrite_access():
global module_var
module_var = '/dev/hello2'
connect(module_var)
window.onload = codeAddress;
should work - here's a demo, and the full code:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Test</title>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<script type="text/javascript">_x000D_
function codeAddress() {_x000D_
alert('ok');_x000D_
}_x000D_
window.onload = codeAddress;_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Test</title>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<script type="text/javascript">_x000D_
function codeAddress() {_x000D_
alert('ok');_x000D_
}_x000D_
_x000D_
</script>_x000D_
</head>_x000D_
<body onload="codeAddress();">_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
And, if you don't want to instantiate Class2, declare UpdateEmployee as static and call it like this:
Class2.UpdateEmployee();
However, you'll normally want to do what @parag said.
Another case is http redirection. If your page redirects http requests to https, then may be your partial view tries to redirect by itself.
It causes same problem again. For this problem, you can reorganize your .net error pages or iis error pages configuration.
Just make sure you are redirecting requests to right error or not found page and make sure this error page contains non problematic partial. If your page supports only https, do not forward requests to error page without using https, if error page contains partial, this partials tries to redirect seperately from requested url, it causes problem.
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
Using the answer from here I was able to create a one liner
top -pid $(pgrep process_name | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ -pid /g')
This works for me on MacOS 10.12 (Sierra)
In java
public static String formatMs(long millis) {
long hours = TimeUnit.MILLISECONDS.toHours(millis);
long mins = TimeUnit.MILLISECONDS.toMinutes(millis);
long secs = TimeUnit.MILLISECONDS.toSeconds(millis);
return String.format("%dh %d min, %d sec",
hours,
mins - TimeUnit.HOURS.toMinutes(hours),
secs - TimeUnit.MINUTES.toSeconds(mins)
);
}
Gives something like this:
12h 1 min, 34 sec
I just put the content in the question in a file called test.php
and ran php test.php
.
(In the folder where the test.php
is.)
$ php foo.php
15
In Python, curly braces are used to define a dictionary.
a={'one':1, 'two':2, 'three':3}
a['one']=1
a['three']=3
In other languages, { } are used as part of the flow control. Python however used indentation as its flow control because of its focus on readable code.
for entry in entries:
code....
There's a little easter egg in Python when it comes to braces. Try running this on the Python Shell and enjoy.
from __future__ import braces
In my case, I was using sys.path.insert()
to import a local module and was getting module not found
from a different library. I had to put sys.path.insert()
below the imports that reported module not found
. I guess the best practice is to put sys.path.insert()
at the bottom of your imports.
The thread is very old, but I came looking for answer here hence providing new solution.
With MongoDB version 3.6+, it is now possible to use the positional operator to update all items in an array. See official documentation here.
Following query would work for the question asked here. I have also verified with Java-MongoDB driver and it works successfully.
.update( // or updateMany directly, removing the flag for 'multi'
{"events.profile":10},
{$set:{"events.$[].handled":0}}, // notice the empty brackets after '$' opearor
false,
true
)
Hope this helps someone like me.
Your action method considers model type asList<string>
. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>
.
You can solve this problem with changing the model in your view to List<string>
.
But, the best approach would be to return IEnumerable<Standings.Models.Teams>
as a model from your action method. Then you haven't to change model type in your view.
But, in my opinion your models are not correctly implemented. I suggest you to change it as:
public class Team
{
public int Position { get; set; }
public string HomeGround {get; set;}
public string NickName {get; set;}
public int Founded { get; set; }
public string Name { get; set; }
}
Then you must change your action method as:
public ActionResult Index()
{
var model = new List<Team>();
model.Add(new Team { Name = "MU"});
model.Add(new Team { Name = "Chelsea"});
...
return View(model);
}
And, your view:
@model IEnumerable<Standings.Models.Team>
@{
ViewBag.Title = "Standings";
}
@foreach (var item in Model)
{
<div>
@item.Name
<hr />
</div>
}
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseYou can also add labels that are tied to your radio buttons with the same ID, which then allows the user to click the radio button or label to select that item. I'm using constants here for "Male", "Female" and "Unknown", but obviously these could be strings in your model.
<%: Html.RadioButtonFor(m => m.Gender, "Male",
new Dictionary<string, object> { { "checked", "checked" }, { "id", "Male" } }) %>
<%: Html.Label("Male") %>
<%: Html.RadioButtonFor(m => m.Gender, "Female",
new Dictionary<string, object> { { "id", "Female" } }) %>
<%: Html.Label("Female")%>
<%: Html.RadioButtonFor(m => m.Gender, "Unknown",
new Dictionary<string, object> { { "id", "Unknown" } }) %>
<%: Html.Label("Unknown")%>
Add -storepass to keytool arguments.
keytool -storepasswd -storepass '' -keystore mykeystore.jks
But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password
$JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts
HashMap
is mutable; there's no need for a builder.
Map<String, Integer> map = Maps.newHashMap();
map.put("a", 1);
map.put("b", 2);
Like this:
void * p = (void *)0x28ff44;
Or if you want it as a char *
:
char * p = (char *)0x28ff44;
...etc.
If you're pointing to something you really, really aren't meant to change, add a const
:
const void * p = (const void *)0x28ff44;
const char * p = (const char *)0x28ff44;
...since I figure this must be some kind of "well-known address" and those are typically (though by no means always) read-only.
Maybe you coul'd use UTF8 bold chars.
For examples: https://yaytext.com/bold-italic/
It works on Chromium 80.0, I don't know on other browsers...
You can use jQuery DataTables plugin for applying column sorting in desired way.
Your hosts file does not include a valid FQDN, nor is localhost
an FQDN. An FQDN must include a hostname part, as well as a domain name part. For example, the following is a valid FQDN:
host.server4-245.com
Choose an FQDN and include it both in your /etc/hosts
file on both the IPv4 and IPv6 addresses you are using (in your case, localhost
or 127.0.0.1
), and change your ServerName
in your httpd configuration to match.
/etc/hosts:
127.0.0.1 localhost.localdomain localhost host.server4-245.com
::1 localhost.localdomain localhost host.server4-245.com
httpd.conf:
ServerName host.server4-245.com
command.Text = "UPDATE Student
SET Address = @add, City = @cit
Where FirstName = @fn and LastName = @add";
prop.table is a nice friendly way of obtaining proportions of tables.
m <- matrix(1:4,2)
m
[,1] [,2]
[1,] 1 3
[2,] 2 4
Leaving margin blank gives you proportions of the whole table
prop.table(m, margin=NULL)
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
Giving it 1 gives you row proportions
prop.table(m, 1)
[,1] [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667
And 2 is column proportions
prop.table(m, 2)
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
There are certain things you have to take care:
NotFoundException
that are encountered by default in the until
condition.To invoke click()
as soon as the element is returned, you can use:
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]"))).click();
To simply validate if the element is located and clickable, wrap up the WebDriverWait in a try-catch{}
block as follows:
try {
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));
System.out.println("Element is clickable");
}
catch(TimeoutException e) {
System.out.println("Element isn't clickable");
}
If WebDriverWait returns the located and clickable element but the element is still not clickable, you need to invoke executeScript()
method as follows:
WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
<Style x:Key="MySeparatorStyle" TargetType="{x:Type Separator}">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}"/>
<Setter Property="Margin" Value="10,0,10,0"/>
<Setter Property="Focusable" Value="false"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Separator}">
<Border
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Height="20"
Width="3"
SnapsToDevicePixels="true"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
use
<StackPanel Orientation="Horizontal" >
<TextBlock>name</TextBlock>
<Separator Style="{StaticResource MySeparatorStyle}" ></Separator>
<Button>preview</Button>
</StackPanel>
I fixed this issue with :
varchar(200)
replaced with
varchar(191)
all the unique or primary varchar keys which have more than 200 replace them with 191 or set them as text.