You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
del df
will not be deleted if there are any reference to the df
at the time of deletion. So you need to to delete all the references to it with del df
to release the memory.
So all the instances bound to df should be deleted to trigger garbage collection.
Use objgragh to check which is holding onto the objects.
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
Above wait statement is a nice example of Explicit wait.
As Explicit waits are intelligent waits that are confined to a particular web element(as mentioned in above x-path).
By Using explicit waits you are basically telling WebDriver at the max it is to wait for X units(whatever you have given as timeoutInSeconds) of time before it gives up.
return results==null ? 0 : ( results[1] || 0 );
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
You have so many choices, how could you be confused :-)? The main controls are:
# \pset format
# \H
# \x
# \pset pager off
Each has options and interactions with the others. The most automatic options are:
# \x off;\pset format wrapped
# \x auto
The newer "\x auto" option switches to line-by-line display only "if needed".
-[ RECORD 1 ]---------------
id | 6
description | This is a gallery of oilve oil brands.
authority | I love olive oil, and wanted to create a place for
reviews and comments on various types.
-[ RECORD 2 ]---------------
id | 19
description | XXX Test A
authority | Testing
The older "\pset format wrapped" is similar in that it tries to fit the data neatly on screen, but falls back to unaligned if the headers won't fit. Here's an example of wrapped:
id | description | authority
----+--------------------------------+---------------------------------
6 | This is a gallery of oilve | I love olive oil, and wanted to
; oil brands. ; create a place for reviews and
; ; comments on various types.
19 | Test Test A | Testing
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
weightSelected = [pickerArray objectAtIndex:row];
}
from subprocess import Popen
Popen('python filename.py')
After insuring that the string "strOutput" has a correct XML structure, you can do this:
Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");
$a = array(1, '', '', '', 2, '', 3, 4);
$b = array_values(array_filter($a));
print_r($b)
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
Another important module that needs reconfiguring before PUT and DELETE will work is the options verb
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="OPTIONSVerbHandler" />
<remove name="WebDAV" />
<add name="OPTIONSVerbHandler" path="*" verb="*" modules="ProtocolSupportModule" resourceType="Unspecified" requireAccess="Script" />
</handlers>
Also see this post: https://stackoverflow.com/a/22018750/9376681
Just tell the file
-input to automatically submit the form on any change:
<form action="http://example.com">_x000D_
<input type="file" onchange="form.submit()" />_x000D_
</form>
_x000D_
This solution works like this:
onchange
makes the input element execute the following script, whenever the value
is modifiedform
references the form, that this input element is part ofsubmit()
causes the form to send all data to the URL, as specified in action
Advantages of this solution:
id
s. It makes life easier, if you have several forms in one html page.In this particular example, it makes no difference. However, the {}
in ${}
are useful if you want to expand the variable foo
in the string
"${foo}bar"
since "$foobar"
would instead expand the variable identified by foobar
.
Curly braces are also unconditionally required when:
${array[42]}
${filename%.*}
(remove extension)"$8 $9 ${10} ${11}"
Doing this everywhere, instead of just in potentially ambiguous cases, can be considered good programming practice. This is both for consistency and to avoid surprises like $foo_$bar.jpg
, where it's not visually obvious that the underscore becomes part of the variable name.
The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).
List implementations:
get add contains next remove(0) iterator.remove
ArrayList O(1) O(1) O(n) O(1) O(n) O(n)
LinkedList O(n) O(1) O(n) O(1) O(1) O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n) O(1) O(n) O(n)
Set implementations:
add contains next notes
HashSet O(1) O(1) O(h/n) h is the table capacity
LinkedHashSet O(1) O(1) O(1)
CopyOnWriteArraySet O(n) O(n) O(1)
EnumSet O(1) O(1) O(1)
TreeSet O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)
Map implementations:
get containsKey next Notes
HashMap O(1) O(1) O(h/n) h is the table capacity
LinkedHashMap O(1) O(1) O(1)
IdentityHashMap O(1) O(1) O(h/n) h is the table capacity
EnumMap O(1) O(1) O(1)
TreeMap O(log n) O(log n) O(log n)
ConcurrentHashMap O(1) O(1) O(h/n) h is the table capacity
ConcurrentSkipListMap O(log n) O(log n) O(1)
Queue implementations:
offer peek poll size
PriorityQueue O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1) O(1) O(1) O(n)
ArrayBlockingQueue O(1) O(1) O(1) O(1)
LinkedBlockingQueue O(1) O(1) O(1) O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue O(log n) O(1) O(log n) O(1)
LinkedList O(1) O(1) O(1) O(1)
ArrayDeque O(1) O(1) O(1) O(1)
LinkedBlockingDeque O(1) O(1) O(1) O(1)
The bottom of the javadoc for the java.util package contains some good links:
I wrote the following function in order to determine if an multidimensional array partially contains a certain value.
function findKeyValue ($array, $needle, $value, $found = false){
foreach ($array as $key => $item){
// Navigate through the array completely.
if (is_array($item)){
$found = $this->findKeyValue($item, $needle, $value, $found);
}
// If the item is a node, verify if the value of the node contains
// the given search parameter. E.G.: 'value' <=> 'This contains the value'
if ( ! empty($key) && $key == $needle && strpos($item, $value) !== false){
return true;
}
}
return $found;
}
Call the function like this:
$this->findKeyValue($array, $key, $value);
Here are three Observables A
, B
, and C
with marble diagrams to explore the difference between first
, take
, and single
operators:
* Legend:
--o--
value
----!
error
----|
completion
Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .
Already having all the answers, I wanted to add a more visual explanation
Hope it helps someone
I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:
dig @ns1.nameserver1.com domain.com txt
Note: Answer has been updated to cover the scenario where background
is an instance of ColorDrawable
. Thanks Tyler Pfaff, for pointing this out.
The drawable is an oval and is the background of an ImageView
Get the Drawable
from imageView
using getBackground()
:
Drawable background = imageView.getBackground();
Check against usual suspects:
if (background instanceof ShapeDrawable) {
// cast to 'ShapeDrawable'
ShapeDrawable shapeDrawable = (ShapeDrawable) background;
shapeDrawable.getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
// cast to 'GradientDrawable'
GradientDrawable gradientDrawable = (GradientDrawable) background;
gradientDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
// alpha value may need to be set again after this call
ColorDrawable colorDrawable = (ColorDrawable) background;
colorDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}
Compact version:
Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
((ShapeDrawable)background).getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
((GradientDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
((ColorDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}
Note that null-checking is not required.
However, you should use mutate()
on the drawables before modifying them if they are used elsewhere. (By default, drawables loaded from XML share the same state.)
I achieved it using some extension methods
private const string endFieldPattern = "^(.*?)>";
public static MvcHtmlString IsDisabled(this MvcHtmlString htmlString, bool disabled)
{
string rawString = htmlString.ToString();
if (disabled)
{
rawString = Regex.Replace(rawString, endFieldPattern, "$1 disabled=\"disabled\">");
}
return new MvcHtmlString(rawString);
}
public static MvcHtmlString IsReadonly(this MvcHtmlString htmlString, bool @readonly)
{
string rawString = htmlString.ToString();
if (@readonly)
{
rawString = Regex.Replace(rawString, endFieldPattern, "$1 readonly=\"readonly\">");
}
return new MvcHtmlString(rawString);
}
and then....
@Html.TextBoxFor(model => model.Name, new { @class= "someclass"}).IsDisabled(Model.ExpireDate == null)
You can do:
foo.instance_of?(String)
And the more general:
foo.kind_of?(String)
If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.
EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character
To get the number of matching rows in SQL you would usually use COUNT(*)
. For example:
SELECT COUNT(*) FROM some_table
To get that in value in PHP you need to fetch the value from the first column in the first row of the returned result. An example using PDO and mysqli is demonstrated below.
However, if you want to fetch the results and then still know how many records you fetched using PHP, you could use count()
or avail of the pre-populated count in the result object if your DB API offers it e.g. mysqli's num_rows
.
Using mysqli you can fetch the first row using fetch_row()
and then access the 0
column, which should contain the value of COUNT(*)
.
// your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'dbuser', 'yourdbpassword', 'db_name');
$mysqli->set_charset('utf8mb4');
// your SQL statement
$stmt = $mysqli->prepare('SELECT COUNT(*) FROM some_table WHERE col1=?');
$stmt->bind_param('s', $someVariable);
$stmt->execute();
$result = $stmt->get_result();
// now fetch 1st column of the 1st row
$count = $result->fetch_row()[0];
echo $count;
If you want to fetch all the rows, but still know the number of rows then you can use num_rows
or count()
.
// your SQL statement
$stmt = $mysqli->prepare('SELECT col1, col2 FROM some_table WHERE col1=?');
$stmt->bind_param('s', $someVariable);
$stmt->execute();
$result = $stmt->get_result();
// If you want to use the results, but still know how many records were fetched
$rows = $result->fetch_all(MYSQLI_ASSOC);
echo $result->num_rows;
// or
echo count($rows);
Using PDO is much simpler. You can directly call fetchColumn()
on the statement to get a single column value.
// your connection code
$pdo = new \PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '', [
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
]);
// your SQL statement
$stmt = $pdo->prepare('SELECT COUNT(*) FROM some_table WHERE col1=?');
$stmt->execute([
$someVariable
]);
// Fetch the first column of the first row
$count = $stmt->fetchColumn();
echo $count;
Again, if you need to fetch all the rows anyway, then you can get it using count()
function.
// your SQL statement
$stmt = $pdo->prepare('SELECT col1, col2 FROM some_table WHERE col1=?');
$stmt->execute([
$someVariable
]);
// If you want to use the results, but still know how many records were fetched
$rows = $stmt->fetchAll();
echo count($rows);
PDO's statement doesn't offer pre-computed property with the number of rows fetched, but it has a method called rowCount()
. This method can tell you the number of rows returned in the result, but it cannot be relied upon and it is generally not recommended to use.
$('div#imageContainer').click(function () {
$('div#imageContainerimg').attr('src', 'YOUR NEW IMAGE URL HERE');
});
The following regex pattern should work with most emails, including russian emails.
[^@]+@[^\.]+\..+
As an alternative to Activator.CreateInstance, FastObjectFactory in the linked url preforms better than Activator (as of .NET 4.0 and significantly better than .NET 3.5. No tests/stats done with .NET 4.5). See StackOverflow post for stats, info and code:
How to pass ctor args in Activator.CreateInstance or use IL?
Try using join on a str conversion of your ints:
print(' '.join(str(x) for x in array))
For python 3.7
Since you're transferring data in xml, you could also (un)marshal directly from/to pojos.
There's an example (and more info) in the jersey user guide, which I copy here:
POJO with JAXB annotations:
@XmlRootElement
public class Planet {
public int id;
public String name;
public double radius;
}
Resource:
@Path("planet")
public class Resource {
@GET
@Produces(MediaType.APPLICATION_XML)
public Planet getPlanet() {
Planet p = new Planet();
p.id = 1;
p.name = "Earth";
p.radius = 1.0;
return p;
}
@POST
@Consumes(MediaType.APPLICATION_XML)
public void setPlanet(Planet p) {
System.out.println("setPlanet " + p.name);
}
}
The xml that gets produced/consumed:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<planet>
<id>1</id>
<name>Earth</name>
<radius>1.0</radius>
</planet>
open
also has an -a flag, that you can use to open up an app from within the Applications folder by it's name (or by bundle identifier with -b flag). You can combine this with the --args option to achieve the result you want:
open -a APP_NAME --args ARGS
To open up a video in VLC player that should scale with a factor 2x and loop you would for example exectute:
open -a VLC --args -L --fullscreen
Note that I could not get the output of the commands to the terminal. (although I didn't try anything to resolve that)
See this table.
A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.
A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.
As mentioned in this tutorial, it's as simple as:
To install
brew install gradle
To upgrade
brew upgrade gradle
(using Homebrew of course)
Also see (finally) updated docs.
Cheers :)!
bash has a builtin
pushd SOME_PATH
run_stuff
...
...
popd
You can also take a look at RoboVM.
It translates Java byte-code into native ARM or x86 code which can run directly on the processor without any VM or interpreter needed. Most of the Obj-C UI elements are already bridged into Java and follows the usual Java design patterns.
Edit Robo VM recently announced that it would be shutting down the service - Source
Ctrl+ H, Select "File Search", indicate the "file name pattern", for example *.xml or *.java. And then select the scope "Workspace"
In case of Windows applications, the error is solved changing the running project properties.
This configuration is not saved to [CurrentProject].csproj (or [CurrentProject].vbproj). It is saved to: [CurrentProject].csproj.user (or [CurrentProject].vbproj.user)
If you use a code repository, usually this file is not saved undo version control.
I don't see what the problem with the timeit
module is. This is probably the simplest way to do it.
import timeit
timeit.timeit(a, number=1)
Its also possible to send arguments to the functions. All you need is to wrap your function up using decorators. More explanation here: http://www.pythoncentral.io/time-a-python-function/
The only case where you might be interested in writing your own timing statements is if you want to run a function only once and are also want to obtain its return value.
The advantage of using the timeit
module is that it lets you repeat the number of executions. This might be necessary because other processes might interfere with your timing accuracy. So, you should run it multiple times and look at the lowest value.
Actually, it is possible. You can check if the clicked position was outside of the element, since this will only happen if ::before
or ::after
was clicked.
This example only checks the element to the right but that should work in your case.
span = document.querySelector('span');_x000D_
_x000D_
span.addEventListener('click', function (e) {_x000D_
if (e.offsetX > span.offsetWidth) {_x000D_
span.className = 'c2';_x000D_
} else {_x000D_
span.className = 'c1';_x000D_
}_x000D_
});
_x000D_
div { margin: 20px; }_x000D_
span:after { content: 'AFTER'; position: absolute; }_x000D_
_x000D_
span.c1 { background: yellow; }_x000D_
span.c2:after { background: yellow; }
_x000D_
<div><span>ELEMENT</span></div>
_x000D_
I will post my answer here since it's the first result in google's search
1) react-native unlink <Module Name>
2) npm unlink <Module Name>
3) npm uninstall --save <Module name
You can use the "Join" function to create a single string out of the array of labels, like this:
=Join(Parameters!Product.Label, ",")
In a multi-project solution, you usually want to have one configuration that generates no PDB or XML files at all. Instead of changing the Debug Info
property of every project to none
, I thought it would be more expedient to add a post-build event that only works in a specific configuration.
Unfortunately, Visual Studio doesn't allow you to specify different post-build events for different configurations. So I decided to do this manually, by editing the csproj
file of the startup project and adding the following (instead of any existing PostBuildEvent
tag):
<PropertyGroup Condition="'$(Configuration)' == 'Publish'">
<PostBuildEvent>
del *.pdb
del *.xml
</PostBuildEvent>
</PropertyGroup>
Unfortunately, this will make the post build event textbox blank and putting anything in it can have unpredictable results.
node.innerHTML = "";
Non-standard, but fast and well supported.
For hibernate5 I solved this issue by puting next lines in my application.properties file:
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
You can use tf.convert_to_tensor()
:
import tensorflow as tf
import numpy as np
data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)
data_tf = tf.convert_to_tensor(data_np, np.float32)
sess = tf.InteractiveSession()
print(data_tf.eval())
sess.close()
Here's a link to the documentation for this method:
https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor
fn + shift + leftArrow = goto beginning of line
fn + shift + rightArrow = goto end of line
these work for me
You can fix your example with the iterator pattern by changing the parametrization of the class:
List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Iterator<Room> i = rooms.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
or much simpler way:
List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Room room : rooms) {
System.out.println(room);
}
You have 2 options:
brew update
to update homebrew packages
brew install jmeter
to install jmeter
Read this blog to know how to map folders from standard jmeter to homebrew installed version.
Install using standard version which I would advise you to do. Steps are:
bin/jmeter
100% - discounted price / full price
this did it for me. you can vary the options for the output format to Base64.Default whatsoever.
// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);
You may do:
a= [1,1,1,2,2,3]
delete_list = [1,3]
delete_list.each do |del|
a.delete_at(a.index(del))
end
result : [1, 1, 2, 2]
Sounds like it might be a realative uri. I ran into this problem when doing cross-browser Silverlight; on my blog I mentioned a workaround: pass a "context" uri as the first parameter.
If the uri is realtive, the context uri is used to create a full uri. If the uri is absolute, then the context uri is ignored.
EDIT: You need a "scheme" in the uri, e.g., "ftp://" or "http://"
UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Tutorial" bundle:nil];
self.window.rootViewController = [storyboard instantiateInitialViewController];
Another much simpler possibility is that one of your property names is wrong (probably one you just changed in the class). This is what it was for me in RazorPages .NET Core 3.
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild
using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
okay got it , you have to use ngAfterViewInit
method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit
will not throw any error because it will render after template loading
Your regex seems a bit too complex in my opinion. Also, remember that the dot is a special character meaning "any character". The following regex should work (note the escaped dots):
^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$
You can use a tool like Expresso to test your regular expressions.
You can use stream
and flatMap
to map &
to &
String str = "begin&end";
String newString = str.chars()
.flatMap(ch -> (ch == '&') ? "&".chars() : IntStream.of(ch))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
We just had a similar issue, looks like the user reset his password on Friday and over the weekend and on Monday he kept getting locked out.
Turned out to be he forgot to update his password on his mobile phone.
to build on what Martin Kuzdowicz posted above. I use the following to do an update using mongoose and a deep merge of json objects. Along with the model.save() function in mongoose this allows mongoose to do a full validation even one that relies on other values in the json. it does require the deepmerge package https://www.npmjs.com/package/deepmerge. But that is a very light weight package.
var merge = require('deepmerge');
app.put('url', (req, res) => {
const modelId = req.body.model_id;
MyModel.findById(modelId).then((model) => {
return Object.assign(model, merge(model.toObject(), req.body));
}).then((model) => {
return model.save();
}).then((updatedModel) => {
res.json({
msg: 'model updated',
updatedModel
});
}).catch((err) => {
res.send(err);
});
});
Use this form:
=(B0+4)/$A$0
The $
tells excel not to adjust that address while pasting the formula into new cells.
Since you are dragging across rows, you really only need to freeze the row part:
=(B0+4)/A$0
Commenters helpfully pointed out that you can toggle relative addressing for a formula in the currently selected cells with these keyboard shortcuts:
ALTER TABLE xxx
AUTO_INCREMENT =1;
or
clear your table by TRUNCATE
At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:
let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent
Also not directly relevant to the OP, but failing to restart a PyCharm Python console, after adding a new object to a module, is also a great way to get a very confusing ImportError: Cannot import name ...
The confusing part is that PyCharm will autocomplete the import in the console, but the import then fails.
You only need to worry about using physically contiguous memory if the buffer will be accessed by a DMA device on a physically addressed bus (like PCI). The trouble is that many system calls have no way to know whether their buffer will eventually be passed to a DMA device: once you pass the buffer to another kernel subsystem, you really cannot know where it is going to go. Even if the kernel does not use the buffer for DMA today, a future development might do so.
vmalloc is often slower than kmalloc, because it may have to remap the buffer space into a virtually contiguous range. kmalloc never remaps, though if not called with GFP_ATOMIC kmalloc can block.
kmalloc is limited in the size of buffer it can provide: 128 KBytes*). If you need a really big buffer, you have to use vmalloc or some other mechanism like reserving high memory at boot.
*) This was true of earlier kernels. On recent kernels (I tested this on 2.6.33.2), max size of a single kmalloc is up to 4 MB! (I wrote a fairly detailed post on this.) — kaiwan
For a system call you don't need to pass GFP_ATOMIC to kmalloc(), you can use GFP_KERNEL. You're not an interrupt handler: the application code enters the kernel context by means of a trap, it is not an interrupt.
(?!Andrea)
This is not exactly an inverted match, but it's the best you can directly do with regex. Not all platforms support them though.
You can list the tags on remote repository with ls-remote
, and then check if it's there. Supposing the remote reference name is origin
in the following.
git ls-remote --tags origin
And you can list tags local with tag
.
git tag
You can compare the results manually or in script.
You will need to Build and Archive your project. You may need to check what code signing settings you have in the project and executable.
Use the Organiser to select your archive version and then you can Share that version of your project. You will need to select the correct code signing again. It will allow you to save the .ipa file where you want.
Drag and drop the .ipa file into iTunes and then sync with your iPhone.
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src','http://example.com/site.js');
document.head.appendChild(my_awesome_script);
Interfaces specify behavior of an object.
Static methods do not specify a behavior of an object, but behavior that affects an object in some way.
Thanks Box. I'm using MyStile Theme and I needed to display the product category name in my search result page. I added this function to my child theme functions.php
Hope it helps others.
/* Post Meta */
if (!function_exists( 'woo_post_meta')) {
function woo_post_meta( ) {
global $woo_options;
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat = $term->name;
break;
}
?>
<aside class="post-meta">
<ul>
<li class="post-category">
<?php the_category( ', ', $post->ID) ?>
<?php echo $product_cat; ?>
</li>
<?php the_tags( '<li class="tags">', ', ', '</li>' ); ?>
<?php if ( isset( $woo_options['woo_post_content'] ) && $woo_options['woo_post_content'] == 'excerpt' ) { ?>
<li class="comments"><?php comments_popup_link( __( 'Leave a comment', 'woothemes' ), __( '1 Comment', 'woothemes' ), __( '% Comments', 'woothemes' ) ); ?></li>
<?php } ?>
<?php edit_post_link( __( 'Edit', 'woothemes' ), '<li class="edit">', '</li>' ); ?>
</ul>
</aside>
<?php
}
}
?>
If you need to disable button add this line of code.
Button button = findViewById(R.id.button)
button.setEnabled(false);
And enable button , just add this line
button.setEnabled(true);
Happy coding :D
You need to use cell-arrays:
names = cell(10,1);
for i=1:10
names{i} = ['Sample Text ' num2str(i)];
end
You can use LEN in combination with SUBSTRING:
SELECT SUBSTRING(myColumn, 7, LEN(myColumn)) from myTable
The simplest way: just open the .dll in any text editor. Look at one of the last lines:
Using the flag -Command
you can execute your entire powershell line as if it was a command in the PowerShell prompt:
powershell -Command "& '<PATH_TO_PS1_FILE>' '<ARG_1>' '<ARG_2>' ... '<ARG_N>'"
This solved my issue with running PowerShell commands in Visual Studio Post-Build and Pre-Build events.
I am on Windows 7 using node.js v0.10.0 and mocha v1.8.2 and npm v1.2.14. I was just trying to get mocha to use the path test/unit to find my tests, After spending to long and trying several things I landed,
Using the "test/unit/*.js" option does not work on windows. For good reasons that windows shell doesn't expand wildcards like unixen.
However using "test/unit" does work, without the file pattern. eg. "mocha test/unit" runs all files found in test/unit folder.
This only still runs one folder files as tests but you can pass multiple directory names as parameters.
Also to run a single test file you can specify the full path and filename. eg. "mocha test/unit/mytest1.js"
I actually setup in package.json for npm "scripts": { "test": "mocha test/unit" },
So that 'npm test' runs my unit tests.
enum NumberError: Error {
case NegativeNumber(number: Int)
case ZeroNumber
case OddNumber(number: Int)
}
extension NumberError: CustomStringConvertible {
var description: String {
switch self {
case .NegativeNumber(let number):
return "Negative number \(number) is Passed."
case .OddNumber(let number):
return "Odd number \(number) is Passed."
case .ZeroNumber:
return "Zero is Passed."
}
}
}
func validateEvenNumber(_ number: Int) throws ->Int {
if number == 0 {
throw NumberError.ZeroNumber
} else if number < 0 {
throw NumberError.NegativeNumber(number: number)
} else if number % 2 == 1 {
throw NumberError.OddNumber(number: number)
}
return number
}
Now Validate Number :
do {
let number = try validateEvenNumber(0)
print("Valid Even Number: \(number)")
} catch let error as NumberError {
print(error.description)
}
From python 3.2, you have the interact
command, which gives you access to the full python/ipython command space.
After you get an error, in the next cell just run %debug
and that's it.
If you would like to use the same kind of syntax as setTimeout
you can write a helper function like this:
const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
setTimeout(() => {
cb();
resolve();
}, timeout);
});
You can then call it like so:
const doStuffAsync = async () => {
await setAsyncTimeout(() => {
// Do stuff
}, 1000);
await setAsyncTimeout(() => {
// Do more stuff
}, 500);
await setAsyncTimeout(() => {
// Do even more stuff
}, 2000);
};
doStuffAsync();
I made a gist: https://gist.github.com/DaveBitter/f44889a2a52ad16b6a5129c39444bb57
Just in case this helps, I solved this by checking the server date format:
SELECT * FROM nls_session_parameters WHERE parameter = 'NLS_DATE_FORMAT';
then by using the following comparison (the left field is a date+time):
AND EV_DTTM >= ('01-DEC-16')
I was trying this with TO_DATE
but kept getting an error. But when I matched my string with the NLS_DATE_FORMAT
and removed TO_DATE
, it worked...
Inline Stored procedure we using as per our need. Example like different Same parameter with different values we have to use in queries..
Create Proc SP1
(
@ID int,
@Name varchar(40)
-- etc parameter list, If you don't have any parameter then no need to pass.
)
AS
BEGIN
-- Here we have some opereations
-- If there is any Error Before Executing SP2 then SP will stop executing.
Exec SP2 @ID,@Name,@SomeID OUTPUT
-- ,etc some other parameter also we can use OutPut parameters like
-- @SomeID is useful for some other operations for condition checking insertion etc.
-- If you have any Error in you SP2 then also it will stop executing.
-- If you want to do any other operation after executing SP2 that we can do here.
END
try
$(document).ready(function(){
$('mybutton').click(function(){
parent.history.back();
return false;
});
});
or
$(document).ready(function(){
$('mybutton').click(function(){
parent.history.back();
});
});
I had this problem and tried various solutions to solve it including many of those listed above (config file, debug ssh etc). In the end, I resolved it by including the -u switch in the git push, per the github instructions when creating a new repository onsite - Github new Repository
As simple as it can be
Use $(this)
here too
$(document).on("click",".appDetails", function () {
var clickedBtnID = $(this).attr('id'); // or var clickedBtnID = this.id
alert('you clicked on button #' + clickedBtnID);
});
Current version:
SQL Server Management Studio
Direct link: http://go.microsoft.com/fwlink/?LinkID=828615
Version Information
This release of SSMS uses the Visual Studio 2015 Isolated shell. The release number: 16.4.1 The build number for this release: 13.0.15900.1 Supported SQL Server versions This version of SSMS works with all supported versions of SQL Server (SQL Server 2008 - SQL Server 2016), and provides the greatest level of support for working with the latest cloud features in Azure SQL Database. There is no explicit block for SQL Server 2000 or SQL Server 2005, but some features may not work properly. Additionally, one SSMS 16.x release or SSMS 2016 can be installed side by side with previous versions of SSMS 2014 and earlier.
Older version of the answer for 2012
Installation steps:
Command: SQLEXPRWT_x64_ENU.exe /ACTION=INSTALL /FEATURES=TOOLS /QUIETSIMPLE /IAcceptSQLServerLicenseTerms
original answer was: https://dba.stackexchange.com/questions/14438/how-to-install-sql-server-2008-r2-profiler Now posted: http://blog.cpodesign.com/blog/sql-2012-installing-sql-profiler/
"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup. When you call setContentView(), it attaches the views it creates from reading the XML to the activity. You can also use LayoutInflater to add views to another ViewGroup, which can be a useful tool in a lot of circumstances.
There you go, this is what I used to fix your problem:
CSS CODE
nav ul { list-style-type: none; }
HTML CODE
<nav>
<ul>
<li><a href="#">Milk</a>
<ul>
<li><a href="#">Goat</a></li>
<li><a href="#">Cow</a></li>
</ul>
</li>
<li><a href="#">Eggs</a>
<ul>
<li><a href="#">Free-range</a></li>
<li><a href="#">Other</a></li>
</ul>
</li>
<li><a href="#">Cheese</a>
<ul>
<li><a href="#">Smelly</a></li>
<li><a href="#">Extra smelly</a></li>
</ul>
</li>
</ul>
</nav>
I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.
As of npm@5
, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify
instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache
to use a temporary cache instead of nuking the actual one.
If you're sure you want to delete the entire cache, rerun:
npm cache clean --force
A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log
.
My numeric control:
function CheckNumeric(event) {
var _key = (window.Event) ? event.which : event.keyCode;
if (_key > 95 && _key < 106) {
return true;
}
else if (_key > 47 && _key < 58) {
return true;
}
else {
return false;
}
}
<input type="text" onkeydown="return CheckNumerick(event);" />
try it
BackSpace key code is 8
as your service is already setup, simply add a broadcast receiver in your service:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
//action for phone state changed
}
}
};
in your service's onCreate
do this:
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more
registerReceiver(receiver, filter);
and in your service's onDestroy
:
unregisterReceiver(receiver);
and you are good to go to receive broadcast for what ever filters you mention in onCreate
. Make sure to add any permission if required. for e.g.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
If you want to know all the shortcut in intellij hit Ctrl + J. This shows all the shortcuts. For System.out.println()
type sout
and press Tab.
update 4.1.0
See also https://github.com/angular/angular/blob/master/CHANGELOG.md#400-rc1-2017-02-24
update 2.1.0
For more details see Animations at angular.io
import { trigger, style, animate, transition } from '@angular/animations';
@Component({
selector: 'my-app',
animations: [
trigger(
'enterAnimation', [
transition(':enter', [
style({transform: 'translateX(100%)', opacity: 0}),
animate('500ms', style({transform: 'translateX(0)', opacity: 1}))
]),
transition(':leave', [
style({transform: 'translateX(0)', opacity: 1}),
animate('500ms', style({transform: 'translateX(100%)', opacity: 0}))
])
]
)
],
template: `
<button (click)="show = !show">toggle show ({{show}})</button>
<div *ngIf="show" [@enterAnimation]>xxx</div>
`
})
export class App {
show:boolean = false;
}
original
*ngIf
removes the element from the DOM when the expression becomes false
. You can't have a transition on a non-existing element.
Use instead hidden
:
<div class="note" [ngClass]="{'transition':show}" [hidden]="!show">
My answer comes from here
You can make a derived class, which will set the timeout property of the base WebRequest
class:
using System;
using System.Net;
public class WebDownload : WebClient
{
/// <summary>
/// Time in milliseconds
/// </summary>
public int Timeout { get; set; }
public WebDownload() : this(60000) { }
public WebDownload(int timeout)
{
this.Timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = this.Timeout;
}
return request;
}
}
and you can use it just like the base WebClient class.
Use css to add a right margin to those particular elements. Generally I would build the control, then run it to see what the resulting html structure is like, then make the css alter just those elements.
Preferably you do this by setting the class. Add the CssClass="myrblclass"
attribute to your list declaration.
You can also add attributes to the items programmatically, which will come out the other side.
rblMyRadioButtonList.Items[x].Attributes.CssStyle.Add("margin-right:5px;")
This may be better for you since you can add that attribute for all but the last one.
I corrected the warning by removing "baseUrl": "", from the tsconfig.json file
I faced this same error too. And i even tried downloading the PhoneGap master from GitHub,but i found out that what i got was Phonegap 2.9. I eventually had to download the Cordova 3 Source
Follow this steps to get it.
Another correct way to get selected value would be using this selector:
$("option[value="0"]:selected")
Best for you!
From a Windows Server OS execute the following command for a dump of the entire Active Director:
csvde -f test.csv
This command is very broad and will give you more than necessary information. To constrain the records to only user records, you would instead want:
csvde -f test.csv -r objectClass=user
You can further restrict the command to give you only the fields you need relevant to the search requested such as:
csvde -f test.csv -r objectClass=user -l DN, sAMAccountName, department, memberOf
If you have an Exchange server and each user associated with a live person has a mailbox (as opposed to generic accounts for kiosk / lab workstations) you can use mailNickname in place of sAMAccountName.
<?php if($condition) : ?>
<a href="http://yahoo.com">This will only display if $condition is true</a>
<?php endif; ?>
By request, here's elseif and else (which you can also find in the docs)
<?php if($condition) : ?>
<a href="http://yahoo.com">This will only display if $condition is true</a>
<?php elseif($anotherCondition) : ?>
more html
<?php else : ?>
even more html
<?php endif; ?>
It's that simple.
The HTML will only be displayed if the condition is satisfied.
use Moment.js for all your JavaScript related date-time calculation
Answer to your question is:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
Complete details can be found here
I just tested this- both CTE and non-CTE (where the query was typed out for every union instance) both took ~31 seconds. CTE made the code much more readable though- cut it down from 241 to 130 lines which is very nice. Temp table on the other hand cut it down to 132 lines, and took FIVE SECONDS to run. No joke. all of this testing was cached- the queries were all run multiple times before.
On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.
This is the most up to date version of how I would solve this problem. I would use:
This is some initial wiring but you are composing primitive blocks on your own, and you can make your own custom hook so that you only need to do this once.
// Generic reusable hook
const useDebouncedSearch = (searchFunction) => {
// Handle the input text state
const [inputText, setInputText] = useState('');
// Debounce the original search async function
const debouncedSearchFunction = useConstant(() =>
AwesomeDebouncePromise(searchFunction, 300)
);
// The async callback is run each time the text changes,
// but as the search function is debounced, it does not
// fire a new request on each keystroke
const searchResults = useAsync(
async () => {
if (inputText.length === 0) {
return [];
} else {
return debouncedSearchFunction(inputText);
}
},
[debouncedSearchFunction, inputText]
);
// Return everything needed for the hook consumer
return {
inputText,
setInputText,
searchResults,
};
};
And then you can use your hook:
const useSearchStarwarsHero = () => useDebouncedSearch(text => searchStarwarsHeroAsync(text))
const SearchStarwarsHeroExample = () => {
const { inputText, setInputText, searchResults } = useSearchStarwarsHero();
return (
<div>
<input value={inputText} onChange={e => setInputText(e.target.value)} />
<div>
{searchResults.loading && <div>...</div>}
{searchResults.error && <div>Error: {search.error.message}</div>}
{searchResults.result && (
<div>
<div>Results: {search.result.length}</div>
<ul>
{searchResults.result.map(hero => (
<li key={hero.name}>{hero.name}</li>
))}
</ul>
</div>
)}
</div>
</div>
);
};
You will find this example running here and you should read react-async-hook documentation for more details.
We often want to debounce API calls to avoid flooding the backend with useless requests.
In 2018, working with callbacks (Lodash/Underscore) feels bad and error-prone to me. It's easy to encounter boilerplate and concurrency issues due to API calls resolving in an arbitrary order.
I've created a little library with React in mind to solve your pains: awesome-debounce-promise.
This should not be more complicated than that:
const searchAPI = text => fetch('/search?text=' + encodeURIComponent(text));
const searchAPIDebounced = AwesomeDebouncePromise(searchAPI, 500);
class SearchInputAndResults extends React.Component {
state = {
text: '',
results: null,
};
handleTextChange = async text => {
this.setState({ text, results: null });
const result = await searchAPIDebounced(text);
this.setState({ result });
};
}
The debounced function ensures that:
this.setState({ result });
will happen per API callEventually, you may add another trick if your component unmounts:
componentWillUnmount() {
this.setState = () => {};
}
Note that Observables (RxJS) can also be a great fit for debouncing inputs, but it's a more powerful abstraction which may be harder to learn/use correctly.
The important part here is to create a single debounced (or throttled) function per component instance. You don't want to recreate the debounce (or throttle) function everytime, and you don't want either multiple instances to share the same debounced function.
I'm not defining a debouncing function in this answer as it's not really relevant, but this answer will work perfectly fine with _.debounce
of underscore or lodash, as well as any user-provided debouncing function.
Because debounced functions are stateful, we have to create one debounced function per component instance.
ES6 (class property): recommended
class SearchBox extends React.Component {
method = debounce(() => {
...
});
}
ES6 (class constructor)
class SearchBox extends React.Component {
constructor(props) {
super(props);
this.method = debounce(this.method.bind(this),1000);
}
method() { ... }
}
ES5
var SearchBox = React.createClass({
method: function() {...},
componentWillMount: function() {
this.method = debounce(this.method.bind(this),100);
},
});
See JsFiddle: 3 instances are producing 1 log entry per instance (that makes 3 globally).
var SearchBox = React.createClass({
method: function() {...},
debouncedMethod: debounce(this.method, 100);
});
It won't work, because during class description object creation, this
is not the object created itself. this.method
does not return what you expect because the this
context is not the object itself (which actually does not really exist yet BTW as it is just being created).
var SearchBox = React.createClass({
method: function() {...},
debouncedMethod: function() {
var debounced = debounce(this.method,100);
debounced();
},
});
This time you are effectively creating a debounced function that calls your this.method
. The problem is that you are recreating it on every debouncedMethod
call, so the newly created debounce function does not know anything about former calls! You must reuse the same debounced function over time or the debouncing will not happen.
var SearchBox = React.createClass({
debouncedMethod: debounce(function () {...},100),
});
This is a little bit tricky here.
All the mounted instances of the class will share the same debounced function, and most often this is not what you want!. See JsFiddle: 3 instances are producting only 1 log entry globally.
You have to create a debounced function for each component instance, and not a single debounced function at the class level, shared by each component instance.
This is related because we often want to debounce or throttle DOM events.
In React, the event objects (i.e., SyntheticEvent
) that you receive in callbacks are pooled (this is now documented). This means that after the event callback has be called, the SyntheticEvent you receive will be put back in the pool with empty attributes to reduce the GC pressure.
So if you access SyntheticEvent
properties asynchronously to the original callback (as may be the case if you throttle/debounce), the properties you access may be erased. If you want the event to never be put back in the pool, you can use the persist()
method.
onClick = e => {
alert(`sync -> hasNativeEvent=${!!e.nativeEvent}`);
setTimeout(() => {
alert(`async -> hasNativeEvent=${!!e.nativeEvent}`);
}, 0);
};
The 2nd (async) will print hasNativeEvent=false
because the event properties have been cleaned up.
onClick = e => {
e.persist();
alert(`sync -> hasNativeEvent=${!!e.nativeEvent}`);
setTimeout(() => {
alert(`async -> hasNativeEvent=${!!e.nativeEvent}`);
}, 0);
};
The 2nd (async) will print hasNativeEvent=true
because persist
allows you to avoid putting the event back in the pool.
You can test these 2 behaviors here: JsFiddle
Read Julen's answer for an example of using persist()
with a throttle/debounce function.
if you have JSON file you can set it on assets folder then call it using this code
InputStream in = mResources.getAssets().open("fragrances.json");
// where mResources object from Resources class
// We can apply `slice` from `Array.prototype`:
Array.prototype.slice.call([]); //-> []
// Since `slice` is available on an array's prototype chain,
'slice' in []; //-> true
[].slice === Array.prototype.slice; //-> true
// … we can just invoke it directly:
[].slice(); //-> []
// `arguments` has no `slice` method
'slice' in arguments; //-> false
// … but we can apply it the same way:
Array.prototype.slice.call(arguments); //-> […]
// In fact, though `slice` belongs to `Array.prototype`,
// it can operate on any array-like object:
Array.prototype.slice.call({0: 1, length: 1}); //-> [1]
This one worked for me
button:focus {
border: none;
outline: none;
}
You use new
to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.
You have no reason to use new
, since A
is an automatic variable. You can simply initialise A
using its constructor:
vector<vector<int> > A(dimension, vector<int>(dimension));
Using your data:
test_data <- data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
Dates = seq.Date(as.Date("2002-01-01"), by="1 month", length.out=100))
I create a stacked version which is what ggplot()
would like to work with:
stacked <- with(test_data,
data.frame(value = c(var0, var1),
variable = factor(rep(c("Var0","Var1"),
each = NROW(test_data))),
Dates = rep(Dates, 2)))
In this case producing stacked
was quite easy as we only had to do a couple of manipulations, but reshape()
and the reshape
and reshape2
might be useful if you have a more complex real data set to manipulate.
Once the data are in this stacked form, it only requires a simple ggplot()
call to produce the plot you wanted with all the extras (one reason why higher-level plotting packages like lattice
and ggplot2
are so useful):
require(ggplot2)
p <- ggplot(stacked, aes(Dates, value, colour = variable))
p + geom_line()
I'll leave it to you to tidy up the axis labels, legend title etc.
HTH
Why not use padding with negative margins? Something like this:
<div class="parent">
<div class="child1">
</div>
<div class="child2">
</div>
</div>
And then
.parent {
padding-top: 1em;
}
.child1 {
margin-top: -1em;
height: 1em;
}
.child2 {
margin-top: 0;
height: 100%;
}
private int[,] MirrorH(int[,] matrix) //the method will return mirror horizintal of matrix
{
int[,] MirrorHorizintal = new int[4, 4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j ++)
{
MirrorHorizintal[i, j] = matrix[i, 3 - j];
}
}
return MirrorHorizintal;
}
date_default_timezone_set('Australia/Melbourne');
$time = date("Y-m-d H:i:s", time());
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
On Windows you do not link with a .dll
file directly – you must use the accompanying .lib
file instead. To do that go to Project -> Properties -> Configuration Properties -> Linker -> Additional Dependencies
and add path to your .lib as a next line.
You also must make sure that the .dll
file is either in the directory contained by the %PATH%
environment variable or that its copy is in Output Directory
(by default, this is Debug\Release
under your project's folder).
If you don't have access to the .lib
file, one alternative is to load the .dll
manually during runtime using WINAPI functions such as LoadLibrary and GetProcAddress.
Poor man's profiling, no extensions required. Supports nested profiles and percent of total:
function p_open($flag) {
global $p_times;
if (null === $p_times)
$p_times = [];
if (! array_key_exists($flag, $p_times))
$p_times[$flag] = [ 'total' => 0, 'open' => 0 ];
$p_times[$flag]['open'] = microtime(true);
}
function p_close($flag)
{
global $p_times;
if (isset($p_times[$flag]['open'])) {
$p_times[$flag]['total'] += (microtime(true) - $p_times[$flag]['open']);
unset($p_times[$flag]['open']);
}
}
function p_dump()
{
global $p_times;
$dump = [];
$sum = 0;
foreach ($p_times as $flag => $info) {
$dump[$flag]['elapsed'] = $info['total'];
$sum += $info['total'];
}
foreach ($dump as $flag => $info) {
$dump[$flag]['percent'] = $dump[$flag]['elapsed']/$sum;
}
return $dump;
}
Example:
<?php
p_open('foo');
sleep(1);
p_open('bar');
sleep(2);
p_open('baz');
sleep(3);
p_close('baz');
sleep(2);
p_close('bar');
sleep(1);
p_close('foo');
var_dump(p_dump());
Yields:
array:3 [
"foo" => array:2 [
"elapsed" => 9.000766992569
"percent" => 0.4736904954747
]
"bar" => array:2 [
"elapsed" => 7.0004580020905
"percent" => 0.36841864946596
]
"baz" => array:2 [
"elapsed" => 3.0001420974731
"percent" => 0.15789085505934
]
]
Use jQuery
html
<div id="b"> </div>
css
div#b {
position: fixed;
top:40px;
left:0;
width: 40px;
height: 40px;
background: url(http://www.wiredforwords.com/IMAGES/FlyingBee.gif) 0 0 no-repeat;
}
script
var b = function($b,speed){
$b.animate({
"left": "50%"
}, speed);
};
$(function(){
b($("#b"), 5000);
});
see jsfiddle http://jsfiddle.net/vishnurajv/Q4Jsh/
You can decode it to str with receive.decode('utf_8')
.
An error message itself says:
"Invalid App Store Icon. The App Store Icon in the asset catalog in 'YourApp.app' can't be transparent nor contain an alpha channel."
All app icon must be square without transparency or semi transparent (alpha value != 1.0
).
Hint: App icon may have rounded corners. (Share your app icons here)
Here is Apple guidelines for App Icon - Human Interface
Try this:
<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>
function getPaging(str)
{
$("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
atof and strtod do what you want but are very forgiving. If you don't want to accept strings like "32asd" as valid you need to wrap strtod in a function such as this:
#include <stdlib.h>
double strict_str2double(char* str)
{
char* endptr;
double value = strtod(str, &endptr);
if (*endptr) return 0;
return value;
}
Where is your problem??
For the stored procedure, just create:
CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
SELECT * -- I would *strongly* recommend specifying the columns EXPLICITLY
FROM dbo.Emp
WHERE ID = @EmpID
That's all there is.
From your ASP.NET application, just create a SqlConnection
and a SqlCommand
(don't forget to set the CommandType = CommandType.StoredProcedure
)
DataTable tblEmployees = new DataTable();
using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
_cmd.Parameters["@EmpID"].Value = 42;
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_dap.Fill(tblEmployees);
}
YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();
and then fill e.g. a DataTable
with that data and bind it to e.g. a GridView.
Make sure you put the onSubmit attribute on the form not the button in case you have a from.
<form onSubmit={e => e.preventDefault()}>
<button onClick={this.handleClick}>Click Me</button>
</form>
Make sure to change the button onClick attribute to your custom function.
1.1 you can do this with this site: http://inloop.github.io/svg2android/ but it does not support all the features of SVG like some gradients.
1.2 you can convert via android studio but it might use some features that only supports API 24 and higher that cuase crashe your app in older devices.
and add vectorDrawables.useSupportLibrary = true
in gradle file and use like this:
<android.support.v7.widget.AppCompatImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="@drawable/ic_item1" />
add this code in application class:
public void onCreate() {
SVGLoader.load(this)
}
and use the SVG like this :
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_android_red"/>
Span starts out as an inline element. You can change its display attribute to block, for instance, and its height/width attributes will start to take effect.
COPY . <destination>
Which would be in your case:
COPY . /
Keep in mind while using HTML5 pushstate if a user copies or bookmarks a deep link and visits it again, then that will be a direct server hit which will 404 so you need to be ready for it and even a pushstate js library won't help you. The easiest solution is to add a rewrite rule to your Nginx or Apache server like so:
Apache (in your vhost if you're using one):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Nginx
rewrite ^(.+)$ /index.html last;
If you already have the string, you can use this function:
bool isNumber( const string& s )
{
bool hitDecimal=0;
for( char c : s )
{
if( c=='.' && !hitDecimal ) // 2 '.' in string mean invalid
hitDecimal=1; // first hit here, we forgive and skip
else if( !isdigit( c ) )
return 0 ; // not ., not
}
return 1 ;
}
1) Put the apk on your SDKCard and install file browsers like "Estrongs File Explorer", "Easy Installer", etc...
https://market.android.com/details?id=com.estrongs.android.pop&feature=search_result https://market.android.com/details?id=mobi.infolife.installer&feature=search_result
2) Go to your mobile settings - applications- debuging - and thick "USB debugging"
I'll post what worked for me, thanks to @xavi-montero.
Put your CSS in your bundle's Resource/public/css
directory, and your images in say Resource/public/img
.
Change assetic paths to the form 'bundles/mybundle/css/*.css'
, in your layout.
In config.yml
, add rule css_rewrite
to assetic:
assetic:
filters:
cssrewrite:
apply_to: "\.css$"
Now install assets and compile with assetic:
$ rm -r app/cache/* # just in case
$ php app/console assets:install --symlink
$ php app/console assetic:dump --env=prod
This is good enough for the development box, and --symlink
is useful, so you don't have to reinstall your assets (for example, you add a new image) when you enter through app_dev.php
.
For the production server, I just removed the '--symlink' option (in my deployment script), and added this command at the end:
$ rm -r web/bundles/*/css web/bundles/*/js # all this is already compiled, we don't need the originals
All is done. With this, you can use paths like this in your .css files: ../img/picture.jpeg
If you'd like a simple method to resolve this problem. (Can be used as an extension)
See below:
public static string RemoveFirstInstanceOfString(this string value, string removeString)
{
int index = value.IndexOf(removeString, StringComparison.Ordinal);
return index < 0 ? value : value.Remove(index, removeString.Length);
}
Usage:
string valueWithPipes = "| 1 | 2 | 3";
string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
//Output, valueWithoutFirstpipe = " 1 | 2 | 3";
Inspired by and modified @LukeH's and @Mike's answer.
Don't forget the StringComparison.Ordinal to prevent issues with Culture settings. https://www.jetbrains.com/help/resharper/2018.2/StringIndexOfIsCultureSpecific.1.html
check your Bundle identifier for your project and you give Bundle identifier for your app which create on developer.facebook.com that they are same or not.
It's a hex number and is 16 decimal.
Another one:
def local_maxima_mask(vec):
"""
Get a mask of all points in vec which are local maxima
:param vec: A real-valued vector
:return: A boolean mask of the same size where True elements correspond to maxima.
"""
mask = np.zeros(vec.shape, dtype=np.bool)
greater_than_the_last = np.diff(vec)>0 # N-1
mask[1:] = greater_than_the_last
mask[:-1] &= ~greater_than_the_last
return mask
Use <object>
instead (of course, replace each URL with your own):
.BackgroundImage {_x000D_
background: url('https://upload.wikimedia.org/wikipedia/commons/b/bd/Test.svg') no-repeat scroll left top;_x000D_
width: 400px;_x000D_
height: 600px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>SVG Test</title>_x000D_
</head>_x000D_
<body>_x000D_
<div id="ObjectTag">_x000D_
<object type="image/svg+xml" data="https://upload.wikimedia.org/wikipedia/commons/b/bd/Test.svg" width="400" height="600">_x000D_
Your browser does not support SVG._x000D_
</object>_x000D_
</div>_x000D_
<div class="BackgroundImage"></div>_x000D_
</body>_x000D_
</html>
_x000D_
64-bit tools are not available on Visual C++ Express by default. To enable 64-bit tools on Visual C++ Express, install the Windows Software Development Kit (SDK) in addition to Visual C++ Express. Otherwise, an error occurs when you attempt to configure a project to target a 64-bit platform using Visual C++ Express.
How to: Configure Visual C++ Projects to Target 64-Bit Platforms
The simplest way to create a manifest is:
Project Properties -> Security -> Click "enable ClickOnce security settings"
(it will generate default manifest in your project Properties) -> then Click
it again in order to uncheck that Checkbox -> open your app.maifest and edit
it as you wish.
Based on the correct answer, but taking into account ASCII control characters as well, the solution that worked for me is this:
SELECT * FROM `table` WHERE NOT `field` REGEXP "[\\x00-\\xFF]|^$";
It does the same thing: searches for violations of the ASCII range in a column, but lets you search for control characters too, since it uses hexadecimal notation for code points. Since there is no comparison or conversion (unlike @Ollie's answer), this should be significantly faster, too. (Especially if MySQL does early-termination on the regex query, which it definitely should.)
It also avoids returning fields that are zero-length. If you want a slightly-longer version that might perform better, you can use this instead:
SELECT * FROM `table` WHERE `field` <> "" AND NOT `field` REGEXP "[\\x00-\\xFF]";
It does a separate check for length to avoid zero-length results, without considering them for a regex pass. Depending on the number of zero-length entries you have, this could be significantly faster.
Note that if your default character set is something bizarre where 0x00-0xFF don't map to the same values as ASCII (is there such a character set in existence anywhere?), this would return a false positive. Otherwise, enjoy!
You could always use "%p" in order to display 8 bit hex numbers.
int main (void)
{
uint8_t a;
uint32_t b;
a=15;
b=a<<28;
printf("%p", b);
return 0;
}
Output:
0xf0000000
Okay, I'll bite. You want something like this: If you declare a "property" like this:
Update: I'm now pretty sure that Fredrik Mörk answered your question and gave a solution. I'm not really happy with the idea, but it seems to answer exactly what I understood from your question.
public class PropertyFoo {
public MyProp<String> Name;
}
this ends up as
public class PropertyFoo {
public string Name {
get { /* do predefined stuff here */ }
set { /*other predefined stuff here */ }
}
}
No. Not possible and not a property, really. Look for template/snippet support in your IDE.
Try this:
retVal = Shell("python.exe <full path to your python script>", vbNormalFocus)
replace <full path to your python script>
with the full path
You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.
Pick an encoding and stick with it:
f.write(printinfo.encode('utf8') + '\n')
or use io.open()
to create a file object that'll encode for you as you write to the file:
import io
f = io.open(filename, 'w', encoding='utf8')
You may want to read:
Pragmatic Unicode by Ned Batchelder
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky
before continuing.
I liked Jed's solution but the issue with that was every time I built my project in debug mode, it would deploy my database project and removed the user again. so I added this MySQL script to the Post-Deployment script. it practically does what Jed said but creates the user every time I deploy.
CREATE USER [NT AUTHORITY\NETWORK SERVICE]
FOR LOGIN [NT AUTHORITY\NETWORK SERVICE]
WITH DEFAULT_SCHEMA = dbo;
Go
EXEC sp_addrolemember 'db_owner', 'NT AUTHORITY\NETWORK SERVICE'
JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.
prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.
Yes, like in plain sql you could specify what kind of properties you want to select:
SELECT i.firstProperty, i.secondProperty FROM ObjectName i WHERE i.id=10
Executing this query will return a list of Object[], where each array contains the selected properties of one object.
Another way is to wrap the selected properties in a custom object and execute it in a TypedQuery:
String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();
Examples can be found in this article.
UPDATE 29.03.2018:
@Krish:
@PatrickLeitermann for me its giving "Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***" exception . how to solve this ?
I guess you’re using JPA in the context of a Spring application, don't you? Some other people had exactly the same problem and their solution was adding the fully qualified name (e. g. com.example.CustomObject) after the SELECT NEW keywords.
Maybe the internal implementation of the Spring data framework only recognizes classes annotated with @Entity or registered in a specific orm file by their simple name, which causes using this workaround.
Write a Boolean function that checks the regex and use apply on the column
foo[foo['b'].apply(regex_function)]
Returns the duplicate item in array and creates a new array with no duplicates:
var a = ["hello", "hi", "hi", "juice", "juice", "test"];
var b = ["ding", "dong", "hi", "juice", "juice", "test"];
var c = a.concat(b);
var dupClearArr = [];
function dupArray(arr) {
for (i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) != i && arr.indexOf(arr[i]) != -1) {
console.log('duplicate item ' + arr[i]);
} else {
dupClearArr.push(arr[i])
}
}
console.log('actual array \n' + arr + ' \nno duplicate items array \n' + dupClearArr)
}
dupArray(c);
For anyone looking for an Angular2 (2.4.8) solution, since this is a generically-popular question when searching:
<div *ngFor="let choice of choices">
<input type="radio" [checked]="choice == defaultChoice">
</div>
This will add the checked
attribute to the input given the condition, but will add nothing if the condition fails.
Do not do this:
[attr.checked]="choice == defaultChoice"
because this will add the attribute checked="false"
to every other input element.
Since the browser only looks for the presence of the checked
attribute (the key), ignoring its value, so the last input in the group will be checked.
Use the square bracket syntax:
if (!empty($row["title"])) {
$catList[$row["datasource_id"]] = $row["title"];
}
$row["datasource_id"]
is the key for where the value of $row["title"]
is stored in.
If you are in a po-up and you want to access the opening window, use window.opener
.
The easiest would be if you could load JQuery in the parent window as well:
window.opener.$("#serverMsg").html
// this uses JQuery in the parent window
or you could use plain old document.getElementById
to get the element, and then extend it using the jquery in your child window. The following should work (I haven't tested it, though):
element = window.opener.document.getElementById("serverMsg");
element = $(element);
If you are in an iframe or frameset and want to access the parent frame, use window.parent
instead of window.opener
.
According to the Same Origin Policy, all this works effortlessly only if both the child and the parent window are in the same domain.
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
Seems to be some relevent info here:
Converting MS Word Documents to PDF in ASP.NET
Also, with Office 2007 having publish to PDF functionality, I guess you could use office automation to open the *.DOC file in Word 2007 and Save as PDF. I'm not too keen on office automation as it's slow and prone to hanging, but just throwing that out there...
I have exactly the same issue. I ran a couple of virtual hosts on my local machine for developing.
First, I changed /etc/apache2/conf-available/php5-fpm.conf
. I replaced every
Order Deny,Allow
Deny from all
to
Require all granted
The configuration has to be enabled by a2enconf php5-fpm
. I did the same with my virtual hosts configurations and made the replacements.
I think this is not advised for security reasons, but as long as I use my server for local purposes only I can live with it.
You can temporarily increase the cache size and do one dummy select and then reset the cache size back to 1. So for example
ALTER SEQUENCE mysequence INCREMENT BY 100;
select mysequence.nextval from dual;
ALTER SEQUENCE mysequence INCREMENT BY 1;
import the ViewChild
decorator from @angular/core
, like so:
HTML Code:
<form #f="ngForm">
...
...
</form>
TS Code:
import { ViewChild } from '@angular/core';
class TemplateFormComponent {
@ViewChild('f') myForm: any;
.
.
.
}
now you can use 'myForm' object to access any element within it in the class.
Read these:
These articles will help you understand how to pass data between two activities in Android.
Use this commad when first connect to psql
=# psql <databaseName> <usernamePostgresql>
You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
./main.go (in package main)
./a/a.go (in package a)
./a/b.go (in package a)
in this case:
main.go import "./a"
It can call the function in the a.go and b.go,that with first letter caps on.
Give an ID to uniquely identify the button, lets say myBtn
// when DOM is ready
$(document).ready(function () {
// Attach Button click event listener
$("#myBtn").click(function(){
// show Modal
$('#myModal').modal('show');
});
});
That functionality is still suspiciously missing from the Java reflection API as far as I know. You can get a package object by just doing this:
Package packageObj = Package.getPackage("my.package");
But as you probably noticed, that won't let you list the classes in that package. As of right now, you have to take sort of a more filesystem-oriented approach.
I found some sample implementations in this post
I'm not 100% sure these methods will work when your classes are buried in JAR files, but I hope one of those does it for you.
I agree with @skaffman...if you have another way of going about this, I'd recommend doing that instead.
If you need an ordered dictionary, you can use odict.
You will also receive this error if you are passing an object back to the client that contains a property of type enum that is not set by default and that enum does not have a value that maps to 0. i.e enum MyEnum{ a=1, b=2};
Try this:
var frm = document.getElementById('search-theme-form') || null;
if(frm) {
frm.action = 'whatever_you_need.ext'
}
Thanks to this guy: https://www.tonyerwin.com/2014/09/redirecting-http-to-https-with-nodejs.html
app.use (function (req, res, next) {
if (req.secure) {
// request was via https, so do no special handling
next();
} else {
// request was via http, so redirect to https
res.redirect('https://' + req.headers.host + req.url);
}
});
I solved problem like yours by this commands:
git reset --hard HEAD^
git push -f <remote> <local branch>:<remote branch>
You can do that like this:
General syntax:
selector {
box-shadow: topBoxShadow, bottomBoxShadow, rightBoxShadow, leftBoxShadow
}
Example: we want to make only a bottom box shadow with red color,
so to do that we have to set all the sides options where we have to set the bottom box shadow options and set all the others as empty as follow:
.box {
-moz-box-shadow: 0 0 0 transparent ,0 0 10px red, 0 0 0 transparent, 0 0 0 transparent
-o-box-shadow: 0 0 0 transparent ,0 0 10px red, 0 0 0 transparent, 0 0 0 transparent
-webkit-box-shadow: 0 0 0 transparent ,0 0 10px red, 0 0 0 transparent, 0 0 0 transparent
box-shadow: 0 0 0 transparent ,0 0 10px red, 0 0 0 transparent, 0 0 0 transparent
}
It should be:
document.getElementById("placehere").appendChild(elem);
And place your div before your javascript, because if you don't, the javascript executes before the div exists. Or wait for it to load. So your code looks like this:
<html>
<body>
<script type="text/javascript">
window.onload=function(){
var elem = document.createElement("img");
elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem);
}
</script>
<div id="placehere">
</div>
</body>
</html>
To prove my point, see this with the onload and this without the onload. Fire up the console and you'll find an error stating that the div doesn't exist or cannot find appendChild method of null.
I never succeeded importing dumb files using phpmyadmin or phpMyBackupPro better is to go to console or command line ( whatever it's called in mac ) and do the following:
mysql -u username -p databasename
replace username with the username you use to connect to mysql, then it will ask you to enter the password for that username, and that's it
you can import any size of dumb using this method
Instead of disabling your constraint, permanently modify it to ON DELETE SET NULL. That will accomplish a similar thing and you wouldn't have to turn key checking on and off. Like so:
ALTER TABLE tablename1 DROP FOREIGN KEY fk_name1; //get rid of current constraints
ALTER TABLE tablename2 DROP FOREIGN KEY fk_name2;
ALTER TABLE tablename1
ADD FOREIGN KEY (table2_id)
REFERENCES table2(id)
ON DELETE SET NULL //add back constraint
ALTER TABLE tablename2
ADD FOREIGN KEY (table1_id)
REFERENCES table1(id)
ON DELETE SET NULL //add back other constraint
Have a read of this (http://dev.mysql.com/doc/refman/5.5/en/alter-table.html) and this (http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html).
From JDK 14+ which includes JEP 305 we can do Pattern Matching for instanceof
Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type.
Before Java 14
if (obj instanceof String) {
String str = (String) obj; // need to declare and cast again the object
.. str.contains(..) ..
}else{
str = ....
}
Java 14 enhancements
if (!(obj instanceof String str)) {
.. str.contains(..) .. // no need to declare str object again with casting
} else {
.. str....
}
We can also combine the type check and other conditions together
if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}
The use of pattern matching in instanceof
should reduce the overall number of explicit casts in Java programs.
PS: instanceOf
will only match when the object is not null, then only it can be assigned to str
.
input[type="text"]
{
width:200px
}
Here's a workaround. If you want to copy everything from A that does not already exist in B:
Copy A to a new directory C. Copy B to C, overwriting anything that overlaps with A. Copy C to B.
You need DjangoJSONEncoder
and list
to make your Queryset
to json
, ref: Python JSON serialize a Decimal object
import json
from django.core.serializers.json import DjangoJSONEncoder
blog = Blog.objects.all().values()
json.dumps(list(blog), cls=DjangoJSONEncoder)
I found the below code very useful, it might help anyone who comes searching here
<html>_x000D_
<body>_x000D_
<div style="width: 50%; height: 50%; background-color: green; float:left;">-</div>_x000D_
<div style="width: 50%; height: 50%; background-color: blue; float:right;">-</div>_x000D_
<div style="width: 100%; height: 50%; background-color: red; clear:both">-</div>_x000D_
</body>_x000D_
</html>
_x000D_
Using a Android clientId (no client_secret) I was getting the following error response:
{
"error": "invalid_grant",
"error_description": "Missing code verifier."
}
I cannot find any documentation for the field 'code_verifier' but I discovered if you set it to equal values in both the authorization and token requests it will remove this error. I'm not sure what the intended value should be or if it should be secure. It has some minimum length (16? characters) but I found setting to null
also works.
I am using AppAuth for the authorization request in my Android client which has a setCodeVerifier()
function.
AuthorizationRequest authRequest = new AuthorizationRequest.Builder(
serviceConfiguration,
provider.getClientId(),
ResponseTypeValues.CODE,
provider.getRedirectUri()
)
.setScope(provider.getScope())
.setCodeVerifier(null)
.build();
Here is an example token request in node:
request.post(
'https://www.googleapis.com/oauth2/v4/token',
{ form: {
'code': '4/xxxxxxxxxxxxxxxxxxxx',
'code_verifier': null,
'client_id': 'xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
'client_secret': null,
'redirect_uri': 'com.domain.app:/oauth2redirect',
'grant_type': 'authorization_code'
} },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Success!');
} else {
console.log(response.statusCode + ' ' + error);
}
console.log(body);
}
);
I tested and this works with both https://www.googleapis.com/oauth2/v4/token
and https://accounts.google.com/o/oauth2/token
.
If you are using GoogleAuthorizationCodeTokenRequest
instead:
final GoogleAuthorizationCodeTokenRequest req = new GoogleAuthorizationCodeTokenRequest(
TRANSPORT,
JSON_FACTORY,
getClientId(),
getClientSecret(),
code,
redirectUrl
);
req.set("code_verifier", null);
GoogleTokenResponse response = req.execute();
You can use Command prompt for VS 2010 and then select the path that your boost located. Use "bootstrap.bat", you can successfully install it.
Here is an example using openssl_encrypt
//Encryption:
$textToEncrypt = "My Text to Encrypt";
$encryptionMethod = "AES-256-CBC";
$secretHash = "encryptionhash";
$iv = mcrypt_create_iv(16, MCRYPT_RAND);
$encryptedText = openssl_encrypt($textToEncrypt,$encryptionMethod,$secretHash, 0, $iv);
//Decryption:
$decryptedText = openssl_decrypt($encryptedText, $encryptionMethod, $secretHash, 0, $iv);
print "My Decrypted Text: ". $decryptedText;
Here is another base R solution. We can use read.table
but since it accepts only one-byte sep
argument and here we have multi-byte separator we can use gsub
to replace the multibyte separator to any one-byte separator and use that as sep
argument in read.table
cbind(before[1], read.table(text = gsub('_and_', '\t', before$type),
sep = "\t", col.names = paste0("type_", 1:2)))
# attr type_1 type_2
#1 1 foo bar
#2 30 foo bar_2
#3 4 foo bar
#4 6 foo bar_2
In this case, we can also make it shorter by replacing it with default sep
argument so we don't have to mention it explicitly
cbind(before[1], read.table(text = gsub('_and_', ' ', before$type),
col.names = paste0("type_", 1:2)))
Since java 8 just use ZonedDateTime.parse("2010-04-05T17:16:00Z")
var jQueryObject = $('<div></div>').html( string ).children();
This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.
This isn't much of an answer, but I'd say that works just fine, personally
Having said that, since it doesn't matter what the values are (you've used 0, 1, 2), I'd use a meaningful string in case you ever wanted to output the current value.
You want to apply the fixed property to the position style of the element.
position: fixed;
What browser are you working with? Not all browsers support the fixed property. Read more about who supports it, who doesn't and some work around here
http://webreflection.blogspot.com/2009/09/css-position-fixed-solution.html
The same could be done with Perl
Because it uses 0-based-indexing instead of 1-based-indexing, the field values are offset by 1
perl -F, -lane 'print join ",", @F[1..3,5..9,11..19]'
is equivalent to:
cut -d, -f2-4,6-10,12-20
If the commas are not needed in the output:
perl -F, -lane 'print "@F[1..3,5..9,11..19]"'
I experienced this issue after recently updating Xcode to version 9.3 The issue was in code signing (under debug) certificate was set to distribution certificate instead of development certificate so this prevented me from installing the app on my devices.
Here is what I did to solve this issue.
Project -> Targets -> Select your app -> Build Settings -> Code Signing Identity -> Debug -> Double tap "iPhone Distribution" and change it to "iPhone Developer".
This link helped me: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
Basically it says that you should use an empty name for the parameter:
public string Post([FromBody]string myParameter){
...
}
$.post("/api/dosomething", { '' : "myvalue" });
You can also encode bytes to Base64. How to get this from a stream see here: How to convert an Stream into a byte[] in C#?
Or I think it should be also possible to use the .ToString() method and encode this.
Use --build-arg in lower case environment variable:
docker build --build-arg http_proxy=http://proxy:port/ --build-arg https_proxy=http://proxy:port/ --build-arg ftp_proxy=http://proxy:port --build-arg no_proxy=localhost,127.0.0.1,company.com -q=false .
You can not sort TreeMap on values.
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide
comparator
forComparator<? super K>
so your comparator should compare on keys.
To provide sort on values you will need SortedSet. Use
SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Map.Entry<String, Double> e1,
Map.Entry<String, Double> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
sortedset.addAll(myMap.entrySet());
To give you an example
SortedMap<String, Double> myMap = new TreeMap<String, Double>();
myMap.put("a", 10.0);
myMap.put("b", 9.0);
myMap.put("c", 11.0);
myMap.put("d", 2.0);
sortedset.addAll(myMap.entrySet());
System.out.println(sortedset);
Output:
[d=2.0, b=9.0, a=10.0, c=11.0]
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
Have a look at here this link and their roadmap. They have RO|C on the way, and that can connect to their web services, which probably includes SOAP (I use the VCL version which definitely includes it).
As I commented, there are a few places on this site that write the contents of a worksheet out to a CSV. This one and this one to point out just two.
Below is my version
UsedRange
- because you want to get all of the contents in the worksheetThe code ...
Sub makeCSV(theSheet As Worksheet)
Dim iFile As Long, myPath As String
Dim myArr() As Variant, outStr As String
Dim iLoop As Long, jLoop As Long
myPath = Application.ActiveWorkbook.Path
iFile = FreeFile
Open myPath & "\myCSV.csv" For Output Lock Write As #iFile
myArr = theSheet.UsedRange
For iLoop = LBound(myArr, 1) To UBound(myArr, 1)
outStr = ""
For jLoop = LBound(myArr, 2) To UBound(myArr, 2) - 1
If InStr(1, myArr(iLoop, jLoop), ",") Then
outStr = outStr & """" & myArr(iLoop, jLoop) & """" & ","
Else
outStr = outStr & myArr(iLoop, jLoop) & ","
End If
Next jLoop
If InStr(1, myArr(iLoop, jLoop), ",") Then
outStr = outStr & """" & myArr(iLoop, UBound(myArr, 2)) & """"
Else
outStr = outStr & myArr(iLoop, UBound(myArr, 2))
End If
Print #iFile, outStr
Next iLoop
Close iFile
Erase myArr
End Sub
When creating a New Project, under the language of your choice, select Web and then change to .NET Framework 3.5 and you will get the option of creating an ASP.NET WEB Service Application.
You don't have to press "CTRL-C", but you can provide an endpoint which does it for you:
from flask import Flask, jsonify, request
import json, os, signal
@app.route('/stopServer', methods=['GET'])
def stopServer():
os.kill(os.getpid(), signal.SIGINT)
return jsonify({ "success": True, "message": "Server is shutting down..." })
Now you can just call this endpoint to gracefully shutdown the server:
curl localhost:5000/stopServer
liteqr is a "Lite QR Reader in Objective C ported from zxing" on github and has support for Xcode 4.
Swift 4:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var height = super.tableView(tableView, heightForRowAt: indexPath)
if (indexPath.row == HIDDENROW) {
height = 0.0
}
return height
}
I had to be logged into Ubuntu as root in order to access Mariadb as root. It may have something to do with that "Harden ..." that it prompts you to do when you first install. So:
$ sudo su
[sudo] password for user: yourubunturootpassword
# mysql -r root -p
Enter password: yourmariadbrootpassword
and you're in.
Wrap the xml in another element
<wrapper>
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
</wrapper>
You have to go to the /etc/nginx/sites-enabled/
and if this is the default configuration, then there should be a file by name: default
.
Edit that file by defining your desired port; in the snippet below, we are serving the Nginx instance on port 81.
server {
listen 81;
}
To start the server, run the command line below;
sudo service nginx start
You may now access your application on port 81 (for localhost, http://localhost:81).
This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n
and the output of np.add.reduce()
are both scalars, this implies that the problem lies with xm
and ym
, the two of which are simply your x
and y
inputs minus their respective means.
Based on this, my guess is that your x
and y
inputs have different shapes from one another, making them incompatible for element-wise multiplication.
** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.