Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
Sometimes the problem is in the composer memory limit. In my case, I tried increasing the php memory limit but still got the error.
You can use COMPOSER_MEMORY_LIMIT=-1
to get around that.
Use it as a prefix:
COMPOSER_MEMORY_LIMIT=-1 composer require the/library
You have to prefix it again in the future.
Hope this helps.
For PHP7.1 install this
sudo apt-get install php7.1-zip
For CentOS, RHEL, Fedora:
$ yum search php-xml
============================================================================================================ N/S matched: php-xml ============================================================================================================
php-xml.x86_64 : A module for PHP applications which use XML
php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php-xmlseclibs.noarch : PHP library for XML Security
php54-php-xml.x86_64 : A module for PHP applications which use XML
php54-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php55-php-xml.x86_64 : A module for PHP applications which use XML
php55-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php56-php-xml.x86_64 : A module for PHP applications which use XML
php56-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php70-php-xml.x86_64 : A module for PHP applications which use XML
php70-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php71-php-xml.x86_64 : A module for PHP applications which use XML
php71-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php72-php-xml.x86_64 : A module for PHP applications which use XML
php72-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php73-php-xml.x86_64 : A module for PHP applications which use XML
php73-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
Then select the php-xml version matching your php version:
# php -v
PHP 7.2.11 (cli) (built: Oct 10 2018 10:00:29) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
# sudo yum install -y php72-php-xml.x86_64
in ubuntu or windows
path php.ini
Remove the ; from ;extension=pdo_mysql or extension=php_pdo_mysql.dll and add extension=pdo_mysql.so
restart xampp or wampp
install sudo apt-get install php-mysql
and
php artisan migrate
So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.
While ENV
, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG
and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args
at every build without changing our docker file.
For more details, you can refer this.
Upload Image See Here click This Link
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class AppConfig {
private static String BASE_URL = "http://mushtaq.16mb.com/";
static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
========================================================
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
interface ApiConfig {
@Multipart
@POST("retrofit_example/upload_image.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file,
@Part("file") RequestBody name);
/*@Multipart
@POST("ImageUpload")
Call<ServerResponseKeshav> uploadFile(@Part MultipartBody.Part file,
@Part("file") RequestBody name);*/
@Multipart
@POST("retrofit_example/upload_multiple_files.php")
Call<ServerResponse> uploadMulFile(@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
}
//https://drive.google.com/open?id=0BzBKpZ4nzNzUMnJfaklVVTJkWEk
This worked for me:
composer require "ext-gd:*" --ignore-platform-reqs
I fetch same problem for <flash-messages></flash-messages>
with angular 5.
You just need add below lines in app.module.ts file
import { ---, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FlashMessageModule } from "angular-flash-message";
@NgModule({
---------------
imports: [
FlashMessageModule,
------------------
],
-----------------
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
------------
})
NB: I am using this one for message flash-messages
If you have lots of columns and only one is different you could do:
In[1]: grouper = df.groupby('Company Name')
In[2]: res = grouper.count()
In[3]: res['Amount'] = grouper.Amount.sum()
In[4]: res
Out[4]:
Organisation Name Amount
Company Name
Vifor Pharma UK Ltd 5 4207.93
Note you can then rename the Organisation Name column as you wish.
If you're using php 7.3 for laravel 5.7. this work for me
sudo apt-get install php-gd php-xml php7.3-mbstring
This problem arises when you have composer installed locally. To make it globally executable,run the below command in terminal
sudo mv composer.phar /usr/local/bin/composer
For CentOS 7 the command is
sudo mv composer.phar /usr/bin/composer
<!DOCTYPE html>
<html>
<head>
<style>
/* styles for '...' */
.block-with-text {
width: 50px;
height: 50px;
/* hide text if it more than N lines */
overflow: hidden;
/* for set '...' in absolute position */
position: relative;
/* use this value to count block height */
line-height: 1.2em;
/* max-height = line-height (1.2) * lines max number (3) */
max-height: 3.6em;
/* fix problem when last visible word doesn't adjoin right side */
text-align: justify;
/* place for '...' */
margin-right: -1em;
padding-right: 1em;
}
/* create the ... */
.block-with-text:before {
/* points in the end */
content: '...';
/* absolute position */
position: absolute;
/* set position to right bottom corner of block */
right: 0;
bottom: 0;
}
/* hide ... if we have text, which is less than or equal to max lines */
.block-with-text:after {
/* points in the end */
content: '';
/* absolute position */
position: absolute;
/* set position to right bottom corner of text */
right: 0;
/* set width and height */
width: 1em;
height: 1em;
margin-top: 0.2em;
/* bg color = bg color under block */
background: white;
}
</style>
</head>
<body>
a
<div class="block-with-text">g fdsfkjsndasdasd asd asd asdf asdf asdf asdfas dfa sdf asdflk jgnsdlfkgj nsldkfgjnsldkfjgn sldkfjgnls dkfjgns ldkfjgn sldkfjngl sdkfjngls dkfjnglsdfkjng lsdkfjgn sdfgsd</div>
<p>This is a paragraph.</p>
</body>
</html>
In my case, I am using homestead.
cd ~/Homestead
and run composer install
.
I had a similar problem but with a different cause:
In my case the problem was that in the interface defining the repository
public interface ItemRepository extends Repository {..}
I was omitting the types of the template. Setting them right:
public interface ItemRepository extends Repository<Item,Long> {..}
did the trick.
give some background color to layout worked for me like:
android:background="@color/catskill_white"
android:layout_height="?attr/actionBarSize"
android:elevation="@dimen/dimen_5dp"
Well I tried a lot of things but none seemed to be working. But the following process did it right, I can now use composer
command in terminal. I'm in mac OS 10.12.1
$ curl -sS https://getcomposer.org/installer | php
$ chmod +x composer.phar
$ mv composer.phar /usr/local/bin/composer
$ composer
The solution for this problem is actually quite simple and there are two ways to go about it. If you have control over the Content.html then simply change the div#ScrolledArea
width CSS to:
width: 1px;
min-width: 100%;
*width: 100%;
Basically the idea here is simple, you set the width
to something that is smaller than the viewport (iframe width in this case) and then overwrite it with min-width: 100%
to allow for actual width: 100%
which iOS Safari by default overwrites. The *width: 100%;
is there so the code would remain IE6 compatible, but if you do not care for IE6 you can omit it. Demo
As you can see now, the div#ScrolledArea
width is actually 100% and the overflow: scroll;
can do it's thing and hide the overflowing content. If you have access to the iframe content, then this is preferable.
However if you do not have access to the iframe content (for what ever reason) then you can actually use the same technique on the iframe itself. Simply use the same CSS on the iframe:
iframe {
width: 1px;
min-width: 100%;
*width: 100%;
}
However, there is one limitation with this, you need to turn off the scrollbars with scrolling="no"
on the iframe for this to work:
<iframe height="950" width="100%" scrolling="no" src="Content.html"></iframe>
If the scrollbars are allowed, then this wont work on the iframe anymore. That said, if you modify the Content.html instead then you can retain the scrolling in the iframe. Demo
your composer.phar should be placed in above way.
You can do it that way:
cd /home/your_username/composer
Then run the following command:
php -r "readfile('https://getcomposer.org/installer');" | php
After that if you want to run composer, you can do it this way (in this caseyou must be in the composer's dir): php composer.phar
As a next step, you can do this:
alias composer="/home/your_username/composer/composer.phar"
.
And run commands like you do it normally: $ composer install
Hope that helps
dont use php composer.phar self-update
First go to Your project directory
simply use composer.phar self-update
This works for me
Run composer self-update
and composer clearcache
remove vendor and composer.lock
restart your local environment and then run
php -d memory_limit=-1 /usr/local/bin/composer install
I too was facing the same issue. Both the answers (the most upvoted one and the accepted one) just give a temporary fix for the same.
Moreover, the config set stop-writes-on-bgsave-error no
is a horrible way to over look this error, since what this option does is stop redis from notifying that writes have been stopped and to move on without writing the data in a snapshot. This is simply ignoring this error.
Refer this
As for setting dir
in config
in redis-cli, once you restart the redis service, this shall get cleared too and the same error shall pop up again. The default value of dir
in redis.conf
is ./
, and if you start redis as root user, then ./
is /
to which write permissions aren't granted, and hence the error.
The best way is to set the dir
parameter in redis.conf file and set proper permissions to that directory. Most of the debian distributions shall have it in /etc/redis/redis.conf
Should be:
curl --cert certificate_file.pem:password https://www.example.com/some_protected_page
You might just have to install the packages.
yum install php-pdo php-mysqli
After they're installed, restart Apache.
httpd restart
or
apachectl restart
Easy, type this commands:
rm -rf vendor/
rm -rf composer.lock
php composer install --prefer-dist
Should work for low memory machines
You can use the following command to update any module with its dependencies
composer update vendor-name/module-name --with-dependencies
To add to @ericbn 's https://stackoverflow.com/a/41111629/579827 here are sample commands I've embedded in a script I run to update all my passwords whenever they are renewed. It's probably not usable as-is as it's quite specific but it shows real life usage of cmdkey.exe
.
? This is a shell script run in cygwin ?
? This works because I use private git repos that all authenticate with the same password (you probably don't want to loop over with the same credentials, but you may reuse this sample
/list
command to extract a list of already registered credentials) ?
entries=`cmdkey.exe /list: | grep git | sed -r -e 's/^[^:]+:\s*(.*)$/\1/gm'`
for entry in ${entries}
do
cmdkey.exe "/delete:${entry}"
cmdkey.exe "/generic:${entry}" "/user:${GIT_USERNAME}" "/pass:${GIT_PASSWORD}"
done
Verify you are editing the correct php.ini file.
Reference: https://github.com/composer/composer/issues/1440
"WAMP uses different php.ini files in the CLI and for Apache. when you enable php_openssl through the WAMP UI, you enable it for Apache, not for the CLI. You need to modify C:\wamp\bin\php\php-X.Y.Z\php.ini to enable it for the CLI."
A bit more generic if you put the batch in the same folder as composer.phar:
@ECHO OFF
SET SUBDIR=%~dp0
php %SUBDIR%/composer.phar %*
I'd write it as a comment, but code isn't avail there
Some of this may be due to the OS your server is running. I recently did a migration to a new hosting environment running Ubuntu. Adding this alias alias composer="/path/to/your/composer"
to .bashrc or .bash_aliases didn't work at first because of two reasons:
The server was running csh, not bash, by default. To check if this is an issue in your case, run echo $0
. If the what is returned is -csh
you will want to change it to bash, since some processes run by Composer will fail using csh/tcsh.
To change it, first check if bash is available on your server by running cat /etc/shells
. If, in the list returned, you see bin/bash
, you can change the default to bash by running chsh -s /bin/csh
.
Now, at this point, you should be able to run Composer, but normally, on Ubuntu, you will have to load the script at every session by sourcing your Bash scripts by running source ~/.bashrc
or source ~/.bash_profile
. This is because, in most cases, Ubuntu won't load your Bash script, since it loads .profile
as the default script.
To load your Bash scripts when you open a session, try adding this to your .profile (this is if your Bash script is .bashrc—modify accordingly if .bash_profile or other):
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi
To test, close your session and reload. If it's working properly, running composer -v
or which composer
should behave as expected.
Try putting your text in another div inside your span:
i.e.
<span><div>some text</div></span>
You can try this:
CommandArgument='<%# "scrapid=" + Eval("ScrapId")+"&"+"UserId="+ Eval("UserId")%>'
You want to use "multiline".
$string =~ /(START)(.+?)(END)/m;
On MAC AMPPS, I updated the php-5.5.ini with the following and now it works.
allow_url_include = On
extension=openssl.so
I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.
$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());
another way of writing it in a more readable fasion:
var valofText = $("#my-Select" + " option").filter(function() {
return this.text == myText
}).val();
$(ElementID).val(valofText);
Pseudocode:
$("#my-Select").val( getValOfText( myText ) );
Study up on multidimensional arrays. This question might help.
I think that's another case of git error messages being misleading. Usually when I've seen that error it's due to ssh problems. Did you add your public ssh key to your github account?
Edit: Also, the xinet.d forum post is referring to running the git-daemon as a service so that people could pull from your system. It's not necessary to run git-daemon to push to github.
If accessibility reasons is important then use the first variant (when customer want to see image without styles)
<div id="logo">
<a href="">
<img src="logo.png" alt="Stack Overflow" />
</a>
</div>
No need to conform imaginary SEO requirements, because the HTML code above has correct structure and only you should decide does this suitable for you visitors.
Also you can use the variant with less HTML code
<h1 id="logo">
<a href=""><span>Stack Overflow</span></a>
</h1>
/* position code, it may be absolute position or normal - depends on other parts of your site */
#logo {
...
}
#logo a {
display:block;
width: actual_image_width;
height: actual_image_height;
background: url(image.png) no-repeat left top;
}
/* for accessibility reasons - without styles variant*/
#logo a span {display: none}
Please note that I have removed all other CSS styles and hacks because they didn't correspond to the task. They may be usefull in particular cases only.
On ubuntu 19.10, mysql 8, this is what worked for me:
$ sudo mysqld --skip-grant-tables &
$ mysql
> use mysql
> alter user set authentication_string='', plugin='mysql_native_password' where user = 'root';
> quit
$ sudo mysqladmin shutdown
$ sudo systemctl start mysql
If you get errors trying to run mysqld_safe
, in particular: /var/run/mysqld for UNIX socket file don't exists
, you can try creating the dir and running mysqld_safe
again.
$ sudo mkdir /var/run/mysqld
$ sudo chown mysql /var/run/mysqld
$ sudo chgrp mysql /var/run/mysqld
create sequence serial start 1;
select * from comments c
join (select unnest(ARRAY[1,3,2,4]) as id, nextval('serial') as id_sorter) x
on x.id = c.id
order by x.id_sorter;
drop sequence serial;
[EDIT]
unnest is not yet built-in in 8.3, but you can create one yourself(the beauty of any*):
create function unnest(anyarray) returns setof anyelement
language sql as
$$
select $1[i] from generate_series(array_lower($1,1),array_upper($1,1)) i;
$$;
that function can work in any type:
select unnest(array['John','Paul','George','Ringo']) as beatle
select unnest(array[1,3,2,4]) as id
As far as I know it's not possible... but you can try something like this:
.underline _x000D_
{_x000D_
color: blue;_x000D_
border-bottom: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
<span class="underline">hello world</span>_x000D_
</div>
_x000D_
A more "C++"ish version
#include <iostream>
#include <sstream>
#include "openssl/sha.h"
using namespace std;
string to_hex(unsigned char s) {
stringstream ss;
ss << hex << (int) s;
return ss.str();
}
string sha256(string line) {
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, line.c_str(), line.length());
SHA256_Final(hash, &sha256);
string output = "";
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
output += to_hex(hash[i]);
}
return output;
}
int main() {
cout << sha256("hello, world") << endl;
return 0;
}
I thought it was (warning: following will wipe out everything)
$ git reset --hard HEAD
$ git clean -fd
The reset
to undo changes. The clean
to remove any untracked files and directories.
Yes, use gzip for this. The best way is to read data as input and redirect the compressed to output file i.e.
cat test.csv | gzip > test.csv.gz
cat test.csv
will send the data as stdout and using pipe-sign gzip will read that data as stdin. Make sure to redirect the gzip output to some file as compressed data will not be written to the terminal.
In version 0.18.1
is added dt.weekday_name
:
print df
my_dates myvals
0 2015-01-01 1
1 2015-01-02 2
2 2015-01-03 3
print df.dtypes
my_dates datetime64[ns]
myvals int64
dtype: object
df['day_of_week'] = df['my_dates'].dt.weekday_name
print df
my_dates myvals day_of_week
0 2015-01-01 1 Thursday
1 2015-01-02 2 Friday
2 2015-01-03 3 Saturday
Another solution with assign
:
print df.assign(day_of_week = df['my_dates'].dt.weekday_name)
my_dates myvals day_of_week
0 2015-01-01 1 Thursday
1 2015-01-02 2 Friday
2 2015-01-03 3 Saturday
Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Instead, the variable containing the List is used as if it were an array.
List[index]
See for instance: https://msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx
What you're doing is fine, but if you feel the need to 'Java-it-up' you could use a Transformer and the collect method from Apache Commons, e.g.:
public class IntegerToStringTransformer implements Transformer<Integer, String> {
public String transform(final Integer i) {
return (i == null ? null : i.toString());
}
}
..and then..
CollectionUtils.collect(
collectionOfIntegers,
new IntegerToStringTransformer(),
newCollectionOfStrings);
Pass Data using NSNotificationCenter
You can also pass data using NotificationCentre in swift 3.0 and NSNotificationCenter in swift 2.0.
Swift 2.0 Version
Pass info using userInfo which is a optional Dictionary of type [NSObject : AnyObject]?
let imageDataDict:[String: UIImage] = ["image": image]
// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)
// Register to receive notification in your class
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)
// handle notification
func showSpinningWheel(notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
Swift 3.0 Version
The userInfo now takes [AnyHashable:Any]? as an argument, which we provide as a dictionary literal in Swift
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
func showSpinningWheel(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
Source pass data using NotificationCentre(swift 3.0) and NSNotificationCenter(swift 2.0)
It seems as if Android Studio is missing some features Eclipse has (which is surprising considering the choice to make Android Studio official IDE).
Eclipse had the ability to export zip files which could be sent over email for example. If you zip the folder from your workspace, and try to send it over Gmail for example, Gmail will refuse because the folder contains executable. Obviously you can delete files but that is inefficient if you do that frequently going back and forth from work.
Here's a solution though: You can use source control. Android Studio supports that. Your code will be stored online. A git will do the trick. Look under "VCS" in the top menu in Android Studio. It has many other benefits as well. One of the downsides though, is that if you use GitHub for free, your code is open source and everyone can see it.
This is what Array#map are good at
var arr = oFullResponse.results.map(obj => ({
key: obj.label,
sortable: true,
resizeable: true
}))
Without using actions the options would be:
move one of the methods to a different controller, so that they don't clash.
use just one method that takes the param, and if it's null call the other method from your code.
On Linux one can find the home directory of Jenkins looking for a file, that Jenkins' home contains, e.g.:
$ find / -name "config.xml" | grep "jenkins"
/var/lib/jenkins/config.xml
I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from Java.util
instead of implementing my own class.
So if the previous answers did not help you, please check that you import
the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.
For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :
import java.util.*; // replace this line
import myCollections.Queue; // by this line
Queue<Edge> theQueue = new Queue<Edge>();
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/>
in a div below the user box.
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
I got similar case but in contrary is to find the used key based on index of a given object's. I could find solution in underscore using Object.values
to returns object in to an array to get the occurred index.
var tv = {id1:1,id2:2};_x000D_
var voteIndex = 1;_x000D_
console.log(_.findKey(tv, function(item) {_x000D_
return _.indexOf(Object.values(tv), item) == voteIndex;_x000D_
}));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
_x000D_
First of all, install the prerequisite libraries:
sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev
Then install rbenv, which is used to install Ruby:
cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL
rbenv install 2.3.1
rbenv global 2.3.1
ruby -v
Then (optional) tell Rubygems to not install local documentation:
echo "gem: --no-ri --no-rdoc" > ~/.gemrc
Credits: https://gorails.com/setup/ubuntu/14.10
Warning!!!
There are issues with Gnome-Shell
. See comment below.
Sadly, no, you can't run 4.5 programs on XP.
And the relevant post from that Connect page:
Posted by Microsoft on 23/03/2012 at 10:39
Thanks for the report. This behavior is by design in .NET Framework 4.5 Beta. The minimum supported operating systems are Windows 7, Windows Server 2008 SP2 and Windows Server 2008 R2 SP1. Windows XP is not a supported operating system for the Beta release.
If you are using Netbeans to develop, use jLabel and change it's icon property.
For programs you are really better off with a verbatim
or alltt
environment, but if you want a blank line that LaTeX will not bitch about, try
my line of text blah blah blah\\
\mbox{ }\\ %% space followed by newline
new line of text with blank line between
This is where netstandard.dll exists: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.7.2\Facades\netstandard.dll Add ref to your Project through this.
Pandas DataFrame object should be thought of as a Series of Series. In other words, you should think of it in terms of columns. The reason why this is important is because when you use pd.DataFrame.iterrows
you are iterating through rows as Series. But these are not the Series that the data frame is storing and so they are new Series that are created for you while you iterate. That implies that when you attempt to assign tho them, those edits won't end up reflected in the original data frame.
Ok, now that that is out of the way: What do we do?
Suggestions prior to this post include:
pd.DataFrame.set_value
is deprecated as of Pandas version 0.21pd.DataFrame.ix
is deprecatedpd.DataFrame.loc
is fine but can work on array indexers and you can do betterMy recommendation
Use pd.DataFrame.at
for i in df.index:
if <something>:
df.at[i, 'ifor'] = x
else:
df.at[i, 'ifor'] = y
You can even change this to:
for i in df.index:
df.at[i, 'ifor'] = x if <something> else y
and what if I need to use the value of the previous row for the if condition?
for i in range(1, len(df) + 1):
j = df.columns.get_loc('ifor')
if <something>:
df.iat[i - 1, j] = x
else:
df.iat[i - 1, j] = y
If you're in the global scope then there's not much difference. Read Kangax's answer for explanation
If you're in a function then var
will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):
// These are both globals
var foo = 1;
bar = 2;
function()
{
var foo = 1; // Local
bar = 2; // Global
// Execute an anonymous function
(function()
{
var wibble = 1; // Local
foo = 2; // Inherits from scope above (creating a closure)
moo = 3; // Global
}())
}
If you're not doing an assignment then you need to use var
:
var x; // Declare x
Here are some ways to edit the text and the size of the box:
rows="insertNumber"
cols="insertNumber"
style="font-size:12pt"
Example:
<textarea rows="5" cols="30" style="font-size: 12pt" id="myText">Enter
Text Here</textarea>
With Guava, you can use Iterables.concat(Iterable<T> ...)
, it creates a live view of all the iterables, concatenated into one (if you change the iterables, the concatenated version also changes). Then wrap the concatenated iterable with Iterables.unmodifiableIterable(Iterable<T>)
(I hadn't seen the read-only requirement earlier).
From the Iterables.concat( .. )
JavaDocs:
Combines multiple iterables into a single iterable. The returned iterable has an iterator that traverses the elements of each iterable in inputs. The input iterators are not polled until necessary. The returned iterable's iterator supports
remove()
when the corresponding input iterator supports it.
While this doesn't explicitly say that this is a live view, the last sentence implies that it is (supporting the Iterator.remove()
method only if the backing iterator supports it is not possible unless using a live view)
Sample Code:
final List<Integer> first = Lists.newArrayList(1, 2, 3);
final List<Integer> second = Lists.newArrayList(4, 5, 6);
final List<Integer> third = Lists.newArrayList(7, 8, 9);
final Iterable<Integer> all =
Iterables.unmodifiableIterable(
Iterables.concat(first, second, third));
System.out.println(all);
third.add(9999999);
System.out.println(all);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9999999]
Edit:
By Request from Damian, here's a similar method that returns a live Collection View
public final class CollectionsX {
static class JoinedCollectionView<E> implements Collection<E> {
private final Collection<? extends E>[] items;
public JoinedCollectionView(final Collection<? extends E>[] items) {
this.items = items;
}
@Override
public boolean addAll(final Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
for (final Collection<? extends E> coll : items) {
coll.clear();
}
}
@Override
public boolean contains(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
@Override
public Iterator<E> iterator() {
return Iterables.concat(items).iterator();
}
@Override
public boolean remove(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
int ct = 0;
for (final Collection<? extends E> coll : items) {
ct += coll.size();
}
return ct;
}
@Override
public Object[] toArray() {
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] a) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(E e) {
throw new UnsupportedOperationException();
}
}
/**
* Returns a live aggregated collection view of the collections passed in.
* <p>
* All methods except {@link Collection#size()}, {@link Collection#clear()},
* {@link Collection#isEmpty()} and {@link Iterable#iterator()}
* throw {@link UnsupportedOperationException} in the returned Collection.
* <p>
* None of the above methods is thread safe (nor would there be an easy way
* of making them).
*/
public static <T> Collection<T> combine(
final Collection<? extends T>... items) {
return new JoinedCollectionView<T>(items);
}
private CollectionsX() {
}
}
Safari & Chrome on iOS 6+ and Android 2.2+ support HTML Media Capture which allows you to take pictures with your device's camera or select an existing one:
<input type="file" accept="image/*">
Here's how it works on iOS 10:
Android 3.0+ and Safari on iOS10.3+ also support the capture
attribute which is used to jump straight to the camera.
<input type="file" accept="image/*" capture>
capture="camera"
(String) and accept="image/*;capture=camera"
(Parameter) were part of old specs and were replaced by capture
(Boolean) the W3C Candidate Recommendation.
Support documentation: this 2013 O'Reilly book and my testing
for (var i in a) {
console.log(a[i],i)
}
http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.
You can try this:
<a href="link.html">
<input type="button" value="Visit Page" />
</a>
This will create button inside a link and it works on any browser
To exit Scale Mode, press:
Right Ctrl (Host Key) + c
Note that your (Host Key) may be different from Right Ctrl. To check the current binding, go to VirtualBox Preferences > Input > Virtual Machine > Host Key Combination
.
I got this error until I realized that I hadn't intialized a Git repository in that folder, on a mounted vagrant machine.
So I typed git init
and then git worked.
You can create "everywhere" custom search engine right from the Google Custom Search homepage ( http://www.google.com/cse/ ). You should just click 'advanced', during adding new engine. There you can provide Schema.org site type. 'Thing' is most generic type, which covers all the web.
Disable caching of script.js only for local development in pure JavaScript.
It injects a random script.js?wizardry=1231234 and blocks regular script.js:
<script type="text/javascript">
if(document.location.href.indexOf('localhost') !== -1) {
const scr = document.createElement('script');
document.setAttribute('type', 'text/javascript');
document.setAttribute('src', 'scripts.js' + '?wizardry=' + Math.random());
document.head.appendChild(scr);
document.write('<script type="application/x-suppress">'); // prevent next script(from other SO answer)
}
</script>
<script type="text/javascript" src="scripts.js">
if (isset($_GET["id"])){
//do stuff
}
What about using Powershell.
Get-Content 'C:\my.csv' | Out-File 'C:\my_utf8.csv' -Encoding UTF8
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:
[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
var value1 = model.SimpleProp1;
var value2 = model.SimpleProp2;
var value3 = model.ComplexProp1.SimpleProp1;
...
... return something ...
}
Another (obviously uglier) way is:
[HttpPost]
public ActionResult SubmitAction()
{
var value1 = Request["SimpleProp1"];
var value2 = Request["SimpleProp2"];
var value3 = Request["ComplexProp1.SimpleProp1"];
...
... return something ...
}
You need to correct your code to wait for the list to be downloaded:
List<Item> list = await GetListAsync();
Also, make sure that the method, where this code is located, has async
modifier.
The reason why you get this error is that GetListAsync
method returns a Task<T>
which is not a completed result. As your list is downloaded asynchronously (because of Task.Run()
) you need to "extract" the value from the task using the await
keyword.
If you remove Task.Run()
, you list will be downloaded synchronously and you don't need to use Task
, async
or await
.
One more suggestion: you don't need to await in GetListAsync
method if the only thing you do is just delegating the operation to a different thread, so you can shorten your code to the following:
private Task<List<Item>> GetListAsync(){
return Task.Run(() => manager.GetList());
}
I've had the same problem you describe. The web site I'm building can be accessed from a mobile phone and from the browser so I need an api to allow users to signup, login and do some specific tasks. Furthermore, I need to support scalability, the same code running on different processes/machines.
Because users can CREATE resources (aka POST/PUT actions) you need to secure your api. You can use oauth or you can build your own solution but keep in mind that all the solutions can be broken if the password it's really easy to discover. The basic idea is to authenticate users using the username, password and a token, aka the apitoken. This apitoken can be generated using node-uuid and the password can be hashed using pbkdf2
Then, you need to save the session somewhere. If you save it in memory in a plain object, if you kill the server and reboot it again the session will be destroyed. Also, this is not scalable. If you use haproxy to load balance between machines or if you simply use workers, this session state will be stored in a single process so if the same user is redirected to another process/machine it will need to authenticate again. Therefore you need to store the session in a common place. This is typically done using redis.
When the user is authenticated (username+password+apitoken) generate another token for the session, aka accesstoken. Again, with node-uuid. Send to the user the accesstoken and the userid. The userid (key) and the accesstoken (value) are stored in redis with and expire time, e.g. 1h.
Now, every time the user does any operation using the rest api it will need to send the userid and the accesstoken.
If you allow the users to signup using the rest api, you'll need to create an admin account with an admin apitoken and store them in the mobile app (encrypt username+password+apitoken) because new users won't have an apitoken when they sign up.
The web also uses this api but you don't need to use apitokens. You can use express with a redis store or use the same technique described above but bypassing the apitoken check and returning to the user the userid+accesstoken in a cookie.
If you have private areas compare the username with the allowed users when they authenticate. You can also apply roles to the users.
Summary:
An alternative without apitoken would be to use HTTPS and to send the username and password in the Authorization header and cache the username in redis.
Yes there is retainAll
check out this
Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);
Compiling the original example in Eclipse at compliance 1.8 and with annotation based null analysis enabled, we get this warning:
directPathToA(y);
^
Null type safety (type annotations): The expression of type 'Integer' needs unchecked conversion to conform to '@NonNull Integer'
This warning is worded in analogy to those warnings you get when mixing generified code with legacy code using raw types ("unchecked conversion"). We have the exact same situation here: method indirectPathToA()
has a "legacy" signature in that it doesn't specify any null contract. Tools can easily report this, so they will chase you down all alleys where null annotations need to be propagated but aren't yet.
And when using a clever @NonNullByDefault
we don't even have to say this every time.
In other words: whether or not null annotations "propagate very far" may depend on the tool you use, and on how rigorously you attend to all the warnings issued by the tool. With TYPE_USE null annotations you finally have the option to let the tool warn you about every possible NPE in your program, because nullness has become an intrisic property of the type system.
Be sure to use System.Net.Mail
, not the deprecated System.Web.Mail
. Doing SSL with System.Web.Mail
is a gross mess of hacky extensions.
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
You can declare variables within a switch statement if you start a new block:
switch (thing)
{
case A:
{
int i = 0; // Completely legal
}
break;
}
The reason is to do with allocating (and reclaiming) space on the stack for storage of the local variable(s).
import codecs
import shutil
import sys
s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
sys.stdout.write(s)
shutil.copyfileobj(sys.stdin, sys.stdout)
This worked for me.
onClick={() => {window.open('https://www.google.com/');}}
Modules go in site-packages
and executables go in your system's executable path. For your environment, this path is /usr/local/bin/
.
To avoid having to deal with this, simply use easy_install
, distribute
or pip
. These tools know which files need to go where.
Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).
So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
produces a format that can parse both "2013-03-11T01:38:18.309Z"
and "2013-03-11T01:38:18.309+0000"
and will give you the same result.
Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.
I actually have more trouble on the JavaScript side to deal with both formats.
Note.
where(:user_id => current_user.id, :notetype => p[:note_type]).
where("date > ?", p[:date]).
order('date ASC, created_at ASC')
or you can also convert everything into the SQL notation
Note.
where("user_id = ? AND notetype = ? AND date > ?", current_user.id, p[:note_type], p[:date]).
order('date ASC, created_at ASC')
echo 'junk "Foo Bar" not empty one "" this "but this" and this neither' | sed 's/[^\"]*\"\([^\"]*\)\"[^\"]*/>\1</g'
This will result in: >Foo Bar<><>but this<
Here I showed the result string between ><'s for clarity, also using the non-greedy version with this sed command we first throw out the junk before and after that ""'s and then replace this with the part between the ""'s and surround this by ><'s.
If you are using freezegun package in tests you may need to have more smart isinstance checks which works well with FakeDate and original Date/Datetime beeing inside with freeze_time context:
def isinstance_date(value):
"""Safe replacement for isinstance date which works smoothly also with Mocked freezetime"""
import datetime
if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):
return True
elif type(datetime.datetime.today().date()) == type(value):
return True
else:
return False
def isinstance_datetime(value):
"""Safe replacement for isinstance datetime which works smoothly also with Mocked freezetime """
import datetime
if isinstance(value, datetime.datetime):
return True
elif type(datetime.datetime.now()) == type(value):
return True
else:
return False
and tests to verify the implementation
class TestDateUtils(TestCase):
def setUp(self):
self.date_orig = datetime.date(2000, 10, 10)
self.datetime_orig = datetime.datetime(2000, 10, 10)
with freeze_time('2001-01-01'):
self.date_freezed = datetime.date(2002, 10, 10)
self.datetime_freezed = datetime.datetime(2002, 10, 10)
def test_isinstance_date(self):
def check():
self.assertTrue(isinstance_date(self.date_orig))
self.assertTrue(isinstance_date(self.date_freezed))
self.assertFalse(isinstance_date(self.datetime_orig))
self.assertFalse(isinstance_date(self.datetime_freezed))
self.assertFalse(isinstance_date(None))
check()
with freeze_time('2005-01-01'):
check()
def test_isinstance_datetime(self):
def check():
self.assertFalse(isinstance_datetime(self.date_orig))
self.assertFalse(isinstance_datetime(self.date_freezed))
self.assertTrue(isinstance_datetime(self.datetime_orig))
self.assertTrue(isinstance_datetime(self.datetime_freezed))
self.assertFalse(isinstance_datetime(None))
check()
with freeze_time('2005-01-01'):
check()
Try:
$a1=@(1,2,3,4,5)
$b1=@(1,2,3,4,5,6)
(Compare-Object $a1 $b1).InputObject
Or, you can use:
(Compare-Object $b1 $a1).InputObject
The order doesn't matter.
I had the same problem and my solution was to add the push notification entitlement from Target -> Capabilities.
> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")
> myMatrix
A B C D E
A 1 3 5 7 9
B 2 4 6 8 10
> myMatrix["A", "A"]
[1] 1
> myMatrix["A", ]
A B C D E
1 3 5 7 9
> myMatrix[, "A"]
A B
1 2
Saish's answer using REGEXP_LIKE
is the right idea but does not support floating numbers. This one will ...
Return values that are numeric
SELECT foo
FROM bar
WHERE REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');
Return values not numeric
SELECT foo
FROM bar
WHERE NOT REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');
You can test your regular expressions themselves till your heart is content at http://regexpal.com/ (but make sure you select the checkbox match at line breaks for this one).
foo->bar
is only shorthand for (*foo).bar
. That's all there is to it.
I've been experimenting with Apache Commons Daemon. It's supports windows (Procrun) and unix (Jsvc). Advanced Installer has a Java Service tutorial with an example project to download. If you get their javaservice.jar running as a windows service you can test it by using "telnet 4444". I used their example because my focus was on getting a java windows service running, not writing java.
Just use the __block
prefix to declare and assign any type of variable inside a block.
For example:
__block Person *aPerson = nil;
__block NSString *name = nil;
a good site, with good explanations:
http://www.wpf-tutorial.com/basic-controls/the-textblock-control-inline-formatting/
here the author gives you good examples for what you are looking for! Overal the site is great for research material plus it covers a great deal of options you have in WPF
Edit
There are different methods to format the text. for a basic formatting (the easiest in my opinion):
<TextBlock Margin="10" TextWrapping="Wrap">
TextBlock with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> text.
</TextBlock>
Example 1 shows basic formatting with Bold Itallic and underscored text.
Following includes the SPAN method, with this you van highlight text:
<TextBlock Margin="10" TextWrapping="Wrap">
This <Span FontWeight="Bold">is</Span> a
<Span Background="Silver" Foreground="Maroon">TextBlock</Span>
with <Span TextDecorations="Underline">several</Span>
<Span FontStyle="Italic">Span</Span> elements,
<Span Foreground="Blue">
using a <Bold>variety</Bold> of <Italic>styles</Italic>
</Span>.
</TextBlock>
Example 2 shows the span function and the different possibilities with it.
For a detailed explanation check the site!
you have to use this code:
with <%@ taglib prefix="c" uri="http://www.springframework.org/tags/form"%>
and
<c:select>
<option value="RCV"
${records[0].getDirection() == 'RCV' ? 'selected="true"' : ''}>
<spring:message code="dropdown.Incoming" text="dropdown.Incoming" />
</option>
<option value="SND"
${records[0].getDirection() == 'SND'? 'selected="true"' : ''}>
<spring:message code="dropdown.Outgoing" text="dropdown.Outgoing" />
</option>
</c:select>
You can use string operators:
$ foo=1:2:3:4:5
$ echo ${foo##*:}
5
This trims everything from the front until a ':', greedily.
${foo <-- from variable foo
## <-- greedy front trim
* <-- matches anything
: <-- until the last ':'
}
Define a class to store your data first
public class YourDataClass {
private String messageType;
private Timestamp timestamp;
private int count;
private int version;
// your get/setters
...........
}
And then initialize your map:
Map<Integer, YourDataClass> map = new HashMap<Integer, YourDataClass>();
I had this problem building jasmine-headless-webkit Ruby gem. Despite having qt4 installed, qmake
(a symlink to qtchooser
) insisted it didn't know about a QT installation. OTOH, it was able to list qt4 when asked directly.
This made everything better:
export QT_SELECT=qt4
qtchooser then knew to use qmake-qt4, and so on.
Using .editorconfig
to fix the tabs automagically:
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
[Makefile]
indent_style = tab
You can't detect it with javascript.
Only events that do detect page unloading/closing are window.onbeforeunload and window.unload. Neither of these events can tell you the way that you closed the page.
The output of this query is very clean (original here)
clear screen
accept uname prompt 'Enter User Name : '
accept outfile prompt ' Output filename : '
spool &&outfile..gen
SET LONG 20000 LONGCHUNKSIZE 20000 PAGESIZE 0 LINESIZE 1000 FEEDBACK OFF VERIFY OFF TRIMSPOOL ON
BEGIN
DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
END;
/
SELECT dbms_metadata.get_ddl('USER','&&uname') FROM dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','&&uname') from dual;
spool off
As of XCode 7 this has become much easier.
Apple has documented the process on their site: https://developer.apple.com/library/ios/recipes/xcode_help-project_editor/RenamingaProject/RenamingaProject.html
Update: XCode 8 link: http://help.apple.com/xcode/mac/8.0/#/dev3db3afe4f
In Data Source
(on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard
. A new window will appear, expand the Connection string, you can find the connection string in there
add this
.carousel .item img {
left: -9999px; /*important */
right: -9999px; /*important */
margin: 0 auto; /*important */
max-width: none; /*important */
min-width: 100%;
position: absolute;
}
And of course one of the parent divs needs to have a position:relative, but I believe it does by default.
See it here: http://paginacrestinului.ro/
this error happen with me because I did the following
Update Model from database
in Edmx) I Renamed manually Property name to match the change in database schema Although all of this, I got this error
so what to do
Update Model from database
this will regenerate the model, and entity framework will
not give you this error
hope this help you
Simple & Easy answer,
The %2C means , comma in URL. when you add the String "abc,defg" in the url as parameter then that comma in the string which is abc , defg is changed to abc%2Cdefg .There is no need to worry about it.
char* result = strcpy((char*)malloc(str.length()+1), str.c_str());
I've had success with this solution. It's almost like Patrick's, with a little twist. You can use these expressions separately or in sequence. If the parameter is blank, it will be ignored and all values for the column that your searching will be displayed, including NULLS.
SELECT * FROM MyTable
WHERE
--check to see if @param1 exists, if @param1 is blank, return all
--records excluding filters below
(Col1 LIKE '%' + @param1 + '%' OR @param1 = '')
AND
--where you want to search multiple columns using the same parameter
--enclose the first 'OR' expression in braces and enclose the entire
--expression
((Col2 LIKE '%' + @searchString + '%' OR Col3 LIKE '%' + @searchString + '%') OR @searchString = '')
AND
--if your search requires a date you could do the following
(Cast(DateCol AS DATE) BETWEEN CAST(@dateParam AS Date) AND CAST(GETDATE() AS DATE) OR @dateParam = '')
I think I was trying something very similar to the original poster. the get() worked for me, although the name inside the chart was not inherited. Here is the code that worked for me.
#install it if you dont have it
library(quantmod)
# a list of stock tickers
myStocks <- c("INTC", "AAPL", "GOOG", "LTD")
# get some stock prices from default service
getSymbols(myStocks)
# to pause in between plots
par(ask=TRUE)
# plot all symbols
for (i in 1:length(myStocks)) {
chartSeries(get(myStocks[i]), subset="last 26 weeks")
}
Add a dot (.
) to indicate floating point numbers
>>> 4/3.
1.3333333333333333
ffmpeg provides this functionality. All you need to do is run someting like
ffmpeg -i <inputfilename> -s 640x480 -b 512k -vcodec mpeg1video -acodec copy <outputfilename>
For newer versions of ffmpeg you need to change -b
to -b:v
:
ffmpeg -i <inputfilename> -s 640x480 -b:v 512k -vcodec mpeg1video -acodec copy <outputfilename>
to convert the input video file to a video with a size of 640 x 480 and a bitrate of 512 kilobits/sec using the MPEG 1 video codec and just copying the original audio stream. Of course, you can plug in any values you need and play around with the size and bitrate to achieve the quality/size tradeoff you are looking for. There are also a ton of other options described in the documentation
Run ffmpeg -formats
or ffmpeg -codecs
for a list of all of the available formats and codecs. If you don't have to target a specific codec for the final output, you can achieve better compression ratios with minimal quality loss using a state of the art codec like H.264.
You can implement the Array.insert
method by doing this:
Array.prototype.insert = function ( index, item ) {
this.splice( index, 0, item );
};
Then you can use it like:
var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');
// => arr == [ 'A', 'B', 'C', 'D', 'E' ]
Click the items in the list view. Add a button that will edit the selected items. Add the code
try
{
LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}
This worked for me on Chrome + FF:
"foo=bar=beer".split(/^[^=]+=/)[1] // "bar=beer"
"foo==".split(/^[^=]+=/)[1] // "="
"foo=".split(/^[^=]+=/)[1] // ""
"foo".split(/^[^=]+=/)[1] // undefined
If you also need the key try this:
"foo=bar=beer".split(/^([^=]+)=/) // Array [ "", "foo", "bar=beer" ]
"foo==".split(/^([^=]+)=/) // [ "", "foo", "=" ]
"foo=".split(/^([^=]+)=/) // [ "", "foo", "" ]
"foo".split(/^([^=]+)=/) // [ "foo" ]
//[0] = ignored (holds the string when there's no =, empty otherwise)
//[1] = hold the key (if any)
//[2] = hold the value (if any)
Found the following options useful to provide all the files for a self signed postgres instance
psql "host={hostname} sslmode=prefer sslrootcert={ca-cert.pem} sslcert={client-cert.pem} sslkey={client-key.pem} port={port} user={user} dbname={db}"
Rephrasing one of the answers in this post, instead of using cmd.split(). Try to use:
import shlex
args = shlex.split(cmd)
Then feed args to subprocess.Popen.
Check this doc for more info: https://docs.python.org/2/library/subprocess.html#popen-constructor
You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?
I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.
Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.
>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
I implemented a rooted tree as a dictionary {child:parent}
. So for instance with the root node 0
, a tree might look like that:
tree={1:0, 2:0, 3:1, 4:2, 5:3}
This structure made it quite easy to go upward along a path from any node to the root, which was relevant for the problem I was working on.
You can use trimLeft()
and trimRight()
also.
const str1 = " string ";
console.log(str1.trimLeft());
// => "string "
const str2 = " string ";
console.log(str2.trimRight());
// => " string"
add_action( 'init', 'remove_category_perma' );
function remove_category_perma() {
unset($GLOBALS['wp_rewrite']->extra_permastructs['category']);
}
Use mysql row instead
mysql_fetch_row($r)
Meanwhile consider using mysqli or PDO
?>
Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
There are some existing implementations of tail on pypi which you can install using pip:
Depending on your situation, there may be advantages to using one of these existing tools.
i found this way useful also.
import tkinter.filedialog
from_filename = tkinter.filedialog.askopenfilename()
here a window will appear so you can browse till you find the file , you click on it then you can continue using open , and read .
from_file = open(from_filename, 'r')
contents = from_file.read()
contents
You can set triangle with position see this code for reference
.top-left-corner {
width: 0px;
height: 0px;
border-top: 0px solid transparent;
border-bottom: 55px solid transparent;
border-left: 55px solid #289006;
position: absolute;
left: 0px;
top: 0px;
}
Here's some sample code. This worked for me.
<LinearLayout
android:gravity="center"
>
<TextView
android:layout_gravity="center"
/>
<Button
android:layout_gravity="center"
/>
</LinearLayout>
So you're designing the Linear Layout to place all its contents (TextView and Button) in its center, and then the TextView and Button are placed relative to the center of the Linear Layout.
As mentioned by many, "ctor" and double TAB works in Visual Studio 2017, but it only creates the constructor with none of the attributes.
To auto-generate with attributes (if there are any), just click on an empty line below them and press Ctrl + .. It'll display a small pop-up from which you can select the "Generate Constructor..." option.
Pass --jars
with the path of jar
files separated by ,
to spark-submit
.
For reference:
--driver-class-path is used to mention "extra" jars to add to the "driver" of the spark job
--driver-library-path is used to "change" the default library path for the jars needed for the spark driver
--driver-class-path will only push the jars to the driver machine. If you want to send the jars to "executors", you need to use --jars
And to set the jars programatically set the following config:
spark.yarn.dist.jars
with comma-separated list of jars.
Eg:
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("Spark config example") \
.config("spark.yarn.dist.jars", "<path-to-jar/test1.jar>,<path-to-jar/test2.jar>") \
.getOrCreate()
abc "$@"
$@
represents all the parameters given to your bash script.
If you have to run composer with sudo, you should change the directory of composer to
/usr/bin
this was tested on Centos8.
The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list of legal elements:
<!ATTLIST contact type CDATA #IMPLIED>
<!ELEMENT address1 ( #PCDATA)>
<!ELEMENT city ( #PCDATA)>
<!ELEMENT state ( #PCDATA)>
<!ELEMENT zip ( #PCDATA)>
XML Schema enables schema authors to specify that element quantity’s data must
be numeric or, even more specifically, an integer. In the following example I used string
:
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="address1" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="state" type="xs:string"/>
<xs:element name="zip" type="xs:string"/>
</xs:sequence>
</xs:complexType>
The ErrorDocument
directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot
. In your case, this means that the actual path to the ErrorDocument
is
ErrorDocument 404 /hellothere/error/404page.html
If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.
No, because single-quotes even inhibit hex code replacement.
echo 'Hello, world!' . "\xA";
Vim has a branch operator \&
that is useful when searching for a line containing a set of words, in any order. Moreover, extending the set of required words is trivial.
For example,
/.*jack\&.*james
will match a line containing jack
and james
, in any order.
See this answer for more information on usage. I am not aware of any other regex flavor that implements branching; the operator is not even documented on the Regular Expression wikipedia entry.
You need some Administrator privilege to your account if your machine in local area network then you apply some administrator privilege to your User else you should start ide as Administrator...
>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()
where a is your x data b is your y data c is your y error if any
note that c is the error in each direction already
select ROW_NUMBER() over (order by pk_field ) as srno
from TableName
Paul's answer is the one you're looking for. However, as a practical matter, I think you may be interested in the pattern I've been using in my own React+Redux apps.
Here's a stripped-down example from one of my routes, showing how you can define your component and export it as default with a single statement:
import React from 'react';
import { connect } from 'react-redux';
@connect((state, props) => ({
appVersion: state.appVersion
// other scene props, calculated from app state & route props
}))
export default class SceneName extends React.Component { /* ... */ }
(Note: I use the term "Scene" for the top-level component of any route).
I hope this is helpful. I think it's much cleaner-looking than the conventional connect( mapState, mapDispatch )( BareComponent )
Check this fiddle. You are going to need to take a look at using border-collapse and border-spacing. There are some quirks for IE (as usual). This is based on an answer to this question.
table.test td {
background-color: lime;
margin: 12px 12px 12px 12px;
padding: 12px 12px 12px 12px;
}
table.test {
border-collapse: separate;
border-spacing: 10px;
*border-collapse: expression('separate', cellSpacing='10px');
}
_x000D_
<table class="test">
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
_x000D_
I was having the same problem when following the Flask tutorial and I found the answer on the official Pytest docs It's a little shift from the way I (and I think many others) are used to do things.
You have to create a setup.py
file in your project's root directory with at least the following two lines:
from setuptools import setup, find_packages
setup(name="PACKAGENAME", packages=find_packages())
where PACKAGENAME is your app's name. Then you have to install it with pip:
pip install -e .
The -e
flag tells pip to intall the package in editable or "develop" mode. So the next time you run pytest
it should find your app in the standard PYTHONPATH
.
I've seen three results to a ping - The one we "want" where the IP replies, "Host Unreachable" and "timed out" (not sure of exact wording).
The first two return ERRORLEVEL of 0.
Timeout returns ERRORLEVEL of 1.
Are the other results and error levels that might be returned? (Besides using an invalid switch which returns the allowable switches and an errorlevel of 1.)
Apparently Host Unreachable can use one of the previously posted methods (although it's hard to figure out when someone replies which case they're writing code for) but does the timeout get returned in a similar manner that it can be parsed?
In general, how does one know what part of the results of the ping can be parsed? (Ie, why might Sent and/or Received and/or TTL be parseable, but not host unreachable?
Oh, and iSid, maybe there aren't many upvotes because the people that read this don't have enough points. So they get their question answered (or not) and leave.
I wasn't posting the above as an answer. It should have been a comment but I didn't see that choice.
Another approach instead of saving the file on the server and retrieving it, is to use .NET 4.0+ ObjectCache with a short expiration until the second Action (at which time it can be definitively dumped). The reason that I want to use JQuery Ajax to do the call, is that it is asynchronous. Building my dynamic PDF file takes quite a bit of time, and I display a busy spinner dialog during that time (it also allows other work to be done). The approach of using the data returned in the "success:" to create a Blob does not work reliably. It depends on the content of the PDF file. It is easily corrupted by data in the response, if it is not completely textual which is all that Ajax can handle.
At first check the type of columns which you want to merge. You will see one of them is string where other one is int
. Then convert it to int as following code:
df["something"] = df["something"].astype(int)
merged = df.merge[df1, on="something"]
Unfortunately that approach is not portable C++ (so far).
All standard names are in namespace std
and moreover you cannot know which names are NOT defined by including and header (in other words it's perfectly legal for an implementation to declare the name std::string
directly or indirectly when using #include <vector>
).
Despite this however you are required by the language to know and tell the compiler which standard header includes which part of the standard library. This is a source of portability bugs because if you forget for example #include <map>
but use std::map
it's possible that the program compiles anyway silently and without warnings on a specific version of a specific compiler, and you may get errors only later when porting to another compiler or version.
In my opinion there are no valid technical excuses because this is necessary for the general user: the compiler binary could have all standard namespace built in and this could actually increase the performance even more than precompiled headers (e.g. using perfect hashing for lookups, removing standard headers parsing or loading/demarshalling and so on).
The use of standard headers simplifies the life of who builds compilers or standard libraries and that's all. It's not something to help users.
However this is the way the language is defined and you need to know which header defines which names so plan for some extra neurons to be burnt in pointless configurations to remember that (or try to find and IDE that automatically adds the standard headers you use and removes the ones you don't... a reasonable alternative).
It's really a 6 of one, a half-dozen of the other situation.
The only possible argument against your approach is $_SERVER['REQUEST_METHOD'] == 'POST' may not be populated on certain web-servers/configuration, whereas the $_POST array will always exist in PHP4/PHP5 (and if it doesn't exist, you have bigger problems (-:)
In the earlier versions of MySQL ( < 5.7.5 ) the only way to set
'innodb_buffer_pool_size'
variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :
[mysqld]
innodb_buffer_pool_size = 2147483648
You need to restart your mysql server to have it's effect in action.
As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:
mysql> SET GLOBAL innodb_buffer_pool_size=402653184;
Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html
You can cast like this:
return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);
Or like this if you want to be compatible with tsx mode:
return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);
Just remember that this is a compile-time cast, and not a runtime cast.
byte[] seed = (SALT2 + username + password).getBytes();
SecureRandom random = new SecureRandom(seed);
KeyGenerator generator;
generator = KeyGenerator.getInstance("AES");
generator.init(random);
generator.init(256);
Key keyObj = generator.generateKey();
Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.
Assuming your file is named myclone.csv
and contains
workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0
this code should give you an idea or two:
>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
... column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
... for h, v in zip(headers, row):
... column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>
To get your numeric values into floats, add this
converters = [str.strip] + [float] * (len(headers) - 1)
up front, and do this
for h, v, conv in zip(headers, row, converters):
column[h].append(conv(v))
for each row instead of the similar two lines above.
Before answering your question:
If you do not have a Person
class, first you must consider whether you want to create a Person
class. Do you plan to reuse the concept of a Person
very often? If so, you should create a Person
class. (You have access to this data in the form of a passed-in variable and you don't care about being messy and sloppy.)
To answer your question:
You have access to their birthyear, so in that case you likely have a Person
class with a someperson.birthdate
field. In that case, you have to ask yourself, is someperson.age
a value that is reusable?
The answer is yes. We often care about age more than the birthdate, so if the birthdate is a field, age should definitely be a derived field. (A case where we would not do this: if we were calculating values like someperson.chanceIsFemale
or someperson.positionToDisplayInGrid
or other irrelevant values, we would not extend the Person
class; you just ask yourself, "Would another program care about the fields I am thinking of extending the class with?" The answer to that question will determine if you extend the original class, or make a function (or your own class like PersonAnalysisData
or something).)
Try git ls-files | xargs du -hs --threshold=1M
.
We use the below command in our CI pipeline, it halts if it finds any big files in the git repo:
test $(git ls-files | xargs du -hs --threshold=1M 2>/dev/null | tee /dev/stderr | wc -l) -gt 0 && { echo; echo "Aborting due to big files in the git repository."; exit 1; } || true
"File" -> "Invalidate Caches..."
worked for me.
You can push a branch to a remote server, say github. You would first have to do the initial project setup, then clone your project and:
git push <remote repo> <your branch>
There are two different ways to use delay in selenium one which is most commonly in use. Please try this:
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
second one which you can use that is simply try catch method by using that method you can get your desire result.if you want example code feel free to contact me defiantly I will provide related code
You could also look at git-svn, which is essentially a git front-end to subversion.
grep -- -X
grep \\-X
grep '\-X'
grep "\-X"
grep -e -X
grep [-]X
I have tried xlrd, pandas, openpyxl and other such libraries and all of them seem to take exponential time as the file size increase as it reads the entire file. The other solutions mentioned above where they used 'on_demand' did not work for me. If you just want to get the sheet names initially, the following function works for xlsx files.
def get_sheet_details(file_path):
sheets = []
file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
# Make a temporary directory with the file name
directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
os.mkdir(directory_to_extract_to)
# Extract the xlsx file as it is just a zip file
zip_ref = zipfile.ZipFile(file_path, 'r')
zip_ref.extractall(directory_to_extract_to)
zip_ref.close()
# Open the workbook.xml which is very light and only has meta data, get sheets from it
path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
with open(path_to_workbook, 'r') as f:
xml = f.read()
dictionary = xmltodict.parse(xml)
for sheet in dictionary['workbook']['sheets']['sheet']:
sheet_details = {
'id': sheet['@sheetId'],
'name': sheet['@name']
}
sheets.append(sheet_details)
# Delete the extracted files directory
shutil.rmtree(directory_to_extract_to)
return sheets
Since all xlsx are basically zipped files, we extract the underlying xml data and read sheet names from the workbook directly which takes a fraction of a second as compared to the library functions.
Benchmarking: (On a 6mb xlsx file with 4 sheets)
Pandas, xlrd: 12 seconds
openpyxl: 24 seconds
Proposed method: 0.4 seconds
Since my requirement was just reading the sheet names, the unnecessary overhead of reading the entire time was bugging me so I took this route instead.
List<Class1> list = new List<Class1>();
int index = list.FindIndex(item => item.Number == textBox6.Text);
Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";
list[index] = newItem;
I had the issue and
QString str = m_UI->myComboBox->currentText();
solved this.
I would recommend separating out all of the foreign-key constraints from your CREATE TABLE
statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.
You can add an FK constraint to a table using SQL like the following:
ALTER TABLE orders ADD CONSTRAINT orders_FK
FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);
In particular, your formats
and library
tables both have foreign-key constraints on one another. The two CREATE TABLE
statements to create these two tables can never run successfully, as each will only work when the other table has already been created.
Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE
statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.
You can generate statement like this: DROP TABLE t1, t2, t3, ...
and then use prepared statements to execute it:
SET FOREIGN_KEY_CHECKS = 0;
SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables
FROM information_schema.tables
WHERE table_schema = 'database_name'; -- specify DB name here.
SET @tables = CONCAT('DROP TABLE ', @tables);
PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;
String(true).toLowerCase() == 'true'; // true
String("true").toLowerCase() == 'true'; // true
String("True").toLowerCase() == 'true'; // true
String("TRUE").toLowerCase() == 'true'; // true
String(false).toLowerCase() == 'true'; // false
If you are not sure of the input, the above works for boolean and as well any string.
This is a similar way I'm using here to generate an unique error code, based on Anton Purin answer, but relying on the more appropriate org.apache.commons.text.RandomStringGenerator
instead of the (once, not anymore) deprecated org.apache.commons.lang3.RandomStringUtils
:
@Singleton
@Component
public class ErrorCodeGenerator implements Supplier<String> {
private RandomStringGenerator errorCodeGenerator;
public ErrorCodeGenerator() {
errorCodeGenerator = new RandomStringGenerator.Builder()
.withinRange('0', 'z')
.filteredBy(t -> t >= '0' && t <= '9', t -> t >= 'A' && t <= 'Z', t -> t >= 'a' && t <= 'z')
.build();
}
@Override
public String get() {
return errorCodeGenerator.generate(8);
}
}
All advices about collision still apply, please be aware of them.
I would suggest the following code, you can use this <script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
to get the latitude and longitude of a location, although it may not be so accurate however it worked for me;
code snippet below
<!DOCTYPE html>
<html>
<head>
<title>Using Javascript's Geolocation API</title>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="mapContainer"></div>
<script type="text/javascript">
var lat = geoip_latitude();
var long = geoip_longitude();
document.write("Latitude: "+lat+"</br>Longitude: "+long);
</script>
</body>
</html>
After a bit of time (and more searching), I found this blog entry by Jomo Fisher.
One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:
Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
[Snip]
The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup>
So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy
attribute reverts back to CLR 2.0 loading.
Yes, you can concatenate using a +
sign. Kotlin has string templates, so it's better to use them like:
var fn = "Hello"
var ln = "World"
"$fn $ln"
for concatenation.
You can even use String.plus()
method.
Apache Spark does not support native CSV output on disk.
You have four available solutions though:
You can convert your Dataframe into an RDD :
def convertToReadableString(r : Row) = ???
df.rdd.map{ convertToReadableString }.saveAsTextFile(filepath)
This will create a folder filepath. Under the file path, you'll find partitions files (e.g part-000*)
What I usually do if I want to append all the partitions into a big CSV is
cat filePath/part* > mycsvfile.csv
Some will use coalesce(1,false)
to create one partition from the RDD. It's usually a bad practice, since it may overwhelm the driver by pulling all the data you are collecting to it.
Note that df.rdd
will return an RDD[Row]
.
With Spark <2, you can use databricks spark-csv library:
Spark 1.4+:
df.write.format("com.databricks.spark.csv").save(filepath)
Spark 1.3:
df.save(filepath,"com.databricks.spark.csv")
With Spark 2.x the spark-csv
package is not needed as it's included in Spark.
df.write.format("csv").save(filepath)
You can convert to local Pandas data frame and use to_csv
method (PySpark only).
Note: Solutions 1, 2 and 3 will result in CSV format files (part-*
) generated by the underlying Hadoop API that Spark calls when you invoke save
. You will have one part-
file per partition.
I use window.onresize = function(){ checkOrientation(); }
And in checkOrientation you can employ window.orientation or body width checking
but the idea is, the "window.onresize" is the most cross browser method, at least with the majority of the mobile and desktop browsers that I've had an opportunity to test with.
My pattern is complicated, but it covers exactly "Any positive integer, excluding 0" (1 - 2147483647, not long). It's for decimal numbers and doesn't allow leading zeros.
^((1?[1-9][0-9]{0,8})|20[0-9]{8}|(21[0-3][0-9]{7})|(214[0-6][0-9]{6})
|(2147[0-3][0-9]{5})|(21474[0-7][0-9]{4})|(214748[0-2][0-9]{3})
|(2147483[0-5][0-9]{2})|(21474836[0-3][0-9])|(214748364[0-7]))$
As input and output streams are just start and end point, the solution is to temporary store data in byte array. So you must create intermediate ByteArrayOutputStream
, from which you create byte[]
that is used as input for new ByteArrayInputStream
.
public void doTwoThingsWithStream(InputStream inStream, OutputStream outStream){
//create temporary bayte array output stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doFirstThing(inStream, baos);
//create input stream from baos
InputStream isFromFirstData = new ByteArrayInputStream(baos.toByteArray());
doSecondThing(isFromFirstData, outStream);
}
Hope it helps.
When I use SourceTree to do the stuff, it will spit out this message.
The message that I encountered:
git -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=sourcetree submodule update --init --recursive
No submodule mapping found in .gitmodules for path 'SampleProject/SampleProject'
Completed with errors, see above
My scenario is I misapplied the project directory the contains .git folder.
SourceTree regarded this folder as git submodule, but actually not.
My solution is use command line to remove it.
$ git rm -r SampleProject --cached
$ git commit -m "clean up folders"
remove the garbage in git and keep it clean.
When you're using iOS >= 4
dispatch_async(dispatch_get_main_queue(), ^{
//Your main thread code goes in here
NSLog(@"Im on the main thread");
});
There are a couple different ways I would do this:
1) Mimic Excel Tables Using with a Named Range
In your example, you named the range A10:A20
"Age". Depending on how you wanted to reference a cell in that range you could either (as @Alex P wrote) use =INDEX(Age, 5)
or if you want to reference a cell in range "Age" that is on the same row as your formula, just use:
=INDEX(Age, ROW()-ROW(Age)+1)
This mimics the relative reference features built into Excel tables but is an alternative if you don't want to use a table.
If the named range is an entire column, the formula simplifies as:
=INDEX(Age, ROW())
2) Use an Excel Table
Alternatively if you set this up as an Excel table and type "Age" as the header title of the Age column, then your formula in columns to the right of the Age column can use a formula like this:
=[@[Age]]
If you want to use numpy, you must define darr
to be a numpy array, not a list
:
import numpy as np
darr = np.array([1, 3.14159, 1e100, -2.71828])
print(darr.min())
darr.argmin()
will give you the index corresponding to the minimum.
The reason you were getting an error is because argmin
is a method understood by numpy arrays, but not by Python lists
.
You can do it in 2 steeps:
1. Use the checkout
for create the local branch:
git checkout -b yourBranchName
Work with your Branch as you want.
2. Use the push
command to autocreate the branch and send the code to the remote repository:
git push -u origin yourBanchName
There are mutiple ways to do this but I think that this way is really simple.
A simple way to do that in VBA is:
YourText = "c:\excel\text.txt"
xString = Mid(YourText, 2 + Len(YourText) - InStr(StrReverse(YourText), "\" ))
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
You can test it in this way
Console.WriteLine(DateTime.Now.ToString("tt "));
The output will be like this:
AM
or
PM
[class*="test"],[class="second"] {
background: #ffff00;
}
# Write a Python program that accepts a string and calculate the number of digits
# andletters.
stre =input("enter the string-->")
countl = 0
countn = 0
counto = 0
for i in stre:
if i.isalpha():
countl += 1
elif i.isdigit():
countn += 1
else:
counto += 1
print("The number of letters are --", countl)
print("The number of numbers are --", countn)
print("The number of characters are --", counto)
You have to use the escaped unicode :
Like
.breadcrumbs a:before {
content: '\0000a0';
}
More info on : http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/
A Java list is a collection of objects ... the elements of a list. The size of the list is the number of elements in that list. If you want that size to be fixed, that means that you cannot either add or remove elements, because adding or removing elements would violate your "fixed size" constraint.
The simplest way to implement a "fixed sized" list (if that is really what you want!) is to put the elements into an array and then Arrays.asList(array)
to create the list wrapper. The wrapper will allow you to do operations like get
and set
, but the add
and remove
operations will throw exceptions.
And if you want to create a fixed-sized wrapper for an existing list, then you could use the Apache commons FixedSizeList
class. But note that this wrapper can't stop something else changing the size of the original list, and if that happens the wrapped list will presumably reflect those changes.
On the other hand, if you really want a list type with a fixed limit (or limits) on its size, then you'll need to create your own List class to implement this. For example, you could create a wrapper class that implements the relevant checks in the various add
/ addAll
and remove
/ removeAll
/ retainAll
operations. (And in the iterator remove
methods if they are supported.)
So why doesn't the Java Collections framework implement these? Here's why I think so:
Collections.sort
.replace:
transport_select.onChange = function(){toggleSelect(transport_select_id);};
with:
transport_select.onchange = function(){toggleSelect(transport_select_id);};
on'C'hange >> on'c'hange
You can use addEventListener too.
Create the base method as virtual
public virtual ActionResult Index()
Create the overridden method as override
public override ActionResult Index()
Edit: This obviously applies only if the override method is in a derived class which appears not to have been the OP's intention.
I was struggling to get this right using the scripts provided above and some other scripts especially when files and folder names had newline or spaces.
Finally stumbled on tmpreaper and it has been worked pretty well for us so far.
tmpreaper -t 5d ~/Downloads
tmpreaper --protect '*.c' -t 5h ~/my_prg
Original Source link
Has features like test, which checks the directories recursively and lists them. Ability to delete symlinks, files or directories and also the protection mode for a certain pattern while deleting
Date td = new Date();
String b = new String("");
SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd");
b = format.format(td);
out.println(b);
If you have added test.c to your Code::Blocks project, the definition will be seen twice - once via the #include and once by the linker. You need to:
From my experience I've found that some commands which run in IPython do not run in base Python. For example, pwd
and ls
don't work alone in base Python. However they will work if prefaced with a %
such as: %pwd
and %ls
.
Also, in IPython, you can run the cd command like: cd C:\Users\
... This doesn't seem to work in base python, even when prefaced with a %
however.
Typically you need to do 5 things to include a library in your project:
1) Add #include statements necessary files with declarations/interfaces, e.g.:
#include "library.h"
2) Add an include directory for the compiler to look into
-> Configuration Properties/VC++ Directories/Include Directories (click and edit, add a new entry)
3) Add a library directory for *.lib files:
-> project(on top bar)/properties/Configuration Properties/VC++ Directories/Library Directories (click and edit, add a new entry)
4) Link the lib's *.lib files
-> Configuration Properties/Linker/Input/Additional Dependencies (e.g.: library.lib;
5) Place *.dll files either:
-> in the directory you'll be opening your final executable from or into Windows/system32
Laravel ^5.7 includes new middleware to handle and redirect unauthenticated users.
It works well with "web" guard... of course the "login" route (or whatever you name your login route) should be defined in web.php.
the problem is when your are using custom guard. Different guard would redirect unauthenticated users to different route.
here's a quick workaround based on John's response (it works for me).
app/Http/Middleware/Authenticate.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* @var array
*/
protected $guards = [];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string[] ...$guards
* @return mixed
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
$this->guards = $guards;
return parent::handle($request, $next, ...$guards);
}
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
if (in_array('admin', $this->guards)) {
return route('admin.login');
}
return route('login');
}
}
}
Source : Issue #26292
This is an example of the use of this pattern that worked for me on empty datagrids.
<Style.Triggers>
<DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
<Setter Property="Background">
<Setter.Value>
<VisualBrush Stretch="None">
<VisualBrush.Visual>
<TextBlock Text="We did't find any matching records for your search..." FontSize="16" FontWeight="SemiBold" Foreground="LightCoral"/>
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
Above of all, I found this library right here. Works out of the box perfectly on a Bootstrap-3 environment.
CSS
<link rel="stylesheet" type="text/css" href="dist/bootstrap-clockpicker.min.css">
HTML
<div class="input-group clockpicker">
<input type="text" class="form-control" value="09:30">
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
JAVASCRIPT
<script type="text/javascript" src="dist/bootstrap-clockpicker.min.js"></script>
<script type="text/javascript">
$('.clockpicker').clockpicker();
</script>
As simple as that! Find more examples on the link above.
If you are using Bootstrap-4, the most popular time/date picker library available right now is Tempus Dominus. It is not fancy looking, but much responsive and modern.
from version 0.16.1 you can do
df.drop(['column_name'], axis = 1, inplace = True, errors = 'ignore')
I had another bug where find_link
on Chrome and Poltergeist could not click an A tag with an EM tag and some text inside of it, although it worked fine in Firefox and rack_test. The solution was to replace click_link(link)
with:
find('a em', text: link).click
Here is an example:
StartupWindow.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class StartupWindow extends JFrame implements ActionListener
{
private JButton btn;
public StartupWindow()
{
super("Simple GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn = new JButton("Open the other JFrame!");
btn.addActionListener(this);
btn.setActionCommand("Open");
add(btn);
pack();
}
@Override
public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();
if(cmd.equals("Open"))
{
dispose();
new AnotherJFrame();
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run()
{
new StartupWindow().setVisible(true);
}
});
}
}
AnotherJFrame.java
import javax.swing.JFrame;
import javax.swing.JLabel;
public class AnotherJFrame extends JFrame
{
public AnotherJFrame()
{
super("Another GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Empty JFrame"));
pack();
setVisible(true);
}
}
I encountered the same problem, but I check find that I hadn't the parent table. So I just edit the parent migration in front of the child migration. Just do it.
We can use __call__
method to use other class methods as static methods.
class _Callable:
def __init__(self, anycallable):
self.__call__ = anycallable
class Model:
def get_instance(conn, table_name):
""" do something"""
get_instance = _Callable(get_instance)
provs_fac = Model.get_instance(connection, "users")
Django Mail Templated is a feature-rich Django application to send emails with Django template system.
Installation:
pip install django-mail-templated
Configuration:
INSTALLED_APPS = (
...
'mail_templated'
)
Template:
{% block subject %}
Hello {{ user.name }}
{% endblock %}
{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}
Python:
from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])
More info: https://github.com/artemrizhov/django-mail-templated
You can simply install PHPUnit to run commands (https://github.com/sebastianbergmann/phpunit/#php-archive-phar):
wget https://phar.phpunit.de/phpunit.phar
chmod +x phpunit.phar
mv phpunit.phar /usr/local/bin/phpunit
Run single test
And then run PHPunit test:
phpunit test.php
Content of test file is following:
<?php
class StackTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
}
public function testSave()
{
}
}
Run test suite
Configuration of test suite: demosuite.xml. demo
is directory containing all tests. Test files must be named as *_test.php
(suffix
).
<testsuites>
<testsuite name="DemoTestSuite">
<directory suffix="test.php">demo</directory>
</testsuite>
</testsuites>
Test suite runs with following commands:
phpunit -c demosuite.xml --testsuite DemoTestSuite
You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".
You can only use real devices.
Emulator Limitations
The functional limitations of the emulator include:
Refer to the documentation
In the tour guide app of Udacity's Basic ANdroid course I have used the concept of Fragments. I got stuck for a while experiencing difficulty to access some string resources described in strings, xml file. Finally got a solution.
This is the main activity class
package com.example.android.tourguidekolkata;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
//lines of code
//lines of code
//lines of code
YourClass adapter = new YourClass(getSupportFragmentManager(), getApplicationContext());
//lines of code
// getApplicationContext() method passses the Context of main activity to the class TourFragmentPageAdapter
}
}
This is the non Activity class that extends FragmentPageAdapter
public class YourClass extends FragmentPagerAdapter {
private String yourStringArray[] = new String[4];
Context context;
public YourClass (FragmentManager fm, Context context)
{
super(fm);
this.context = context; // store the context of main activity
// now you can use this context to access any resource
yourStringArray[0] = context.getResources().getString(R.string.tab1);
yourStringArray[1] = context.getResources().getString(R.string.tab2);
yourStringArray[2] = context.getResources().getString(R.string.tab3);
yourStringArray[3] = context.getResources().getString(R.string.tab4);
}
@Override
public Fragment getItem(int position)
{
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return yourStringArras[position];
}
}
Prototype makes it dead simple
new Ajax.Request( '/myurl', {
method: 'get',
parameters: { 'param1': 'value1'},
onSuccess: function(response){
alert(response.responseText);
},
onFailure: function(){
alert('ERROR');
}
});
I had the same error message in my localhost development with my Visual Studio. Note that everything was working when released with Microsoft Release Management (MRM). I fixed my situation by changing the initial value that was a MRM reference.
My App.config initial value was the following:
<connectionStrings>
<add name="BDORA" connectionString="__token3__" />
</connectionStrings>
Locally, the application execution could not interpret the token3 reference to its real value in Tokens.xml. To make it work on my localhost, I had to force the value from token3 in Tokens.xml into the App.config file.
With all respect the most likely thing is that you are mistaken about why the click is being 'rejected'. Why do you think some program is trying to determine if it's human or not? The Robot class (have used it a lot) should send messages that the operating system has no way to distinguish from a user doing the click.
header('Location: '.$_SERVER['REQUEST_URI']);
This code works for me: check this link
This is my code when i stop and start service in activity
case R.id.buttonStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
}
And in service class:
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
HAPPY CODING!
To answer the question more generally, the answer is:
select: function( event , ui ) {
alert( "You selected: " + ui.item.label );
}
Complete example :
$('#test').each(function(i, el) {_x000D_
var that = $(el);_x000D_
that.autocomplete({_x000D_
source: ['apple','banana','orange'],_x000D_
select: function( event , ui ) {_x000D_
alert( "You selected: " + ui.item.label );_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
$('.a .b , .a .c').css('border', '2px solid yellow');_x000D_
//selects b and c
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="a">a_x000D_
<div class="b">b</div>_x000D_
<div class="c">c</div>_x000D_
<div class="d">d</div>_x000D_
</div>
_x000D_
first you have to import: import javax.swing.JOptionPane; then you can call it using this:
JOptionPane.showMessageDialog(null,
"ALERT MESSAGE",
"TITLE",
JOptionPane.WARNING_MESSAGE);
the null puts it in the middle of the screen. put whatever in quotes under alert message. Title is obviously title and the last part will format it like an error message. if you want a regular message just replace it with PLAIN_MESSAGE
. it works pretty well in a lot of ways mostly for errors.
An alternative way is to install the Maven for Java
plugin and create a maven project within Visual Studio. The steps are described in the official documentation:
To declare a string literal as an output column, leave the Table
off and just use Test
. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta()
, the table name will be an empty string because it isn't associated with a table.
SELECT
`field1`,
`field2`,
'Test' AS `field3`
FROM `Test`;
Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.
If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:
SELECT
field1,
field2,
field3
FROM
/* subquery wraps all fields to put the literal inside a table */
(SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test
Now field3
will come in the output as Test.field3
.
Don't forget that we have the slide to back gesture now. You probably want to remove this as well. Don't forget to enable it back again if necessary.
if ([self.navigationItem respondsToSelector:@selector(hidesBackButton)]) {
self.navigationItem.hidesBackButton = YES;
}
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
You can use body or * to make margin and padding 0px;
*{
margin: 0px;
padding:0px;
}
Similarly I did for long:
myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;
I would think this: http://jsfiddle.net/Skooljester/S3y5p/1/ should do it. If I don't have the class names 100% correct you can just change them to whatever you need them to be.
The standard approach is to use sprintf(buffer, "%lu", value);
to write a string rep of value
to buffer
. However, overflow is a potential problem, as sprintf
will happily (and unknowingly) write over the end of your buffer.
This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.
This site discusses this and related problems at some length.
Some libraries offer snprintf
as an alternative which lets you specify a maximum buffer size.
The state of the database is maintained from the start of the transaction. If you retrieve a value in session1, then update that value in session2, retrieving it again in session1 will return the same results. Reads are repeatable.
session1> BEGIN;
session1> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> BEGIN;
session2> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> UPDATE names SET firstname = 'Bob' WHERE id = 7;
session2> SELECT firstname FROM names WHERE id = 7;
Bob
session2> COMMIT;
session1> SELECT firstname FROM names WHERE id = 7;
Aaron
Within the context of a transaction, you will always retrieve the most recently committed value. If you retrieve a value in session1, update it in session2, then retrieve it in session1again, you will get the value as modified in session2. It reads the last committed row.
session1> BEGIN;
session1> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> BEGIN;
session2> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> UPDATE names SET firstname = 'Bob' WHERE id = 7;
session2> SELECT firstname FROM names WHERE id = 7;
Bob
session2> COMMIT;
session1> SELECT firstname FROM names WHERE id = 7;
Bob
Makes sense?
At line 5 there is a /
missing.
There is a good answer on the differences between ;
and /
here.
Basically, when running a CREATE
block via script, you need to use /
to let SQLPlus know when the block ends, since a PL/SQL block can contain many instances of ;
.
In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)
Meaning the first answer was correct actually char ch = (char) yourInt;
if in yourint=49 (or 0x31), ch will be '1'
When I was going through the Angular basics guide on forms, and hit the resetting of forms section, I was very much left in surprise when I read the following in regards to the solution they give.
This is a temporary workaround while we await a proper form reset feature.
I personally haven't tested if the workaround they provided works (i assume it does), but I believe it is not neat, and that there must be a better way to go about the issue.
According to the FormGroup API (which is marked as stable) there already is a 'reset' method.
I tried the following. In my template.html file i had
<form (ngSubmit)="register(); registrationForm.reset();" #registrationForm="ngForm">
...
</form>
Notice that in the form element, I've initialised a template reference variable 'registrationForm' and initialized it to the ngForm Directive, which "governs the form as a whole". This gave me access to the methods and attributes of the governing FormGroup, including the reset() method.
Binding this method call to the ngSubmit event as show above reset the form (including pristine, dirty, model states etc) after the register() method is completed. For a demo this is ok, however it isn't very helpful for real world applications.
Imagine the register() method performs a call to the server. We want to reset the form when we know that the server responded back that everything is OK. Updating the code to the following caters for this scenario.
In my template.html file :
<form (ngSubmit)="register(registrationForm);" #registrationForm="ngForm">
...
</form>
And in my component.ts file :
@Component({
...
})
export class RegistrationComponent {
register(form: FormGroup) {
...
// Somewhere within the asynchronous call resolve function
form.reset();
}
}
Passing the 'registrationForm' reference to the method would allow us to call the reset method at the point of execution that we want to.
Hope this helps you in any way. :)
Note: This approach is based on Angular 2.0.0-rc.5
Another simple solution (not very elegant, but not too ugly also) is to place a inner div / span
then get his height ($(this).find('span).height()
).
Here is an example of using this strategy:
$(".more").click(function(){_x000D_
if($(this).parent().find('.showMore').length) {_x000D_
$(this).parent().find('.showMore').removeClass('showMore').css('max-height','90px');_x000D_
$(this).parent().find('.more').removeClass('less').text('More');_x000D_
} else {_x000D_
$(this).parent().find('.text').addClass('showMore').css('max-height',$(this).parent().find('span').height());_x000D_
$(this).parent().find('.more').addClass('less').text('Less');_x000D_
}_x000D_
});
_x000D_
* {transition: all 0.5s;}_x000D_
.text {position:relative;width:400px;max-height:90px;overflow:hidden;}_x000D_
.showMore {}_x000D_
.text::after {_x000D_
content: "";_x000D_
position: absolute; bottom: 0; left: 0;_x000D_
box-shadow: inset 0 -26px 22px -17px #fff;_x000D_
height: 39px;_x000D_
z-index:99999;_x000D_
width:100%;_x000D_
opacity:1;_x000D_
}_x000D_
.showMore::after {opacity:0;}_x000D_
.more {border-top:1px solid gray;width:400px;color:blue;cursor:pointer;}_x000D_
.more.less {border-color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<div class="text">_x000D_
<span>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</span></div>_x000D_
<div class="more">More</div>_x000D_
</div>
_x000D_
(This specific example is using this trick to animate the max-height and avoiding animation delay when collapsing (when using high number for the max-height property).
My client reported this error. I found that he was messing with *.ldf files. He copied *ldf file on one database and renamed it to match a second database (which I asked him to place in a folder).
I replicated the same scenario, and got this same error in my development system. Error got fixed after deleting the *ldf file(s).
I just wanted to follow up on something I found working with Python 2.7 on Centos 6. Adding the package_data or data_files as mentioned above did not work for me. I added a MANIFEST.IN with the files I wanted which put the non-python files into the tarball, but did not install them on the target machine via RPM.
In the end, I was able to get the files into my solution using the "options" in the setup/setuptools. The option files let you modify various sections of the spec file from setup.py. As follows.
from setuptools import setup
setup(
name='theProjectName',
version='1',
packages=['thePackage'],
url='',
license='',
author='me',
author_email='[email protected]',
description='',
options={'bdist_rpm': {'install_script': 'filewithinstallcommands'}},
)
file - MANIFEST.in:
include license.txt
file - filewithinstallcommands:
mkdir -p $RPM_BUILD_ROOT/pathtoinstall/
#this line installs your python files
python setup.py install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES
#install license.txt into /pathtoinstall folder
install -m 700 license.txt $RPM_BUILD_ROOT/pathtoinstall/
echo /pathtoinstall/license.txt >> INSTALLED_FILES
Refer below Code Snip
In HTML Page
<input id="test" type="number" value="0"/>
In Java Script
document.getElementById("test").value=request.responseText;// in case of String
document.getElementById("test").value=new Number(responseText);// in case of Number
You need either
A foreign key needs to uniquely identify the parent row: you currently have no way to do that because Title is not unique.
Clustering uses shared storage of some kind (a drive cage or a SAN, for example), and puts two database front-ends on it. The front end servers share an IP address and cluster network name that clients use to connect, and they decide between themselves who is currently in charge of serving client requests.
If you're asking about a particular database server, add that to your question and we can add details on their implementation, but at its core, that's what clustering is.
There are several ways to do an email from HTML. Typically you see people doing a mailto like so:
<a href="mailto:[email protected]">Click to email</a>
But if you are doing it from a button you may want to look into a javascript solution.
It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/
In cpp, you need to pay special attention to string types when using execvp
:
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;
const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());
// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
string arg;
cin >> arg;
if (arg.empty()) {
argv[arg_i] = nullptr;
break;
} else {
argv[arg_i] = strdup(arg.c_str());
}
++arg_i;
}
// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
// Print error if command not found
cerr << "command '" << command << "' not found\n";
}
Reference: execlp?execvp?????
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}