If you setWantsLayer to YES first, you can directly manipulate the layer background.
[self.view setWantsLayer:YES];
[self.view.layer setBackgroundColor:[[NSColor whiteColor] CGColor]];
Go to Dev Settings -> to Debug server host & port for device -> Input your Computer Wifi IP address (Mac OS : Go to System Preferences -> Wifi to get Wifi IP address)
Final Rebuild application and Run
Max. capacity is 2 gigabytes of space - so you're looking at just over 1 billion 2-byte characters that will fit into a NVARCHAR(MAX)
field.
Using the other answer's more detailed numbers, you should be able to store
(2 ^ 31 - 1 - 2) / 2 = 1'073'741'822 double-byte characters
1 billion, 73 million, 741 thousand and 822 characters to be precise
in your NVARCHAR(MAX)
column (unfortunately, that last half character is wasted...)
Update: as @MartinMulder pointed out: any variable length character column also has a 2 byte overhead for storing the actual length - so I needed to subtract two more bytes from the 2 ^ 31 - 1
length I had previously stipulated - thus you can store 1 Unicode character less than I had claimed before.
You do not specify why you think it is wrong but I can se two dangers:
BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.
Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.
DIY
private boolean isNull(Object obj) {
return obj == null;
}
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (isNull(drawable)) {
drawable = getRandomDrawable();
}
The best method is to wrap the span inside a button and disable the button
$("#buttonD").click(function(){_x000D_
alert("button clicked");_x000D_
})_x000D_
_x000D_
$("#buttonS").click(function(){_x000D_
alert("span clicked");_x000D_
})
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<button class="btn btn-success" disabled="disabled" id="buttonD">_x000D_
<span>Disabled button</span>_x000D_
</button>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<span class="btn btn-danger" disabled="disabled" id="buttonS">Disabled span</span>
_x000D_
Because none mentioned, when using Number
and parseInt
with numeric separator, they also behave differently:
const num1 = 5_0; // 50
const num2 = Number(5_0); // 50
const num3 = Number("5_0"); // NaN
const num4 = parseInt(5_0); // 50
const num5 = parseInt("5_0"); // 5
>>> from itertools import repeat
>>> for foo, bars in zip(foos, repeat(bars)):
... print foo, bars
...
1.0 [1, 2, 3]
2.0 [1, 2, 3]
3.0 [1, 2, 3]
4.0 [1, 2, 3]
5.0 [1, 2, 3]
I'll tell you how it can be done in eclipse. My dev system - Windows 64bit, Eclipse Luna, Perlipse plugin for eclipse, Strawberry pearl installer. I use perl.exe as my interpreter.
Eclipse > create new perl project > right click project > build path > configure build path > libraries tab > add external source folder > go to the folder where all your perl modules are installed > ok > ok. Done !
This should do the trick:
image = open("image.png", "wb")
image.write(base64string.decode('base64'))
image.close()
You said :
Maybe my data.frame is not in a good format?
Yes this is true. Your data is in the wide format You need to put it in the long format. Generally speaking, long format is better for variables comparison.
Using reshape2
for example , you do this using melt
:
dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work
Then you get your barplot:
ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
geom_bar(stat='identity')
But using lattice
and barchart
smart formula notation , you don't need to reshape your data , just do this:
barchart(F1+F2+F3~Rank,data=dat)
You could use the following regex code to validate 2 names separeted by a space with the following regex code:
^[A-Za-zÀ-ú]+ [A-Za-zÀ-ú]+$
[[:lower:]] = [a-zà-ú]
[[:upper:]] =[A-ZÀ-Ú]
[[:alpha:]] = [A-Za-zÀ-ú]
[[:alnum:]] = [A-Za-zÀ-ú0-9]
For me also it was not working. Then i try with javascript inside php like
echo "<script type='text/javascript'> window.location='index.php'; </script>";
This will definitely working.
If you look at the code of %in%
function (x, table) match(x, table, nomatch = 0L) > 0L
then you should be able to write your version of opposite. I use
`%not in%` <- function (x, table) is.na(match(x, table, nomatch=NA_integer_))
Another way is:
function (x, table) match(x, table, nomatch = 0L) == 0L
For ubuntu 16.04, there is firewall issue. You need to open 8080 port using following command:
sudo ufw allow 8080
Detailed steps are given here: https://www.digitalocean.com/community/tutorials/how-to-install-jenkins-on-ubuntu-16-04
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
In the hope that it will be useful to some, you may want to check out my go at it:
While there are a couple of good and well-documented IMAP libraries for .NET available, none of them are free for personal, let alone commercial use...and I was just not all that satisfied with the mostly abandoned free alternatives I found.
S22.Imap supports IMAP IDLE notifications as well as SSL and partial message fetching. I have put some effort into producing documentation and keeping it up to date, because with the projects I found, documentation was often sparse or non-existent.
Feel free to give it a try and let me know if you run into any issues!
mod_deflate requires fewer resources on your server, although you may pay a small penalty in terms of the amount of compression.
If you are serving many small files, I'd recommend benchmarking and load testing your compressed and uncompressed solutions - you may find some cases where enabling compression will not result in savings.
if you are using the MySQLWorkbench you have the option to change the to change the query_alloc_block_size= 16258 and save it.
Step 1. click on the options file
at the left side.
Step 2: click on General
and select the checkBox
of query_alloc_block_size and increase their size. for example change 8129 --> 16258
Actually with Java 8 the right way is to use:
System.getProperty("user.home");
The bug JDK-6519127 has been fixed and the "Incompatibilities between JDK 8 and JDK 7" section of the release notes states:
Area: Core Libs / java.lang
Synopsis
The steps used to determine the user's home directory on Windows have changed to follow the Microsoft recommended approach. This change might be observable on older editions of Windows or where registry settings or environment variables are set to other directories. Nature of Incompatibility
behavioral RFE 6519127
Despite the question being old I leave this for future reference.
Put the loops in a subroutine and call return
From this post:
Default template arguments are not part of the signature of a template
But one can do something like this:
#include <iostream>
struct Foo {
template < class T,
class std::enable_if < !std::is_integral<T>::value, int >::type = 0 >
void f(const T& value)
{
std::cout << "Not int" << std::endl;
}
template<class T,
class std::enable_if<std::is_integral<T>::value, int>::type = 0>
void f(const T& value)
{
std::cout << "Int" << std::endl;
}
};
int main()
{
Foo foo;
foo.f(1);
foo.f(1.1);
// Output:
// Int
// Not int
}
You're only adding the File object to the JSON object. The File object only contains meta information about the file: Path, name and so on.
You must load the image and read the bytes from it. Then put these bytes into the JSON object.
Some useful links that will help you:
Call Path.GetFullPath on the combined path http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx
> Path.GetFullPath(Path.Combine(@"C:\blah\",@"..\bling"))
C:\bling
(I agree Path.Combine ought to do this by itself)
Set: A Set cannot have Duplicate elements in its collections. it is also an unordered collection. To access the data from Set, it is required to use Iterator only and index based retrieve is not possible for it. It is mainly used whenever required uniqueness collection.
List: A List can have duplicate elements, with the natural ordered as it is inserted. Thus, it can be retrieved data based on index or iterator. It is widely used to store collection which needs to access based on index.
PHP complains if one of the files like mcrypt.so
is included using the syntax extension="mcrypt.so"
but the file is not in the extension_dir
path ( use <?php phpinfo(); ?>
or php -i
to check that).
It will also tell you which php.ini
config file is being loaded so you will know where the settings are coming from. Most likely it will be something like /usr/local/etc/php/5.4/php.ini
if you are using the homebrew version.
Take note of the part under it that says something like "Scan this dir for additional .ini files" because what that means is it gives you a place to put your own file, like tweaks.ini
that is loaded after the main configuration file so that you can make changes and keep up with them easily. Also remember that all the files in this directory get loaded in alphabetical order, so if you have one called adjustments.ini
that contains mcrypt
directives, and there is a mcrypt.ini
, most likely your settings will be overridden.
One alternative to specifying extension="mcrypt.so"
is to specify the full path to the mcrypt.so
file. The other option is to edit the extension_dir
setting.
On Mavericks I didn't have to do either. I did a fresh install of homebrew
and then added the josegonzalez tap using:
brew tap josegonzalez/homebrew-php
(My other laptop was running Mountain Lion and was also using homebrew in this setup.)
After you've tapped that awesome repo you can install php
and mcrypt
using something like:
brew install php54 php54-mcrypt
I would highly advise trying this route before downloading and building it from source. It's not hard to build from source - but I don't want to have to maintain that. It's one of the reasons to use homebrew
in the first place - it's a package manager (with a HUGE community).
There is a lot of development on the homebrew
project and - if you have problems I'd suggest checking out their issues page
So yes you can build it from source and that might seem like a good option right now if you just want mcrypt to work but you may hate yourself for doing this later...
If you don't want to be using php54
there is also the php53
branch. They have some instructions at the repo about how to use both of them / switch between them.
If you're new to homebrew you should know that you check out what else is available using brew search php54
, which gives something like:
php54 php54-lzf php54-snappy
php54-amqp php54-mailparse php54-solr
php54-apc php54-mcrypt php54-ssh2
php54-apcu php54-memcache php54-stats
php54-boxwood php54-memcached php54-svm
php54-chdb php54-midgard2 php54-tidy
php54-couchbase php54-mongo php54-timezonedb
php54-dbase php54-msgpack php54-tokyotyrant
php54-ev php54-mysqlnd_ms php54-twig
php54-gearman php54-oauth php54-uploadprogress
php54-geoip php54-opcache php54-uuid
php54-gmagick php54-parsekit php54-varnish
php54-graphdat php54-pcntl php54-wbxml
php54-http php54-pdflib php54-xcache
php54-igbinary php54-phalcon php54-xdebug
php54-imagick php54-proctitle php54-xhgui
php54-inclued php54-pspell php54-xhp
php54-intl php54-pthreads php54-xhprof
php54-ioncubeloader php54-raphf php54-xmldiff
php54-jsmin php54-redis php54-yac
php54-judy php54-riak php54-yaf
php54-leveldb php54-runkit php54-yaml
php54-libevent php54-scrypt php54-yaz
php54-libvirt
homebrew
to install mcrypt
if at all possibleextension_dir
path and figure out where the mcrypt.so
file is and see if there is a discrepancy (or specify the full path)ArrayList is a Collection of elements (in the form of list), primitive are stored as wrapper class object but at the same time i can store objects of String class as well. SUM will not make sense in that. BTW why are so afraid to use for loop (enhanced or through iterator) anyways?
I've found out a nice workaround to IP blocking when scraping sites. It lets you run a Scraper indefinitely by running it from Google App Engine and redeploying it automatically when you get a 429.
Check out this article
If I remember correctly the user postgres
has no DB password set on Ubuntu by default. That means, that you can login to that account only by using the postgres
OS user account.
Assuming, that you have root
access on the box you can do:
sudo -u postgres psql
If that fails with a database "postgres" does not exists
error, then you are most likely not on a Ubuntu or Debian server :-) In this case simply add template1
to the command:
sudo -u postgres psql template1
If any of those commands fail with an error psql: FATAL: password authentication failed for user "postgres"
then check the file /etc/postgresql/8.4/main/pg_hba.conf
: There must be a line like this as the first non-comment line:
local all postgres ident
For newer versions of PostgreSQL ident
actually might be peer
. That's OK also.
Inside the psql
shell you can give the DB user postgres
a password:
ALTER USER postgres PASSWORD 'newPassword';
You can leave the psql
shell by typing CtrlD or with the command \q
.
Now you should be able to give pgAdmin a valid password for the DB superuser and it will be happy too. :-)
My approach was to make a virtual attribute instead of adding database columns.
class Choice
belongs_to :user
belongs_to :answer
# ------- Helpers -------
def question
answer.question
end
# extra sugar
def question_id
answer.question_id
end
end
This approach is pretty simple, but comes with tradeoffs. It requires Rails to load answer
from the db, and then question
. This can be optimized later by eager loading the associations you need (i.e. c = Choice.first(include: {answer: :question})
), however, if this optimization is necessary, then stephencelis' answer is probably a better performance decision.
There's a time and place for certain choices, and I think this choice is better when prototyping. I wouldn't use it for production code unless I knew it was for an infrequent use case.
i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:
your jQuery script needs to be after the elements you are referring to !
so your script needs to be after the html-code you want to access!
seems like jQuery can't access it otherwise.
Just a simple folder drill down.
sub sample()
Dim FileSystem As Object
Dim HostFolder As String
HostFolder = "C:\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
end sub
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
' Operate on each file
Next
End Sub
A more up to date answer for anyone else who comes across this:
(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)
Compile automatically:
To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option
Show all errors in one place:
The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.
Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.
While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.
I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:
http://docs.sqlalchemy.org/en/latest/orm/tutorial.html
The code would look something like this (to count user objects):
from sqlalchemy import func
session.query(func.count(User.id)).scalar()
For me, the answer that FINALLY WORKED, was the comment from James Shapiro from Alex R's answer (second most upvoted). I got into this API Gateway problem in the first place, by trying to get a static webpage hosted in S3 to use lambda to process the contact-us page and send an email. Simply checking [ ] Default 4XX fixed the error message.
If your existing code is already relying on from datetime import datetime
, you can also simply also import date
from datetime import datetime, timedelta, date
print isinstance(datetime.today().date(), date)
This deals with computational round-off. You set the epsilon as desired:
bool IsInteger(float value)
{
return fabs(ceilf(value) - value) < EPSILON;
}
keep sqljdbc_auth.dll
in your windows/system32 folder and it will work.Download sqljdbc driver from this link Unzip it and you will find sqljdbc_auth.dll
.Now keep the sqljdbc_auth.dll
inside system32 folder and run your program
You can't alloc UIImage, this is impossible. Proper code with UIImageView allocate:
UIImageView *_image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"something.png"]] ;
Draw image:
CGContextDrawImage(context, rect, _image.image.CGImage);
Instead of:
void addStudent(person)
{
return;
}
try this:
void addStudent(student person)
{
return;
}
Since you have already declared a structure called 'student' you don't necessarily have to specify so in the function implementation as in:
void addStudent(struct student person)
{
return;
}
For anyone else who comes here looking, I'm afraid I'm with @usama sulaiman here.
Using the enqueue function provides a safe way to load style sheets and scripts according to the script dependencies and is WordPress' recommended method of achieving what the original poster was trying to achieve. Just think of all the plugins trying to load their own copy of jQuery for instance; you better hope they're using enqueue :D.
Also, wherever possible create a plugin; as adding custom code to your functions file can be pita if you don't have a back-up and you upgrade your theme and overwrite your functions file in the process.
Having a plugin handle this and other custom functions also means you can switch them off if you think their code is clashing with some other plugin or functionality.
Something along the following in a plugin file is what you are looking for:
<?php
/*
Plugin Name: Your plugin name
Description: Your description
Version: 1.0
Author: Your name
Author URI:
Plugin URI:
*/
function $yourJS() {
wp_enqueue_script(
'custom_script',
plugins_url( '/js/your-script.js', __FILE__ ),
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', '$yourJS' );
add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );
function prefix_add_my_stylesheet() {
wp_register_style( 'prefix-style', plugins_url( '/css/your-stylesheet.css', __FILE__ ) );
wp_enqueue_style( 'prefix-style' );
}
?>
Structure your folders as follows:
Plugin Folder
|_ css folder
|_ js folder
|_ plugin.php ...contains the above code - modified of course ;D
Then zip it up and upload it to your WordPress installation using your add plugins interface, activate it and Bob's your uncle.
I know it's not the asnwer to the precise question (Chrome Developer Tools) but I'm using this workaround with success: http://www.telerik.com/fiddler
(pretty sure some of the web devs already know about this tool)
Full docs: http://docs.telerik.com/fiddler/KnowledgeBase/AutoResponder
PS. I would rather have it implemented in Chrome as a flag preserve after reload
, cannot do this now, forums and discussion groups blocked on corporate network :)
Using Java Class
new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
Using Annotation
@JsonIgnoreProperties(ignoreUnknown=true)
I think this is no longer available due to 'security issues'.
console.log(console)
from code gives:
Console
memory: MemoryInfo
profiles: Array[0]
__proto__: Console
From outside of code, _commandLineAPI is available. Kind of annoying because sometimes I want to just log and not see the old output.
Create a button with an id share and add the following code snippet.
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Your body here";
String shareSub = "Your subject here";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
});
The above code snippet will open the share chooser on share button click action. However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.
You can get the events from pygame and then watch out for the KEYDOWN
event, instead of looking at the keys returned by get_pressed()
(which gives you keys that are currently pressed down, whereas the KEYDOWN
event shows you which keys were pressed down on that frame).
What's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
location -= 1
if event.key == pygame.K_RIGHT:
location += 1
To support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.
move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
if move_ticker == 0:
move_ticker = 10
location -= 1
if location == -1:
location = 0
if keys[K_RIGHT]:
if move_ticker == 0:
move_ticker = 10
location+=1
if location == 5:
location = 4
Then somewhere during the game loop you would do something like this:
if move_ticker > 0:
move_ticker -= 1
This would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)
Long after accept answer.
Use sprintf()
, or related functions, as many others have answers suggested, but use a better format specifier.
Using "%.*e"
, code solves various issues:
The maximum buffer size needed is far more reasonable, like 18 for float
(see below). With "%f"
, sprintf(buf, "%f", FLT_MAX);
could need 47+. sprintf(buf, "%f", DBL_MAX);
may need 317+
Using ".*"
allows code to define the number of decimal places needed to distinguish a string version of float x
and it next highest float
. For deatils, see Printf width specifier to maintain precision of floating-point value
Using "%e"
allows code to distinguish small float
s from each other rather than all printing "0.000000"
which is the result when |x| < 0.0000005
.
Example usage
#include <float.h>
#define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4 +1)
// - d . dddddddd e - dddd \0
char buf[FLT_STRING_SIZE];
sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);
Ideas:
IMO, better to use 2x buffer size for scratch pads like buf[FLT_STRING_SIZE*2]
.
For added robustness, use snprintf()
.
As a 2nd alterative consider "%.*g"
. It is like "%f"
for values exponentially near 1.0 and like "%e"
for others.
The guys have given the simple solution, which will do be you should have a look at the help - it's good, looks like a lot in one go but it's actually quick to read:
get-help about_Remote_Troubleshooting | more
use the flex-row-reverse class
<nav class="navbar navbar-toggleable-md navbar-light">
<div class="container">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">
<i class="fa fa-hospital-o fa-2x" aria-hidden="true"></i>
</a>
<div class="collapse navbar-collapse flex-row-reverse" id="navbarNavAltMarkup">
<ul class="navbar-nav">
<li><a class="nav-item nav-link active" href="#" style="background-color:#666">Home <span class="sr-only">(current)</span></a</li>
<li><a class="nav-item nav-link" href="#">Doctors</a></li>
<li><a class="nav-item nav-link" href="#">Specialists</a></li>
<li><a class="nav-item nav-link" href="#">About</a></li>
</ul>
</div>
</div>
</nav>
Latest phpMyAdmin versions require mysqli extension and will no longer work with mysql one (note the extra "i" at the end of its name).
For PHP 5
sudo apt-get install php5-mysqli
For PHP 7.3
sudo apt-get install php7.3-mysqli
Will install package containing both old one and the new one, so afterwards all you need to do is to add
extension=mysqli.so
in your php.ini, under the subject Dynamic Extensions.
Restart apache:
sudo systemctl restart apache2
Authenitacate and press enter.
Should be done! If problem still occurs remove the browser cache.
data = "abcdefg hi j 12345"
digits_count = 0
letters_count = 0
others_count = 0
for i in userinput:
if i.isdigit():
digits_count += 1
elif i.isalpha():
letters_count += 1
else:
others_count += 1
print("Result:")
print("Letters=", letters_count)
print("Digits=", digits_count)
Output:
Please Enter Letters with Numbers:
abcdefg hi j 12345
Result:
Letters = 10
Digits = 5
By using str.isalpha()
you can check if it is a letter.
You can't do that. It's not possible to resize an array. You have to create a new array and copy the data to it:
bArray = addByteToArray(bArray, newByte);
code:
public byte[] addByteToArray(byte[] bArray, byte newByte)
{
byte[] newArray = new byte[bArray.Length + 1];
bArray.CopyTo(newArray, 1);
newArray[0] = newByte;
return newArray;
}
Depending on your needs, like if you want to allow the data to eventually expire or set limitations on how many records to store, you could also look at https://github.com/jmdobry/angular-cache which allows you to define if the cache sits in memory, localStorage, or sessionStorage.
I tried 2 solutions, both work.
Solution_1
.yml
available-users-list:
configurations:
-
username: eXvn817zDinHun2QLQ==
password: IP2qP+BQfWKJMVeY7Q==
-
username: uwJlOl/jP6/fZLMm0w==
password: IP2qP+BQKJLIMVeY7Q==
LoginInfos.java
@ConfigurationProperties(prefix = "available-users-list")
@Configuration
@Component
@Data
public class LoginInfos {
private List<LoginInfo> configurations;
@Data
public static class LoginInfo {
private String username;
private String password;
}
}
List<LoginInfos.LoginInfo> list = loginInfos.getConfigurations();
Solution_2
.yml
available-users-list: '[{"username":"eXvn817zHBVn2QLQ==","password":"IfWKJLIMVeY7Q=="}, {"username":"uwJlOl/g9jP6/0w==","password":"IP2qWKJLIMVeY7Q=="}]'
Java
@Value("${available-users-listt}")
String testList;
ObjectMapper mapper = new ObjectMapper();
LoginInfos.LoginInfo[] array = mapper.readValue(testList, LoginInfos.LoginInfo[].class);
I'd go for recursions:
l = ['a', 'b', 'c', 'd', 'e', ' ']
d = dict([(k, v) for k,v in zip (l[::2], l[1::2])])
There is no "Syntax Error" in the code above - it either ocurred in some other line (the above is not all of your code, as there are no imports, neither the declaration of your path
variable) or you got some other error type.
The example above worked fine for me, testing on the interactive interpreter.
It seems like Error -38 means a state-exception (as the error-message indicates). For example if you call start()
, before the song was ready, or when you call pause()
, even if the song isn't playing at all.
To fix this issue check the state of the mediaPlayer before calling the methods. For example:
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
Additionally, the MediaPlayer is sending event-messages. Even if you do not need the prepared-event (although it would be a good idea to not start the playback before this event was fired) you must set a callback-listener. This also holds true for the OnErrorListener
, OnCompletionListener
, OnPreparedListener
and OnSeekCompletedListener
(if you call the seek method).
Listeners can be attached simply by
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
// Do something. For example: playButton.setEnabled(true);
}
});
Best way to swap images with javascript with left vertical clickable thumbnails
SCRIPT FILE: function swapImages() {
window.onload = function () {
var img = document.getElementById("img_wrap");
var imgall = img.getElementsByTagName("img");
var firstimg = imgall[0]; //first image
for (var a = 0; a <= imgall.length; a++) {
setInterval(function () {
var rand = Math.floor(Math.random() * imgall.length);
firstimg.src = imgall[rand].src;
}, 3000);
imgall[1].onmouseover = function () {
//alert("what");
clearInterval();
firstimg.src = imgall[1].src;
}
imgall[2].onmouseover = function () {
clearInterval();
firstimg.src = imgall[2].src;
}
imgall[3].onmouseover = function () {
clearInterval();
firstimg.src = imgall[3].src;
}
imgall[4].onmouseover = function () {
clearInterval();
firstimg.src = imgall[4].src;
}
imgall[5].onmouseover = function () {
clearInterval();
firstimg.src = imgall[5].src;
}
}
}
}
For Excel 2013:
http://blogmines.com/blog/how-to-import-text-file-in-excel-2013/
When I
git init
a folder it doesn't create a master branch
This is true, and expected behaviour. Git will not create a master
branch until you commit something.
When I do
git --bare init
it creates the files.
A non-bare git init
will also create the same files, in a hidden .git
directory in the root of your project.
When I type
git branch master
it says "fatal: Not a valid object name: 'master'"
That is again correct behaviour. Until you commit, there is no master branch.
You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add
them to prepare a commit. Then git commit
to create your initial commit and master
branch.
To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100
in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application.
If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.
It's worth to mention that using concerns is considered bad idea by many.
Some reasons:
include
method, there is a whole dependency handling system - way too much complexity for something that's trivial good old Ruby mixin pattern.Concerns are easy way to shoot yourself in the leg, be careful with them.
@crobar, you are right that there is a dearth of multi-file examples, so I decided to share the following in the hopes that it helps others:
::::::::::::::
main.cpp
::::::::::::::
#include <iostream>
#include "UseSomething.h"
#include "Something.h"
int main()
{
UseSomething y;
std::cout << y.getValue() << '\n';
}
::::::::::::::
Something.h
::::::::::::::
#ifndef SOMETHING_H_
#define SOMETHING_H_
class Something
{
private:
static int s_value;
public:
static int getValue() { return s_value; } // static member function
};
#endif
::::::::::::::
Something.cpp
::::::::::::::
#include "Something.h"
int Something::s_value = 1; // initializer
::::::::::::::
UseSomething.h
::::::::::::::
#ifndef USESOMETHING_H_
#define USESOMETHING_H_
class UseSomething
{
public:
int getValue();
};
#endif
::::::::::::::
UseSomething.cpp
::::::::::::::
#include "UseSomething.h"
#include "Something.h"
int UseSomething::getValue()
{
return(Something::getValue());
}
It's a shorthand for <?php echo $a; ?>
.
It's enabled by default since 5.4 regardless of php.ini
settings.
We can create a new CSS class for div.
.div {
position: absolute;
left: 150px;
width: 200px;
height: 120px;
}
:
is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]
[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"
Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.
Works with tuples and strings, too.
This is one way of doing it:
datagridview.DataSource = null;
datagridview.Refresh();
I hope it works for you because it is working for me.
I think following function with time complexity of o(log n) will be better.
function palindrom(s){
s = s.toString();
var f = true; l = s.length/2, len = s.length -1;
for(var i=0; i < l; i++){
if(s[i] != s[len - i]){
f = false;
break;
}
}
return f;
}
console.log(palindrom(12321));
This is what I've done for Angular 4:
<style type="text/css">
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transform: -webkit-translate(-50%, -50%);
transform: -moz-translate(-50%, -50%);
transform: -ms-translate(-50%, -50%);
color:darkred;
}
</style>
</head>
<body>
<app-root>
<div class="centered">
<h1>Loading...</h1>
</div>
</app-root>
</body>
Simply add below maven jar version in properties tag in pom.xml, <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
Then follow below steps,
Step 1: mvn clean
Step 2 : update project
Problem solved for me! You should also try this :)
There's a bug here: currently cannot pass arguments to str.lstrip
and str.rstrip
:
http://github.com/pydata/pandas/issues/2411
EDIT: 2012-12-07 this works now on the dev branch:
In [8]: df['result'].str.lstrip('+-').str.rstrip('aAbBcC')
Out[8]:
1 52
2 62
3 44
4 30
5 110
Name: result
You're checking if the result of IndexOf is larger or equal 0, meaning whether the match starts anywhere in the string. Try checking if it's equal to 0:
if (testList.FindAll(x => x.IndexOf(keyword,
StringComparison.OrdinalIgnoreCase) >= 0).Count > 0)
Console.WriteLine("Found in list");
Now "goat" and "oat" won't match, but "goat" and "goa" will. To avoid this, you can compare the lenghts of the two strings.
To avoid all this complication, you can use a dictionary instead of a list. They key would be the lowercase string, and the value would be the real string. This way, performance isn't hurt because you don't have to use ToLower
for each comparison, but you can still use Contains
.
(This method works for if
s, multiple nested loops and other constructs that you can't break
from easily.)
Wrap the code in its own function. Instead of break
, use return
.
Example:
def some_function():
if condition_a:
# do something and return early
...
return
...
if condition_b:
# do something else and return early
...
return
...
return
if outer_condition:
...
some_function()
...
$ b=$( ( a=$( (echo stdout;echo stderr >&2) ) ) 2>&1 )
$ echo "a=>$a b=>$b"
a=>stdout b=>stderr
In Windows, you can also use ctypes with GetSystemMetrics()
:
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
so that you don't need to install the pywin32 package; it doesn't need anything that doesn't come with Python itself.
For multi-monitor setups, you can retrieve the combined width and height of the virtual monitor:
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(78), user32.GetSystemMetrics(79)
Maybe you simply want the standard format string "N"
, as in
number.ToString("N")
It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo
) you use, as does the number of decimals (which will normally by 2, as you require).
If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N
, as in .ToString("N2")
.
Edit: The sizes of the groups between the commas are governed by the
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes
array, given that you don't specify a special format provider.
View
<div ng-app="myapp">
{{AssignedDate.now() | date:'yyyy-MM-dd HH:mm:ss'}}
</div>
Controller
var app = angular.module('myapp',[])
app.run(function($rootScope){
$rootScope.AssignedDate = Date;
})
input[type="text"], textarea {
background-color : #d1d1d1;
}
Hope that helps :)
Edit: working example, http://jsfiddle.net/C5WxK/
Take a look at the very recently released SSHD, which is based on the Apache MINA project.
The accepted answer works, but if:
use this:
.centered {
position: fixed; /* or absolute */
top: 50%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
}
More information about centering content in this excellent CSS-Tricks article.
.center{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
Another great guide about flexboxs from CSS Tricks; http://css-tricks.com/snippets/css/a-guide-to-flexbox/
I did it like this
func showAlert() {
let alert = UIAlertController(title: "Thanks!", message: "We'll get back to you as soon as posible.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
self.dismissView()
}))
self.present(alert, animated: true)
}
func dismissView() {
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
}
its even easier:
fileList.Where(item => filterList.Contains(item))
in case you want to filter not for an exact match but for a "contains" you can use this expression:
var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));
I updated Visual Studio 2015 update 2 to Visual Studio 2015 update 3, and it solved my problem.
you can use setAccessibilityIdentifier method for any subclass of UIView
UIImageView *image ;
[image setAccessibilityIdentifier:@"file name"] ;
NSString *file_name = [image accessibilityIdentifier] ;
In my experience, I had to stop my existing service to update code. after updating the code and while START the Service I got the same error "Error 1053 the service did not respond to the start or control request in a timely fashion".
But this got resolve after RESTARTING THE MACHINE.
By default Mocha will read a file named test/mocha.opts
that can contain command line arguments. So you could create such a file that contains:
--timeout 5000
Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.
Another way which may be better depending on your situation is to set it like this in a top level describe
call in your test file:
describe("something", function () {
this.timeout(5000);
// tests...
});
This would allow you to set a timeout only on a per-file basis.
You could use both methods if you want a global default of 5000 but set something different for some files.
Note that you cannot generally use an arrow function if you are going to call this.timeout
(or access any other member of this
that Mocha sets for you). For instance, this will usually not work:
describe("something", () => {
this.timeout(5000); //will not work
// tests...
});
This is because an arrow function takes this
from the scope the function appears in. Mocha will call the function with a good value for this
but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:
Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.
You can use the DataGridView refresh method. But... in a lot of cases you have to refresh the DataGridView from methods running on a different thread than the one where the DataGridView is running. In order to do that you should implement the following method and call it rather than directly typing DataGridView.Refresh():
private void RefreshGridView()
{
if (dataGridView1.InvokeRequired)
{
dataGridView1.Invoke((MethodInvoker)delegate ()
{
RefreshGridView();
});
}
else
dataGridView1.Refresh();
}
!
is non-null assertion operator (post-fix expression) - it just saying to type checker that you're sure that a
is not null
or undefined
.
the operation
a!
produces a value of the type ofa
withnull
andundefined
excluded
Optional chaining finally made it to typescript (3.7)
The optional chaining operator
?.
permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The?.
operator functions similarly to the.
chaining operator, except that instead of causing an error if a reference is nullish (null
orundefined
), the expression short-circuits with a return value ofundefined
. When used with function calls, it returnsundefined
if the given function does not exist.
Syntax:
obj?.prop // Accessing object's property
obj?.[expr] // Optional chaining with expressions
arr?.[index] // Array item access with optional chaining
func?.(args) // Optional chaining with function calls
Pay attention:
Optional chaining is not valid on the left-hand side of an assignment
const object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
There is no jquery needed:
var matchedPosition = str.search(/[a-z]/i);
if(matchedPosition != -1) {
alert('found');
}
Use XStream toXML/fromXML in memory. Extremely fast and has been around for a long time and is going strong. Objects don't need to be Serializable and you don't have use reflection (although XStream does). XStream can discern variables that point to the same object and not accidentally make two full copies of the instance. A lot of details like that have been hammered out over the years. I've used it for a number of years and it is a go to. It's about as easy to use as you can imagine.
new XStream().toXML(myObj)
or
new XStream().fromXML(myXML)
To clone,
new XStream().fromXML(new XStream().toXML(myObj))
More succinctly:
XStream x = new XStream();
Object myClone = x.fromXML(x.toXML(myObj));
I think error is not coming from the specified line but from the first 3 lines. Try this instead :
node {
stage("first") {
def foo = "foo"
sh "echo ${foo}"
}
}
I think you had some extra lines that are not valid...
From declaractive pipeline model documentation, it seems that you have to use an environment
declaration block to declare your variables, e.g.:
pipeline {
environment {
FOO = "foo"
}
agent none
stages {
stage("first") {
sh "echo ${FOO}"
}
}
}
Somebody was asking about list of formatting mailing addresses, and I think this is what he was looking for...
Frank's Compulsive Guide to Postal Addresses: http://www.columbia.edu/~fdc/postal/ Doesn't help much with street-level issues, however.
My work uses a couple of tools to assist with this: - Lexis-Nexis services, including NCOA lookups (you'll get address standardization for "free") - "Melissa Data" http://www.melissadata.com
777
is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.. in general we give this permission to assets which are not much needed to be hidden from public on a web server, for example images..
You said I am using windows 7.
if that means that your web server is Windows based then you should login to that and right click the folder and set permissions to everyone
and if you are on a windows client and server is unix/linux based then use some ftp software and in the parent directory right click and change the permission for the folder.
If you want permission to be set on sub-directories
too then usually their is option to set permission recursively use that.
And, if you feel like doing it from command line the use putty and login to server and go to the parent directory includes
and write the following command
chmod 0777 module_installation/
for recursive
chmod -R 0777 module_installation/
Hope this will help you
You can use stri_detect_fixed function from stringi
package
stri_detect_fixed(c("REVERSE223","GENJJS"),"REVERSE")
[1] TRUE FALSE
google play service is just a library to create application but in order to use application that use google play service library , you need to install google play in your emulator.and for that it need the unique device id. and device id is only on the real device not have on emulator. so for testing it , you need real android device.
SELECT p.pid, p.cid, p.pname, c1.name1, c2.name2
FROM product p
LEFT JOIN customer1 c1 ON p.cid = c1.cid
LEFT JOIN customer2 c2 ON p.cid = c2.cid
I note that the question is simply, "Is there any other way to break all of the loops?" I don't see any qualification but that it not be goto
, in particular the OP didn't ask for a good way. So, how about we longjmp
out of the inner loop? :-)
#include <stdio.h>
#include <setjmp.h>
int main(int argc, char* argv[]) {
int counter = 0;
jmp_buf look_ma_no_goto;
if (!setjmp(look_ma_no_goto)) {
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if (i == 500 && j == 500) {
longjmp(look_ma_no_goto, 1);
}
counter++;
}
}
}
printf("counter=%d\n", counter);
}
The setjmp
function returns twice. The first time, it returns 0 and the program executes the nested for loops. Then when the both i
and j
are 500, it executes longjmp
, which causes setjmp
to return again with the value 1, skipping over the loop.
Not only will longjmp
get you out of nested loops, it works with nested functions too!
I would use lambda
function on a Series
of a DataFrame
like this:
f = lambda x: 0 if x>100 else 1
df['my_column'] = df['my_column'].map(f)
I do not assert that this is an efficient way, but it works fine.
Apple provides detailed, illustrated instructions covering every step of the process. Log in to the iPhone developer site and click the "program portal" link. In the program portal you'll find a link to the program portal user's guide, which is a really good reference and guide on this topic.
My solution to this is pretty unbelievable.
<script type="text/javascript" src="/js/dataLayer.js?v=1"></script>
The filename in the src attribute needed to be lowercase:
<script type="text/javascript" src="/js/datalayer.js?v=1"></script>
and that somewhat inexplicably fixed the problem.
In both cases the reference was returning 404 for testing.
There are many methods to this, here are some of them:
Using the predefined str
method islower()
:
>>> c = 'a'
>>> c.islower()
True
Using the ord()
function to check whether the ASCII code of the letter is in the range of the ASCII codes of the lowercase characters:
>>> c = 'a'
>>> ord(c) in range(97, 123)
True
Checking if the letter is equal to it's lowercase form:
>>> c = 'a'
>>> c.lower() == c
True
Checking if the letter is in the list ascii_lowercase
of the string
module:
>>> from string import ascii_lowercase
>>> c = 'a'
>>> c in ascii_lowercase
True
But that may not be all, you can find your own ways if you don't like these ones: D.
Finally, let's start detecting:
d = str(input('enter a string : '))
lowers = [c for c in d if c.islower()]
# here i used islower() because it's the shortest and most-reliable
# one (being a predefined function), using this list comprehension
# is (probably) the most efficient way of doing this
Math.Pow()
returns double
so nice would be to write like this:
double d = Math.Pow(100.00, 3.00);
One line after form InitializeComponent();
cbo_MyDropBox.Text = "Select a server...";
You only need it once right? All you need to do if a pick is mandatory is check if the box index != -1
. Could anyone elaborate why the other answers jump through hoops to get this going?
The only thing I'm missing here is having just this initial text grayed out. If you really want that just use a label in front and turn it off once the index is changed.
They each return the same singleton None
-- There is no functional difference.
I think that it is reasonably idiomatic to leave off the return
statement unless you need it to break out of the function early (in which case a bare return
is more common), or return something other than None
. It also makes sense and seems to be idiomatic to write return None
when it is in a function that has another path that returns something other than None
. Writing return None
out explicitly is a visual cue to the reader that there's another branch which returns something more interesting (and that calling code will probably need to handle both types of return values).
Often in Python, functions which return None
are used like void
functions in C -- Their purpose is generally to operate on the input arguments in place (unless you're using global data (shudders)). Returning None
usually makes it more explicit that the arguments were mutated. This makes it a little more clear why it makes sense to leave off the return
statement from a "language conventions" standpoint.
That said, if you're working in a code base that already has pre-set conventions around these things, I'd definitely follow suit to help the code base stay uniform...
Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.
Make sure nginx has http dav module enabled, it should, but nonetheless verify it.
Configure nginx http dav module:
In Windows: d:\servers\nginx\nginx.conf
location / {
# maven repository
dav_methods PUT DELETE MKCOL COPY MOVE;
create_full_put_path on;
dav_access user:rw group:rw all:r;
}
In Linux (Ubuntu): /etc/nginx/sites-available/default
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
# try_files $uri $uri/ =404; # IMPORTANT comment this
dav_methods PUT DELETE MKCOL COPY MOVE;
create_full_put_path on;
dav_access user:rw group:rw all:r;
}
Don't forget to give permissions to the directory where the repo will be located:
sudo chmod +777 /var/www/html/repository
In your project's pom.xml
add the respective configuration:
Retrieve artifacts:
<repositories>
<repository>
<id>repository</id>
<url>http://<your.ip.or.hostname>/repository</url>
</repository>
</repositories>
Publish artifacts:
<build>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-http</artifactId>
<version>3.2.0</version>
</extension>
</extensions>
</build>
<distributionManagement>
<repository>
<id>repository</id>
<url>http://<your.ip.or.hostname>/repository</url>
</repository>
</distributionManagement>
To publish artifacts use mvn deploy
. To retrieve artifacts, maven will do it automatically.
And there you have it a simple maven repo.
On UNIX systems, you can use sigaction
call to register a signal handler for SIGINT
signal which represents the Control+C key sequence. The signal handler can set a flag which will be checked in the loop making it to break appropriately.
You can do it like this:
angular.element('#modal').modal('hide');
You're trying to use a dict
as a key to another dict
or in a set
. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:
>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:
>>> key = frozenset(dict_key.items())
Now you may use key
as a key in a dict
or set
:
>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}
Of course you need to repeat the exercise whenever you want to look up something using a dict:
>>> some_dict[dict_key] # Doesn't work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())] # Works
True
If the dict
you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:
def freeze(d):
if isinstance(d, dict):
return frozenset((key, freeze(value)) for key, value in d.items())
elif isinstance(d, list):
return tuple(freeze(value) for value in d)
return d
You must use Color.FromArgb method to create new color structure
var newColor = Color.FromArgb(0xCC,0xBB,0xAA);
Facing Same issues following Link helped solving the problem. The above solutions were not helpful for me. deployment-failed-could-not-access-the-package-manager-is-the-system-running
By restarting server using CMD application was back to work. Open cmd (Run as administrator), open this
cd C:\Program Files (x86)\Android\android-sdk\platform-tools
(this path must specify your android-sdk installation folder )
Now, first write,
adb kill-server
and then adb start-server
.
String text = "In early March, the city of Topeka, Kansas," + "<br>" +
"temporarily changed its name to Google..." + "<br>" + "<br>" +
"...in an attempt to capture a spot" + "<br>" +
"in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
"source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");
for xampp vm on MacOS capitan, high sierra, MacOS Mojave (10.12+), you can follow these
1. mount /opt/lampp
2. explore the folder
3. open terminal from the folder
4. cd to `htdocs`>yourapp (ex: techaz.co)
5. vim .htaccess
6. paste your .htaccess content (that is suggested on options-permalink.php)
SELECT id, GROUP_CONCAT(CONCAT_WS(':', Name, CAST(Value AS CHAR(7))) SEPARATOR ',') AS result
FROM test GROUP BY id
you must use cast or convert, otherwise will be return BLOB
result is
id Column
1 A:4,A:5,B:8
2 C:9
you have to handle result once again by program such as python or java
Here's an example of a transaction that will rollback on error and return the error code.
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_CREATE_SERVER_USER`(
IN P_server_id VARCHAR(100),
IN P_db_user_pw_creds VARCHAR(32),
IN p_premium_status_name VARCHAR(100),
IN P_premium_status_limit INT,
IN P_user_tag VARCHAR(255),
IN P_first_name VARCHAR(50),
IN P_last_name VARCHAR(50)
)
BEGIN
DECLARE errno INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET CURRENT DIAGNOSTICS CONDITION 1 errno = MYSQL_ERRNO;
SELECT errno AS MYSQL_ERROR;
ROLLBACK;
END;
START TRANSACTION;
INSERT INTO server_users(server_id, db_user_pw_creds, premium_status_name, premium_status_limit)
VALUES(P_server_id, P_db_user_pw_creds, P_premium_status_name, P_premium_status_limit);
INSERT INTO client_users(user_id, server_id, user_tag, first_name, last_name, lat, lng)
VALUES(P_server_id, P_server_id, P_user_tag, P_first_name, P_last_name, 0, 0);
COMMIT WORK;
END$$
DELIMITER ;
This is assuming that autocommit is set to 0. Hope this helps.
Caveat: you can't prevent users from pirating, but only make it easier for honest users to do the right thing.
Assuming you don't want to do a special build for each user, then:
But, I repeat: this won't prevent piracy
I have recently read that this approach is not cryptographically very sound. But this solution is already weak (as the software itself has to include the secret key somewhere), so I don't think this discovery invalidates the solution as far as it goes.
Just thought I really ought to mention this, though; if you're planning to derive something else from this, beware.
I'm new in ASP.NET MVC. I faced the same problem, the following is my workable in my Erorr.vbhtml (it work if you only need to log the error using Elmah log)
@ModelType System.Web.Mvc.HandleErrorInfo
@Code
ViewData("Title") = "Error"
Dim item As HandleErrorInfo = CType(Model, HandleErrorInfo)
//To log error with Elmah
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(New Elmah.Error(Model.Exception, HttpContext.Current))
End Code
<h2>
Sorry, an error occurred while processing your request.<br />
@item.ActionName<br />
@item.ControllerName<br />
@item.Exception.Message
</h2>
It is simply!
The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.
import numpy as np
names = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 , 0.5678 , 0.9123 ])
ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats
np.savetxt('test.txt', ab, fmt="%10s %10.3f")
Update: This example also works properly in Python 3 by using the 'U6'
Unicode string dtype, when creating the ab
structured array, instead of the 'S6'
byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1'
in Python 3.
R has gotten to the point where the OS cannot allocate it another 75.1Mb chunk of RAM. That is the size of memory chunk required to do the next sub-operation. It is not a statement about the amount of contiguous RAM required to complete the entire process. By this point, all your available RAM is exhausted but you need more memory to continue and the OS is unable to make more RAM available to R.
Potential solutions to this are manifold. The obvious one is get hold of a 64-bit machine with more RAM. I forget the details but IIRC on 32-bit Windows, any single process can only use a limited amount of RAM (2GB?) and regardless Windows will retain a chunk of memory for itself, so the RAM available to R will be somewhat less than the 3.4Gb you have. On 64-bit Windows R will be able to use more RAM and the maximum amount of RAM you can fit/install will be increased.
If that is not possible, then consider an alternative approach; perhaps do your simulations in batches with the n per batch much smaller than N
. That way you can draw a much smaller number of simulations, do whatever you wanted, collect results, then repeat this process until you have done sufficient simulations. You don't show what N
is, but I suspect it is big, so try smaller N
a number of times to give you N
over-all.
How to implement:
import 'package:intl/intl.dart';
getCustomFormattedDateTime(String givenDateTime, String dateFormat) {
// dateFormat = 'MM/dd/yy';
final DateTime docDateTime = DateTime.parse(givenDateTime);
return DateFormat(dateFormat).format(docDateTime);
}
How to call:
getCustomFormattedDateTime('2021-02-15T18:42:49.608466Z', 'MM/dd/yy');
Result:
02/15/21
Above code solved my problem. I hope, this will also help you. Thanks for asking this question.
To have multiple Inline styles in React.
<div onClick={eleTemplate} style={{'width': '50%', textAlign: 'center'}}/>
Update
I also implemented the following solution in my Python script here on GitHub.
I also verified that damaged files (jpg) frequently are not 'broken' images i.e, a damaged picture file sometimes remains a legit picture file, the original image is lost or altered but you are still able to load it with no errors. But, file truncation cause always errors.
End Update
You can use Python Pillow(PIL) module, with most image formats, to check if a file is a valid and intact image file.
In the case you aim at detecting also broken images, @Nadia Alramli correctly suggests the im.verify()
method, but this does not detect all the possible image defects, e.g., im.verify
does not detect truncated images (that most viewers often load with a greyed area).
Pillow is able to detect these type of defects too, but you have to apply image manipulation or image decode/recode in or to trigger the check. Finally I suggest to use this code:
try:
im = Image.load(filename)
im.verify() #I perform also verify, don't know if he sees other types o defects
im.close() #reload is necessary in my case
im = Image.load(filename)
im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
im.close()
except:
#manage excetions here
In case of image defects this code will raise an exception. Please consider that im.verify is about 100 times faster than performing the image manipulation (and I think that flip is one of the cheaper transformations). With this code you are going to verify a set of images at about 10 MBytes/sec with standard Pillow or 40 MBytes/sec with Pillow-SIMD module (modern 2.5Ghz x86_64 CPU).
For the other formats psd,xcf,.. you can use Imagemagick wrapper Wand, the code is as follows:
im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()
But, from my experiments Wand does not detect truncated images, I think it loads lacking parts as greyed area without prompting.
I red that Imagemagick has an external command identify that could make the job, but I have not found a way to invoke that function programmatically and I have not tested this route.
I suggest to always perform a preliminary check, check the filesize to not be zero (or very small), is a very cheap idea:
statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
#manage here the 'faulty image' case
@Hung Tran's answer works perfect. As an improvement, I would suggest not showing values that are 0. Say you have 5 elements and 2 of them are 0 and rest of them have values, the solution above will show 0 and 0%. It is better to filter that out with a not equal to 0 check!
var val = dataset.data[i]; var percent = String(Math.round(val/total*100)) + "%"; if(val != 0) { ctx.fillText(dataset.data[i], model.x + x, model.y + y); // Display percent in another line, line break doesn't work for fillText ctx.fillText(percent, model.x + x, model.y + y + 15); }
Updated code below:
var data = {
datasets: [{
data: [
11,
16,
7,
3,
14
],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
}],
labels: [
"Red",
"Green",
"Yellow",
"Grey",
"Blue"
]
};
var pieOptions = {
events: false,
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
total = dataset._meta[Object.keys(dataset._meta)[0]].total,
mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
start_angle = model.startAngle,
end_angle = model.endAngle,
mid_angle = start_angle + (end_angle - start_angle)/2;
var x = mid_radius * Math.cos(mid_angle);
var y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
if (i == 3){ // Darker text color for lighter background
ctx.fillStyle = '#444';
}
var val = dataset.data[i];
var percent = String(Math.round(val/total*100)) + "%";
if(val != 0) {
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
// Display percent in another line, line break doesn't work for fillText
ctx.fillText(percent, model.x + x, model.y + y + 15);
}
}
});
}
}
};
var pieChartCanvas = $("#pieChart");
var pieChart = new Chart(pieChartCanvas, {
type: 'pie', // or doughnut
data: data,
options: pieOptions
});
On some systems (Windows with VC springs to mind, currently), RAND_MAX
is ridiculously small, i. e. only 15 bit. When dividing by RAND_MAX
you are only generating a mantissa of 15 bit instead of the 23 possible bits. This may or may not be a problem for you, but you're missing out some values in that case.
Oh, just noticed that there was already a comment for that problem. Anyway, here's some code that might solve this for you:
float r = (float)((rand() << 15 + rand()) & ((1 << 24) - 1)) / (1 << 24);
Untested, but might work :-)
in your css:
.selected{
background: #F00;
}
in the jquery:
$("#data tr").click(function(){
$(this).toggleClass('selected');
});
Basically you create a class and adds/removes it from the selected row.
Btw you could have shown more effort, there's no css or jquery/js at all in your code xD
I don't think the scrollTop is a valid property. If you want to animate scrolling, try the scrollTo plugin for jquery
A query of type MyEntity
is going to return MyEntity
. You want a query for a Long
.
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.
:set go=a
ggVG
See :help go-a
:
'a' Autoselect: If present, then whenever VISUAL mode is started,
or the Visual area extended, Vim tries to become the owner of
the windowing system's global selection. This means that the
Visually highlighted text is available for pasting into other
applications as well as into Vim itself. When the Visual mode
ends, possibly due to an operation on the text, or when an
application wants to paste the selection, the highlighted text
is automatically yanked into the "* selection register.
Thus the selection is still available for pasting into other
applications after the VISUAL mode has ended.
If not present, then Vim won't become the owner of the
windowing system's global selection unless explicitly told to
by a yank or delete operation for the "* register.
The same applies to the modeless selection.
If you don't want to go down the VBA path, there is this trick from a previous question.
Excel 2010: how to use autocomplete in validation list
It does add some annoying bulk to the top of your sheets, and potential maintenance (should you need more options, adding names of people from a staff list, new projects etc.) but works all the same.
This answer similar to others, but using preferred stringr::str_detect
and dplyr rownames_to_column
.
library(tidyverse)
mtcars %>%
rownames_to_column("type") %>%
filter(stringr::str_detect(type, 'Toyota|Mazda') )
#> type mpg cyl disp hp drat wt qsec vs am gear carb
#> 1 Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 2 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 3 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
#> 4 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
Created on 2018-06-26 by the reprex package (v0.2.0).
I'd like to suggest automatic way with gradle only
** Define also at least one additional param for keystore in last command e.g. country '-dname', 'c=RU'
**
apply plugin: 'com.android.application'
// define here sign properties
def sPassword = 'storePassword_here'
def kAlias = 'keyAlias_here'
def kPassword = 'keyPassword_here'
android {
...
signingConfigs {
release {
storeFile file("keystore/release.jks")
storePassword sPassword
keyAlias kAlias
keyPassword kPassword
}
}
buildTypes {
debug {
signingConfig signingConfigs.release
}
release {
shrinkResources true
minifyEnabled true
useProguard true
signingConfig signingConfigs.release
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
...
}
...
task generateKeystore() {
exec {
workingDir projectDir
commandLine 'mkdir', '-p', 'keystore'
}
exec {
workingDir projectDir
commandLine 'rm', '-f', 'keystore/release.jks'
}
exec {
workingDir projectDir
commandLine 'keytool', '-genkey', '-noprompt', '-keystore', 'keystore/release.jks',
'-alias', kAlias, '-storepass', sPassword, '-keypass', kPassword, '-dname', 'c=RU',
'-keyalg', 'RSA', '-keysize', '2048', '-validity', '10000'
}
}
project.afterEvaluate {
preBuild.dependsOn generateKeystore
}
This will generate keystore on project sync and build
> Task :app:generateKeystore UP-TO-DATE
> Task :app:preBuild UP-TO-DATE
Private Sub Click_Click()
Dim vaFiles As Variant
Dim i As Long
For j = 1 To 2
vaFiles = Application.GetOpenFilename _
(FileFilter:="Excel Filer (*.xlsx),*.xlsx", _
Title:="Open File(s)", MultiSelect:=True)
If Not IsArray(vaFiles) Then Exit Sub
With Application
.ScreenUpdating = False
For i = 1 To UBound(vaFiles)
Workbooks.Open vaFiles(i)
wrkbk_name = vaFiles(i)
Next i
.ScreenUpdating = True
End With
If j = 1 Then
work1 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
Else: work2 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
End If
Next j
'Filling the values of the group name
'check = Application.WorksheetFunction.Search(Name, work1)
check = InStr(UCase("Qoute Request"), work1)
If check = 1 Then
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
End If
ActiveWorkbook.Sheets("GI Quote Request").Select
ActiveSheet.Range("B4:C12").Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Range("K3").Select
ActiveSheet.Paste
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
Range("D3").Value = Range("L3").Value
Range("D7").Value = Range("L9").Value
Range("D11").Value = Range("L7").Value
For i = 4 To 5
If i = 5 Then
GoTo NextIteration
End If
If Left(ActiveSheet.Range("B" & i).Value, Len(ActiveSheet.Range("B" & i).Value) - 1) = Range("K" & i).Value Then
ActiveSheet.Range("D" & i).Value = Range("L" & i).Value
End If
NextIteration:
Next i
'eligibles part
Count = Range("D11").Value
For i = 27 To Count + 24
Range("C" & i).EntireRow.Offset(1, 0).Insert
Next i
check = Left(work1, InStrRev(work1, ".") - 1)
'check = InStr("Census", work1)
If check = "Census" Then
workbk = work1
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
workbk = work2
End If
'DOB
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("D2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
ActiveSheet.Range("C27").Select
ActiveSheet.Paste
'Gender
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("C2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False
ActiveSheet.Range("k27").Select
ActiveSheet.Paste
For i = 27 To Count + 27
ActiveSheet.Range("E" & i).Value = Left(ActiveSheet.Range("k" & i).Value, 1)
Next i
'Salary
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("N2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False
ActiveSheet.Range("F27").Select
ActiveSheet.Paste
ActiveSheet.Range("K3:L" & Count).Select
selction.ClearContents
End Sub
The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize queue
to null when you declare it.
Queue queue = null;
These commands fixed the issue for me,
sudo rm /var/lib/mongodb/mongod.lock
sudo mongod --repair
sudo service mongod start
sudo service mongod status
If you are behind proxy, use:-
export http_proxy="http://username:[email protected]:port/"
export https_proxy="http://username:[email protected]:port/"
Reference: https://stackoverflow.com/a/24410282/4359237
The problem is an issue of semantic meaning (as BoltClock mentions) and visual rendering.
Originally HTML used <b>
and <i>
for these purposes, entirely stylistic commands, laid down in the semantic environment of the document markup. CSS is an attempt to separate out as far as possible the stylistic elements of the medium. Thus style information such as bold and italics should go in CSS.
<strong>
and <em>
were introduced to fill the semantic need for text to be marked as more important or stressed. They have default stylistic interpretations akin to bold and italic, but they are not bound to that fate.
According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.
This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.
select num_rows from all_tables where table_name = 'MY_TABLE'
This query counts the current number of rows in MY_TABLE
select count(*) from my_table
By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.
In the documentation there's an asterisk by the column name, which leads to this note:
Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.
This means that unless you have gathered statistics on the table then this column will not have any data.
Statistics gathered in 11g+ with the default estimate_percent
, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent
less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.
If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.
Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.
The line should read either:
0 0-23/2 * * * /home/username/test.sh
or
0 0,2,4,6,8,10,12,14,16,18,20,22 * * * /home/username/test.sh
set
is used to assign a reference to an object. The C equivalent would be
int i;
int* ref_i;
i = 4; // Assigning a value (in VBA: i = 4)
ref_i = &i; //assigning a reference (in VBA: set ref_i = i)
var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +' value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
});
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);
hash: Nowadays webGL2.0 is there so integers are available in (w)GLSL. -> for quality portable hash (at similar cost than ugly float hashes) we can now use "serious" hashing techniques. IQ implemented some in https://www.shadertoy.com/view/XlXcW4 (and more)
E.g.:
const uint k = 1103515245U; // GLIB C
//const uint k = 134775813U; // Delphi and Turbo Pascal
//const uint k = 20170906U; // Today's date (use three days ago's dateif you want a prime)
//const uint k = 1664525U; // Numerical Recipes
vec3 hash( uvec3 x )
{
x = ((x>>8U)^x.yzx)*k;
x = ((x>>8U)^x.yzx)*k;
x = ((x>>8U)^x.yzx)*k;
return vec3(x)*(1.0/float(0xffffffffU));
}
To achieve goto-like functionality while keeping the call stack clean, I am using this method:
// in other languages:
// tag1:
// doSomething();
// tag2:
// doMoreThings();
// if (someCondition) goto tag1;
// if (otherCondition) goto tag2;
function tag1() {
doSomething();
setTimeout(tag2, 0); // optional, alternatively just tag2();
}
function tag2() {
doMoreThings();
if (someCondition) {
setTimeout(tag1, 0); // those 2 lines
return; // imitate goto
}
if (otherCondition) {
setTimeout(tag2, 0); // those 2 lines
return; // imitate goto
}
setTimeout(tag3, 0); // optional, alternatively just tag3();
}
// ...
Please note that this code is slow since the function calls are added to timeouts queue, which is evaluated later, in browser's update loop.
Please also note that you can pass arguments (using setTimeout(func, 0, arg1, args...)
in browser newer than IE9, or setTimeout(function(){func(arg1, args...)}, 0)
in older browsers.
AFAIK, you shouldn't ever run into a case that requires this method unless you need to pause a non-parallelable loop in an environment without async/await support.
You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example
class Example {
public static string NonInstanceMethod() {
return "static";
}
public string InstanceMethod() {
return "non-static";
}
}
static void SomeMethod() {
Console.WriteLine(Example.NonInstanceMethod());
Console.WriteLine(Example.InstanceMethod()); // Does not compile
Example v1 = new Example();
Console.WriteLine(v1.InstanceMethod());
}
your_string = 'Hello world';
words_array = your_tring.split(' ');
string_without_space = '';
for(i=0; i<words_array.length; i++){
new_text += words_array[i];
}
console.log("The new word:" new_text);
The output:
HelloWorld
In my case I had a naked --env
switch, i.e. one without an actual variable name or value, e.g.:
docker run \
--env \ <----- This was the offending item
--rm \
--volume "/home/shared:/shared" "$(docker build . -q)"
You want to add the IN()
clause to your WHERE
SELECT *
FROM `Buses`
WHERE `BusID` IN (Id1, ID2, ID3,.... put your ids here)
If you have a list of Ids stored in a table you can also do this:
SELECT *
FROM `Buses`
WHERE `BusID` IN (SELECT Id FROM table)
Change the code where you load the partial view to:
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable
I finally understood what was going on.
When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.
When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.
My test now works just fine.
Definitely compact
is the best approach for solving this task. However, we can achieve the same result just with a simple subtraction:
[1, nil, 3, nil, nil] - [nil]
=> [1, 3]
I was searching for the option where I can define the line range and found the answer. For example I want to change host1 to host2 from line 36-57.
sed '36,57 s/host1/host2/g' myfile.txt > myfile1.txt
You can use gi option as well to ignore the character case.
sed '30,40 s/version/story/gi' myfile.txt > myfile1.txt
In Firefox there is Ctrl+Shift+K for the Web console, then you type
;decodeURIComponent("%2c")
and you get the answer:
","
Having unsigned
in variable declaration is more useful for the programmers themselves - don't treat the variables as negative. As you've noticed, both -1
and 4294967295
have exact same bit representation for a 4 byte integer. It's all about how you want to treat or see them.
The statement unsigned int a = -1;
is converting -1
in two's complement and assigning the bit representation in a
. The printf()
specifier x
, d
and u
are showing how the bit representation stored in variable a
looks like in different format.
Well - you won't be able to do it server-side on post-back as the file will get submitted (uploaded) during the post-back.
I think you may be able to do it on the client using JavaScript. Personally, I use a third party component called radUpload by Telerik. It has a good client-side and server-side API, and it provides a progress bar for big file uploads.
I'm sure there are open source solutions available, too.
Use python command to launch scripts, not shell directly. E.g.
python2 /usr/bin/command
AFAIK this is the recommended method to workaround scripts with bad env interpreter line.
This is probably due to its lack of connections to the Hive Meta Store,my hive Meta Store is stored in Mysql
,so I need to visit Mysql
,So I add a dependency in my build.sbt
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.38"
and the problem is solved!
To extend on the answer of weijia.wang:
extension Data {
func hexString() -> String {
let nsdataStr = NSData.init(data: self)
return nsdataStr.description.trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
}
}
use it with deviceToken.hexString()
If you run your code from a competent IDE, such as Code::Blocks, the IDE will manage the console it uses to run the code, keeping it open when the application closes. You don't want to add special code to keep the console open, because this will prevent it functioning correctly when you use it for real, outside of the IDE.
Waqas Raja's answer with some LINQ lambda fun:
List<int> listValues = new List<int>();
Request.Form.AllKeys
.Where(n => n.StartsWith("List"))
.ToList()
.ForEach(x => listValues.Add(int.Parse(Request.Form[x])));
After doing that don't forget to change your href
in,
<a href="{the chosen redirected name}"> home</a>
Example:
.htaccess
file
RewriteEngine On
RewriteRule ^about/$ /about.php
PHP file:
<a href="about/"> about</a>
If I were you, I would use BABEL: http://babel.pocoo.org/en/latest/index.html
from babel.numbers import format_decimal
format_decimal(188518982.18, locale='en_US')
You might have to re-check the order in which you are merging the files, it should be something like:
Think about expectations.
As a client app, you expect to know if something goes wrong on the server side. If the server needs to throw an error when blah
is missing or the requestedResource
value is incorrect than a 400 error would be appropriate.
Briefly, with more detail below,
window
is the execution context and global object for that context's JavaScriptdocument
contains the DOM, initialized by parsing HTMLscreen
describes the physical display's full screenSee W3C and Mozilla references for details about these objects. The most basic relationship among the three is that each browser tab has its own window
, and a window
has window.document
and window.screen
properties. The browser tab's window
is the global context, so document
and screen
refer to window.document
and window.screen
. More details about the three objects are below, following Flanagan's JavaScript: Definitive Guide.
window
Each browser tab has its own top-level window
object. Each <iframe>
(and deprecated <frame>
) element has its own window
object too, nested within a parent window. Each of these windows gets its own separate global object. window.window
always refers to window
, but window.parent
and window.top
might refer to enclosing windows, giving access to other execution contexts. In addition to document
and screen
described below, window
properties include
setTimeout()
and setInterval()
binding event handlers to a timerlocation
giving the current URLhistory
with methods back()
and forward()
giving the tab's mutable historynavigator
describing the browser softwaredocument
Each window
object has a document
object to be rendered. These objects get confused in part because HTML elements are added to the global object when assigned a unique id. E.g., in the HTML snippet
<body>
<p id="holyCow"> This is the first paragraph.</p>
</body>
the paragraph element can be referenced by any of the following:
window.holyCow
or window["holyCow"]
document.getElementById("holyCow")
document.querySelector("#holyCow")
document.body.firstChild
document.body.children[0]
screen
The window
object also has a screen
object with properties describing the physical display:
screen properties width
and height
are the full screen
screen properties availWidth
and availHeight
omit the toolbar
The portion of a screen displaying the rendered document is the viewport in JavaScript, which is potentially confusing because we call an application's portion of the screen a window when talking about interactions with the operating system. The getBoundingClientRect()
method of any document
element will return an object with top
, left
, bottom
, and right
properties describing the location of the element in the viewport.
https://stackoverflow.com/a/10835114/1113510
Although you can put an annotation for each date field, is better to do a global configuration for your object mapper. If you use jackson you can configure your spring as follow:
<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>
For CustomObjectMapper:
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
super();
configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
}
}
Of course, SimpleDateFormat can use any format you need.
You can align text anywhere in the scaffold or container except center:-
Its works for me anywhere in my application:-
new Text(
"Nextperience",
//i have setted in center.
textAlign: TextAlign.center,
//when i want it left.
//textAlign: TextAlign.left,
//when i want it right.
//textAlign: TextAlign.right,
style: TextStyle(
fontSize: 16,
color: Colors.blue[900],
fontWeight: FontWeight.w500),
),
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Stopwatch {
static int interval;
static Timer timer;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input seconds => : ");
String secs = sc.nextLine();
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = Integer.parseInt(secs);
System.out.println(secs);
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
}
private static final int setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}
}
Try this.
There is also the approach of organizing the folders not by the structure of the framework, but by the structure of the application's function. There is a github starter Angular/Express application that illustrates this called angular-app.
Interestingly, it seems that in Windows Embedded Compact 7, you cannot specify a title string. The first parameter has to be the command or program.
You can use esentutl to copy (mainly big) files with a progress bar:
esentutl /y "my.file" /d "another.file" /o
the progress bar looks like this:
Try setting 'clientCredentialType' to 'Windows' instead of 'Ntlm'.
I think that this is what the server is expecting - i.e. when it says the server expects "Negotiate,NTLM", that actually means Windows Auth, where it will try to use Kerberos if available, or fall back to NTLM if not (hence the 'negotiate')
I'm basing this on somewhat reading between the lines of: Selecting a Credential Type
It's best if you judge on your own,
1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).
http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text
This Link is no more working so please watch this video for similar details Video
Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)
Some Variation: Some user find plugins useful for PHP coders on that
http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html
although, there are many plugins for Notepad Plus Plus ..
I am not sure of your requirements, nor I am promoter of either of these editors :)
So, judge on basis of your requirements, this should satisfy you query...
Yes we can add that both are evolving and changing fast..
You can either
fig, ax = plt.subplots() #create figure and axes
candlestick(ax, quotes, ...)
or
candlestick(plt.gca(), quotes) #get the axis when calling the function
The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot
Look into xcopy, which will recursively copy files and subdirectories.
There are examples, 2/3 down the page. Of particular use is:
To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:
xcopy a: b: /s /e
Android Market requires you to sign all apps you publish with a certificate, using a public/private key mechanism (the certificate is signed with your private key). This provides a layer of security that prevents, among other things, remote attackers from pushing malicious updates to your application to market (all updates must be signed with the same key).
From The App-Signing Guide of the Android Developer's site:
In general, the recommended strategy for all developers is to sign all of your applications with the same certificate, throughout the expected lifespan of your applications. There are several reasons why you should do so...
Using the same key has a few benefits - One is that it's easier to share data between applications signed with the same key. Another is that it allows multiple apps signed with the same key to run in the same process, so a developer can build more "modular" applications.
I don't think you should use either of the methods in the question as they're both confusing, and the second one is fragile as Mehrdad suggests.
I would advocate the following, as it looks like a standard library function and makes its intention clear:
#include <iterator>
template <class RandomIt>
void reverse_sort(RandomIt first, RandomIt last)
{
std::sort(first, last,
std::greater<typename std::iterator_traits<RandomIt>::value_type>());
}
Instead of having to create a function in the ts file you can toggle a variable from the template itself. You can then use the variable to apply a specific class to the element. Like so-
<div (click)="status=!status"
[ngClass]="status ? 'success' : 'danger'">
Some content
</div>
So when status is true the class success is applied. When it is false danger class is applied.
This will work without any additional code in the ts file.
if you have installed NDK succesfully then start with it sample application
http://developer.android.com/sdk/ndk/overview.html#samples
if you are interested another ways of this then may this will help
http://shareprogrammingtips.blogspot.com/2018/07/cross-compile-cc-based-programs-and-run.html
I also want to know is it possible to push the compiled binary into android device or AVD and run using the terminal of the android device or AVD?
here you can see NestedVM
NestedVM provides binary translation for Java Bytecode. This is done by having GCC compile to a MIPS binary which is then translated to a Java class file. Hence any application written in C, C++, Fortran, or any other language supported by GCC can be run in 100% pure Java with no source changes.
Example: Cross compile Hello world C program and run it on android
In windows this command does not work for me..I have tried the following command and it works..using this command I created session in couchdb sync gate way for the specific user...
curl -v -H "Content-Type: application/json" -X POST -d "{ \"name\": \"abc\",\"password\": \"abc123\" }" http://localhost:4984/todo/_session
I guess this should work. I solved my problem with this.
$ sudo yum clean all
$ sudo yum --disablerepo="epel" update nss
Structure that represent time difference in Python is called timedelta. If you have start_time
and end_time
as datetime
types you can calculate the difference using -
operator like:
diff = end_time - start_time
you should do this before converting to particualr string format (eg. before start_time.strftime(...)). In case you have already string representation you need to convert it back to time/datetime by using strptime method.
We can make optional parameter by Method overloading or Using DataType...
|*| Method overloading :
RetDataType NameFnc(int NamePsgVar)
{
// |* Code Todo *|
return RetVar;
}
RetDataType NameFnc(String NamePsgVar)
{
// |* Code Todo *|
return RetVar;
}
RetDataType NameFnc(int NamePsgVar1, String NamePsgVar2)
{
// |* Code Todo *|
return RetVar;
}
Easiest way is
|*| DataType... can be optional parameter
RetDataType NameFnc(int NamePsgVar, String... stringOpnPsgVar)
{
if(stringOpnPsgVar.length == 0) stringOpnPsgVar = DefaultValue;
// |* Code Todo *|
return RetVar;
}
You can send intent MASTER_CLEAR in adb:
adb shell am broadcast -a android.intent.action.MASTER_CLEAR
or as root
adb shell "su -c 'am broadcast -a android.intent.action.MASTER_CLEAR'"
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
# plt.axis([x[0], x[-1], -1, 1]) # disable autoscaling
for point in x:
plt.plot(point, np.sin(2 * point), '.', color='b')
plt.draw()
plt.pause(0.01)
# plt.clf() # clear the current figure
if the amount of data is too much you can lower the update rate with a simple counter
cnt += 1
if (cnt == 10): # update plot each 10 points
plt.draw()
plt.pause(0.01)
cnt = 0
This was my actual problem that couldn't find satisfactory answer for, I wanted plotting that didn't close after the script was finished (like MATLAB),
If you think about it, after the script is finished, the program is terminated and there is no logical way to hold the plot this way, so there are two options
this wasn't satisfactory for me so I found another solution outside of the box
For this the saving and viewing should be both fast and the viewer shouldn't lock the file and should update the content automatically
vector based formats are both small and fast
For PDF there are several good options
On Windows I use SumatraPDF which is free, fast and light (only uses 1.8MB RAM for my case)
On Linux there are several options such as Evince (GNOME) and Ocular (KDE)
Sample code for outputing plot to a file
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(2 * x)
plt.plot(x, y)
plt.savefig("fig.pdf")
after first run, open the output file in one of the viewers mentioned above and enjoy.
Here is a screenshot of VSCode alongside SumatraPDF, also the process is fast enough to get semi-live update rate (I can get near 10Hz on my setup just use time.sleep()
between intervals)
I got error sometimes when using $(`code`)
constructor.
Finally i got some approach to that here: https://stackoverflow.com/a/7902174/2480481
Basically, using Tee to read again the ouput and putting it into a variable. Theres how you see the normal output then read it from the ouput.
is not? I guess your current task genhash will output just that, a single string hash so might work for you.
Im so neewbie and still looking for full output & save into 1 command. Regards.
Using Angular latest version (1.2.1) and track by $index
. This issue is fixed
<div ng-repeat="(i, name) in names track by $index">
Value: {{name}}
<input ng-model="names[i]">
</div>
In .NET 4.5, at least, there's this version that is much shorter and has the added bonus of evaluating any file criteria for inclusion in the list:
public static IEnumerable<string> GetAllFiles(string path,
Func<FileInfo, bool> checkFile = null)
{
string mask = Path.GetFileName(path);
if (string.IsNullOrEmpty(mask)) mask = "*.*";
path = Path.GetDirectoryName(path);
string[] files = Directory.GetFiles(path, mask, SearchOption.AllDirectories);
foreach (string file in files)
{
if (checkFile == null || checkFile(new FileInfo(file)))
yield return file;
}
}
Use like this:
var list = GetAllFiles(mask, (info) => Path.GetExtension(info.Name) == ".html").ToList();
You can use =A4, in case A4 is having long formula
import base64
from PIL import Image
import io
image = base64.b64decode(str('stringdata'))
fileName = 'test.jpeg'
imagePath = ('D:\\base64toImage\\'+"test.jpeg")
img = Image.open(io.BytesIO(image))
img.save(imagePath, 'jpeg')
overflow: scroll
? Or auto.
in the style attribute.
I've been playing around with shadows on Lollipop for a bit and this is what I've found:
ViewGroup
's bounds cutoff the shadow of its children for some reason; andandroid:elevation
are cutoff by the View
's bounds, not the bounds extended through the margin;android:clipToPadding="false"
on that parent.Here's my suggestion to you based on what I know:
RelativeLayout
to have padding equal to the margins you've set on the relative layout that you want to show shadow;android:clipToPadding="false"
on the same RelativeLayout
;RelativeLayout
that also has elevation set;At the end of the day, your top-level relative layout should look like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
style="@style/block"
android:gravity="center"
android:layout_gravity="center"
android:background="@color/lightgray"
android:paddingLeft="40dp"
android:paddingRight="40dp"
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:clipToPadding="false"
>
The interior relative layout should look like this:
<RelativeLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:background="[some non-transparent color]"
android:elevation="30dp"
>
I had that problem when I upgraded Postgres to 9.3.x. The quick fix for me was to downgrade to whichever 9.2.x version I had before (no need to install a new one).
$ ls /usr/local/Cellar/postgresql/
9.2.4
9.3.2
$ brew switch postgresql 9.2.4
$ launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
<open a new Terminal tab or window to reload>
$ psql
"Homebrew install specific version of formula?" offers a much more comprehensive explanation along with alternative ways to fix the problem.
Assuming that you're constrained to using Date
, you can do the following:
Date diff = new Date(d2.getTime() - d1.getTime());
Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date
).
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.
>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}
You might want to you use the @property
decorator,
>>> class Foo():
... @property
... def todo(self):
... raise NotImplementedError("To be implemented")
...
>>> f = Foo()
>>> f.todo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in todo
NotImplementedError: To be implemented
With Bootstrap 4 .hidden-*
classes were completely removed (yes, they were replaced by hidden-*-*
but those classes are also gone from v4 alphas).
Starting with v4-beta, you can combine .d-*-none
and .d-*-block
classes to achieve the same result.
visible-* was removed as well; instead of using explicit .visible-*
classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:
<div class="col d-none d-sm-block">
<span class="vcard">
…
</span>
</div>
<div class="col d-none d-xl-block">
<div class="d-none d-md-block">
…
</div>
<div class="d-none d-sm-block">
…
</div>
</div>
class="hidden-xs"
becomes class="d-none d-sm-block"
(or d-none d-sm-inline-block) ...
<span class="d-none d-sm-inline">hidden-xs</span>
<span class="d-none d-sm-inline-block">hidden-xs</span>
An example of Bootstrap 4 responsive utilities:
<div class="d-none d-sm-block"> hidden-xs
<div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
<div class="d-none d-lg-block"> visible-lg and up (hidden-md and down)
<div class="d-none d-xl-block"> visible-xl </div>
</div>
</div>
</div>
<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>
<div class="d-xl-none"> hidden-xl (visible-lg and down)
<div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
<div class="d-md-none d-lg-none d-xl-none"> visible-sm and down (or hidden-md and up)
<div class="d-sm-none"> visible-xs </div>
</div>
</div>
</div>