To add to Irfan's answer, here is a shorter and faster version of get()
since it requires no iteration over the map contents:
get() {
mapName=$1; key=$2
map=${!mapName}
value="$(echo $map |sed -e "s/.*--${key}=\([^ ]*\).*/\1/" -e 's/:SP:/ /g' )"
}
For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also
// 24 = 192 bits
private const int SaltByteSize = 24;
private const int HashByteSize = 24;
private const int HasingIterationsCount = 10101;
public static string HashPassword(string password)
{
// http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(HashByteSize);
}
byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
return Convert.ToBase64String(dst);
}
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] _passwordHashBytes;
int _arrayLen = (SaltByteSize + HashByteSize) + 1;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != _arrayLen) || (src[0] != 0))
{
return false;
}
byte[] _currentSaltBytes = new byte[SaltByteSize];
Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);
byte[] _currentHashBytes = new byte[HashByteSize];
Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
{
_passwordHashBytes = bytes.GetBytes(SaltByteSize);
}
return AreHashesEqual(_currentHashBytes, _passwordHashBytes);
}
private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
{
int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
var xor = firstHash.Length ^ secondHash.Length;
for (int i = 0; i < _minHashLength; i++)
xor |= firstHash[i] ^ secondHash[i];
return 0 == xor;
}
In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.
All those results generate garbage in a zealous attempt to handle more than two arguments. I'd be curious to see how they perform compared to good 'ol:
def max (a,b)
a>b ? a : b
end
which is, by-the-way, my official answer to your question.
Below are the differences between CrudRepository
and JpaRepository
as:
CrudRepository
CrudRepository
is a base interface and extends the Repository
interface.CrudRepository
mainly provides CRUD (Create, Read, Update, Delete) operations.saveAll()
method is Iterable
.CrudRepository
.JpaRepository
JpaRepository
extends PagingAndSortingRepository
that extends CrudRepository
.JpaRepository
provides CRUD and pagination operations, along with additional methods like flush()
, saveAndFlush()
, and deleteInBatch()
, etc.saveAll()
method is a List
.JpaRepository
.I know this is old but I've used this successfully for quite a while.
private void PopulateDerivedFromBase<TB,TD>(TB baseclass,TD derivedclass)
{
//get our baseclass properties
var bprops = baseclass.GetType().GetProperties();
foreach (var bprop in bprops)
{
//get the corresponding property in the derived class
var dprop = derivedclass.GetType().GetProperty(bprop.Name);
//if the derived property exists and it's writable, set the value
if (dprop != null && dprop.CanWrite)
dprop.SetValue(derivedclass,bprop.GetValue(baseclass, null),null);
}
}
You can initialize a Dictionary
(and other collections) inline. Each member is contained with braces:
Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
{ 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
{ 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
{ 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};
See Microsoft Docs for details.
With Java 8 Optional
:
for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
// do whatever
}
Exercise 16 from Zed Shaw's book? You can use escape characters as follows:
paragraph1 = "%s \n %s \n %s \n" % (line1, line2, line3)
target.write(paragraph1)
target.close()
I found solution in this post: https://stackoverflow.com/questions/11883378/class-memcache-not-found-php#=
I found the working dll files for PHP 5.4.4
I don't knowhow stable they are but they work for sure. Credits goes to this link.
http://x32.elijst.nl/php_memcache-5.4-nts-vc9-x86.zip
http://x32.elijst.nl/php_memcache-5.4-vc9-x86.zip
It is the 2.2.5.0 version, I noticed after compiling it (for PHP 5.4.4).
Please note that it is not 2.2.6 but works. I also mirrored them in my own FTP. Mirror links:
http://mustafabugra.com/resim/php_memcache-5.4-vc9-x86.zip http://mustafabugra.com/resim/php_memcache-5.4-nts-vc9-x86.zip
If you can't find the build path error, sometimes menu Project ? Clean... works like a charm.
The package broom
comes in handy here (it uses the "tidy" format).
tidy(mg)
will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).
Example from broom
's github repo:
lmfit <- lm(mpg ~ wt, mtcars)
require(broom)
tidy(lmfit)
term estimate std.error statistic p.value
1 (Intercept) 37.285 1.8776 19.858 8.242e-19
2 wt -5.344 0.5591 -9.559 1.294e-10
is.data.frame(tidy(lmfit))
[1] TRUE
One thing I find that is often missing from these is an ability to look up row locks. At least on the larger databases I have worked on, row locks are not shown in pg_locks (if they were, pg_locks would be much, much larger and there isn't a real data type to show the locked row in that view properly).
I don't know that there is a simple solution to this but usually what I do is look at the table where the lock is waiting and search for rows where the xmax is less than the transaction id present there. That usually gives me a place to start, but it is a bit hands-on and not automation friendly.
Note that shows you uncommitted writes on rows on those tables. Once committed, the rows are not visible in the current snapshot. But for large tables, that is a pain.
For me it worked when on the right tab > Localization, I checked English check box. Initially only Base was checked. After that I had no more problems. Hope this helps!
Most people advise against using global variables. If you want the same logger class in different modules you can do this
logger.js
module.exports = new logger(customConfig);
foobar.js
var logger = require('./logger');
logger('barfoo');
If you do want a global variable you can do:
global.logger = new logger(customConfig);
Easiest Solution I've found:
After installing the MySQL package for Mac OS X Snow Leopard (check whether you have a 32bit or 64bit processor). Can always default to the 32bit version to be safe.
Simply click to install the MySQL preferences inside the dmg and when prompted whether to allow access for just you or for the entire system, choose entire system.
This worked great for me.
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
Removing the borders should make the background color paint without any gaps between the cells. If you look carefully at this jsFiddle, you should see that the light blue color stretches across the row with no white gaps.
If all else fails, try this:
table { border-collapse: collapse; }
I had same problem. I just solved it with declaring adapter
public before onCreate
of class.
PostAdapter postAdapter;
after that
postAdapter = new PostAdapter(getActivity(), posts);
recList.setAdapter(postAdapter);
at last I have called:
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// Display the size of your ArrayList
Log.i("TAG", "Size : " + posts.size());
progressBar.setVisibility(View.GONE);
postAdapter.notifyDataSetChanged();
}
May this will helps you.
Websockets and SSE (Server Sent Events) are both capable of pushing data to browsers, however they are not competing technologies.
Websockets connections can both send data to the browser and receive data from the browser. A good example of an application that could use websockets is a chat application.
SSE connections can only push data to the browser. Online stock quotes, or twitters updating timeline or feed are good examples of an application that could benefit from SSE.
In practice since everything that can be done with SSE can also be done with Websockets, Websockets is getting a lot more attention and love, and many more browsers support Websockets than SSE.
However, it can be overkill for some types of application, and the backend could be easier to implement with a protocol such as SSE.
Furthermore SSE can be polyfilled into older browsers that do not support it natively using just JavaScript. Some implementations of SSE polyfills can be found on the Modernizr github page.
Gotchas:
www.example1.com
and another 6 SSE connections to www.example2.com
(thanks Phate).HTML5Rocks has some good information on SSE. From that page:
Server-Sent Events vs. WebSockets
Why would you choose Server-Sent Events over WebSockets? Good question.
One reason SSEs have been kept in the shadow is because later APIs like WebSockets provide a richer protocol to perform bi-directional, full-duplex communication. Having a two-way channel is more attractive for things like games, messaging apps, and for cases where you need near real-time updates in both directions. However, in some scenarios data doesn't need to be sent from the client. You simply need updates from some server action. A few examples would be friends' status updates, stock tickers, news feeds, or other automated data push mechanisms (e.g. updating a client-side Web SQL Database or IndexedDB object store). If you'll need to send data to a server, XMLHttpRequest is always a friend.
SSEs are sent over traditional HTTP. That means they do not require a special protocol or server implementation to get working. WebSockets on the other hand, require full-duplex connections and new Web Socket servers to handle the protocol. In addition, Server-Sent Events have a variety of features that WebSockets lack by design such as automatic reconnection, event IDs, and the ability to send arbitrary events.
Advantages of SSE over Websockets:
Advantages of Websockets over SSE:
Ideal use cases of SSE:
SSE gotchas:
I think we should go with StringBuilder append approach. Reason being :
The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects.
With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.
This works for me,
db.student.find({},{"roll":1})
no condition in where clause i.e., inside first curly braces. inside next curly braces: list of projection field names to be needed in the result and 1 indicates particular field is the part of the query result
Because (amongst other reasons) it's much harder to ensure the input data is sanitized. If you use parametrized queries, as one does with PDO or mysqli you can entirely avoid the risk.
As an example, someone could use "enhzflep); drop table users"
as a username. The old functions will allow executing multiple statements per query, so something like that nasty bugger can delete a whole table.
If one were to use PDO of mysqli, the user-name would end-up being "enhzflep); drop table users"
.
See bobby-tables.com.
// @param db, readable database from SQLiteOpenHelper
public boolean doesTableExist(SQLiteDatabase db, String tableName) {
Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName + "'", null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
I think what you may be thinking of is expressions
or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:
width:expression(document.body.clientWidth > 800? "800px": "auto" );
This code makes IE emulate the max-width
property it doesn't support.
All things considered, however, avoid using these. They are a bad, bad thing.
You can try this:
d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)
It has a very simple solution.
After installing opencv
place
cv2.pyd
from C:\opencv\build\python\2.7\ **x64**
to C:\Python27\Lib\site-packages
instead of, place cv2.pyd
from C:\opencv\build\python\2.7\ **x86**
to C:\Python27\Lib\site-packages
This is one of those things that can be difficult to search for if you don't already know where to look.
[
is actually a command, not part of the bash shell syntax as you might expect. It happens to be a Bash built-in command, so it's documented in the Bash manual.
There's also an external command that does the same thing; on many systems, it's provided by the GNU Coreutils package.
[
is equivalent to the test
command, except that [
requires ]
as its last argument, and test
does not.
Assuming the bash documentation is installed on your system, if you type info bash
and search for 'test'
or '['
(the apostrophes are part of the search), you'll find the documentation for the [
command, also known as the test
command. If you use man bash
instead of info bash
, search for ^ *test
(the word test
at the beginning of a line, following some number of spaces).
Following the reference to "Bash Conditional Expressions" will lead you to the description of -ne
, which is the numeric inequality operator ("ne" stands for "not equal). By contrast, !=
is the string inequality operator.
You can also find bash documentation on the web.
test
and [
)-ne
is under "arg1 OP arg2")test
The official definition of the test
command is the POSIX standard (to which the bash implementation should conform reasonably well, perhaps with some extensions).
Try: sudo chmod go-w /usr/local/bin
The /usr/local/bin directory is owned by the root
(i.e. administrator) account, so even if you can write to it, you can't change the permissions on it. The sudo
command means "run the following command as root", and works a lot like clicking that lock icon in the System Preferences dialogs.
Read the input continuously within the loop so that the variable line
is assigned a value other than the initial value
while ((line = br.readLine()) !=null) {
...
}
Aside: This problem has already been solved using CSV libraries such as OpenCSV. Here are examples for reading and writing CSV files
I see that there is already an answer about the @return tag, but I want to give more details about it.
First of all, the official JSDoc 3 documentation doesn't give us any examples about the @return for a custom object. Please see https://jsdoc.app/tags-returns.html. Now, let's see what we can do until some standard will appear.
Function returns object where keys are dynamically generated. Example: {1: 'Pete', 2: 'Mary', 3: 'John'}
. Usually, we iterate over this object with the help of for(var key in obj){...}
.
Possible JSDoc according to https://google.github.io/styleguide/javascriptguide.xml#JsTypes
/**
* @return {Object.<number, string>}
*/
function getTmpObject() {
var result = {}
for (var i = 10; i >= 0; i--) {
result[i * 3] = 'someValue' + i;
}
return result
}
Function returns object where keys are known constants. Example: {id: 1, title: 'Hello world', type: 'LEARN', children: {...}}
. We can easily access properties of this object: object.id
.
Possible JSDoc according to https://groups.google.com/forum/#!topic/jsdoc-users/TMvUedK9tC4
Fake It.
/**
* Generate a point.
*
* @returns {Object} point - The point generated by the factory.
* @returns {number} point.x - The x coordinate.
* @returns {number} point.y - The y coordinate.
*/
var pointFactory = function (x, y) {
return {
x:x,
y:y
}
}
The Full Monty.
/**
@class generatedPoint
@private
@type {Object}
@property {number} x The x coordinate.
@property {number} y The y coordinate.
*/
function generatedPoint(x, y) {
return {
x:x,
y:y
};
}
/**
* Generate a point.
*
* @returns {generatedPoint} The point generated by the factory.
*/
var pointFactory = function (x, y) {
return new generatedPoint(x, y);
}
Define a type.
/**
@typedef generatedPoint
@type {Object}
@property {number} x The x coordinate.
@property {number} y The y coordinate.
*/
/**
* Generate a point.
*
* @returns {generatedPoint} The point generated by the factory.
*/
var pointFactory = function (x, y) {
return {
x:x,
y:y
}
}
According to https://google.github.io/styleguide/javascriptguide.xml#JsTypes
The record type.
/**
* @return {{myNum: number, myObject}}
* An anonymous type with the given type members.
*/
function getTmpObject() {
return {
myNum: 2,
myObject: 0 || undefined || {}
}
}
It is also good for Unit Testing, you can inject your own classes (that meet the requirements of the interface) into a class that depends on it
Are you talking about gets
?
puts "Enter A"
a = gets.chomp
puts "Enter B"
b = gets.chomp
c = a.to_i + b.to_i
puts c
Something like that?
Kernel.gets
tries to read the params found in ARGV
and only asks to console if not ARGV
found. To force to read from console even if ARGV
is not empty use STDIN.gets
I just added the oracle folder to my environmental variables and that fixed my identical error
There is a very easy trick. Set padding of that div to a positive number and margin to negativ
#wrapper {
background: url(xxx.jpeg);
padding-left: 10px;
margin-left: -10px;
}
How about this EXAMPLE? It seems straightforward.
final EditText txtUrl = new EditText(this);
// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");
new AlertDialog.Builder(this)
.setTitle("Moustachify Link")
.setMessage("Paste in the link of an image to moustachify!")
.setView(txtUrl)
.setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String url = txtUrl.getText().toString();
moustachify(null, url);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();
BEST ANSWER 1:
ActionNameSelectorAttribute
mentioned in
ANSWER 2
Reference: dotnet-tricks - Handling multiple submit buttons on the same form - MVC Razor
Second Approach
Adding a new Form for handling Cancel button click. Now, on Cancel button click we will post the second form and will redirect to the home page.
Third Approach: Client Script
<button name="ClientCancel" type="button"
onclick=" document.location.href = $('#cancelUrl').attr('href');">Cancel (Client Side)
</button>
<a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))"
style="display:none;"></a>
For form login:
<form method="post" action="/login">
<input type="text" id="email" name="email" size="35" maxlength="40" placeholder="Email" />
<input type="password" id="password" name="password" size="15" maxlength="20" placeholder="Password"/>
<input type="submit" id="send" value="Send">
</form>
Javascript:
$(document).ready(function() {
$('#send').prop('disabled', true);
$('#email, #password').keyup(function(){
if ($('#password').val() != '' && $('#email').val() != '')
{
$('#send').prop('disabled', false);
}
else
{
$('#send').prop('disabled', true);
}
});
});
Collection initializers are only available in VB.NET 2010, released 2010-04-12:
Dim theVar = New List(Of String) From { "one", "two", "three" }
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
If you want a generic solution without boxing:
public class KeyBasedEqualityComparer<T, TKey> : IEqualityComparer<T>
{
private readonly Func<T, TKey> _keyGetter;
public KeyBasedEqualityComparer(Func<T, TKey> keyGetter)
{
_keyGetter = keyGetter;
}
public bool Equals(T x, T y)
{
return EqualityComparer<TKey>.Default.Equals(_keyGetter(x), _keyGetter(y));
}
public int GetHashCode(T obj)
{
TKey key = _keyGetter(obj);
return key == null ? 0 : key.GetHashCode();
}
}
public static class KeyBasedEqualityComparer<T>
{
public static KeyBasedEqualityComparer<T, TKey> Create<TKey>(Func<T, TKey> keyGetter)
{
return new KeyBasedEqualityComparer<T, TKey>(keyGetter);
}
}
usage:
KeyBasedEqualityComparer<Class_reglement>.Create(x => x.Numf)
maybe this is what u want?
<a href="#" id="bottle" onclick="document.location=this.id+'.html';return false;" >
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" />
</a>
edit: keep in mind that anyone who does not have javascript enabled will not be able to navaigate to the image page....
USE IT
$info = random_bytes(16);
$info[6] = chr(ord($info[6]) & 0x0f | 0x40);
$info[8] = chr(ord($info[8]) & 0x3f | 0x80);
$result =vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($info), 4));
return $result;
You can use ref.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {}
},
template: `
<div>
<ChildForm :item="item" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.$refs.form.submit()
}
},
components: { ChildForm },
})
If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {},
bus: new Vue(),
},
template: `
<div>
<ChildForm :item="item" :bus="bus" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.bus.$emit('submit')
}
},
components: { ChildForm },
})
Code of component.
<template>
...
</template>
<script>
export default {
name: 'NowForm',
props: ['item', 'bus'],
methods: {
submit() {
...
}
},
mounted() {
this.bus.$on('submit', this.submit)
},
}
</script>
https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
C:\>sqlplus /nolog
SQL> connect / as SYSDBA
SQL> select * from dba_profiles;
SQL> alter profile default limit password_life_time unlimited;
SQL> alter user database_name identified by new_password;
SQL> commit;
SQL> exit;
I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.
As it was mentioned @PropertySource
doesn't load yaml file. As a workaround load the file on your own and add loaded properties to Environment
.
Implemement ApplicationContextInitializer
:
public class YamlFileApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
try {
Resource resource = applicationContext.getResource("classpath:file.yml");
YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
PropertySource<?> yamlTestProperties = sourceLoader.load("yamlTestProperties", resource, null);
applicationContext.getEnvironment().getPropertySources().addFirst(yamlTestProperties);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Add your initializer to your test:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class, initializers = YamlFileApplicationContextInitializer.class)
public class SimpleTest {
@Test
public test(){
// test your properties
}
}
I've written a little tool called psql2csv
that encapsulates the COPY query TO STDOUT
pattern, resulting in proper CSV. It's interface is similar to psql
.
psql2csv [OPTIONS] < QUERY
psql2csv [OPTIONS] QUERY
The query is assumed to be the contents of STDIN, if present, or the last argument. All other arguments are forwarded to psql except for these:
-h, --help show help, then exit
--encoding=ENCODING use a different encoding than UTF8 (Excel likes LATIN1)
--no-header do not output a header
I used the following psd that I derived from http://www.teehanlax.com/blog/?p=447
http://www.chrisandtennille.com/pictures/backbutton.psd
I then just created a custom UIView that I use in the customView property of the toolbar item.
Works well for me.
Edit: As pointed out by PrairieHippo, maralbjo found that using the following, simple code did the trick (requires custom image in bundle) should be combined with this answer. So here is additional code:
// Creates a back button instead of default behaviour (displaying title of previous screen)
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow.png"]
style:UIBarButtonItemStyleBordered
target:self
action:@selector(backAction)];
tipsDetailViewController.navigationItem.leftBarButtonItem = backButton;
[backButton release];
var a = [1,2,3];
if ( a.indexOf( 1 ) !== -1 ) { }
Note that indexOf is not in the core ECMAScript. You'll need to have a snippet for IE and possibly other browsers that dont support Array.prototype.indexOf.
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(searchElement /*, fromIndex */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0)
{
n = Number(arguments[1]);
if (n !== n)
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
On my Galaxy S4 having > 441dpi > 1080 x 1920 > Getting Actionbar height with getResources().getDimensionPixelSize I got 144 pixels.
Using formula px = dp x (dpi/160), I was using 441dpi, whereas my device lies
in the category 480dpi. so putting that confirms the result.
You can't access element like you did (document.frm_new_user_request
). You have to use the function getElementById
:
document.getElementById("frm_new_user_request")
So getting a value from an input could look like this:
var value = document.getElementById("frm_new_user_request").value
Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.
Getting a value from an input using jQuery would look like this:
var value = $("#element).value
var value = $(".element).value
If you need know if a annotation specific is present. You can do so:
Field[] fieldList = obj.getClass().getDeclaredFields();
boolean isAnnotationNotNull, isAnnotationSize, isAnnotationNotEmpty;
for (Field field : fieldList) {
//Return the boolean value
isAnnotationNotNull = field.isAnnotationPresent(NotNull.class);
isAnnotationSize = field.isAnnotationPresent(Size.class);
isAnnotationNotEmpty = field.isAnnotationPresent(NotEmpty.class);
}
And so on for the other annotations...
I hope help someone.
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
I actually found that calling fullScroll twice does the trick:
myScrollView.fullScroll(View.FOCUS_DOWN);
myScrollView.post(new Runnable() {
@Override
public void run() {
myScrollView.fullScroll(View.FOCUS_DOWN);
}
});
It may have something to do with the activation of the post() method right after performing the first (unsuccessful) scroll. I think this behavior occurs after any previous method call on myScrollView, so you can try replacing the first fullScroll() method by anything else that may be relevant to you.
There is no good answer as Python and Java are both specifications for which there are many different implementations. For example, CPython, IronPython, Jython, and PyPy are just a handful of Python implementations out there. For Java, there is the HotSpot VM, the Mac OS X Java VM, OpenJRE, etc. Jython generates Java bytecode, and so it would be using more-or-less the same underlying Java. CPython implements quite a handful of things directly in C, so it is very fast, but then again Java VMs also implement many functions in C. You would probably have to measure on a function-by-function basis and across a variety of interpreters and VMs in order to make any reasonable statement.
Update for HTTPS:
GitHub has launched a new program for Windows that stores your credentials when you're using HTTPS:
To use:
Download the program from here
Once you run the program, it will edit your .gitconfig
file. Recheck if it edited the correct .gitconfig
in case you have several of them. If it didn't edit the correct one, add the following to your .gitconfig
[credential]
helper = !'C:\\Path\\To\\Your\\Downloaded\\File\\git-credential-winstore.exe'
NOTE the line break after [credential]
. It is required.
Open up your command line client and try git push origin master
once. If it asks you for a password, enter it and you're through. Password saved!
It exists a property called XmlElementAttribute.IsNullable
If the IsNullable property is set to true, the xsi:nil attribute is generated for class members that have been set to a null reference.
The following example shows a field with the XmlElementAttribute
applied to it, and the IsNullable property set to false.
public class MyClass
{
[XmlElement(IsNullable = false)]
public string Group;
}
You can have a look to other XmlElementAttribute
for changing names in serialization etc.
I think that your problem is that you are expecting np.append
to add the column in-place, but what it does, because of how numpy data is stored, is create a copy of the joined arrays
Returns
-------
append : ndarray
A copy of `arr` with `values` appended to `axis`. Note that `append`
does not occur in-place: a new array is allocated and filled. If
`axis` is None, `out` is a flattened array.
so you need to save the output all_data = np.append(...)
:
my_data = np.random.random((210,8)) #recfromcsv('LIAB.ST.csv', delimiter='\t')
new_col = my_data.sum(1)[...,None] # None keeps (n, 1) shape
new_col.shape
#(210,1)
all_data = np.append(my_data, new_col, 1)
all_data.shape
#(210,9)
Alternative ways:
all_data = np.hstack((my_data, new_col))
#or
all_data = np.concatenate((my_data, new_col), 1)
I believe that the only difference between these three functions (as well as np.vstack
) are their default behaviors for when axis
is unspecified:
concatenate
assumes axis = 0
hstack
assumes axis = 1
unless inputs are 1d, then axis = 0
vstack
assumes axis = 0
after adding an axis if inputs are 1dappend
flattens arrayBased on your comment, and looking more closely at your example code, I now believe that what you are probably looking to do is add a field to a record array. You imported both genfromtxt
which returns a structured array and recfromcsv
which returns the subtly different record array (recarray
). You used the recfromcsv
so right now my_data
is actually a recarray
, which means that most likely my_data.shape = (210,)
since recarrays are 1d arrays of records, where each record is a tuple with the given dtype.
So you could try this:
import numpy as np
from numpy.lib.recfunctions import append_fields
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
data = np.array( list(zip(x,y,z)), dtype=[('x',float),('y',float),('z',float)])
data = np.recarray(data.shape, data.dtype, buf=data)
data.shape
#(10,)
tot = data['x'] + data['y'] + data['z'] # sum(axis=1) won't work on recarray
tot.shape
#(10,)
all_data = append_fields(data, 'total', tot, usemask=False)
all_data
#array([(0.4374783740738456 , 0.04307289878861764, 0.021176067323686598, 0.5017273401861498),
# (0.07622262416466963, 0.3962146058689695 , 0.27912715826653534 , 0.7515643883001745),
# (0.30878532523061153, 0.8553768789387086 , 0.9577415585116588 , 2.121903762680979 ),
# (0.5288343561208022 , 0.17048864443625933, 0.07915689716226904 , 0.7784798977193306),
# (0.8804269791375121 , 0.45517504750917714, 0.1601389248542675 , 1.4957409515009568),
# (0.9556552723429782 , 0.8884504475901043 , 0.6412854758843308 , 2.4853911958174133),
# (0.0227638618687922 , 0.9295332854783015 , 0.3234597575660103 , 1.275756904913104 ),
# (0.684075052174589 , 0.6654774682866273 , 0.5246593820025259 , 1.8742119024637423),
# (0.9841793718333871 , 0.5813955915551511 , 0.39577520705133684 , 1.961350170439875 ),
# (0.9889343795296571 , 0.22830104497714432, 0.20011292764078448 , 1.4173483521475858)],
# dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8'), ('total', '<f8')])
all_data.shape
#(10,)
all_data.dtype.names
#('x', 'y', 'z', 'total')
We'll do it using just CSS pseudo selectors!
This technique will work with dynamically generated content and different font sizes and widths.
HTML:
<div class='split-color'>Two is better than one.</div>
CSS:
.split-color > span {
white-space: pre-line;
position: relative;
color: #409FBF;
}
.split-color > span:before {
content: attr(data-content);
pointer-events: none; /* Prevents events from targeting pseudo-element */
position: absolute;
overflow: hidden;
color: #264A73;
width: 50%;
z-index: 1;
}
To wrap the dynamically generated string, you could use a function like this:
// Wrap each letter in a span tag and return an HTML string
// that can be used to replace the original text
function wrapString(str) {
var output = [];
str.split('').forEach(function(letter) {
var wrapper = document.createElement('span');
wrapper.dataset.content = wrapper.innerHTML = letter;
output.push(wrapper.outerHTML);
});
return output.join('');
}
// Replace the original text with the split-color text
window.onload = function() {
var el = document.querySelector('.split-color'),
txt = el.innerHTML;
el.innerHTML = wrapString(txt);
}
you can use this method
public static void copyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
To track down the correct parameters you need to go first to ?plot.default
, which refers you to ?par
and ?axis
:
plot(1, 1 ,xlab="x axis", ylab="y axis", pch=19,
col.lab="red", cex.lab=1.5, # for the xlab and ylab
col="green") # for the points
If you get the context via the parameter list of Configure in Startup.cs, You can instead do this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, LoggerFactory loggerFactory,
ApplicationDbContext context)
{
context.Database.Migrate();
...
Just use div { padding: 20px; }
and substract 40px
from your original div
width.
Like Philip Wills pointed out, you can also use box-sizing
instead of substracting 40px
:
div {
padding: 20px;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
The -moz-box-sizing
is for Firefox.
var CurrentMouseXPostion;
var CurrentMouseYPostion;
$(document).mousemove(function(event) {
CurrentMouseXPostion = event.pageX;
CurrentMouseYPostion = event.pageY;
});
Make an eventListener on the main object , in my case the document object, to get the mouse coords every frame and store them in global variables, and like that you can read mouse Y & Z whenever youlike , wherever you like.
Yes:
float[] values = {0.1f, 0.2f, 0.3f};
This syntax is only permissible in an initializer. You cannot use it in an assignment, where the following is the best you can do:
values = new float[3];
or
values = new float[] {0.1f, 0.2f, 0.3f};
Trying to find a reference in the language spec for this, but it's as unreadable as ever. Anyone else find one?
In my case, it was caused by an unseen trailing space at the end of the column name. Just check if you really use "y" or "y " instead.
Use max-width on modal-dialog for angular 5
.mod-class .modal-dialog {
max-width: 1000px;
}
and use windowClass as others recommended, TS eg:
this.modalService.open(content, { windowClass: 'mod-class' }).result.then(
(result) => {
// this.closeResult = `Closed with: ${result}`;
}, (reason) => {
// this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
Also, I had to put the css code in global styles > styles.css.
This can also happen if you have Chrome update automatically. Open Check chrome://help
. The status should be:
Google Chrome is up to date.
Sometimes the status is requesting for a Chrome restart. In this case I had similar issues with several resources failing to load due to net::ERR_INSECURE_RESPONSE
. After restarting Chrome, everything worked normally.
select *
from [ServerName(IP)].[DatabaseName].[dbo].[TableName]
import * as Rx from 'rxjs/Rx';
We should add the above import to make the blow code to work
Let obs = Rx.Observable
.interval(1000).take(3);
obs.subscribe(value => console.log('Subscriber: ' + value));
The closest equivalent to Java's toString
is to implement __str__
for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__
to aid in debugging.
See here for more information:
From Github guide: Getting your project to Github:(using Github desktop version)
Set up your project in GitHub Desktop
The easiest way to get your project into GitHub Desktop is to drag the folder which contains your project files onto the main application screen.
If you are dragging in an existing Git repository, you can skip ahead and push your code to GitHub.com.
If the folder isn’t a Git repository yet, GitHub Desktop will prompt you to turn it into a repository. Turning your project into a Git repository won’t delete or ruin the files in your folder—it will simply create some hidden files that allow Git to do its magic.
In Windows it looks like this:(GitHub desktop 3.0.5.2)
this is not the most geeky way but it works.
Here is a solution that works with Xcode 10.1 (FEB 23 2019) :
func getCurrentDateTime() {
let now = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "fr_FR")
formatter.dateFormat = "EEEE dd MMMM YYYY"
labelDate.text = formatter.string(from: now)
labelDate.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
labelDate.textColor = UIColor.lightGray
let text = formatter.string(from: now)
labelDate.text = text.uppercased()
}
I Don't know why, but in my case, even if I remove bin folder from project, when I build project it copies old version of newtonsoft.json, I copied new version's dll from packages folder and It solves for now.
# Define the types of logger and level of logging
log4j.rootLogger = DEBUG,console, FILE
# Define the File appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Define Console Appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
# Define the layout for console appender. If you do not
# define it, you will get an error
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# Set the name of the file
log4j.appender.FILE.File=log.out
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
Check out Hex.encodeHexString from Apache Commons Codec.
import org.apache.commons.codec.binary.Hex;
String hex = Hex.encodeHexString(bytes);
WebClient client = new WebClient();
using (Stream data = client.OpenRead(Text))
{
using (StreamReader reader = new StreamReader(data))
{
string content = reader.ReadToEnd();
string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
MatchCollection matches = Regex.Matches(content,pattern);
List<string> urls = new List<string>();
foreach (Match match in matches)
{
urls.Add(match.Value);
}
}
Because '' is not a valid Javascript/JSON object. An empty object would be '{}'
For reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Set this in HTML:
<div class="modal-body " [formGroup]="Form">
<div class="">
<mat-checkbox formControlName="a" [disabled]="true"> Display 1</mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="b" [disabled]="true"> Display 2 </mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="c" [disabled]="true"> Display 3 </mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="d" [disabled]="true"> Display 4</mat-checkbox>
</div>
<div class="">
<mat-checkbox formControlName="e" [disabled]="true"> Display 5 </mat-checkbox>
</div>
</div>
Changes in Ts file
this.Form = this.formBuilder.group({
a: false,
b: false,
c: false,
d: false,
e: false,
});
Conditionvalidation in Ur Business logic
if(true){
this.Form.patch(a: true);
}
Another method through re
module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.
>>> import re
>>> s = "many fancy word \nhello \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']
Above regex would match one or more non-space characters.
If you just want to create a default POM and enable m2eclipse features: so I'm assuming you do not currently have an alternative automated build setup you're trying to import, and I'm assuming you're talking about the m2eclipse plugin.
The m2eclipse plugin provides a right-click option on a project to add this default pom.xml:
Newer M2E versions
Right click on Project -> submenu Configure -> Convert to Maven Project
Older M2E versions
Right click on Project -> submenu Maven -> Enable Dependency Management.
That'll do the necessary to enable the plugin for that project.
To answer 'is there an automatic importer or wizard?': not that I know of. Using the option above will allow you to enable the m2eclipse plugin for your existing project avoiding the manual copying. You will still need to actually set up the dependencies and other stuff you need to build yourself.
You could try adding a bool so the algorithm would know when the button was activated. When it's clicked, the bool checks true, the new form shows and the last gets closed.
It's important to know that forms consume some ram (at least a little bit), so it's a good idea to close those you're not gonna use, instead of just hiding it. Makes the difference in big projects.
If you want a fluffier interface than the terminal, http://hurl.it/ is awesome.
See the following snippet, is this what you want?
body {
background: silver;
padding: 0 10px;
}
#content:after {
height: 10px;
display: block;
width: 100px;
background: #808080;
border-right: 1px white;
content: '';
}
#footer:before {
display: block;
content: '';
background: silver;
height: 10px;
margin-top: -20px;
margin-left: 101px;
}
#content {
background: white;
}
#footer {
padding-top: 10px;
background: #404040;
}
p {
padding: 100px;
text-align: center;
}
#footer p {
color: white;
}
_x000D_
<body>
<div id="content"><p>#content</p></div>
<div id="footer"><p>#footer</p></div>
</body>
_x000D_
Thank you, user374559 and reneD -- that code and description is very helpful.
My stab at some Python to parse and print out the information in a Unix ls-l like format:
#!/usr/bin/env python
import sys
def getint(data, offset, intsize):
"""Retrieve an integer (big-endian) and new offset from the current offset"""
value = 0
while intsize > 0:
value = (value<<8) + ord(data[offset])
offset = offset + 1
intsize = intsize - 1
return value, offset
def getstring(data, offset):
"""Retrieve a string and new offset from the current offset into the data"""
if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
return '', offset+2 # Blank string
length, offset = getint(data, offset, 2) # 2-byte length
value = data[offset:offset+length]
return value, (offset + length)
def process_mbdb_file(filename):
mbdb = {} # Map offset of info in this file => file info
data = open(filename).read()
if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
offset = 4
offset = offset + 2 # value x05 x00, not sure what this is
while offset < len(data):
fileinfo = {}
fileinfo['start_offset'] = offset
fileinfo['domain'], offset = getstring(data, offset)
fileinfo['filename'], offset = getstring(data, offset)
fileinfo['linktarget'], offset = getstring(data, offset)
fileinfo['datahash'], offset = getstring(data, offset)
fileinfo['unknown1'], offset = getstring(data, offset)
fileinfo['mode'], offset = getint(data, offset, 2)
fileinfo['unknown2'], offset = getint(data, offset, 4)
fileinfo['unknown3'], offset = getint(data, offset, 4)
fileinfo['userid'], offset = getint(data, offset, 4)
fileinfo['groupid'], offset = getint(data, offset, 4)
fileinfo['mtime'], offset = getint(data, offset, 4)
fileinfo['atime'], offset = getint(data, offset, 4)
fileinfo['ctime'], offset = getint(data, offset, 4)
fileinfo['filelen'], offset = getint(data, offset, 8)
fileinfo['flag'], offset = getint(data, offset, 1)
fileinfo['numprops'], offset = getint(data, offset, 1)
fileinfo['properties'] = {}
for ii in range(fileinfo['numprops']):
propname, offset = getstring(data, offset)
propval, offset = getstring(data, offset)
fileinfo['properties'][propname] = propval
mbdb[fileinfo['start_offset']] = fileinfo
return mbdb
def process_mbdx_file(filename):
mbdx = {} # Map offset of info in the MBDB file => fileID string
data = open(filename).read()
if data[0:4] != "mbdx": raise Exception("This does not look like an MBDX file")
offset = 4
offset = offset + 2 # value 0x02 0x00, not sure what this is
filecount, offset = getint(data, offset, 4) # 4-byte count of records
while offset < len(data):
# 26 byte record, made up of ...
fileID = data[offset:offset+20] # 20 bytes of fileID
fileID_string = ''.join(['%02x' % ord(b) for b in fileID])
offset = offset + 20
mbdb_offset, offset = getint(data, offset, 4) # 4-byte offset field
mbdb_offset = mbdb_offset + 6 # Add 6 to get past prolog
mode, offset = getint(data, offset, 2) # 2-byte mode field
mbdx[mbdb_offset] = fileID_string
return mbdx
def modestr(val):
def mode(val):
if (val & 0x4): r = 'r'
else: r = '-'
if (val & 0x2): w = 'w'
else: w = '-'
if (val & 0x1): x = 'x'
else: x = '-'
return r+w+x
return mode(val>>6) + mode((val>>3)) + mode(val)
def fileinfo_str(f, verbose=False):
if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
else:
print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
type = '?' # unknown
info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" %
(type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'],
f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
for name, value in f['properties'].items(): # extra properties
info = info + ' ' + name + '=' + repr(value)
return info
verbose = True
if __name__ == '__main__':
mbdb = process_mbdb_file("Manifest.mbdb")
mbdx = process_mbdx_file("Manifest.mbdx")
for offset, fileinfo in mbdb.items():
if offset in mbdx:
fileinfo['fileID'] = mbdx[offset]
else:
fileinfo['fileID'] = "<nofileID>"
print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
print fileinfo_str(fileinfo, verbose)
similar solution can be found here using jquery to set the auto width when focus (or mouseenter) and set the orignal width back when blur (or mouseleave) http://css-tricks.com/select-cuts-off-options-in-ie-fix/.
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
It depends on how the events are attached. For illustration presume we have the following click handler:
var handler = function() { alert('clicked!') };
We're going to attach it to our element using different methods, some which allow inspection and some that don't.
Method A) single event handler
element.onclick = handler;
// inspect
console.log(element.onclick); // "function() { alert('clicked!') }"
Method B) multiple event handlers
if(element.addEventListener) { // DOM standard
element.addEventListener('click', handler, false)
} else if(element.attachEvent) { // IE
element.attachEvent('onclick', handler)
}
// cannot inspect element to find handlers
Method C): jQuery
$(element).click(handler);
1.3.x
// inspect
var clickEvents = $(element).data("events").click;
jQuery.each(clickEvents, function(key, value) {
console.log(value) // "function() { alert('clicked!') }"
})
1.4.x (stores the handler inside an object)
// inspect
var clickEvents = $(element).data("events").click;
jQuery.each(clickEvents, function(key, handlerObj) {
console.log(handlerObj.handler) // "function() { alert('clicked!') }"
// also available: handlerObj.type, handlerObj.namespace
})
1.7+ (very nice)
Made using knowledge from this comment.
events = $._data(this, 'events');
for (type in events) {
events[type].forEach(function (event) {
console.log(event['handler']);
});
}
(See jQuery.fn.data
and jQuery.data
)
Method D): Prototype (messy)
$(element).observe('click', handler);
1.5.x
// inspect
Event.observers.each(function(item) {
if(item[0] == element) {
console.log(item[2]) // "function() { alert('clicked!') }"
}
})
1.6 to 1.6.0.3, inclusive (got very difficult here)
// inspect. "_eventId" is for < 1.6.0.3 while
// "_prototypeEventID" was introduced in 1.6.0.3
var clickEvents = Event.cache[element._eventId || (element._prototypeEventID || [])[0]].click;
clickEvents.each(function(wrapper){
console.log(wrapper.handler) // "function() { alert('clicked!') }"
})
1.6.1 (little better)
// inspect
var clickEvents = element.getStorage().get('prototype_event_registry').get('click');
clickEvents.each(function(wrapper){
console.log(wrapper.handler) // "function() { alert('clicked!') }"
})
When clicking the resulting output in the console (which shows the text of the function), the console will navigate directly to the line of the function's declaration in the relevant JS file.
The reason for this is that you are trying to use an IntentService. Here is the line from the API Docs
The IntentService does the following:
Stops the service after all start requests have been handled, so you never have to call stopSelf().
Thus if you want your service to run indefinitely i suggest you extend the Service class instead. However this does not guarantee your service will run indefinitely. Your service will still have a chance of being killed by the kernel in a state of low memory if it is low priority.So you have two options:
1)Keep it running in the foreground by calling the startForeground()
method.
2)Restart the service if it gets killed.
Here is a part of the example from the docs where they talk about restarting the service after it is killed
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
The command line tool ExifTool by Phil Harvey works with dozens of images formats - including plenty of proprietary RAW formats - and can manipulate a variety of metadata formats including EXIF, GPS, IPTC, XMP, JFIF.
Very easy to use, lightweight, impressive application.
There is a specific example that "_" be used:
type StringMatcher = String => (String => Boolean)
def starts: StringMatcher = (prefix:String) => _ startsWith prefix
may be equal to :
def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix
Applying “_” in some scenarios will automatically convert to “(x$n) => x$n ”
Short answer - no.
You will only be charged for the time that your instance is up and running, in hour increments. If you are using other services in conjunction you may be charged for those but it would be separate from your server instance.
http://petrnohejl.github.io/Android-Cheatsheet-For-Graphic-Designers/
Text size
Type Dimension
Micro 12 sp
Small 14 sp
Medium 18 sp
Large 22 sp
A very simple example of a swing component to draw lines. It keeps internally a list with the lines that have been added with the method addLine. Each time a new line is added, repaint is invoked to inform the graphical subsytem that a new paint is required.
The class also includes some example of usage.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LinesComponent extends JComponent{
private static class Line{
final int x1;
final int y1;
final int x2;
final int y2;
final Color color;
public Line(int x1, int y1, int x2, int y2, Color color) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.color = color;
}
}
private final LinkedList<Line> lines = new LinkedList<Line>();
public void addLine(int x1, int x2, int x3, int x4) {
addLine(x1, x2, x3, x4, Color.black);
}
public void addLine(int x1, int x2, int x3, int x4, Color color) {
lines.add(new Line(x1,x2,x3,x4, color));
repaint();
}
public void clearLines() {
lines.clear();
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Line line : lines) {
g.setColor(line.color);
g.drawLine(line.x1, line.y1, line.x2, line.y2);
}
}
public static void main(String[] args) {
JFrame testFrame = new JFrame();
testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final LinesComponent comp = new LinesComponent();
comp.setPreferredSize(new Dimension(320, 200));
testFrame.getContentPane().add(comp, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel();
JButton newLineButton = new JButton("New Line");
JButton clearButton = new JButton("Clear");
buttonsPanel.add(newLineButton);
buttonsPanel.add(clearButton);
testFrame.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
newLineButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int x1 = (int) (Math.random()*320);
int x2 = (int) (Math.random()*320);
int y1 = (int) (Math.random()*200);
int y2 = (int) (Math.random()*200);
Color randomColor = new Color((float)Math.random(), (float)Math.random(), (float)Math.random());
comp.addLine(x1, y1, x2, y2, randomColor);
}
});
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
comp.clearLines();
}
});
testFrame.pack();
testFrame.setVisible(true);
}
}
If you already have the package name you wish to activate, you can use the following code which is a bit more generic:
PackageManager pm = context.getPackageManager();
Intent appStartIntent = pm.getLaunchIntentForPackage(appPackageName);
if (null != appStartIntent)
{
context.startActivity(appStartIntent);
}
I found that it works better for cases where the main activity was not found by the regular method of start the MAIN activity.
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
I think str_replace(array("\\r\\n", "\\r", "\\n"), " ", $string);
will work.
You can use the Environment class's static NewLine property to get the proper newline:
$errorMsg = "{0} Error {1}{2} key {3} expected: {4}{5} local value is: {6}" -f `
(Get-Date),$keyPath,$value,$key,$policyValue,([Environment]::NewLine),$localValue
Add-Content -Path $logpath $errorMsg
In a Form, Create a text box, with in text box properties select data tab
Default value =CurrentUser()
Current source "select table field name"
It will display current user log on name in text box / label as well as saves the user name in the table field
As You're getting values from textfield as jTextField3.getText();
.
As it is a textField
it will return you string format as its format says:
String getText()
Returns the text contained in this TextComponent.
So, convert your String
to Integer
as:
int jml = Integer.parseInt(jTextField3.getText());
instead of directly setting
int jml = jTextField3.getText();
In the IndexProcessor
class you need a way of setting a flag which informs the thread that it will need to terminate, similar to the variable run
that you have used just in the class scope.
When you wish to stop the thread, you set this flag and call join()
on the thread and wait for it to finish.
Make sure that the flag is thread safe by using a volatile variable or by using getter and setter methods which are synchronised with the variable being used as the flag.
public class IndexProcessor implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
private volatile boolean running = true;
public void terminate() {
running = false;
}
@Override
public void run() {
while (running) {
try {
LOGGER.debug("Sleeping...");
Thread.sleep((long) 15000);
LOGGER.debug("Processing");
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
running = false;
}
}
}
}
Then in SearchEngineContextListener
:
public class SearchEngineContextListener implements ServletContextListener {
private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);
private Thread thread = null;
private IndexProcessor runnable = null;
@Override
public void contextInitialized(ServletContextEvent event) {
runnable = new IndexProcessor();
thread = new Thread(runnable);
LOGGER.debug("Starting thread: " + thread);
thread.start();
LOGGER.debug("Background process successfully started.");
}
@Override
public void contextDestroyed(ServletContextEvent event) {
LOGGER.debug("Stopping thread: " + thread);
if (thread != null) {
runnable.terminate();
thread.join();
LOGGER.debug("Thread successfully stopped.");
}
}
}
For those who created rating bar programmatically and want set small rating bar instead of default big rating bar
private LinearLayout generateRatingView(float value){ LinearLayout linearLayoutRating=new LinearLayout(getContext()); linearLayoutRating.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); linearLayoutRating.setGravity(Gravity.CENTER); RatingBar ratingBar = new RatingBar(getContext(),null, android.R.attr.ratingBarStyleSmall); ratingBar.setEnabled(false); ratingBar.setStepSize(Float.parseFloat("0.5"));//for enabling half star ratingBar.setNumStars(5); ratingBar.setRating(value); linearLayoutRating.addView(ratingBar); return linearLayoutRating; }
Change:
<select name="select2" ...
To:
<select name="select2[]" ...
Yes, image alt text can be styled using any style property you use for regular text, such as font-size, font-weight, line-height, color, background-color,etc. The line-height (of text) or vertical-align (if display:table-cell used) could also be used to vertically align alt text within an image element or image wrapping container, i.e. div.
To prevent accessibility issues regarding contrast, and inheriting the browser's default black font color when you've set a dark blue background-color, always set both the color of your font and its background-color at the same time.
for some more useful info, visit Alternate text for background images or The Ultimate Guide to Styled ALT Text in Email
Just start it with a slash? This means root. As long as you're testing on a web server (e.g. localhost) and not a file system (e.g. C:) then that should be all you need to do.
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.Number = 12;
MyDynamic.MyMethod = new Func<int>(() =>
{
return 55;
});
Console.WriteLine(MyDynamic.MyMethod());
Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.
Maybe you could try
List<Article> findAllByPublicationDate(Date publicationDate);
The detail could be checked in this article:
XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"
//production[not(contains(category,'Business'))]
I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.
To remove a scrollbar from a view (and its subclass) via xml:
android:scrollbars="none"
http://developer.android.com/reference/android/view/View.html#attr_android:scrollbars
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
$password = Input::get('password_from_user');
$hashed = Hash::make($password); // save $hashed value
// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
// Password is not matching
} else {
// Password is matching
}
The String class comes with the format abilities:
System.out.println(String.format("%02d", 5));
for full documentation, here is the doc
PS> Get-CimInstance -ComputerName bobPC win32_logicaldisk | where caption -eq "C:" | foreach-object {write " $($_.caption) $('{0:N2}' -f ($_.Size/1gb)) GB total, $('{0:N2}' -f ($_.FreeSpace/1gb)) GB free "}
C: 117.99 GB total, 16.72 GB free
PS>
The below command will work if you want create a new user give him all the access to a specific database(not all databases in your Mysql) on your localhost.
GRANT ALL PRIVILEGES ON test_database.* TO 'user'@'localhost' IDENTIFIED BY 'password';
This will grant all privileges to one database test_database
(in your case dbTest
) to that user on localhost.
Check what permissions that above command issued to that user by running the below command.
SHOW GRANTS FOR 'user'@'localhost'
Just in case, if you want to limit the user access to only one single table
GRANT ALL ON mydb.table_name TO 'someuser'@'host';
Without the need of an external package:
if your date is in the following format:
myDate = as.POSIXct("2013-01-01")
Then to get the month number:
format(myDate,"%m")
And to get the month string:
format(myDate,"%B")
Try this:
in.nextLine();
This advances the Scanner to the next line.
The key is "argument-less git-pull". When you do a git pull
from a branch, without specifying a source remote or branch, git looks at the branch.<name>.merge
setting to know where to pull from. git push -u
sets this information for the branch you're pushing.
To see the difference, let's use a new empty branch:
$ git checkout -b test
First, we push without -u
:
$ git push origin test
$ git pull
You asked me to pull without telling me which branch you
want to merge with, and 'branch.test.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.
If you often merge with the same branch, you may want to
use something like the following in your configuration file:
[branch "test"]
remote = <nickname>
merge = <remote-ref>
[remote "<nickname>"]
url = <url>
fetch = <refspec>
See git-config(1) for details.
Now if we add -u
:
$ git push -u origin test
Branch test set up to track remote branch test from origin.
Everything up-to-date
$ git pull
Already up-to-date.
Note that tracking information has been set up so that git pull
works as expected without specifying the remote or branch.
Update: Bonus tips:
git pull
this setting also affects default behavior of git push
. If you get in the habit of using -u
to capture the remote branch you intend to track, I recommend setting your push.default
config value to upstream
.git push -u <remote> HEAD
will push the current branch to a branch of the same name on <remote>
(and also set up tracking so you can do git push
after that).Find missing all elements from array
int[] array = {3,5,7,8,2,1,32,5,7,9,30,5};
TreeMap<Integer, Integer> map = new TreeMap<>();
for(int i=0;i<array.length;i++) {
map.put(array[i], 1);
}
int maxSize = map.lastKey();
for(int j=0;j<maxSize;j++) {
if(null == map.get(j))
System.out.println("Missing `enter code here`No:"+j);
}
Use this
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.someplace.com");
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
This can be used to grab the whole webpage as a string of html, i.e., "<html>...</html>"
Note
You need to declare the following 'uses-permission' in the android manifest xml file
... answer by @Squonk here
And also check this answer
I made this into a jQuery function:
jQuery.fn.sortDivs = function sortDivs() {
$("> div", this[0]).sort(dec_sort).appendTo(this[0]);
function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}
So you have a big div like "#boo" and all your little divs inside of there:
$("#boo").sortDivs();
You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html
Thanks , but i found an alternative solution using ffmpeg:
def save():
os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")
But thank you for your help :)
In my case, I was looking for a keydown ctrl key and click event. My jquery looks like this:
$('.linkAccess').click( function (event) {
if(true === event.ctrlKey) {
/* Extract the value */
var $link = $('.linkAccess');
var value = $link.val();
/* Verified if the link is not null */
if('' !== value){
window.open(value);
}
}
});
Where "linkAccess" is the class name for some specific fields where I have a link and I want to access it using my combination of key and click.
You just have to write sudo
instead of su
.
Then just copy the PHP file to the var/www/ directory
.
Then go to the browser, and write local host/test.php
or whatever the .php
filename is.
As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.
You almost have it! The way to do nested list comprehensions is to put the for
statements in the same order as they would go in regular nested for
statements.
Thus, this
for inner_list in outer_list:
for item in inner_list:
...
corresponds to
[... for inner_list in outer_list for item in inner_list]
So you want
[image for menuitem in list_of_menuitems for image in menuitem]
You can use following commands to extract public/private key from a PKCS#12 container:
PKCS#1 Private key
openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem
Certificates:
openssl pkcs12 -in yourP12File.pfx -clcerts -nokeys -out publicCert.pem
Find the index
of the array element you want to remove using indexOf
, and then remove that index with splice
.
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
const array = [2, 5, 9];_x000D_
_x000D_
console.log(array);_x000D_
_x000D_
const index = array.indexOf(5);_x000D_
if (index > -1) {_x000D_
array.splice(index, 1);_x000D_
}_x000D_
_x000D_
// array = [2, 9]_x000D_
console.log(array);
_x000D_
The second parameter of splice
is the number of elements to remove. Note that splice
modifies the array in place and returns a new array containing the elements that have been removed.
For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5
from [2,5,9,1,5,8,5]
), while the second function removes all occurrences:
function removeItemOnce(arr, value) {_x000D_
var index = arr.indexOf(value);_x000D_
if (index > -1) {_x000D_
arr.splice(index, 1);_x000D_
}_x000D_
return arr;_x000D_
}_x000D_
_x000D_
function removeItemAll(arr, value) {_x000D_
var i = 0;_x000D_
while (i < arr.length) {_x000D_
if (arr[i] === value) {_x000D_
arr.splice(i, 1);_x000D_
} else {_x000D_
++i;_x000D_
}_x000D_
}_x000D_
return arr;_x000D_
}_x000D_
//Usage_x000D_
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))_x000D_
console.log(removeItemAll([2,5,9,1,5,8,5], 5))
_x000D_
If you used...
$(function(){
function myFunc() {
// ... do something ...
};
$('#saveBtn').click(myFunc);
});
... then it will be easier to unbind later.
I ran into this trying to integrate React Native into an existing swift project using cocoapods. The FB docs (at time of writing) did not specify that npm install react-native
wouldn't work without first having a package.json
file. Per the RN docs set your entry point: (index.js)
as index.ios.js
in code
listView.setSelector(getResources().getDrawable(R.drawable.transparent));
and add small transparent image to drawable folder.
Like: transparent.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#00000000"/>
</shape>
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;
Use the createFromFormat
method:
$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);
UPDATE
I now recommend the use of Carbon
If you are using Dev C++ then your .exe
or mean to say your program already running and you are trying to run it again.
sqlplus / as SYSDBA
ALTER USER existing_account_name IDENTIFIED BY new_password ACCOUNT UNLOCK;
If you are using tinker and want to log the SQL query formed you can do
$ php artisan tinker
Psy Shell v0.9.9 (PHP 7.3.5 — cli) by Justin Hileman
>>> DB::listen(function ($query) { dump($query->sql); dump($query->bindings); dump($query->time); });
=> null
>>> App\User::find(1)
"select * from `users` where `users`.`id` = ? limit 1"
array:1 [
0 => 1
]
6.99
=> App\User {#3131
id: 1,
name: "admin",
email: "[email protected]",
created_at: "2019-01-11 19:06:23",
updated_at: "2019-01-11 19:06:23",
}
>>>
Wikipedia has the answer, along with a number of other sources.
A segfault basically means you did something bad with pointers. This is probably a segfault:
char *c = NULL;
...
*c; // dereferencing a NULL pointer
Or this:
char *c = "Hello";
...
c[10] = 'z'; // out of bounds, or in this case, writing into read-only memory
Or maybe this:
char *c = new char[10];
...
delete [] c;
...
c[2] = 'z'; // accessing freed memory
Same basic principle in each case - you're doing something with memory that isn't yours.
I has able to choose a simplier solution > Add a new Headers to the defaults options merge or load by your api get (or other) function.
get(endpoint: string, params?: any, options?: RequestOptions) {
if (!options) {
options = new RequestOptions();
options.headers = new Headers( { "Accept": "application/json" } ); <<<<
}
// [...]
}
Of course you can externalize this Headers in default options or whatever in your class. This is in the Ionic generated api.ts @Injectable() export class API {}
It is very quick and it work for me. I didn't want json/ld format.
I've used bundle update --source
myself for a long time but there are scenarios where it doesn't work. Luckily, there's a gem called bundler-patch
which has the goal of fixing this shortcoming.
I also wrote a short blog post about how to use bundler-patch
and why bundle update --source
doesn't work consistently. Also, be sure to check out a post by chrismo that explains in great detail what the --source
option does.
The reason mine was showing the "Lock" message was actually due to me having opened an SQLite3 IDE on my mac and that was the reason it was locked. I assume I was playing around with the DB within the IDE and hadn't saved the changes and therefor a lock was placed.
Cut long story short, check that there are no unsaved changes on the db and also that it is not being used elsewhere.
You can get all details by order object.
// Get $order object from order ID
$order = wc_get_order( $order_id );
// Now you have access to (see above)...
if ( $order ) {
// Get Order ID and Key
$order->get_id();
$order->get_order_key();
// Get Order Totals $0.00
$order->get_formatted_order_total();
$order->get_cart_tax();
$order->get_currency();
$order->get_discount_tax();
$order->get_discount_to_display();
$order->get_discount_total();
$order->get_fees();
$order->get_formatted_line_subtotal();
$order->get_shipping_tax();
$order->get_shipping_total();
$order->get_subtotal();
$order->get_subtotal_to_display();
$order->get_tax_location();
$order->get_tax_totals();
$order->get_taxes();
$order->get_total();
$order->get_total_discount();
$order->get_total_tax();
$order->get_total_refunded();
$order->get_total_tax_refunded();
$order->get_total_shipping_refunded();
$order->get_item_count_refunded();
$order->get_total_qty_refunded();
$order->get_qty_refunded_for_item();
$order->get_total_refunded_for_item();
$order->get_tax_refunded_for_item();
$order->get_total_tax_refunded_by_rate_id();
$order->get_remaining_refund_amount();
}
Having Clause may come prior/before the group by clause.
Example: select * FROM test_std; ROLL_NO SNAME DOB TEACH
1 John 27-AUG-18 Wills
2 Knit 27-AUG-18 Prestion
3 Perl 27-AUG-18 Wills
4 Ohrm 27-AUG-18 Woods
5 Smith 27-AUG-18 Charmy
6 Jony 27-AUG-18 Wills
Warner 20-NOV-18 Wills
Marsh 12-NOV-18 Langer
FINCH 18-OCT-18 Langer
9 rows selected.
select teach, count() count from test_std having count() > 1 group by TEACH ;
TEACH COUNT
Langer 2 Wills 4
Finally I imported my Gradle project. These are the steps:
JAVA_HOME
to JDK 8 (it was 7th previously) as I had
figured out by experiments that Gradle Wrapper could process the
project with JDK 8 only. org.gradle.java.home
variable) in windows user .gradle directory
as, I guessed, it didn't bring any additional value to Gradle.You must use OverridePendingTransition method to achieve it, which is in the Activity class. Sample Animations in the apidemos example's res/anim folder. Check it. More than check the demo in ApiDemos/App/Activity/animation.
Example:
@Override
public void onResume(){
// TODO LC: preliminary support for views transitions
this.overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}
Based on Anastasiya's answer. I think this is the shortest vba command:
Option Explicit
Sub Sample()
Dim sColumnLetter as String
Dim iColumnNumber as Integer
sColumnLetter = "C"
iColumnNumber = Columns(sColumnLetter).Column
MsgBox "The column number is " & iColumnNumber
End Sub
Caveat: The only condition for this code to work is that a worksheet is active, because Columns
is equivalent to ActiveSheet.Columns
. ;)
Use the update flag: -u
Example:
zip -ur existing.zip myFolder
This command will compress and add myFolder
(and it's contents) to the existing.zip
.
Advanced Usage:
The update flag actually compares the incoming files against the existing ones and will either add new files, or update existing ones.
Therefore, if you want to add/update a specific subdirectory within the zip file, just update the source as desired, and then re-zip the entire source with the -u
flag. Only the changed files will be zipped.
If you don't have access to the source files, you can unzip the zip file, then update the desired files, and then re-zip with the -u
flag. Again, only the changed files will be zipped.
Example:
Original Source Structure
ParentDir
+-- file1.txt
+-- file2.txt
+-- ChildDir
¦ +-- file3.txt
¦ +-- Logs
¦ ¦ +-- logs1.txt
¦ ¦ +-- logs2.txt
¦ ¦ +-- logs3.txt
Updated Source Structure
ParentDir
+-- file1.txt
+-- file2.txt
+-- ChildDir
¦ +-- file3.txt
¦ +-- Logs
¦ ¦ +-- logs1.txt
¦ ¦ +-- logs2.txt
¦ ¦ +-- logs3.txt
¦ ¦ +-- logs4.txt <-- NEW FILE
Usage
$ zip -ur existing.zip ParentDir
> updating: ParentDir/ChildDir/Logs (stored 0%)
> adding: ParentDir/ChildDir/Logs/logs4.txt (stored 96%)
If you are using hibernate with JPA annotations then this will be useful. In your service class there should be a setter for entity manager with @PersistenceContext. change this to @PersistenceContext(type = PersistenceContextType.EXTENDED). Then you can access lazy property in any where.
Aren't you performing the operations in the wrong order? You requirement seems to be foo[:-3].replace(" ", "").upper()
Why not use padStart
?
var dt = new Date();
year = dt.getFullYear();
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day = dt.getDate().toString().padStart(2, "0");
console.log(year + '/' + month + '/' + day);
_x000D_
This will always return 2 digit numbers even if the month or day is less than 10.
Notes:
getFullYear()
returns the 4 digit year and doesn't require padStart
.getMonth()
returns the month from 0 to 11.
getDate()
returns the day from 1 to 31.
07
and so we do not need to add 1 before padding the string.Not able to understand your actual problem but your case statement is incorrect
CASE
WHEN
TABLE3.COL3 IS NULL
THEN TABLE2.COL3
ELSE
TABLE3.COL3
END
AS
COL4
you can use the collector like this
Stream<String> io = Stream.of("foo" , "lan" , "mql");
io.collect(Collectors.toCollection(ArrayList<String>::new));
Add the following line on the top of your file
require 'json'
Then you can use:
car = {:make => "bmw", :year => "2003"}
car.to_json
Alternatively, you can use:
JSON.generate({:make => "bmw", :year => "2003"})
The behaviour is not really that strange. Looking into the implementation of the classes, it is caused by:
Charset.defaultCharset()
is not caching the determined character set in Java 5.Charset.defaultCharset()
again causes a second evaluation of the system property, no character set with the name "Latin-1" is found, so Charset.defaultCharset()
defaults to "UTF-8".OutputStreamWriter
is however caching the default character set and is probably used already during VM initialization, so that its default character set diverts from Charset.defaultCharset()
if the system property "file.encoding" has been changed at runtime.As already pointed out, it is not documented how the VM must behave in such a situation. The Charset.defaultCharset()
API documentation is not very precise on how the default character set is determined, only mentioning that it is usually done on VM startup, based on factors like the OS default character set or default locale.
Surely using array_map
and if using a container implementing ArrayAccess
to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN()
clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait
cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr
you could always $arr = array_map
and be explicit.
If you have jQuery enabled you can use an escapeXml function and not have to worry about escaping arrows or special characters.
<pre>
${fn:escapeXml('
<!-- all your code -->
')};
</pre>
In your handler, check the window.event
object for the property ctrlKey
as such:
function selectMe(){
if (window.event.ctrlKey) {
//ctrl was held down during the click
}
}
UPDATE: the above solution depends on a proprietary property on the window object, which perhaps should not be counted on to exist in all browsers. Luckily, we now have a working draft that takes care of our needs, and according to MDN, it is widely supported. Example:
HTML
<span onclick="handler(event)">Click me</span>
JS
function handler(ev) {
console.log('CTRL pressed during click:', ev.ctrlKey);
}
The same applies for keyboard events
See also KeyboardEvent.getModifierState()
You can as well use $.when()
to wait until the promise
finished:
var myEvent = function() {
$( selector ).fadeOut( 'fast' );
};
$.when( myEvent() ).done( function() {
console.log( 'Task finished.' );
} );
In case you're doing a request that could as well fail, then you can even go one step further:
$.when( myEvent() )
.done( function( d ) {
console.log( d, 'Task done.' );
} )
.fail( function( err ) {
console.log( err, 'Task failed.' );
} )
// Runs always
.then( function( data, textStatus, jqXHR ) {
console.log( jqXHR.status, textStatus, 'Status 200/"OK"?' );
} );
There is a little "hack" on CSS that also allows you to disable scrolling:
.lock-screen {
height: 100%;
overflow: hidden;
width: 100%;
position: fixed;
}
Adding that class to the body will prevent scrolling.
DECLARE @v XML = (SELECT * FROM <tablename> FOR XML AUTO)
Insert the above statement at the point where you want to view the table's contents. The table's contents will be rendered as XML in the locals window, or you can add @v
to the watches window.
Here are tests for a few methods:
%timeit np.where(np.isnan(df['b']))[0]
%timeit pd.isnull(df['b']).nonzero()[0]
%timeit np.where(df['b'].isna())[0]
%timeit df.loc[pd.isna(df['b']), :].index
And their corresponding timings:
333 µs ± 9.95 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
280 µs ± 220 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
313 µs ± 128 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
6.84 ms ± 1.59 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
It would appear that pd.isnull(df['DRGWeight']).nonzero()[0]
wins the day in terms of timing, but that any of the top three methods have comparable performance.
No need to use grep. ps
in Android can filter by COMM
value (last 15 characters of the package name in case of java app)
Let's say we want to check if com.android.phone
is running:
adb shell ps m.android.phone
USER PID PPID VSIZE RSS WCHAN PC NAME
radio 1389 277 515960 33964 ffffffff 4024c270 S com.android.phone
Filtering by COMM
value option has been removed from ps
in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof
command:
adb shell pidof com.android.phone
It returns the PID if such process was found or an empty string otherwise.
Cross browser compatible JS solution:
var e = document.getElementById('elem');_x000D_
var spin = false;_x000D_
_x000D_
var spinner = function(){_x000D_
e.classList.toggle('running', spin);_x000D_
if (spin) setTimeout(spinner, 2000);_x000D_
}_x000D_
_x000D_
e.onmouseover = function(){_x000D_
spin = true;_x000D_
spinner();_x000D_
};_x000D_
_x000D_
e.onmouseout = function(){_x000D_
spin = false;_x000D_
};
_x000D_
body { _x000D_
height:300px; _x000D_
}_x000D_
#elem {_x000D_
position:absolute;_x000D_
top:20%;_x000D_
left:20%;_x000D_
width:0; _x000D_
height:0;_x000D_
border-style: solid;_x000D_
border-width: 75px;_x000D_
border-color: red blue green orange;_x000D_
border-radius: 75px;_x000D_
}_x000D_
_x000D_
#elem.running {_x000D_
animation: spin 2s linear 0s infinite;_x000D_
}_x000D_
_x000D_
@keyframes spin { _x000D_
100% { transform: rotate(360deg); } _x000D_
}
_x000D_
<div id="elem"></div>
_x000D_
Sorry, I didn't notice the PHP tag - however someone else might be interested in a VB solution:
Module Module1
Sub Main()
Dim d As Date = Now
Dim nextFriday As Date = DateAdd(DateInterval.Weekday, DayOfWeek.Friday - d.DayOfWeek(), Now)
Console.WriteLine("next friday is " & nextFriday)
Console.ReadLine()
End Sub
End Module
You're looking for the File
, StreamWriter
, and StreamReader
classes.
Try downgrading your java version, this will happen when your systems java version isn't compatible with the one from android. Once you changed you the java version just run flutter doctor
it will automatically accepts the licenses.
The date is parsed correctly, it's just toString that converts it to your local timezone:
let s = "2005-07-08T11:22:33+0000";_x000D_
let d = new Date(Date.parse(s));_x000D_
_x000D_
// this logs for me _x000D_
// "Fri Jul 08 2005 13:22:33 GMT+0200 (Central European Summer Time)" _x000D_
// and something else for you_x000D_
_x000D_
console.log(d.toString()) _x000D_
_x000D_
// this logs_x000D_
// Fri, 08 Jul 2005 11:22:33 GMT_x000D_
// for everyone_x000D_
_x000D_
console.log(d.toUTCString())
_x000D_
Javascript Date object are timestamps - they merely contain a number of milliseconds since the epoch. There is no timezone info in a Date object. Which calendar date (day, minutes, seconds) this timestamp represents is a matter of the interpretation (one of to...String
methods).
The above example shows that the date is being parsed correctly - that is, it actually contains an amount of milliseconds corresponding to "2005-07-08T11:22:33" in GMT.
If you posting form using ajax then you can not send image using $.ajax method, you have to use classic xmlHttpobject method for saving image, other alternative of it use submit type instead of button
So if the insert time is what you need, it's already there:
Login to mongodb shell
ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test
Create your database by inserting items
> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
>
Lets make that database the one we are on now
> use penguins
switched to db penguins
Get the rows back:
> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }
Get each row in yyyy-MM-dd HH:mm:ss format:
> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53
If that last one-liner confuses you I have a walkthrough on how that works here: https://stackoverflow.com/a/27613766/445131
Deleting .gradle
as suggested by Suragch wasn't enough for me. Additionally, I had to perform a Build > Clean Project
.
Note that, in order to see .gradle
, you need to switch to the "Project" view in the navigator on the top left:
Wrap the modal into a connected container and perform the async operation in here. This way you can reach both the dispatch to trigger actions and the onClose prop too. To reach dispatch
from props, do not pass mapDispatchToProps
function to connect
.
class ModalContainer extends React.Component {
handleDelete = () => {
const { dispatch, onClose } = this.props;
dispatch({type: 'DELETE_POST'});
someAsyncOperation().then(() => {
dispatch({type: 'DELETE_POST_SUCCESS'});
onClose();
})
}
render() {
const { onClose } = this.props;
return <Modal onClose={onClose} onSubmit={this.handleDelete} />
}
}
export default connect(/* no map dispatch to props here! */)(ModalContainer);
The App where the modal is rendered and its visibility state is set:
class App extends React.Component {
state = {
isModalOpen: false
}
handleModalClose = () => this.setState({ isModalOpen: false });
...
render(){
return (
...
<ModalContainer onClose={this.handleModalClose} />
...
)
}
}
DECLARE @TableName varchar(max)=NULL
SELECT @TableName=COALESCE(@TableName+',','')+t.TABLE_CATALOG+'.'+ t.TABLE_SCHEMA+'.'+o.Name
FROM sysindexes AS i
INNER JOIN sysobjects AS o ON i.id = o.id
INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME=o.name
WHERE i.indid < 2
AND OBJECTPROPERTY(o.id,'IsMSShipped') = 0
AND i.rowcnt >350
AND o.xtype !='TF'
ORDER BY o.name ASC
print @tablename
You can get list of tables which has rowcounts >350 . You can see at the solution list of table as row.
If you want to make multiple operation use
select (sel1.s1+sel2+s2)
(select sum(hours) s1 from resource) sel1
join
(select sum(hours) s2 from projects-time)sel2
on sel1.s1=sel2.s2
Firt add a reference to System.web
, if you don't have. Do that in the References folder.
You can then use Hosting.HostingEnvironment.MapPath(path);
SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;
DAY
---------
TUESDAY
SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;
DAY
---
TUE
SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;
DAY
---
Tue
(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)
Or maybe and that is prob it
<img src="path" onclick="this.src='path'">
_x000D_
As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.
datetime
is a module which contains a type that is also called datetime
. You appear to want to use both, but you're trying to use the same name to refer to both. The type and the module are two different things and you can't refer to both of them with the name datetime
in your program.
If you need to use anything from the module besides the datetime
type (as you apparently do), then you need to import the module with import datetime
. You can then refer to the "date" type as datetime.date
and the datetime type as datetime.datetime
.
You could also do this:
from datetime import datetime, date
today_date = date.today()
date_time = datetime.strp(date_time_string, '%Y-%m-%d %H:%M')
Here you import only the names you need (the datetime and date types) and import them directly so you don't need to refer to the module itself at all.
Ultimately you have to decide what names from the module you need to use, and how best to use them. If you are only using one or two things from the module (e.g., just the date
and datetime
types), it may be okay to import those names directly. If you're using many things, it's probably better to import the module and access the things inside it using dot syntax, to avoid cluttering your global namespace with date-specific names.
Note also that, if you do import the module name itself, you can shorten the name to ease typing:
import datetime as dt
today_date = dt.date.today()
date_time = dt.datetime.strp(date_time_string, '%Y-%m-%d %H:%M')
Visual Studio 2008: (3,30 GB) http://download.microsoft.com/download/8/1/d/81d3f35e-fa03-485b-953b-ff952e402520/VS2008ProEdition90dayTrialENUX1435622.iso
To upgrade from trial version to Pro version, check: http://msdn.microsoft.com/en-us/library/ms246600%28VS.80%29.aspx
I have been suffering of this issue for very long time. I was unable to open websites like GitHub. I almost tried all the answer on web and not anyone worked. Tried to reinstall chrome also. I found the solution for this from our network guy and it worked. There is a fix in registry which will resolve this error for permanent basis.
The solution above is for Windows 8. It is almost identical in later versions but i’m not sure for earlier versions like XP and vista. So that needs to be checked.
TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.
http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
Since Laravel 5.2 you can use File Responses
Basically you can call it like this:
return response()->file($pathToFile);
and it will display files as PDF and images inline in the browser.
I used the content+wrapper
approach ... but I did something different than mentioned so far: I made sure that my wrapper's boundaries did NOT line up with the content's boundaries in the direction that I wanted to be visible.
Important NOTE: It was easy enough to get the content+wrapper, same-bounds
approach to work on one browser or another depending on various css combinations of position
, overflow-*
, etc ... but I never could use that approach to get them all correct (Edge, Chrome, Safari, ...).
But when I had something like:
<div id="hack_wrapper" // created solely for this purpose
style="position:absolute; width:100%; height:100%; overflow-x:hidden;">
<div id="content_wrapper"
style="position:absolute; width:100%; height:15%; overflow:visible;">
... content with too-much horizontal content ...
</div>
</div>
... all browsers were happy.
Compile the program with:
g++ -Wall -Wextra -Werror -c main.cpp -o main.o
^^^^^^^^^^^^^^^^^^^^ <- For listing all warnings when your code is compiled.
as cout
is present in the C++ standard library, which would need explicit linking with -lstdc++
when using gcc
; g++
links the standard library by default.
With gcc
, (g++
should be preferred over gcc
)
gcc main.cpp -lstdc++ -o main.o
In my understanding runtime is exactly what it means - the time when the program is run. You can say something happens at runtime / run time or at compile time.
I think runtime and runtime library should be (if they aren't) two separate things. "C runtime" doesn't seem right to me. I call it "C runtime library".
Answers to your other questions: I think the term runtime can be extended to include also the environment and the context of the program when it is run, so:
This answer is to some extend just my opinion, not a fact or definition.
I recently spent a week studying lot of solutions to validate my forms in an app. I started with all the most stared one but I couldn't find one who was working as I was expected. After few days, I became quite frustrated until i found a very new and amazing plugin: https://github.com/kettanaito/react-advanced-form
The developper is very responsive and his solution, after my research, merit to become the most stared one from my perspective. I hope it could help and you'll appreciate.
This is piggy backing off of other answers. It's just a thought I had for managing the query strings.
Person.cs
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public static string Select()
{
return $"select top 1 person_id {nameof(PersonId)}, first_name {nameof(FirstName)}, last_name {nameof(LastName)}from Person";
}
}
API Method
using (var conn = ConnectionFactory.GetConnection())
{
var person = conn.Query<Person>(Person.Select()).ToList();
return person;
}
I faced the same problem due to illegal spaces in my entire code.
I fixed it by selecting one of these spaces and use find and replace
to replace all matches with regular spaces.
You can optionally actually use the get
method of a dict
:
x = {i<100: -1, -10<=i<=10: 0, i>100: 1}.get(True, 2)
You don't need the get
method if one of the keys is guaranteed to evaluate to True
:
x = {i<0: -1, i==0: 0, i>0: 1}[True]
At most one of the keys should ideally evaluate to True
. If more than one key evaluates to True
, the results could seem unpredictable.
Dispose() calls the code below, which closes the connections opened by the HttpClient instance. The code was created by decompiling with dotPeek.
HttpClientHandler.cs - Dispose
ServicePointManager.CloseConnectionGroups(this.connectionGroupName);
If you don't call dispose then ServicePointManager.MaxServicePointIdleTime, which runs by a timer, will close the http connections. The default is 100 seconds.
ServicePointManager.cs
internal static readonly TimerThread.Callback s_IdleServicePointTimeoutDelegate = new TimerThread.Callback(ServicePointManager.IdleServicePointTimeoutCallback);
private static volatile TimerThread.Queue s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(100000);
private static void IdleServicePointTimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
ServicePoint servicePoint = (ServicePoint) context;
if (Logging.On)
Logging.PrintInfo(Logging.Web, SR.GetString("net_log_closed_idle", (object) "ServicePoint", (object) servicePoint.GetHashCode()));
lock (ServicePointManager.s_ServicePointTable)
ServicePointManager.s_ServicePointTable.Remove((object) servicePoint.LookupString);
servicePoint.ReleaseAllConnectionGroups();
}
If you haven't set the idle time to infinite then it appears safe not to call dispose and let the idle connection timer kick-in and close the connections for you, although it would be better for you to call dispose in a using statement if you know you are done with an HttpClient instance and free up the resources faster.
div will not expand if it has other floating divs inside, so remove the float from the internal divs and it will expand.
Add the "code" folder to the project properties within Visual Studio
Project->Properties->Configuration Properties->C/C++->Additional Include Directories
For a string such as #box2
, this should work:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle:
As mentioned in a comment above, you can have expressions within the template strings/literals. Example:
const one = 1;_x000D_
const two = 2;_x000D_
const result = `One add two is ${one + two}`;_x000D_
console.log(result); // output: One add two is 3
_x000D_
You can also set background is transparent. So the button looks like fit your icon.
<ImageButton
android:id="@+id/Button01"
android:scaleType="fitcenter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cropToPadding="false"
android:paddingLeft="10dp"
android:background="@android:color/transparent"
android:src="@drawable/eye" />
This is old thread, so I figured for anyone looking for a modern answer, I would suggest using Object.keys();
var myDiv = document.getElementById("myDiv");
var css = {
"font-size": "14px",
"color": "#447",
"font-family": "Arial",
"text-decoration": "underline"
};
function applyInlineStyles(obj) {
var result = "";
Object.keys(obj).forEach(function (prop) {
result += prop + ": " + obj[prop] + "; ";
});
return result;
}
myDiv.style = applyInlineStyles(css);