Both i++
and ++i
are short-hand for i = i + 1
.
In addition to changing the value of i, they also return the value of i, either before adding one (i++
) or after adding one (++i
).
In a loop the third component is a piece of code that is executed after each iteration.
for (int i=0; i<10; i++)
The value of that part is not used, so the above is just the same as
for(int i=0; i<10; i = i+1)
or
for(int i=0; i<10; ++i)
Where it makes a difference (between i++
and ++i
)is in these cases
while(i++ < 10)
for (int i=0; i++ < 10; )
public static Date getZeroTimeDate(Date fecha) {
Date res = fecha;
Calendar calendar = Calendar.getInstance();
calendar.setTime( fecha );
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
res = calendar.getTime();
return res;
}
Date currentDate = getZeroTimeDate(new Date());// get current date
this is the simplest way to solve this problem.
<RatingBar
android:id="@+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/ratingBarStyleSmall"
android:numStars="5"
android:stepSize="0.1"
android:isIndicator="true" />
in code
mRatingBar.setRating(int)
It also depends on what you need. For basic SQL transactions you could try doing TSQL transactions by using BEGIN TRANS and COMMIT TRANS in your code. That is the easiest way but it does have complexity and you have to be careful to commit properly (and rollback).
I would use something like
SQLTransaction trans = null;
using(trans = new SqlTransaction)
{
...
Do SQL stuff here passing my trans into my various SQL executers
...
trans.Commit // May not be quite right
}
Any failure will pop you right out of the using
and the transaction will always commit or rollback (depending on what you tell it to do). The biggest problem we faced was making sure it always committed. The using ensures the scope of the transaction is limited.
Things you can add to declarations: [] in modules
Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.
let nietos = [];
function nieto(aData) {
let o = {};
for ( let i = 0; i < aData.length; i++ ) {
let key = "0" + (i + 1);
o[key] = aData[i];
}
nietos.push(o);
}
nieto( ["Band", "Ramones"] );
nieto( ["Style", "RockPunk"] );
nieto( ["", "", "", "Another String"] );
/* convert array of object into string json */
var jsonString = JSON.stringify(nietos);
document.write(jsonString);
_x000D_
For linux/unix OS, you can use the shell syntax
const shell = require('child_process').execSync ;
const currentPath= `/path/to/name.png`;
const newPath= `/path/to/another_name.png`;
shell(`mv ${currentPath} ${newPath}`);
That's it!
base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z
, a-z
, 0-9
, +
, /
* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.
Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b''
syntax.
If you remove the b
, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)
In your second example:
>>> encoded = base64.b64encode('data to be encoded')
All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with
>>> encoded = 'data to be encoded'.encode('ascii')
Or simpler:
>>> encoded = b'data to be encoded'
Which would be the same thing in this case.
* Most base64 flavours may also include a =
at the end as padding. In addition, some base64 variants may use characters other than +
and /
. See the Variants summary table at Wikipedia for an overview.
I have a previously-working code that throws this error now. No issue on password. No need to convert message to base64 either. Turns out, i need to do the following:
Working code
public static void SendEmail(string emailTo, string subject, string body)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("[email protected]", "secretpassword"),
EnableSsl = true
};
client.Send("[email protected]", emailTo, subject, body);
}
Turning off 2-factor authentication
Set "Allow less secure apps" to ON (same page, need to scroll to bottom)
Even in base Python you can do the computation in generic form
result = sum(x**2 for x in some_vector) ** 0.5
x ** 2
is surely not an hack and the computation performed is the same (I checked with cpython source code). I actually find it more readable (and readability counts).
Using instead x ** 0.5
to take the square root doesn't do the exact same computations as math.sqrt
as the former (probably) is computed using logarithms and the latter (probably) using the specific numeric instruction of the math processor.
I often use x ** 0.5
simply because I don't want to add math
just for that. I'd expect however a specific instruction for the square root to work better (more accurately) than a multi-step operation with logarithms.
In spring boot 2.x you need to reference provider specific properties.
The default, hikari can be set with spring.datasource.hikari.maximum-pool-size
.
you can also use MEDIUMBLOB/LONGBLOB or MEDIUMTEXT/LONGTEXT
A BLOB type in MySQL can store up to 65,534 bytes, if you try to store more than this much data MySQL will truncate the data. MEDIUMBLOB can store up to 16,777,213 bytes, and LONGBLOB can store up to 4,294,967,292 bytes.
The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'
It also allows the placeholder to depend on the instance for ModelForms with instance specified.
As was said you need to remove the FKs before. On Mysql do it like this:
ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`;
ALTER TABLE `table_name` DROP INDEX `id_name_fk`;
CPANEL solution
Go to Cpanel, look for Remote MySQL. Add the the IP in the input field:
Host (% wildcard is allowed)
Comment to remember what IP that is. That was it for me.
i it integer, int to Integer
Integer intObj = new Integer(i);
add to collection
list.add(String.valueOf(intObj));
the & is the default value for DEFINE, which allows you to use substitution variables. I like to turn it off using
SET DEFINE OFF
then you won't have to worry about escaping or CHR(38).
What class do you have on the image tag?
Try this
<img src="/images/myimage.jpg" style="border:none;" alt="my image" />
This is easier since Java 9. A Duration
still isn’t formattable, but methods for getting the hours, minutes and seconds are added, which makes the task somewhat more straightforward:
LocalDateTime start = LocalDateTime.of(2019, Month.JANUARY, 17, 15, 24, 12);
LocalDateTime end = LocalDateTime.of(2019, Month.JANUARY, 18, 15, 43, 33);
Duration diff = Duration.between(start, end);
String hms = String.format("%d:%02d:%02d",
diff.toHours(),
diff.toMinutesPart(),
diff.toSecondsPart());
System.out.println(hms);
The output from this snippet is:
24:19:21
This:
doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));
should be:
doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));
LoadXml()
is for loading an XML string, not a file name.
<!-- const cars=['Audi','Merc','BMW','Volvo','Tesla'] -->
<ul>
<li *ngFor="let car of cars">{{car}}</li>
</ul>
/*
*ngFor="let c of oneDimArray | sortBy:'asc'"
*ngFor="let c of arrayOfObjects | sortBy:'asc':'propertyName'"
*/
import { Pipe, PipeTransform } from '@angular/core';
import { orderBy } from 'lodash';
@Pipe({ name: 'sortBy' })
export class SortByPipe implements PipeTransform {
transform(value: any[], order = '', column: string = ''): any[] {
if (!value || order === '' || !order) { return value; } // no array
if (!column || column === '') { return sortBy(value); } // sort 1d array
if (value.length <= 1) { return value; } // array with only one item
return orderBy(value, [column], [order]);
}
}
Code for set background color, for SolidColor
:
button.Background = new SolidColorBrush(Color.FromArgb(Avalue, rValue, gValue, bValue));
I know this doesn't answer OPs exact question but I came here with the same symptom but a different cause:
I had the .scss files of Slick Slider included like this:
@import "../../../node_modules/slick-carousel/slick/slick.scss";
On closer inspection it turned out that the it was trying to load the font from an invalid location (<host>/assets/css/fonts/slick.woff
), the way it was referenced from the stylesheet.
I ended up simply copying the /font/
to my assets/css/
and the issue was resolved for me.
Using dialog methods:
$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');
Or directly, hacky though:
$("span.ui-dialog-title").text('My New Title');
For future reference, you can skip google with jQuery. The jQuery API will answer your questions most of the time. In this case, the Dialog API page. For the main library: http://api.jquery.com
Along with the above answers, do also consider this site; https://google-webfonts-helper.herokuapp.com/fonts
Advantage:
allows you to self-host those google fonts for better response times
choose your font(s)
E.g your_theme.css
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'),
url('css_fonts/open-sans-v15-latin-regular.woff2') format('woff2'),
url('css_fonts/open-sans-v15-latin-regular.woff') format('woff');
}
body {
font-family: 'Open Sans',sans-serif;
}
OTRS, Cerberus
For multi-line shell scripts or those run multiple times, I would create a new bash script file (starting from #!/bin/bash
), and simply run it with sh
from Jenkinsfile:
sh 'chmod +x ./script.sh'
sh './script.sh'
I've just found a great tool for that need, it is called tabulate.
It prints tabular data and works with DataFrame
.
from tabulate import tabulate
import pandas as pd
df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})
print(tabulate(df, headers='keys', tablefmt='psql'))
+----+-----------+-------------+
| | col_two | column_3 |
|----+-----------+-------------|
| 0 | 0.0001 | ABCD |
| 1 | 1e-05 | ABCD |
| 2 | 1e-06 | long string |
| 3 | 1e-07 | ABCD |
+----+-----------+-------------+
Note:
To suppress row indices for all types of data, pass
showindex="never"
orshowindex=False
.
For .NET Core, this is how I'll know the version of EntityFramework that I'm using. Let's assume that the name of my project is DemoApi, I have the following at my disposal:
dotnet list DemoApi.csproj package
Adding a reference to System.Net.Http.Formatting.dll may cause DLL mismatch issues. Right now, System.Net.Http.Formatting.dll appears to reference version 4.5.0.0 of Newtonsoft.Json.DLL, whereas the latest version is 6.0.0.0. That means you'll need to also add a binding redirect to avoid a .NET Assembly exception if you reference the latest Newtonsoft NuGet package or DLL:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
So an alternative solution to adding a reference to System.Net.Http.Formatting.dll is to read the response as a string and then desearalize yourself with JsonConvert.DeserializeObject(responseAsString). The full method would be:
public async Task<T> GetHttpResponseContentAsType(string baseUrl, string subUrl)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(subUrl);
response.EnsureSuccessStatusCode();
var responseAsString = await response.Content.ReadAsStringAsync();
var responseAsConcreteType = JsonConvert.DeserializeObject<T>(responseAsString);
return responseAsConcreteType;
}
}
If you have Excel 2007 or later use COUNTIFS
with an "S" on the end, i.e.
=COUNTIFS(B2:B292,">10",B2:B292,"<10000")
You may need to change commas , to semi-colons ;
In earlier versions of excel use SUMPRODUCT
like this
=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))
Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=
echo "$string" | tr xyz _
would replace each occurrence of x
, y
, or z
with _
, giving A__BC___DEF__LMN
in your example.
echo "$string" | sed -r 's/[xyz]+/_/g'
would replace repeating occurrences of x
, y
, or z
with a single _
, giving A_BC_DEF_LMN
in your example.
Here's an example of how you would accomplish such a task:
#import <Foundation/Foundation.h>
typedef int (^IntBlock)();
@interface myobj : NSObject
{
IntBlock compare;
}
@property(readwrite, copy) IntBlock compare;
@end
@implementation myobj
@synthesize compare;
- (void)dealloc
{
// need to release the block since the property was declared copy. (for heap
// allocated blocks this prevents a potential leak, for compiler-optimized
// stack blocks it is a no-op)
// Note that for ARC, this is unnecessary, as with all properties, the memory management is handled for you.
[compare release];
[super dealloc];
}
@end
int main () {
@autoreleasepool {
myobj *ob = [[myobj alloc] init];
ob.compare = ^
{
return rand();
};
NSLog(@"%i", ob.compare());
// if not ARC
[ob release];
}
return 0;
}
Now, the only thing that would need to change if you needed to change the type of compare would be the typedef int (^IntBlock)()
. If you need to pass two objects to it, change it to this: typedef int (^IntBlock)(id, id)
, and change your block to:
^ (id obj1, id obj2)
{
return rand();
};
I hope this helps.
EDIT March 12, 2012:
For ARC, there are no specific changes required, as ARC will manage the blocks for you as long as they are defined as copy. You do not need to set the property to nil in your destructor, either.
For more reading, please check out this document: http://clang.llvm.org/docs/AutomaticReferenceCounting.html
You not only have to put the meta tag, telling that it is UTF-8 but really make the document UTF-8. You can do that with good editors (like notepad++) by converting them to "unicode" or "UTF-8 without BOM". Than you can simply use arabic characters
As this page is UTF-8, here are some examples (I hope I don't write anything rude here): ???
If you use a server side scripting language make sure that it does not output the page in a different encoding. In PHP e.g. you can set it like this:
header('Content-Type: text/html; charset=utf-8');
in the servlet you should put
response.setStatus(response.SC_MOVED_PERMANENTLY);
to send the '301' xmlHttp status you need for a redirection...
and in the $.ajax function you should not use the .toString()
function..., just
if (xmlHttp.status == 301) {
top.location.href = 'xxxx.jsp';
}
the problem is it is not very flexible, you can't decide where you want to redirect..
redirecting through the servlets should be the best way. but i still can not find the right way to do it.
Use 10.0.2.2
for default AVD and 10.0.3.2
for genymotion.
I've just seen this problem myself, Jboss AS7 with jdk1.5.0_09. Update System Property JAVA_HOME to jdk1.7+ to fix (I'm using jdk1.7.0_67).
Have a look at the example http://www.cplusplus.com/reference/clibrary/cstdarg/va_arg/, they pass the number of arguments to the method but you can ommit that and modify the code appropriately (see the example).
I would use instead "checkout -b" and it is easier to understand.
git checkout myFeature
git rebase master
git push origin --delete myFeature
git push origin myFeature
when you delete you prevent to push in an exiting branch that contains different SHA ID. I am deleting only the remote branch in this case.
If this is related to a form submission, use a hidden inputinside the form and change the hidden input value to this variable value. Then you can get that hidden input value in the php page and assign it to your php variable after form submission.
Update:
According to your edit, it seems you don't understand how javascript and php works. Javascript is a client side language, and php is a serverside language. Therefore you cannot execute javascript logic and use that variable value to a php variable when you execute relevant page in the server. You can run the relevant javascript logic after client browser process the web page returned from the web server (which has already executed the php code for the relevant page). After the execution of the javascript code and after assigning the relevant value to the relevant javascript variable, you can use form submission or ajax to send that javascript variable value to use by another php page (or a request to process and get the same php page).
In Codeignitor version 3.0.x the system/core/Codeigniter.php do not contain the time constraint as well as inserting
ini_set('MAX_EXECUTION_TIME', -1);
will not work since codeignitor will override that with its own function set_time_limit() . So either you have to delete that function from codeignitor or simply you can insert
set_time_limit('1000');
in the beginning of the php file if you wanna change that to 1000 seconds. Set the time to 0 (zero) if you want to run it as long as it want.
With CentOS, you can do it using a combination of fastcgi for one version of PHP, and php-fpm for the other, as described here:
wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
wget http://download.fedora.redhat.com/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
sudo rpm -ivh rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
sudo rpm -ivh epel-release-5-4.noarch.rpm
CentOS/RHEL 5.x series have php-5.1 in box, simply install it with yum, eg:
sudo yum install php php-mysql php-mbstring php-mcrypt
For php 5.2 and 5.3, we can find many rpm packages on the Internet. However, they all conflict with the php which comes with CentOS, so, we’d better build and install them from soure, this is not difficult, the point is to install php at different location.
However, when install php as an apache module, we can only use one version of php at the same time. If we need to run different version of php on the same server, at the same time, for example, different virtual host may need different version of php. Fortunately, the cool FastCGI and PHP-FPM can help.
Build and install php-5.2 with fastcgi enabled
yum install gcc libxml2-devel bzip2-devel zlib-devel \
curl-devel libmcrypt-devel libjpeg-devel \
libpng-devel gd-devel mysql-devel
wget http://cn.php.net/get/php-5.2.17.tar.bz2/from/this/mirror
tar -xjf php-5.2.17.tar.bz2
cd php-5.2.17
./configure --prefix=/usr/local/php52 \
--with-config-file-path=/etc/php52 \
--with-config-file-scan-dir=/etc/php52/php.d \
--with-libdir=lib64 \
--with-mysql \
--with-mysqli \
--enable-fastcgi \
--enable-force-cgi-redirect \
--enable-mbstring \
--disable-debug \
--disable-rpath \
--with-bz2 \
--with-curl \
--with-gettext \
--with-iconv \
--with-openssl \
--with-gd \
--with-mcrypt \
--with-pcre-regex \
--with-zlib
make -j4 > /dev/null
sudo make install
sudo mkdir /etc/php52
sudo cp php.ini-recommended /etc/php52/php.ini
create file /usr/local/php52/bin/fcgiwrapper.sh
#!/bin/bash
PHP_FCGI_MAX_REQUESTS=10000
export PHP_FCGI_MAX_REQUESTS
exec /usr/local/php52/bin/php-cgi
chmod a+x /usr/local/php52/bin/fcgiwrapper.sh
Build and install php-5.3 with fpm enabled
wget http://cn.php.net/get/php-5.3.6.tar.bz2/from/this/mirror
tar -xjf php-5.3.6.tar.bz2
cd php-5.3.6
./configure --prefix=/usr/local/php53 \
--with-config-file-path=/etc/php53 \
--with-config-file-scan-dir=/etc/php53/php.d \
--enable-fpm \
--with-fpm-user=apache \
--with-fpm-group=apache \
--with-libdir=lib64 \
--with-mysql \
--with-mysqli \
--enable-mbstring \
--disable-debug \
--disable-rpath \
--with-bz2 \
--with-curl \
--with-gettext \
--with-iconv \
--with-openssl \
--with-gd \
--with-mcrypt \
--with-pcre-regex \
--with-zlib
make -j4 && sudo make install
sudo mkdir /etc/php53
sudo cp php.ini-production /etc/php53/php.ini
sed -i -e 's#php_fpm_CONF=\${prefix}/etc/php-fpm.conf#php_fpm_CONF=/etc/php53/php-fpm.conf#' \
sapi/fpm/init.d.php-fpm
sudo cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
sudo chmod a+x /etc/init.d/php-fpm
sudo /sbin/chkconfig --add php-fpm
sudo /sbin/chkconfig php-fpm on
sudo cp sapi/fpm/php-fpm.conf /etc/php53/
Configue php-fpm
Edit /etc/php53/php-fpm.conf, change some settings. This step is mainly to uncomment some settings, you can adjust the value if you like.
pid = run/php-fpm.pid
listen = 127.0.0.1:9000
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
Then, start fpm
sudo /etc/init.d/php-fpm start
Install and setup mod_fastcgi, mod_fcgid
sudo yum install libtool httpd-devel apr-devel
wget http://www.fastcgi.com/dist/mod_fastcgi-current.tar.gz
tar -xzf mod_fastcgi-current.tar.gz
cd mod_fastcgi-2.4.6
cp Makefile.AP2 Makefile
sudo make top_dir=/usr/lib64/httpd/ install
sudo sh -c "echo 'LoadModule fastcgi_module modules/mod_fastcgi.so' > /etc/httpd/conf.d/mod_fastcgi.conf"
yum install mod_fcgid
Setup and test virtual hosts
1) Add the following line to /etc/hosts
127.0.0.1 web1.example.com web2.example.com web3.example.com
2) Create web document root and drop an index.php under it to show phpinfo switch to user root, run
mkdir /var/www/fcgi-bin
for i in {1..3}; do
web_root=/var/www/web$i
mkdir $web_root
echo "<?php phpinfo(); ?>" > $web_root/index.php
done
Note: The empty /var/www/fcgi-bin directory is required, DO NOT REMOVE IT LATER
3) Create Apache config file(append to httpd.conf)
NameVirtualHost *:80
# module settings
# mod_fcgid
<IfModule mod_fcgid.c>
idletimeout 3600
processlifetime 7200
maxprocesscount 17
maxrequestsperprocess 16
ipcconnecttimeout 60
ipccommtimeout 90
</IfModule>
# mod_fastcgi with php-fpm
<IfModule mod_fastcgi.c>
FastCgiExternalServer /var/www/fcgi-bin/php-fpm -host 127.0.0.1:9000
</IfModule>
# virtual hosts...
#################################################################
#1st virtual host, use mod_php, run php-5.1
#################################################################
<VirtualHost *:80>
ServerName web1.example.com
DocumentRoot "/var/www/web1"
<ifmodule mod_php5.c>
<FilesMatch \.php$>
AddHandler php5-script .php
</FilesMatch>
</IfModule>
<Directory "/var/www/web1">
DirectoryIndex index.php index.html index.htm
Options -Indexes FollowSymLinks
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
#################################################################
#2nd virtual host, use mod_fcgid, run php-5.2
#################################################################
<VirtualHost *:80>
ServerName web2.example.com
DocumentRoot "/var/www/web2"
<IfModule mod_fcgid.c>
AddHandler fcgid-script .php
FCGIWrapper /usr/local/php52/bin/fcgiwrapper.sh
</IfModule>
<Directory "/var/www/web2">
DirectoryIndex index.php index.html index.htm
Options -Indexes FollowSymLinks +ExecCGI
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
#################################################################
#3rd virtual host, use mod_fastcgi + php-fpm, run php-5.3
#################################################################
<VirtualHost *:80>
ServerName web3.example.com
DocumentRoot "/var/www/web3"
<IfModule mod_fastcgi.c>
ScriptAlias /fcgi-bin/ /var/www/fcgi-bin/
AddHandler php5-fastcgi .php
Action php5-fastcgi /fcgi-bin/php-fpm
</IfModule>
<Directory "/var/www/web3">
DirectoryIndex index.php index.html index.htm
Options -Indexes FollowSymLinks +ExecCGI
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
4) restart apache. visit the 3 sites respectly to view phpinfo and validate the result. ie:
http://web1.example.com
http://web2.example.com
http://web3.example.com
If all OK, you can use one of the 3 virtual host as template to create new virtual host, with the desired php version.
How about
^[A-Za-z]\S*
a letter followed by 0 or more non-space characters (will include all special symbols).
Update 2020
Products are located mainly in the following tables:
wp_posts
table with post_type
like product
(or product_variation
),
wp_postmeta
table with post_id
as relational index (the product ID).
wp_wc_product_meta_lookup
table with product_id
as relational index (the post ID) | Allow fast queries on specific product data (since WooCommerce 3.7)
wp_wc_order_product_lookup
table with product_id
as relational index (the post ID) | Allow fast queries to retrieve products on orders (since WooCommerce 3.7)
Product types, categories, subcategories, tags, attributes and all other custom taxonomies are located in the following tables:
wp_terms
wp_termmeta
wp_term_taxonomy
wp_term_relationships
- column object_id
as relational index (the product ID)
wp_woocommerce_termmeta
wp_woocommerce_attribute_taxonomies
(for product attributes only)
wp_wc_category_lookup
(for product categories hierarchy only since WooCommerce 3.7)
Product types are handled by custom taxonomy product_type
with the following default terms:
simple
grouped
variable
external
Some other product types for Subscriptions and Bookings plugins:
subscription
variable-subscription
booking
Since Woocommerce 3+ a new custom taxonomy named product_visibility
handle:
exclude-from-search
and exclude-from-catalog
featured
outofstock
rated-1
to rated-5
Particular feature: Each product attribute is a custom taxonomy…
References:
// this isn't set up for good processing.
//I don't know what data set has the expiration
//dates of your accounts. I assume a list.
// matchfound is a single variablethat returns true if any 1 record is expired.
bool matchFound = false;
DateTime dateOfExpiration = DateTime.Today.AddDays(-30);
List<DateTime> accountExpireDates = new List<DateTime>();
foreach (DateTime date in accountExpireDates)
{
if (DateTime.Compare(dateOfExpiration, date) != -1)
{
matchFound = true;
}
}
Try the following.
Execute a database backup query from PHP file. Below is an example of using SELECT INTO OUTFILE query for creating table backup:
<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$tableName = 'yourtable';
$backupFile = 'backup/yourtable.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysqli_query($con,$query);
?>
To restore the backup you just need to run LOAD DATA INFILE query like this:
<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$tableName = 'yourtable';
$backupFile = 'yourtable.sql';
$query = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);
?>
f.write(plaintext)
f.write("\n".encode("utf-8"))
This is a tool to open Java class file binaries, view their internal structure, modify portions of it if required and save the class file back. It also generates readable reports similar to the javap utility. Easy to use Java Swing GUI. The user interface tries to display as much detail as possible and tries to present a structure as close as the actual Java class file structure. At the same time ease of use and class file consistency while doing modifications is also stressed. For example, when a method is deleted, the associated constant pool entry will also be deleted if it is no longer referenced. In built verifier checks changes before saving the file. This tool has been used by people learning Java class file internals. This tool has also been used to do quick modifications in class files when the source code is not available." this is a quote from the website.
This gets the last value and handles empty values:
=INDEX( FILTER( H:H ; NOT(ISBLANK(H:H))) ; ROWS( FILTER( H:H ; NOT(ISBLANK(H:H)) ) ) )
I want to add a point that you can also (and should if what you are writing is complex) add a test variable to rollback if you are in test mode. Then you can execute the whole thing at once. Often I also add code to see the before and after results of various operations especially if it is a complex script.
Example below:
USE AdventureWorks;
GO
DECLARE @TEST INT = 1--1 is test mode, use zero when you are ready to execute
BEGIN TRANSACTION;
BEGIN TRY
IF @TEST= 1
BEGIN
SELECT *FROM Production.Product
WHERE ProductID = 980;
END
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
IF @TEST= 1
BEGIN
SELECT *FROM Production.Product
WHERE ProductID = 980;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0 AND @TEST = 0
COMMIT TRANSACTION;
GO
Use an array or vector of strings with matching values:
char *ErrorTypes[] =
{
"errorA",
"errorB",
"errorC"
};
cout << ErrorTypes[anError];
EDIT: The solution above is applicable when the enum is contiguous, i.e. starts from 0 and there are no assigned values. It will work perfectly with the enum in the question.
To further proof it for the case that enum doesn't start from 0, use:
cout << ErrorTypes[anError - ErrorA];
If you can use repeated letters, you can use the *
operator:
>>> 'a'*5
'aaaaa'
I have used this to remove unwanted words from text files:
bad_words = ['abc', 'def', 'ghi', 'jkl']
with open('List of words.txt') as badfile, open('Clean list of words.txt', 'w') as cleanfile:
for line in badfile:
clean = True
for word in bad_words:
if word in line:
clean = False
if clean == True:
cleanfile.write(line)
Or to do the same for all files in a directory:
import os
bad_words = ['abc', 'def', 'ghi', 'jkl']
for root, dirs, files in os.walk(".", topdown = True):
for file in files:
if '.txt' in file:
with open(file) as filename, open('clean '+file, 'w') as cleanfile:
for line in filename:
clean = True
for word in bad_words:
if word in line:
clean = False
if clean == True:
cleanfile.write(line)
I'm sure there must be a more elegant way to do it, but this did what I wanted it to.
You have to use attachEvent
in IE versions prior to IE9. Detect whether addEventListener
is defined and use attachEvent
if it isn't:
if(_checkbox.addEventListener)
_checkbox.addEventListener("click",setCheckedValues,false);
else
_checkbox.attachEvent("onclick",setCheckedValues);
// ^^ -- onclick, not click
Note that IE11 will remove attachEvent
.
See also:
The error you mean is due to missing additional include path. Try adding it with: INCLUDEPATH += C:\path\to\include\files\ Hope it works. Regards.
Get Network and Local Printer List in ASP.NET
This method uses the Windows Management Instrumentation or the WMI interface. It’s a technology used to get information about various systems (hardware) running on a Windows Operating System.
private void GetAllPrinterList()
{
ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
objScope.Connect();
SelectQuery selectQuery = new SelectQuery();
selectQuery.QueryString = "Select * from win32_Printer";
ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
ManagementObjectCollection MOC = MOS.Get();
foreach (ManagementObject mo in MOC)
{
lstPrinterList.Items.Add(mo["Name"].ToString());
}
}
Click here to download source and application demo
Demo of application which listed network and local printer
A possible solution is using the collect_list()
function from pyspark.sql.functions
. This will aggregate all column values into a pyspark array that is converted into a python list when collected:
mvv_list = df.select(collect_list("mvv")).collect()[0][0]
count_list = df.select(collect_list("count")).collect()[0][0]
MySQL subtract days from now:
select now(), now() - interval 1 day
Prints:
2014-10-08 09:00:56 2014-10-07 09:00:56
Other Interval Temporal Expression Unit arguments:
https://dev.mysql.com/doc/refman/5.5/en/expressions.html#temporal-intervals
select now() - interval 1 microsecond
select now() - interval 1 second
select now() - interval 1 minute
select now() - interval 1 hour
select now() - interval 1 day
select now() - interval 1 week
select now() - interval 1 month
select now() - interval 1 year
The following seems to work:
ul#menu li a {
color:#696969;
display:block;
font-weight:bold;
line-height:2.8;
text-decoration:none;
width:100%;
}
your have to comment that line in ~/.bashrc:
#export PATH=/home/jolth/miniconda3/bin:$PATH
and run:
source ~/.bashrc
For those that need Powershell to return additional information like the Http StatusCode, here's an example. Included are the two most likely ways to pass in credentials.
Its a slightly modified version of this SO answer:
How to obtain numeric HTTP status codes in PowerShell
$req = [system.Net.WebRequest]::Create($url)
# method 1 $req.UseDefaultCredentials = $true
# method 2 $req.Credentials = New-Object System.Net.NetworkCredential($username, $pwd, $domain);
try
{
$res = $req.GetResponse()
}
catch [System.Net.WebException]
{
$res = $_.Exception.Response
}
$int = [int]$res.StatusCode
$status = $res.StatusCode
return "$int $status"
Bit late to the party on this question, but in case anyone finds it useful I just created a subclass:
public class ArrayList2<T> extends ArrayList<T>
{
private static final long serialVersionUID = 1L;
public T getLast()
{
if (this.isEmpty())
{
return null;
}
else
{
return this.get(this.size() - 1);
}
}
}
You could start by using git merge --no-commit
, and then edit the merge however you like i.e. by unstaging config.xml
or any other file, then commit. I suspect you'd want to automate it further after that using hooks, but I think it'd be worth going through manually at least once.
In my case, none of the above solutions worked. I found that it's easier to overlap the disabled button using an absolute element as:
<div rel="tooltip" title="I workz" class="wrap">
<div class="overlap"></div>
<button>I workz</button>
</div>
<div rel="tooltip" title="Boo!!" class="wrap poptooltip">
<div class="overlap"></div>
<button disabled>I workz disabled</button>
</div>
.wrap {
display: inline-block;
position: relative;
}
.overlap {
display: none
}
.poptooltip .overlap {
display: block;
position: absolute;
height: 100%;
width: 100%;
z-index: 1000;
}
Hopefully this can help somebody: for some reason I couldn't track because of lack of time, if you have a form like:
<form (ngSubmit)="doSubmit($event)">
<button (click)="clearForm()">Clear</button>
<button type="submit">Submit</button>
</form>
when you hit the Enter
button, the clearForm
function is called, even though the expected behaviour was to call the doSubmit
function.
Changing the Clear
button to a <a>
tag solved the issue for me.
I would still like to know if that's expected or not. Seems confusing to me
If choosing between OAuth versions, go with OAuth 2.0.
OAuth bearer tokens should only be used with a secure transport.
OAuth bearer tokens are only as secure or insecure as the transport that encrypts the conversation. HTTPS takes care of protecting against replay attacks, so it isn't necessary for the bearer token to also guard against replay.
While it is true that if someone intercepts your bearer token they can impersonate you when calling the API, there are plenty of ways to mitigate that risk. If you give your tokens a long expiration period and expect your clients to store the tokens locally, you have a greater risk of tokens being intercepted and misused than if you give your tokens a short expiration, require clients to acquire new tokens for every session, and advise clients not to persist tokens.
If you need to secure payloads that pass through multiple participants, then you need something more than HTTPS/SSL, since HTTPS/SSL only encrypts one link of the graph. This is not a fault of OAuth.
Bearer tokens are easy to for clients to obtain, easy for clients to use for API calls and are widely used (with HTTPS) to secure public facing APIs from Google, Facebook, and many other services.
I want to mention the Ning Async Http Client Library. I've never used it but my colleague raves about it as compared to the Apache Http Client, which I've always used in the past. I was particularly interested to learn it is based on Netty, the high-performance asynchronous i/o framework, with which I am more familiar and hold in high esteem.
You need to commit at least one time on master before creating a new branch.
Assuming this is for a C# project and assuming that you want to change the default namespace, you need to go to Project Properties, Application tab, and specify "Default Namespace".
Default namespace is the namespace that Visual studio sets when you create a new class. Next time you do Right Click > Add > Class it would use the namespace you specified in the above step.
yauzl is a robust library for unzipping. Design principles:
Currently has 97% test coverage.
Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return false;
}
if(getCookie("KoiMilGaya")) {
//alert('found');
// Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again..
} else {
//alert('nothing');
// Display popup or anthing here. it shows on first visit only.
// this will load again when user closer browser and open again.
setCookie('KoiMilGaya','1');
}
Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:
String.prototype.format = function(placeholders) {
var s = this;
for(var propertyName in placeholders) {
var re = new RegExp('{' + propertyName + '}', 'gm');
s = s.replace(re, placeholders[propertyName]);
}
return s;
};
usage:
"{greeting} {who}!".format({greeting: "Hello", who: "world"})
String.prototype.format = function(placeholders) {_x000D_
var s = this;_x000D_
for(var propertyName in placeholders) {_x000D_
var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
s = s.replace(re, placeholders[propertyName]);_x000D_
} _x000D_
return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
I think your issue may be in the url pattern. Changing
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
and
<form action="/Register" method="post">
may fix your problem
You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:
If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.
Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.
Good practice to work with SQL Server.
Create below stored procedure and set short key,
CREATE PROCEDURE [dbo].[Searchinall]
(@strFind AS VARCHAR(MAX))
AS
BEGIN
SET NOCOUNT ON;
--TO FIND STRING IN ALL PROCEDURES
BEGIN
SELECT OBJECT_NAME(OBJECT_ID) SP_Name
,OBJECT_DEFINITION(OBJECT_ID) SP_Definition
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+@strFind+'%'
END
--TO FIND STRING IN ALL VIEWS
BEGIN
SELECT OBJECT_NAME(OBJECT_ID) View_Name
,OBJECT_DEFINITION(OBJECT_ID) View_Definition
FROM sys.views
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+@strFind+'%'
END
--TO FIND STRING IN ALL FUNCTION
BEGIN
SELECT ROUTINE_NAME Function_Name
,ROUTINE_DEFINITION Function_definition
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%'+@strFind+'%'
AND ROUTINE_TYPE = 'FUNCTION'
ORDER BY
ROUTINE_NAME
END
--TO FIND STRING IN ALL TABLES OF DATABASE.
BEGIN
SELECT t.name AS Table_Name
,c.name AS COLUMN_NAME
FROM sys.tables AS t
INNER JOIN sys.columns c
ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%'+@strFind+'%'
ORDER BY
Table_Name
END
END
Now - Set short key as below,
So next time whenever you want to find a particular text in any of the four objects like Store procedure
, Views
, Functions
and Tables
. You just need to write that keyword and press shortcut key.
For example: I want to search 'PaymentTable' then write 'PaymentTable' and make sure you select or highlight the written keyword in query editor and press shortcut key ctrl+4
- it will provide you full result.
To get an element by its ID, use this:
document.getElementById("p2")
Instead of:
document.getElementsByName("p2")
So the final product would be:
document.getElementsById("p2").style.visibility = "hidden";
Lambda expressions have a type of Action<parameters>
(in case they don't return a value) or Func<parameters,return>
(in case they have a return value). In your case you have two input parameters, and you need to return a value, so you should use:
Func<FullTimeJob, Student, FullTimeJob>
You could have a look at Sheetfu. The following is an example from the README. It gives a super easy syntax to interact with spreadsheets as if it was a database table.
from sheetfu import Table
spreadsheet = SpreadsheetApp('path/to/secret.json').open_by_id('<insert spreadsheet id here>')
data_range = spreadsheet.get_sheet_by_name('people').get_data_range()
table = Table(data_range, backgrounds=True)
for item in table:
if item.get_field_value('name') == 'foo':
item.set_field_value('surname', 'bar') # this set the surname field value
age = item.get_field_value('age')
item.set_field_value('age', age + 1)
item.set_field_background('age', '#ff0000') # this set the field 'age' to red color
# Every set functions are batched for speed performance.
# To send the batch update of every set requests you made,
# you need to commit the table object as follow.
table.commit()
Disclaimer: I'm the author of this library.
With the release of TypeScript 3.7, optional chaining (the ?
operator) is now officially available.
As such, you can simplify your expression to the following:
const data = change?.after?.data();
You may read more about it from that version's release notes, which cover other interesting features released on that version.
Run the following to install the latest stable release of TypeScript.
npm install typescript
That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null
or undefined
values
const data = change?.after?.data() ?? someOtherData();
Check out std::isdigit()
function.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var height:CGFloat = CGFloat()
if indexPath.row == 1 {
height = 150
}
else {
height = 50
}
return height
}
I know, it is long ago, but since the easiest answer was not yet posted I will do so for other user that might step by.
Just move the var inside the "name" block:
- name: Download apache
vars:
url: czxcxz
shell: wget {{url}}
use the exchange using java. setText = "...", for class java there are many more methods for implementation.
//button fechar
btnclose.setEnabled(false);
btnclose.setText("FECHADO");
View.OnClickListener close = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (btnclose.isClickable()) {
btnOpen.setEnabled(true);
btnOpen.setText("ABRIR");
btnclose.setEnabled(false);
btnclose.setText("FECHADO");
} else {
btnOpen.setEnabled(false);
btnOpen.setText("ABERTO");
btnclose.setEnabled(true);
btnclose.setText("FECHAR");
}
Toast.makeText(getActivity(), "FECHADO", Toast.LENGTH_SHORT).show();
}
};
btnclose.setOnClickListener(close);
Try with
ToString("#,##0.00")
From MSDN
*The "0" custom format specifier serves as a zero-placeholder symbol. If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string. The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.
The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.*
You might also want to try loading a control, and then rendering it to a string and setting that as the HTML Body:
// Declare stringbuilder to render control to
StringBuilder sb = new StringBuilder();
// Load the control
UserControl ctrl = (UserControl) LoadControl("~/Controls/UserControl.ascx");
// Do stuff with ctrl here
// Render the control into the stringbuilder
StringWriter sw = new StringWriter(sb);
Html32TextWriter htw = new Html32TextWriter(sw);
ctrl.RenderControl(htw);
// Get full body text
string body = sb.ToString();
You could then construct your email as usual:
MailMessage message = new MailMessage();
message.From = new MailAddress("[email protected]", "from name");
message.Subject = "Email Subject";
message.Body = body;
message.BodyEncoding = Encoding.ASCII;
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("server");
smtp.Send(message);
You user control could contain other controls, such as a header and footer, and also take advantage of functionality such as data binding.
Another way is to look at the source for Symfony\Component\HttpKernel\Kernel
for where const VERSION
is defined. Example on GitHub
Locally this would be located in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php
.
You can design a lowpass Butterworth filter in runtime, using butter()
function, and then apply that to the signal.
fc = 300; % Cut off frequency
fs = 1000; % Sampling rate
[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal
Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html
If you never want to have duplicates, you should declare this as a table constraint:
CREATE TABLE bookmarks(
users_id INTEGER,
lessoninfo_id INTEGER,
UNIQUE(users_id, lessoninfo_id)
);
(A primary key over both columns would have the same effect.)
It is then possible to tell the database that you want to silently ignore records that would violate such a constraint:
INSERT OR IGNORE INTO bookmarks(users_id, lessoninfo_id) VALUES(123, 456)
I think that your reasoning is sound. But in practice I have found that it is far more common to omit the ===
comparison. I think that there are three reasons for that:
undefined
or null
value. Often you just want your test to fail in such cases. (Though I try to balance this view with the "fail fast" motto).Consider this example:
var someString = getInput();
var normalized = someString && trim(someString);
// trim() removes leading and trailing whitespace
if (normalized) {
submitInput(normalized);
}
I think that this kind of code is not uncommon. It handles cases where getInput()
returns undefined
, null
, or an empty string. Due to the two boolean evaluations submitInput()
is only called if the given input is a string that contains non-whitespace characters.
In JavaScript &&
returns its first argument if it is falsy or its second argument if the first argument is truthy; so normalized
will be undefined
if someString
was undefined and so forth. That means that none of the inputs to the boolean expressions above are actually boolean values.
I know that a lot of programmers who are accustomed to strong type-checking cringe when seeing code like this. But note applying strong typing would likely require explicit checks for null
or undefined
values, which would clutter up the code. In JavaScript that is not needed.
I really like @luke-schafer's prototype idea, but also hear what he is saying about the issues with prototypes. What about using a simple function?
function sortKeysAndDo( obj, worker ) {_x000D_
var keys = Object.keys(obj);_x000D_
keys.sort();_x000D_
for (var i = 0; i < keys.length; i++) {_x000D_
worker(keys[i], obj[keys[i]]);_x000D_
}_x000D_
}_x000D_
_x000D_
function show( key, value ) {_x000D_
document.write( key + ' : ' + value +'<br>' );_x000D_
}_x000D_
_x000D_
var a = new Array();_x000D_
a['b'] = 1;_x000D_
a['z'] = 1;_x000D_
a['a'] = 1;_x000D_
_x000D_
sortKeysAndDo( a, show);_x000D_
_x000D_
var my_object = { 'c': 3, 'a': 1, 'b': 2 };_x000D_
_x000D_
sortKeysAndDo( my_object, show);
_x000D_
This seems to eliminate the issues with prototypes and still provide a sorted iterator for objects. I am not really a JavaScript guru, though, so I'd love to know if this solution has hidden flaws I missed.
This function returns an array regardless of the size of the range.
Ranges will return an array unless the range is only 1 cell and then it returns a single value instead. This function will turn the single value into an array (1 based, the same as the array's returned by ranges)
This answer improves on previous answers as it will return an array from a range no matter what the size. It is also more efficient that other answers as it will return the array generated by the range if possible. Works with single dimension and multi-dimensional arrays
The function works by trying to find the upper bounds of the array. If that fails then it must be a single value so we'll create an array and assign the value to it.
Public Function RangeToArray(inputRange As Range) As Variant()
Dim size As Integer
Dim inputValue As Variant, outputArray() As Variant
' inputValue will either be an variant array for ranges with more than 1 cell
' or a single variant value for range will only 1 cell
inputValue = inputRange
On Error Resume Next
size = UBound(inputValue)
If Err.Number = 0 Then
RangeToArray = inputValue
Else
On Error GoTo 0
ReDim outputArray(1 To 1, 1 to 1)
outputArray(1,1) = inputValue
RangeToArray = outputArray
End If
On Error GoTo 0
End Function
For those who are getting the path dynamicly... e.g. drag&drop:
Some main constructions get drag&dropped file with double quotes like:
"C:\MyPath\MyFile.txt"
Quick and nice solution is to use this function to remove chars from string:
void removeCharsFromString( string &str, char* charsToRemove ) {
for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
}
}
string myAbsolutepath; //fill with your absolute path
removeCharsFromString( myAbsolutepath, "\"" );
myAbsolutepath
now contains just C:\MyPath\MyFile.txt
The function needs these libraries: <iostream>
<algorithm>
<cstring>
.
The function was based on this answer.
Working Fiddle: http://ideone.com/XOROjq
It looks like you're trying to replace the extension with the following code:
if (myFile[-4:] == ".asm"):
newFile = myFile[:4]+".hack"
However, you appear to have the array indexes mixed up. Try the following:
if (myFile[-4:] == ".asm"):
newFile = myFile[:-4]+".hack"
Note the use of -4
instead of just 4
in the second line of code. This explains why your program is trying to create /Use.hack
, which is the first four characters of your file name (/Use
), with .hack
appended to it.
Node.js is an open source command line tool built for the server side JavaScript code. You can download a tarball, compile and install the source. It lets you run JavaScript programs.
The JavaScript is executed by the V8, a JavaScript engine developed by Google which is used in Chrome browser. It uses a JavaScript API to access the network and file system.
It is popular for its performance and the ability to perform parallel operations.
Understanding node.js is the best explanation of node.js I have found so far.
Following are some good articles on the topic.
You should not use this setting:
spring.jpa.show-sql=true
The problem with show-sql
is that the SQL statements are printed in the console, so there is no way to filter them, as you'd normally do with a Logging framework.
In your log configuration file, if you add the following logger:
<logger name="org.hibernate.SQL" level="debug"/>
Then, Hibernate will print the SQL statements when the JDBC PreparedStatement
is created. That's why the statement will be logged using parameter placeholders:
INSERT INTO post (title, version, id) VALUES (?, ?, ?)
If you want to log the bind parameter values, just add the following logger as well:
<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="trace"/>
Once you set the BasicBinder
logger, you will see that the bind parameter values are logged as well:
DEBUG [main]: o.h.SQL - insert into post (title, version, id) values (?, ?, ?)
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [1] as [VARCHAR] - [High-Performance Java Persistence, part 1]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [2] as [INTEGER] - [0]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [3] as [BIGINT] - [1]
The datasource-proxy OSS framework allows you to proxy the actual JDBC DataSource
, as illustrated by the following diagram:
You can define the dataSource
bean that will be used by Hibernate as follows:
@Bean
public DataSource dataSource(DataSource actualDataSource) {
SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener();
loggingListener.setQueryLogEntryCreator(new InlineQueryLogEntryCreator());
return ProxyDataSourceBuilder
.create(actualDataSource)
.name(DATA_SOURCE_PROXY_NAME)
.listener(loggingListener)
.build();
}
Notice that the actualDataSource
must be the DataSource
defined by the [connection pool][2] you are using in your application.
Next, you need to set the net.ttddyy.dsproxy.listener
log level to debug
in your logging framework configuration file. For instance, if you're using Logback, you can add the following logger:
<logger name="net.ttddyy.dsproxy.listener" level="debug"/>
Once you enable datasource-proxy
, the SQl statement are going to be logged as follows:
Name:DATA_SOURCE_PROXY, Time:6, Success:True,
Type:Prepared, Batch:True, QuerySize:1, BatchSize:3,
Query:["insert into post (title, version, id) values (?, ?, ?)"],
Params:[(Post no. 0, 0, 0), (Post no. 1, 0, 1), (Post no. 2, 0, 2)]
The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)
A & B (A and B are evaluated)
A && B (B is only evaluated if A is true)
InnoDB doesn't cope well with 'random' primary keys. Try a sequential key or auto-increment, and I believe you'll see better performance. Your 'real' key field could still be indexed, but for a bulk insert you might be better off dropping and recreating that index in one hit after the insert in complete. Would be interested to see your benchmarks for that!
Some related questions
According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource
, as per this line:
java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource
class in it.
I was getting the exact same problem with no chnges to the code base or servers. It turned out to be that the DB server was running at 100% CPU and SQL Server was being starved of any CPU time, which caused the timeout.
TortoiseMerge is a separate utility that comes bundled with TortoiseSVN.
It can also be can be downloaded separately in the TortoiseDiff.zip archive. This will allow you to apply unified diffs to non-versioned files.
Don’t Repeat Your CSS
a.abc, a.xyz{
margin-left:20px;
}
OR
a{
margin-left:20px;
}
If you don't want to change your markup, this function does the trick:
jQuery('button').click( function(e) {
jQuery('.collapse').collapse('hide');
});
Whenever a BUTTON is clicked, all sections become collapsed. Then bootstrap opens the one you selected.
Per sys.hexversion and API and ABI Versioning:
import sys
if sys.hexversion >= 0x3000000:
print('Python 3.x hexversion %s is in use.' % hex(sys.hexversion))
The length function will do it. See http://www.techonthenet.com/oracle/functions/length.php
You should set responseType: ResponseContentType.Blob
in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.
Here is an working example:
Create image.service.ts
and put following code:
Angular 4:
getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, { responseType: ResponseContentType.Blob })
.map((res: Response) => res.blob());
}
Angular 5+:
getImage(imageUrl: string): Observable<Blob> {
return this.httpClient.get(imageUrl, { responseType: 'blob' });
}
Important: Since Angular 5+ you should use the new HttpClient
.
The new HttpClient
returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'
. Read more about that here.
Now you need to create some function in your image.component.ts
to get image and show it in html.
For creating an image from Blob you need to use JavaScript's FileReader
.
Here is function which creates new FileReader
and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:
imageToShow: any;
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
Now you should use your created ImageService
to get image from api. You should to subscribe to data and give this data to createImageFromBlob
-function. Here is an example function:
getImageFromService() {
this.isImageLoading = true;
this.imageService.getImage(yourImageUrl).subscribe(data => {
this.createImageFromBlob(data);
this.isImageLoading = false;
}, error => {
this.isImageLoading = false;
console.log(error);
});
}
Now you can use your imageToShow
-variable in HTML template like this:
<img [src]="imageToShow"
alt="Place image title"
*ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
<img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>
I hope this description is clear to understand and you can use it in your project.
See the working example for Angular 5+ here.
To safe, you should add: mContext.getResources().getString(R.string.your_string);
mContext can be: context in onAttach() of Fragment or this of Activity.
Sometimes I resolved similar situations (such as using pandas.apply method) using closures
In order to use them, you define a function which dynamically defines and returns a wrapper for your function, effectively making one of the parameters a constant.
Something like this:
def add(x, y):
return x + y
def add_constant(y):
def f(x):
return add(x, y)
return f
Then, add_constant(y)
returns a function which can be used to add y
to any given value:
>>> add_constant(2)(3)
5
Which allows you to use it in any situation where parameters are given one at a time:
>>> map(add_constant(2), [1,2,3])
[3, 4, 5]
edit
If you do not want to have to write the closure function somewhere else, you always have the possibility to build it on the fly using a lambda function:
>>> map(lambda x: add(x, 2), [1, 2, 3])
[3, 4, 5]
I will soon released a new version of my app to support to galaxy ace.
You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree
In order to solve your problem you should do this:
this._camera = Camera.open();
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);
params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);
don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true
to turn off the led just release the camera
If you will use Generics and define your map as
Map<String,String> map = new HashMap<String,String>();
then fetching value as
String s = map.get("keyStr");
you wont be required to typecast the map.get() or call toString method to get String value
you can set a password to your vba code but this can be quite easily broken up.
you can also create an addin and compile it into a DLL. See here for more information. That's at least the most secure way to protect your code.
Regards,
The full code with details about how to install as MySQL plugin are here: https://github.com/lucasepe/lib_mysqludf_haversine
I posted this last year as comment. Since kindly @TylerCollier suggested me to post as answer, here it is.
Another way is to write a custom UDF function that returns the haversine distance from two points. This function can take in input:
lat1 (real), lng1 (real), lat2 (real), lng2 (real), type (string - optinal - 'km', 'ft', 'mi')
So we can write something like this:
SELECT id, name FROM MY_PLACES WHERE haversine_distance(lat1, lng1, lat2, lng2) < 40;
to fetch all records with a distance less then 40 kilometers. Or:
SELECT id, name FROM MY_PLACES WHERE haversine_distance(lat1, lng1, lat2, lng2, 'ft') < 25;
to fetch all records with a distance less then 25 feet.
The core function is:
double
haversine_distance( UDF_INIT* initid, UDF_ARGS* args, char* is_null, char *error ) {
double result = *(double*) initid->ptr;
/*Earth Radius in Kilometers.*/
double R = 6372.797560856;
double DEG_TO_RAD = M_PI/180.0;
double RAD_TO_DEG = 180.0/M_PI;
double lat1 = *(double*) args->args[0];
double lon1 = *(double*) args->args[1];
double lat2 = *(double*) args->args[2];
double lon2 = *(double*) args->args[3];
double dlon = (lon2 - lon1) * DEG_TO_RAD;
double dlat = (lat2 - lat1) * DEG_TO_RAD;
double a = pow(sin(dlat * 0.5),2) +
cos(lat1*DEG_TO_RAD) * cos(lat2*DEG_TO_RAD) * pow(sin(dlon * 0.5),2);
double c = 2.0 * atan2(sqrt(a), sqrt(1-a));
result = ( R * c );
/*
* If we have a 5th distance type argument...
*/
if (args->arg_count == 5) {
str_to_lowercase(args->args[4]);
if (strcmp(args->args[4], "ft") == 0) result *= 3280.8399;
if (strcmp(args->args[4], "mi") == 0) result *= 0.621371192;
}
return result;
}
You can try color-sampler. It's an easy way to pick color in a canvas. See demo.
Try
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here
For both hardware device back button and soft home (back) button e.g. " <- " this is what works for me. (*Note I have an app bar / toolbar in the activity)
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//finish();
onBackPressed();
break;
}
return true;
}
@Override
public void onBackPressed() {
//Execute your code here
finish();
}
Cheers!
I did it this way with Bootstrap 4.3.1
:
<div class="d-flex vh-100">
<div class="d-flex w-100 justify-content-center align-self-center">
I'm in the middle
</div>
</div>
As a key-hardened salted hash, using a secure algorithm such as sha-512.
For me it was due to "multiple" attribute on select input control as Angular has different ValueAccessor for this type of control.
const countryControl = new FormControl();
And inside template use like this
<select multiple name="countries" [formControl]="countryControl">
<option *ngFor="let country of countries" [ngValue]="country">
{{ country.name }}
</option>
</select>
More details ref Official Docs
http://en.wikipedia.org/wiki/Type_system
Static typing
A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time. In static typing, types are associated with variables not values. Statically typed languages include Ada, C, C++, C#, JADE, Java, Fortran, Haskell, ML, Pascal, Perl (with respect to distinguishing scalars, arrays, hashes and subroutines) and Scala. Static typing is a limited form of program verification (see type safety): accordingly, it allows many type errors to be caught early in the development cycle. Static type checkers evaluate only the type information that can be determined at compile time, but are able to verify that the checked conditions hold for all possible executions of the program, which eliminates the need to repeat type checks every time the program is executed. Program execution may also be made more efficient (i.e. faster or taking reduced memory) by omitting runtime type checks and enabling other optimizations.
Because they evaluate type information during compilation, and therefore lack type information that is only available at run-time, static type checkers are conservative. They will reject some programs that may be well-behaved at run-time, but that cannot be statically determined to be well-typed. For example, even if an expression always evaluates to true at run-time, a program containing the code
if <complex test> then 42 else <type error>
will be rejected as ill-typed, because a static analysis cannot determine that the else branch won't be taken.[1] The conservative behaviour of static type checkers is advantageous when evaluates to false infrequently: A static type checker can detect type errors in rarely used code paths. Without static type checking, even code coverage tests with 100% code coverage may be unable to find such type errors. Code coverage tests may fail to detect such type errors because the combination of all places where values are created and all places where a certain value is used must be taken into account.
The most widely used statically typed languages are not formally type safe. They have "loopholes" in the programming language specification enabling programmers to write code that circumvents the verification performed by a static type checker and so address a wider range of problems. For example, Java and most C-style languages have type punning, and Haskell has such features as unsafePerformIO: such operations may be unsafe at runtime, in that they can cause unwanted behaviour due to incorrect typing of values when the program runs.
Dynamic typing
A programming language is said to be dynamically typed, or just 'dynamic', when the majority of its type checking is performed at run-time as opposed to at compile-time. In dynamic typing, types are associated with values not variables. Dynamically typed languages include Groovy, JavaScript, Lisp, Lua, Objective-C, Perl (with respect to user-defined types but not built-in types), PHP, Prolog, Python, Ruby, Smalltalk and Tcl. Compared to static typing, dynamic typing can be more flexible (e.g. by allowing programs to generate types and functionality based on run-time data), though at the expense of fewer a priori guarantees. This is because a dynamically typed language accepts and attempts to execute some programs which may be ruled as invalid by a static type checker.
Dynamic typing may result in runtime type errors—that is, at runtime, a value may have an unexpected type, and an operation nonsensical for that type is applied. This operation may occur long after the place where the programming mistake was made—that is, the place where the wrong type of data passed into a place it should not have. This makes the bug difficult to locate.
Dynamically typed language systems, compared to their statically typed cousins, make fewer "compile-time" checks on the source code (but will check, for example, that the program is syntactically correct). Run-time checks can potentially be more sophisticated, since they can use dynamic information as well as any information that was present during compilation. On the other hand, runtime checks only assert that conditions hold in a particular execution of the program, and these checks are repeated for every execution of the program.
Development in dynamically typed languages is often supported by programming practices such as unit testing. Testing is a key practice in professional software development, and is particularly important in dynamically typed languages. In practice, the testing done to ensure correct program operation can detect a much wider range of errors than static type-checking, but conversely cannot search as comprehensively for the errors that both testing and static type checking are able to detect. Testing can be incorporated into the software build cycle, in which case it can be thought of as a "compile-time" check, in that the program user will not have to manually run such tests.
References
- Pierce, Benjamin (2002). Types and Programming Languages. MIT Press. ISBN 0-262-16209-1.
Assuming the parent has a fixed width, e.g #page { width: 1000px; }
and is centered #page { margin: auto; }
, you want the child to fit the width of browser viewport you could simply do:
#page {
margin: auto;
width: 1000px;
}
.fullwidth {
margin-left: calc(500px - 50vw); /* 500px is half of the parent's 1000px */
width: 100vw;
}
More general, for arbitrary sized bitmaps:
#define BITS 8
#define BIT_SET( p, n) (p[(n)/BITS] |= (0x80>>((n)%BITS)))
#define BIT_CLEAR(p, n) (p[(n)/BITS] &= ~(0x80>>((n)%BITS)))
#define BIT_ISSET(p, n) (p[(n)/BITS] & (0x80>>((n)%BITS)))
sorted(dict1, key=dict1.get)
Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question Code golf: Word frequency chart). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display a list of the top words, sorted by decreasing frequency.
If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as:
from collections import defaultdict
d = defaultdict(int)
for w in text.split():
d[w] += 1
then you can get a list of the words, ordered by frequency of use with sorted(d, key=d.get)
- the sort iterates over the dictionary keys, using the number of word occurrences as a sort key .
for w in sorted(d, key=d.get, reverse=True):
print(w, d[w])
I am writing this detailed explanation to illustrate what people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.
This worked for me:
After re-importing the entire project, installation of dependencies will start which will take some minutes to complete depending upon your internet connection.
If you want a distiction for this case I would recommend to use a matrix
instead, where:
matrix([1,2,3]) == matrix([1,2,3]).transpose()
gives:
matrix([[ True, False, False],
[False, True, False],
[False, False, True]], dtype=bool)
You can also use a ndarray
explicitly adding a second dimension:
array([1,2,3])[None,:]
#array([[1, 2, 3]])
and:
array([1,2,3])[:,None]
#array([[1],
# [2],
# [3]])
$(this).closest('ul').attr('id');
I had the same issue with a plist. Turns out I had two copies of it, one was empty and one was in my localized resources folder. Removing one of them (the empty one) solved the issue.
If you check your error, lines 1) and 2) have different paths. You likely have this file defined twice in your copy phase.
Check your target properties, Build Phases, Copy Bundle Resources, and look for a duplicate info.plist. Figure out which path is incorrect and remove it. (You'll probably want to delete it from the filesystem also.)
One might consider adding this line to ~/.bash_profile
(or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.
alias utc='date -u && date -u +%s'
Best way to the solution of your problem is to use button block btn-block with desired column width.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="col-md-12">_x000D_
<button class="btn btn-primary btn-block">Save</button>_x000D_
</div>_x000D_
<div class="col-md-12">_x000D_
<button class="btn btn-success btn-block">Download</button>_x000D_
</div>
_x000D_
Within Nano use Ctrl+O to save and Ctrl+X to exit if you were wondering
This problem is generally caused by the website/intranet URL being placed in one of:
On corporate networks, these compatibility view settings are often controlled centrally via group policy. In your case, Enterprise Mode appears to be the culprit.
Unfortunately setting META X-UA-Compatible
will not override this.
Sometimes the only way for end-users to override this is to press F12 and change the Document Mode under the Emulation Tab. However this setting is not permanent and may revert once Developer Tools is closed.
You can also try to exclude your site from the Intranet zone. But the list of domains which belong to the Intranet zone is usually also controlled by the group policy, so the chance of this working is slim.
To see the list of domains that belong to the Intranet zone, go to:
Tools -> Internet Options -> Security -> Sites -> Advanced
If the list contains your subdomain and is greyed out, then you will not be able to override compatibility view until your network admin allows it.
You really need to contact your network administrator to allow changing the compatibility view settings in the group policy.
Loading the website with Developer Tools open (F12) will often report the reason that IE is switching to an older mode.
All 3 settings mentioned above are generally controlled via Group Policy, although can sometimes be overridden on user machines.
If Enterprise Mode is the issue (as appears to be the case for the original poster), the following two articles might be helpful:
You could use a macro, but it’s simpler to use styles. Define a character style that has the desired text color and assign a shortcut key to it, say Alt+R. In order to be able to switch color using just the keyboard, define another character style, say “normal”, that has no special feature—just for use to get normal text after switching to your colored style, and assign another shortcut to it, say Alt+N. Then you would just type text, press Alt+R to switch to colored text, type that text, press Alt+N to resume normal text color, etc.
You need to intent
your current context
to another activity first with startActivity
. After that you can finish
your current activity
from where you redirect.
Intent intent = new Intent(this, FirstActivity.class);// New activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); // Call once you redirect to another activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
- Clears the activity stack. If you don't want to clear the activity stack. PLease don't use that flag then.
You can do:
if not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
else:
do sth. # condition is satisfied
Using a loop:
while not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
do sth. # condition is satisfied
If you have to write code for Internet Explorer make sure you chose an implementation, which uses array joins. Concatenating strings with the +
or +=
operator are extremely slow on IE. This is especially true for IE6. On modern browsers +=
is usually just as fast as array joins.
When I have to do lots of string concatenations I usually fill an array and don't use a string builder class:
var html = [];
html.push(
"<html>",
"<body>",
"bla bla bla",
"</body>",
"</html>"
);
return html.join("");
Note that the push
methods accepts multiple arguments.
Actually you are right: it runs another instance of make. A possible solution would be:
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
By calling make fresh
you get first the clean
target, then the clearscreen
which runs clear
and finally all
which does the job.
EDIT Aug 4
What happens in the case of parallel builds with make’s -j
option?
There's a way of fixing the order. From the make manual, section 4.2:
Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
Hence the makefile becomes
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
EDIT Dec 5
It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
For the question:
How to save Console.Writeline Outputs to text file?
I would use Console.SetOut
as others have mentioned.
However, it looks more like you are keeping track of your program flow. I would consider using Debug
or Trace
for keeping track of the program state.
It works similar the console except you have more control over your input such as WriteLineIf
.
Debug
will only operate when in debug mode where as Trace
will operate in both debug or release mode.
They both allow for listeners such as output files or the console.
TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(tr1);
TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
Debug.Listeners.Add(tr2);
Make sure you're calling super()
as the first thing in your constructor.
You should set this
for setAuthorState
method
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
constructor(props) {
super(props);
this.handleAuthorChange = this.handleAuthorChange.bind(this);
}
handleAuthorChange(event) {
let {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
Another alternative based on arrow function
:
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
handleAuthorChange = (event) => {
const {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
You can enable and disable the submit button based on the javascript validation below is the validation code. Working Example Here
<script>
function validate() {
var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));
$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
return true;
}
function checkEmail(obj) {
var result = true;
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
result = checkEmpty(obj);
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
var email_regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}
return result;
}
</script>
I think that Joseph flipped controller and action. First comes the action then the controller. This is somewhat strange, but the way the signature looks.
Just to clarify things, this is the version that works (adaption of Joseph's example):
Html.ActionLink(article.Title,
"Login", // <-- ActionMethod
"Item", // <-- Controller Name
new { id = article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none
)
Or without the year:
DateTime.Now.ToString("M/dd")
If you put an asterisk in for build and revision visual studio uses the number of days since Jan. 1st 2000 as the build number, and the number of seconds since midnight divided by 2 as the revision.
A MUCH better life saver solution is http://autobuildversion.codeplex.com/
It works like a charm and it's VERY flexible.
download the library Gradle:
compile 'com.google.code.gson:gson:2.8.2'
To use the library in a method.
Gson gson = new Gson();
//transform a java object to json
System.out.println("json =" + gson.toJson(Object.class).toString());
//Transform a json to java object
String json = string_json;
List<Object> lstObject = gson.fromJson(json_ string, Object.class);
In terms that an OOP programmer would understand (without any functional programming background), what is a monad?
What problem does it solve and what are the most common places it's used?are the most common places it's used?
In terms of OO programming, a monad is an interface (or more likely a mixin), parameterized by a type, with two methods, return
and bind
that describe:
The problem it solves is the same type of problem you'd expect from any interface, namely, "I have a bunch of different classes that do different things, but seem to do those different things in a way that has an underlying similarity. How can I describe that similarity between them, even if the classes themselves aren't really subtypes of anything closer than 'the Object' class itself?"
More specifically, the Monad
"interface" is similar to IEnumerator
or IIterator
in that it takes a type that itself takes a type. The main "point" of Monad
though is being able to connect operations based on the interior type, even to the point of having a new "internal type", while keeping - or even enhancing - the information structure of the main class.
See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.
Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.
The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.
It does look like the checkout --orphan
is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init
a repo, set up a remote
tracking branch (you do want the one branch only?), and then fetch
that single branch, which feels long winded with more opportunity for mistakes.
Edit: For the 'clone' step see this answer
I think you can use thread like demon-thread for reading your input and your output reader will already be in while loop in main thread so you can read and write at same time.You can modify your program like this:
Thread T=new Thread(new Runnable() {
@Override
public void run() {
while(true)
{
String input = scan.nextLine();
input += "\n";
try {
writer.write(input);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} );
T.start();
and you can reader will be same as above i.e.
while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}
make your writer as final otherwise it wont be able to accessible by inner class.
Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:
> df[df=="" | df==12] <- NA
> df
A B
1 <NA> <NA>
2 xyz <NA>
3 jkl 100
For factors, zxzak's code already yields factors:
> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame': 3 obs. of 2 variables:
$ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
$ B: Factor w/ 3 levels "","100","12": 3 1 2
If in trouble, I'd suggest to temporarily drop the factors.
df[] <- lapply(df, as.character)
Ok i finally managed to do it without using the --privileged mode.
I'm running on ubuntu server 14.04 and i'm using the latest cuda (6.0.37 for linux 13.04 64 bits).
Install nvidia driver and cuda on your host. (it can be a little tricky so i will suggest you follow this guide https://askubuntu.com/questions/451672/installing-and-testing-cuda-in-ubuntu-14-04)
ATTENTION : It's really important that you keep the files you used for the host cuda installation
We need to run docker daemon using lxc driver to be able to modify the configuration and give the container access to the device.
One time utilization :
sudo service docker stop
sudo docker -d -e lxc
Permanent configuration Modify your docker configuration file located in /etc/default/docker Change the line DOCKER_OPTS by adding '-e lxc' Here is my line after modification
DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4 -e lxc"
Then restart the daemon using
sudo service docker restart
How to check if the daemon effectively use lxc driver ?
docker info
The Execution Driver line should look like that :
Execution Driver: lxc-1.0.5
Here is a basic Dockerfile to build a CUDA compatible image.
FROM ubuntu:14.04
MAINTAINER Regan <http://stackoverflow.com/questions/25185405/using-gpu-from-a-docker-container>
RUN apt-get update && apt-get install -y build-essential
RUN apt-get --purge remove -y nvidia*
ADD ./Downloads/nvidia_installers /tmp/nvidia > Get the install files you used to install CUDA and the NVIDIA drivers on your host
RUN /tmp/nvidia/NVIDIA-Linux-x86_64-331.62.run -s -N --no-kernel-module > Install the driver.
RUN rm -rf /tmp/selfgz7 > For some reason the driver installer left temp files when used during a docker build (i don't have any explanation why) and the CUDA installer will fail if there still there so we delete them.
RUN /tmp/nvidia/cuda-linux64-rel-6.0.37-18176142.run -noprompt > CUDA driver installer.
RUN /tmp/nvidia/cuda-samples-linux-6.0.37-18176142.run -noprompt -cudaprefix=/usr/local/cuda-6.0 > CUDA samples comment if you don't want them.
RUN export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64 > Add CUDA library into your PATH
RUN touch /etc/ld.so.conf.d/cuda.conf > Update the ld.so.conf.d directory
RUN rm -rf /temp/* > Delete installer files.
First you need to identify your the major number associated with your device. Easiest way is to do the following command :
ls -la /dev | grep nvidia
If the result is blank, use launching one of the samples on the host should do the trick. The result should look like that As you can see there is a set of 2 numbers between the group and the date. These 2 numbers are called major and minor numbers (wrote in that order) and design a device. We will just use the major numbers for convenience.
Why do we activated lxc driver? To use the lxc conf option that allow us to permit our container to access those devices. The option is : (i recommend using * for the minor number cause it reduce the length of the run command)
--lxc-conf='lxc.cgroup.devices.allow = c [major number]:[minor number or *] rwm'
So if i want to launch a container (Supposing your image name is cuda).
docker run -ti --lxc-conf='lxc.cgroup.devices.allow = c 195:* rwm' --lxc-conf='lxc.cgroup.devices.allow = c 243:* rwm' cuda
service.use(function(req, res, next) {_x000D_
res.header("Access-Control-Allow-Origin", "*");_x000D_
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");_x000D_
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");_x000D_
next();_x000D_
});
_x000D_
Error:Execution failed for task ':app:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1
The upper error occure due to lot of reason. So I can put why this error occure and how to solve it.
REASON 1 : Duplicate of class file name
SOLUTION :
when your refactoring of some of your class files to a library project. and that time you write name of class file So, double check that you do not have any duplicate names
REASON 2 : When you have lot of cache Memory
SOLUTION :
Sometime if you have lot of cache memory then this error occure so solve it.
go to File/Invalidate caches / Restart
then select Invalidate and Restart
it will clean your cache memory.
REASON 3 : When there is internal bug or used beta Version to Switch back to stable version.
SOLUTION :
Solution is just simple go to Build menu and click Clean Project
and after cleaning click Rebuild Project
.
REASON 4 : When you memory of the system Configuration is low.
SOLUTION :
open Task Manager and stop the other application which are not most used at that time so it will free the space and solve OutOfMemory
.
REASON 5 : The problem is your method count has exceed from 65K.
SOLUTION :
open your Project build.gradle
file add
defaultConfig {
...
multiDexEnabled true
}
and in dependencies add below line.
dependencies
{
compile 'com.android.support:multidex:1.0.0'
}
Maybe you are already using the system proxy setting - in this case unset all git proxies will work:
git config --global --unset http.proxy
git config --global --unset https.proxy
If you have the correct encoding in the string, you need not do more to get the bytes for another encoding.
public static void main(String[] args) throws Exception {
printBytes("â");
System.out.println(
new String(new byte[] { (byte) 0xE2 }, "ISO-8859-1"));
System.out.println(
new String(new byte[] { (byte) 0xC3, (byte) 0xA2 }, "UTF-8"));
}
private static void printBytes(String str) {
System.out.println("Bytes in " + str + " with ISO-8859-1");
for (byte b : str.getBytes(StandardCharsets.ISO_8859_1)) {
System.out.printf("%3X", b);
}
System.out.println();
System.out.println("Bytes in " + str + " with UTF-8");
for (byte b : str.getBytes(StandardCharsets.UTF_8)) {
System.out.printf("%3X", b);
}
System.out.println();
}
Output:
Bytes in â with ISO-8859-1
E2
Bytes in â with UTF-8
C3 A2
â
â
Caesar's solution is the best in my opinion, but if you still insist to use the strcpy
function, then after you have your strings ready:
string a = "text";
string b = "image";
You can try either:
strcpy(a.data(), b.data());
or
strcpy(a.c_str(), b.c_str());
Just call either the data()
or c_str()
member functions of the std::string
class, to get the char*
pointer of the string object.
The strcpy()
function doesn't have overload to accept two std::string
objects as parameters.
It has only one overload to accept two char*
pointers as parameters.
Both data
and c_str
return what does strcpy()
want exactly.
This whole thread confused the h#$l out of me until I realized you have to be running the debugger to see ANY trace or debug output. I needed a debug output (outside of the debugger) because my WebApp runs fine when I debug it but not when the debugger isn't running (SqlDataSource is instantiated correctly when running through the debugger).
Just because debug output can be seen when you're running in release mode doesn't mean you'll see anything if you're not running the debugger. Careful reading of Writing to output window of Visual Studio? gave me DebugView as an alternative. Extremely useful!
Hopefully this helps anyone else confused by this.
You can use filter() to do that:
var tableRow = $("td").filter(function() {
return $(this).text() == "foo";
}).closest("tr");
The pickle (and gzip if the file is compressed) module need to be used
NOTE: These are already in the standard Python library. No need to install anything new
I think one of the easiest ways to achieve this is to replace "continue" with "break" statement,i.e.
for ii in range(200):
for jj in range(200, 400):
...block0...
if something:
break
...block1...
For example, here is the easy code to see how exactly it goes on:
for i in range(10):
print("doing outer loop")
print("i=",i)
for p in range(10):
print("doing inner loop")
print("p=",p)
if p==3:
print("breaking from inner loop")
break
print("doing some code in outer loop")
In my case I just remove the SoapAction
instruction from the HttpWebRequest
object. So, I don't define .Headers.Add("SOAPAction","someurl")
in HttpWebRequest
definitions and my code works fine.
ResultXML
is an XDocument
.
ResultString
is a string.
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
//req.Headers.Add("SOAPAction", "http://tempuri.org/IWebService/GetMessage");
req.ProtocolVersion = HttpVersion.Version11;
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.KeepAlive = true;
req.Method = "POST";
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
stmw.Write(soapStr);
}
using (StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream()))
{
string result = responseReader.ReadToEnd();
ResultXML = XDocument.Parse(result);
ResultString = result;
}
}
This is not the same as using a sequence. When using a sequence, you are not inserting or updating anything. You are simply retrieving the next sequence value. It looks like hibernate does not support it.
What you should do is create an imap of a certain key to a series of commands, in this case the commands will drop you into normal mode, delete the current word and then put you back in insert:
:imap <C-d> <C-[>diwi
Building on theosp's answer, I wrote a script called git-cdc
(for change date commit) that I put in my PATH
.
The name is important: git-xxx
anywhere in your PATH
allows you to type:
git xxx
# here
git cdc ...
That script is in bash, even on Windows (since Git will be calling it from its msys environment)
#!/bin/bash
# commit
# date YYYY-mm-dd HH:MM:SS
commit="$1" datecal="$2"
temp_branch="temp-rebasing-branch"
current_branch="$(git rev-parse --abbrev-ref HEAD)"
date_timestamp=$(date -d "$datecal" +%s)
date_r=$(date -R -d "$datecal")
if [[ -z "$commit" ]]; then
exit 0
fi
git checkout -b "$temp_branch" "$commit"
GIT_COMMITTER_DATE="$date_timestamp" GIT_AUTHOR_DATE="$date_timestamp" git commit --amend --no-edit --date "$date_r"
git checkout "$current_branch"
git rebase --autostash --committer-date-is-author-date "$commit" --onto "$temp_branch"
git branch -d "$temp_branch"
With that, you can type:
git cdc @~ "2014-07-04 20:32:45"
That would reset author/commit date of the commit before HEAD (@~
) to the specified date.
git cdc @~ "2 days ago"
That would reset author/commit date of the commit before HEAD (@~
) to the same hour, but 2 days ago.
Ilya Semenov mentions in the comments:
For OS X you may also install GNU
coreutils
(brew install coreutils
), add it toPATH
(PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
) and then use "2 days ago
" syntax.
<Window.Resources>
<Style x:Key="TextBoxUserStyle" BasedOn="{x:Null}" TargetType="{x:Type TextBox}">
<Setter Property="Foreground" Value="Black"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Width" Value="225"/>
<Setter Property="Height" Value="25"/>
<Setter Property="FontSize" Value="12"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Margin" Value="5"/>
<Setter Property="AllowDrop" Value="true"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border x:Name="OuterBorder" BorderBrush="#5AFFFFFF" BorderThickness="1,1,1,1" CornerRadius="4,4,4,4">
<Border x:Name="InnerBorder" Background="#FFFFFFFF" BorderBrush="#33000000" BorderThickness="1,1,1,1" CornerRadius="3,3,3,3">
<ScrollViewer SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" x:Name="PART_ContentHost"/>
</Border>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="PasswordBoxVistaStyle" BasedOn="{x:Null}" TargetType="{x:Type PasswordBox}">
<Setter Property="Foreground" Value="Black"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Width" Value="225"/>
<Setter Property="Height" Value="25"/>
<Setter Property="FontSize" Value="12"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Margin" Value="5"/>
<Setter Property="AllowDrop" Value="true"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type PasswordBox}">
<Border x:Name="OuterBorder" BorderBrush="#5AFFFFFF" BorderThickness="1,1,1,1" CornerRadius="4,4,4,4">
<Border x:Name="InnerBorder" Background="#FFFFFFFF" BorderBrush="#33000000" BorderThickness="1,1,1,1" CornerRadius="3,3,3,3">
<Grid>
<Label x:Name="lblPwd" Content="Password" FontSize="11" VerticalAlignment="Center" Margin="2,0,0,0" FontFamily="Verdana" Foreground="#828385" Padding="0"/>
<ScrollViewer SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" x:Name="PART_ContentHost"/>
</Grid>
</Border>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Visibility" TargetName="lblPwd" Value="Hidden"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<PasswordBox Style="{StaticResource PasswordBoxVistaStyle}" Margin="169,143,22,0" Name="txtPassword" FontSize="14" TabIndex="2" Height="31" VerticalAlignment="Top" />
This can help check it with your code.When applied to password box,it will show Password,which will disappear when usertypes.
First, get the intent which has started your activity using the getIntent()
method:
Intent intent = getIntent();
If your extra data is represented as strings, then you can use intent.getStringExtra(String name)
method. In your case:
String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");
I got re-directed here when clicking on the first Google hit when clicking on the error URL for CS0433
, specifically,
The type 'Package' exists in both 'Windows... Version=N.N.N.N, Culture=neutral, PublicKeyToken=null, ContentType=Windows...' and 'Windows..., Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=Windows...'
Instead of outlining all the things I did to fix it, let me tell you what I did that broke it. I went to update the NuGet packages for a repo that needed a code update. The packages were pretty old (1 year or so) and all I initially tried to do was update it for a C# project.
Sometime between starting that process and encountering this error, I somehow downgraded the version of the C++ projects in that SLN to target 15063
. I also noticed that the C# project had both the TargetPlatformMinVersion
and TargetPlatformVersion
newly set to 10.0.17134.0
The only thing I had to do to "fix" it was change the TargetPlatformMinVersion
to a higher version than the TargetPlatformMinVersion
for the C# project. Modifying the C++ project to either version didn't change behavior. I'm not sure why this suddenly stopped working but hopefully someone similarly blocked might get out of a pickle using similar strategies.
From MSDN:
A
String
object is a sequential collection ofSystem.Char
objects that represent a string.
So you can use this:
var howManyBytes = yourString.Length * sizeof(Char);
If the above doesn't work, find the loginname of the spid and disable it in Security - Logins
I had the same Issue. my solution was built up from two projects. A Class library
and a website referencing to the class library project. the problem was that i was trying to access the App.config
in my Class library
project but the system was searching in Web.config
of the website. I put the connection string inside Web.config
and ... problem solved!
The main reason was that despite ConfigurationManager
was used in another assembly it was searching inside the runnig project .
The methods below scales AND rotates the bitmap according to the orientation:
public Bitmap scaleAndRotateImage(String path, int orientation, final int targetWidth, final int targetHeight)
{
Bitmap bitmap = null;
try
{
// Check the dimensions of the Image
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Adjust the Width and Height
int sourceWidth, sourceHeight;
if (orientation == 90 || orientation == 270)
{
sourceWidth = options.outHeight;
sourceHeight = options.outWidth;
}
else
{
sourceWidth = options.outWidth;
sourceHeight = options.outHeight;
}
// Calculate the maximum required scaling ratio if required and load the bitmap
if (sourceWidth > targetWidth || sourceHeight > targetHeight)
{
float widthRatio = (float)sourceWidth / (float)targetWidth;
float heightRatio = (float)sourceHeight / (float)targetHeight;
float maxRatio = Math.max(widthRatio, heightRatio);
options.inJustDecodeBounds = false;
options.inSampleSize = (int)maxRatio;
bitmap = BitmapFactory.decodeFile(path, options);
}
else
{
bitmap = BitmapFactory.decodeFile(path);
}
// We need to rotate the bitmap (if required)
int orientationInDegrees = exifToDegrees(orientation);
if (orientation > 0)
{
Matrix matrix = new Matrix();
if (orientation != 0f)
{
matrix.preRotate(orientationInDegrees);
};
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
// Re-scale the bitmap if necessary
sourceWidth = bitmap.getWidth();
sourceHeight = bitmap.getHeight();
if (sourceWidth != targetWidth || sourceHeight != targetHeight)
{
float widthRatio = (float)sourceWidth / (float)targetWidth;
float heightRatio = (float)sourceHeight / (float)targetHeight;
float maxRatio = Math.max(widthRatio, heightRatio);
sourceWidth = (int)((float)sourceWidth / maxRatio);
sourceHeight = (int)((float)sourceHeight / maxRatio);
bitmap = Bitmap.createScaledBitmap(bitmap, sourceWidth, sourceHeight, true);
}
}
catch (Exception e)
{
Logger.d("Could not rotate the image");
Logger.d(e.getMessage());
}
return bitmap;
}
Example:
public void getPictureFromDevice(Uri Uri,ImageView imageView)
{
try
{
ExifInterface exifInterface = new ExifInterface(Uri.getPath());
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
Bitmap bitmap = scaleAndRotateImage(Uri.getPath(), orientation, imageView.getWidth(), imageView.getHeight());
imageView.setImageBitmap(bitmap);
}
catch (OutOfMemoryError outOfMemoryError)
{
Logger.d(outOfMemoryError.getLocalizedMessage());
Logger.d("Failed to load image from filePath (out of memory)");
Logger.d(Uri.toString());
}
catch (Exception e)
{
Logger.d("Failed to load image from filePath");
Logger.d(Uri.toString());
}
}
It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS
version and any Simulator. You will have to use device for testing camera purpose.
Open Command Prompt and type in the following command: java -version
Upon successful execution, the command will output the version of Java along with Java SE Runtime Environment’s build and Java HotSpot Client VM’s build.
You can set the title in action-bar using AndroidManifest.xml
. Add label to the activity
<activity
android:name=".YourActivity"
android:label="Your Title" />
I was having the same problem, in both Git Bash and Git GUI. Both programs use to run nicely, but then they randomly slowed down to a crawl, and I couldn't figure out why.
As it turns out, it was Avast. Avast has caused odd things to happen to various programs (including programs I write), so I disabled it for a second, and sure enough, Bash now runs as fast as it does on Linux. I just added the Git program files folder (C:\Program Files\Git
) to the Avast exclusion list, and now it runs as fast as it does on Linux.
And yes, I realize the antivirus software was not the issue in the original post, but I'll just put this here in case it's useful to someone.
With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As javascript reads down a page).
<head>
<script type="text/javascript">
function insert(){
var src = document.getElementById("gamediv");
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src.appendChild(img);
}
</script>
</head>
<body>
<div id="gamediv">
<script type="text/javascript">
insert();
</script>
</div>
</body>
More Info on ValidationSettings:UnobtrusiveValidationMode
Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.
Type: UnobtrusiveValidationMode
Default value: None
Remarks: If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic. If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.
Example:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
When elements are positioned outside the normal flow, they can overlap other elements.
according to Overlapping Elements section on http://web.archive.org/web/20130501103219/http://w3schools.com/css/css_positioning.asp
The syntax has changed in that print
is now a function. This means that the %
formatting needs to be done inside the parenthesis:1
print("%d. %s appears %d times." % (i, key, wordBank[key]))
However, since you are using Python 3.x., you should actually be using the newer str.format
method:
print("{}. {} appears {} times.".format(i, key, wordBank[key]))
Though %
formatting is not officially deprecated (yet), it is discouraged in favor of str.format
and will most likely be removed from the language in a coming version (Python 4 maybe?).
1Just a minor note: %d
is the format specifier for integers, not %s
.
This solution worked for me in PHP. It opens the PDF in the browser.
// $path is the path to the pdf file
public function showPDF($path) {
if($path) {
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=filename.pdf");
@readfile($path);
}
}
In HTML 4, the type attribute is required. In my experience, all browsers will default to text/javascript if it is absent, but that behaviour is not defined anywhere. While you can in theory leave it out and assume it will be interpreted as JavaScript, it's invalid HTML, so why not add it.
In HTML 5, the type attribute is optional and defaults to text/javascript
Use <script type="text/javascript">
or simply <script>
(if omitted, the type is the same). Do not use <script language="JavaScript">
; the language attribute is deprecated
Ref :
http://social.msdn.microsoft.com/Forums/vstudio/en-US/65aaf5f3-09db-4f7e-a32d-d53e9720ad4c/script-languagejavascript-or-script-typetextjavascript-?forum=netfxjscript
and
Difference between <script> tag with type and <script> without type?
Do you need type attribute at all?
I am using HTML5- No
I am not using HTML5 - Yes
A simple little extension function for this:
public static bool IsBetween(this DateTime now, TimeSpan start, TimeSpan end)
{
var time = now.TimeOfDay;
// Scenario 1: If the start time and the end time are in the same day.
if (start <= end)
return time >= start && time <= end;
// Scenario 2: The start time and end time is on different days.
return time >= start || time <= end;
}
First Convert your string into HTML then convert it into spannable. do as suggest the following codes.
Spannable spannable = new SpannableString(Html.fromHtml(labelText));
spannable.setSpan(new ForegroundColorSpan(Color.parseColor(color)), spannable.toString().indexOf("•"), spannable.toString().lastIndexOf("•") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
?These can help you:
let formData = new FormData();
formData.append("name", "John");
formData.append("password", "John123");
fetch("https://yourwebhook", {
method: "POST",
mode: "no-cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "form-data"
},
body: formData
});
//router.push("/registro-completado");
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
})
.catch(function(error) {
console.log("Error getting document:", error);
});
You demonstrate a fundamental misunderstanding.
You never created an instance of SimpleClass at all, because you didn't call it.
for count in xrange(4):
x = SimpleClass()
x.attr = count
simplelist.append(x)
Or, if you let the class take parameters, instead, you can use a list comprehension.
simplelist = [SimpleClass(count) for count in xrange(4)]
In this bit of code:
getRadioButtonValue(this["whichThing"]))
you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.
EDIT To get the value out of the radio buttons, grab the JQuery library, and then use this:
$('input[name=whichThing]:checked').val()
Edit 2 Due to the desire to reinvent the wheel, here's non-Jquery code:
var t = '';
for (i=0; i<document.myform.whichThing.length; i++) {
if (document.myform.whichThing[i].checked==true) {
t = t + document.myform.whichThing[i].value;
}
}
or, basically, modify the original line of code to read thusly:
getRadioButtonValue(document.myform.whichThing))
Edit 3 Here's your homework:
function handleClick() {
alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
//event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="aye" onSubmit="return handleClick()">
<input name="Submit" type="submit" value="Update" />
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.
In the function itself, I modified the how the form was being accessed. The structure is: document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.
The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.
EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.
See the difference in this method:
function handleClick() {
alert("Direct Access: " + document.aye["whichThing"]);
alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
return false; // prevent further bubbling of event
}
Go to Reference and add a new reference of your dll file which is causing the problem and make sure that all your dlls are compiled against the same version. It works for me I hope it works for you also.
(copied from: source)
====================
1) there should not be any output (i.e. echo..
or HTML codes) before the header(.......);
command.
2) remove any white-space(or newline) before <?php
and after ?>
tags.
3) GOLDEN RULE! - check if that php file (and also, if you include
other files) have UTF8 without BOM encoding (and not just UTF-8). That is problem in many cases (because UTF8 encoded file has something special character in the start of php file, which your text-editor doesnt show)!!!!!!!!!!!
4) After header(...);
you must use exit;
5) always use 301 or 302 reference:
header("location: http://example.com", true, 301 ); exit;
6) Turn on error reporting, and find the error. Your error may be caused by a function that is not working. When you turn on error reporting, you should always fix top-most error first. For example, it might be "Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings." - then farther on down you may see "headers not sent" error. After fixing top-most (1st) error, re-load your page. If you still have errors, then again fix the top-most error.
7) If none of above helps, use JAVSCRIPT redirection(however, strongly non-recommended method), may be the last chance in custom cases...:
echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>"; exit;
Very simple and easy to use custom jQuery plugin. Just add the attribute scroll=
to your clickable element and set its value to the selector you want to scroll to.
Like so: <a scroll="#product">Click me</a>
. It can be used on any element.
(function($){
$.fn.animateScroll = function(){
console.log($('[scroll]'));
$('[scroll]').click(function(){
selector = $($(this).attr('scroll'));
console.log(selector);
console.log(selector.offset().top);
$('html body').animate(
{scrollTop: (selector.offset().top)}, //- $(window).scrollTop()
1000
);
});
}
})(jQuery);
// RUN
jQuery(document).ready(function($) {
$().animateScroll();
});
// IN HTML EXAMPLE
// RUN ONCLICK ON OBJECT WITH ATTRIBUTE SCROLL=".SELECTOR"
// <a scroll="#product">Click To Scroll</a>
For a long time, DOM3 mutation events were the best available solution, but they have been deprecated for performance reasons. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver
(or as the vendor-prefixed WebKitMutationObserver
in old versions of Chrome):
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
This example listens for DOM changes on document
and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:
childList
- Set to
true
if mutations to target's children are to be observed.attributes
- Set to
true
if mutations to target's attributes are to be observed.characterData
- Set to
true
if mutations to target's data are to be observed.subtree
- Set to
true
if mutations to not just target, but also target's descendants are to be observed.attributeOldValue
- Set to
true
ifattributes
is set to true and target's attribute value before the mutation needs to be recorded.characterDataOldValue
- Set to
true
ifcharacterData
is set to true and target's data before the mutation needs to be recorded.attributeFilter
- Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.
(This list is current as of April 2014; you may check the specification for any changes.)
The FFT output coefficients (for complex input of size N) are from 0 to N - 1 grouped as [LOW,MID,HI,HI,MID,LOW] frequency.
I would consider that the element at k has the same frequency as the element at N-k since for real data, FFT[N-k] = complex conjugate of FFT[k].
The order of scanning from LOW to HIGH frequency is
0,
1,
N-1,
2,
N-2
...
[N/2] - 1,
N - ([N/2] - 1) = [N/2]+1,
[N/2]
There are [N/2]+1 groups of frequency from index i = 0 to [N/2], each having the frequency = i * SamplingFrequency / N
So the frequency at bin FFT[k] is:
if k <= [N/2] then k * SamplingFrequency / N
if k >= [N/2] then (N-k) * SamplingFrequency / N
Usage of javascript:void(0)
means that the author of the HTML is misusing the anchor element in place of the button element.
Anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. These values cause unexpected behavior when copying/dragging links, opening links in a new tabs/windows, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a
<button>
instead. In general you should only use an anchor for navigation using a proper URL.
Source: MDN's <a>
Page.
What if you want to do a comparison for values that ARE NOT equal? Just using a "NOT" in front of the previously mentioned comparisons does not work. The best I could come up with is:
(Field1 <> Field2) OR (NULLIF(Field1, Field2) IS NOT NULL) OR (NULLIF(Field2, Field1) IS NOT NULL)
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
mktemp
is probably the most versatile, especially if you plan to work with the file for a while.
You can also use a process substitution operator <()
if you only need the file temporarily as input to another command, e.g.:
$ diff <(echo hello world) <(echo foo bar)
Since nobody so far felt fit to point out why what you're trying doesn't work:
NA == NA
doesn't return TRUE
, it returns NA
(since comparing to undefined values should yield an undefined result). apply
on an atomic vector. You can't use apply
to loop over the elements in a column. a$x
, which is just the column (an atomic vector).I'd fix up 3. to get to a$x[is.na(a$x)] <- 0
If this don't work
Even easier, especially with tab completion:
db.test.find(ObjectId('4ecc05e55dd98a436ddcc47c'))
Edit: also works with the findOne
command for prettier output.
you can do top level await since typescript 3.8
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#-top-level-await
From the post:
This is because previously in JavaScript (along with most other languages with a similar feature), await was only allowed within the body of an async function. However, with top-level await, we can use await at the top level of a module.
const response = await fetch("...");
const greeting = await response.text();
console.log(greeting);
// Make sure we're a module
export {};
Note there’s a subtlety: top-level await only works at the top level of a module, and files are only considered modules when TypeScript finds an import or an export. In some basic cases, you might need to write out export {} as some boilerplate to make sure of this.
Top level await may not work in all environments where you might expect at this point. Currently, you can only use top level await when the target compiler option is es2017 or above, and module is esnext or system. Support within several environments and bundlers may be limited or may require enabling experimental support.
What about a little trickery like NgModel does with NgForm? You have to register your parent as a provider, then load your parent in the constructor of the child.
That way, you don't have to put [sharedList]
on all your children.
// Parent.ts
export var parentProvider = {
provide: Parent,
useExisting: forwardRef(function () { return Parent; })
};
@Component({
moduleId: module.id,
selector: 'parent',
template: '<div><ng-content></ng-content></div>',
providers: [parentProvider]
})
export class Parent {
@Input()
public sharedList = [];
}
// Child.ts
@Component({
moduleId: module.id,
selector: 'child',
template: '<div>child</div>'
})
export class Child {
constructor(private parent: Parent) {
parent.sharedList.push('Me.');
}
}
Then your HTML
<parent [sharedList]="myArray">
<child></child>
<child></child>
</parent>
You can find more information on the subject in the Angular documentation: https://angular.io/guide/dependency-injection-in-action#find-a-parent-component-by-injection
It's also provided in the GNU libc (Linux) and FreeBSD versions of sys/param.h, and has the definition provided by dreamlax.
On Debian:
$ uname -sr
Linux 2.6.11
$ cat /etc/debian_version
5.0.2
$ egrep 'MIN\(|MAX\(' /usr/include/sys/param.h
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
$ head -n 2 /usr/include/sys/param.h | grep GNU
This file is part of the GNU C Library.
On FreeBSD:
$ uname -sr
FreeBSD 5.5-STABLE
$ egrep 'MIN\(|MAX\(' /usr/include/sys/param.h
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
The source repositories are here: