*
*
Linkers and Loaders from LinuxJournal explains this concept with clarity. It also explains how the classic name a.out came. (assembler output)
A quick summary,
c program --> [compiler] --> objectFile --> [linker] --> executable file (say, a.out)
we got the executable, now give this file to your friend or to your customer who is in need of this software :)
when they run this software, say by typing it in command line ./a.out
execute in command line ./a.out --> [Loader] --> [execve] --> program is loaded in memory
Once the program is loaded into the memory, control is transferred to this program by making the PC (program counter) pointing to the first instruction of a.out
u can do lik
var config = {
// TODO: Add common Configuration
module: {},
};
var x= Object.assign({}, config, {
name: "x",
entry: "./public/x/js/x.js",
output: {
path: __dirname+"/public/x/jsbuild",
filename: "xbundle.js"
},
});
var y= Object.assign({}, config, {
name: "y",
entry: "./public/y/js/FBRscript.js",
output: {
path: __dirname+"/public/fbr/jsbuild",
filename: "ybundle.js"
},
});
let list=[x,y];
for(item of list){
module.exports =item;
}
Well, this largely depends on how you're loading the elements needed in the 'intensive call', my initial thought is that you're doing those loads via ajax. If that's the case, then you could use the 'beforeSend' option and make an ajax call like this:
$.ajax({
type: 'GET',
url: "some.php",
data: "name=John&location=Boston",
beforeSend: function(xhr){ <---- use this option here
$('.select_element_you_want_to_load_into').html('Loading...');
},
success: function(msg){
$('.select_element_you_want_to_load_into').html(msg);
}
});
EDIT
I see, in that case, using one of the 'display:block'/'display:none'
options above in conjunction with $(document).ready(...)
from jQuery is probably the way to go. The $(document).ready()
function waits for the entire document structure to be loaded before executing (but it doesn't wait for all media to load). You'd do something like this:
$(document).ready( function() {
$('table#with_slow_data').show();
$('div#loading image or text').hide();
});
As of Xcode 11, "Application Loader is no longer included with Xcode", per the Xcode 11 Release Notes:
Xcode supports uploading apps from the Organizer window or from the command line with
xcodebuild
orxcrun altool
. Application Loader is no longer included with Xcode. (29008875)
The Xcode Help page, Upload an app to App Store Connect, explains how to upload from the Xcode Archives Organizer.
In October 2019, Apple announced the Transporter app for macOS, now available in the Mac App Store.
With Transporter you can:
- Upload your .ipa or .pkg files to App Store Connect.
- View delivery progress, including validation warnings, errors, and delivery logs, so you can quickly fix any issues.
- See a history of past deliveries, including date and time.
This was previously a download from iTunes Connect for qualified partners (FAQ)
I've uploaded non-Xcode builds with xcrun altool --upload-app -f path-to-build.ipa -u [email protected]
. It won't show any progress, but you can see the network traffic in Activity Monitor. It finishes with No errors uploading 'path-to-build.ipa'
.
See xcrun altool --help
for usage. If your account has 2FA enabled, first visit https://appleid.apple.com/ and generate an app password.
I recently switch to set strict-mode -version 2.0 and my null tests failed.
I added a function:
#use in strict mode to validate property exists before using
function exists {
param($obj,$prop)
try {
if ($null -ne $obj[$prop]) {return $true}
return $false
} catch {
return $false
}
return $false
}
Now I code
if (exists $run main) { ...
rather than
if ($run.main -ne $null) { ...
and we are on our way. Seems to work on objects and hashtables
As an unintended benefit it is less typing.
Your compound PRIMARY KEY
specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT
(already implied), too:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
... or just resultlist.RemoveAt(1)
if you know exactly the index.
Inline tag is used to add another src of document to the current html element.
In your case an video of a youtube and we need to specify the html type(4 or 5) to the browser externally to the link
so add ?html=5 to the end of the link.. :)
If you are using AngularJS, you can use a custom directive for easy access:
define(['angular'], function () {
angular.module("selectionHelper", [])
.directive('selectOnClick', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function () {
this.select();
});
}
};
});
});
Now one can just use it like this:
<input type="text" select-on-click ... />
The sample is with requirejs - so the first and the last line can be skipped if using something else.
Nicky De Maeyer asked after a background picture; I simply get it from the css and replace the "url()":
var div = $('#my-bg-div');
var url = div.css('background-image').replace(/^url\(\'?(.*)\'?\)$/, '$1');
var img = new Image();
img.src = url;
console.log('img:', img.width + 'x' + img.height); // zero, image not yet loaded
console.log('div:', div.width() + 'x' + div.height());
img.onload = function() {
console.log('img:', img.width + 'x' + img.height, (img.width/div.width()));
}
The XMLHttpRequest.timeout
property represents a number of milliseconds a request can take before automatically being terminated. The default value is 0
, which means there is no timeout. An important note the timeout shouldn't be used for synchronous XMLHttpRequests
requests, used in a document environment or it will throw an InvalidAccessError
exception. You may not use a timeout for synchronous requests with an owning window.
IE10 and 11 do not support synchronous requests, with support being phased out in other browsers too. This is due to detrimental effects resulting from making them.
More info can be found here.
Quick note: You are importing a class, you can't call properties on a class unless they are static properties. Read more about classes here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
There's an easy way to do this, though. If you are making helper functions, you should instead make a file that exports functions like this:
export function HelloChandu() {
}
export function HelloTester() {
}
Then import them like so:
import { HelloChandu } from './helpers'
or...
import functions from './helpers'
then
functions.HelloChandu
As the answers indicate (if you examine them carefully!), your question is ambiguous. What do you mean by "an A-z letter" or a digit?
If you want to know if a character is a Unicode letter or digit, then use the Character.isLetter
and Character.isDigit
methods.
If you want to know if a character is an ASCII letter or digit, then the best thing to do is to test by comparing with the character ranges 'a' to 'z', 'A' to 'Z' and '0' to '9'.
Note that all ASCII letters / digits are Unicode letters / digits ... but there are many Unicode letters / digits characters that are not ASCII. For example, accented letters, cyrillic, sanskrit, ...
The general solution is to do this:
Character.UnicodeBlock block = Character.UnicodeBlock.of(someCodePoint);
and then test to see if the block is one of the ones that you are interested in. In some cases you will need to test for multiple blocks. For example, there are (at least) 4 code blocks for Cyrillic characters and 7 for Latin. The Character.UnicodeBlock
class defines static constants for well-known blocks; see the javadocs.
Note that any code point will be in at most one block.
The Facebook "Graph API Rate Limiting" docs says that an error with code #4
is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:
This rate limiting is applied globally at the app level. Ads api calls are excluded.
- Rate limiting happens real time on sliding window for past one hour.
- Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
- There is a limit for each resource multiplied by monthly active users of a given app.
- When the app uses more than its allowed resources the error is thrown.
- Error, Code: 4, Message: Application request limit reached
The docs also give recommendations for avoiding the rate limits. For app level limits, they are:
Recommendations:
- Verify the error code (4) to confirm the throttling type.
- Do not make burst of calls, spread out the calls throughout the day.
- Do smart fetching of data (important data, non duplicated data, etc).
- Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
- Don't fetch users feed twice (in the case that two App users have a specific friend in common)
- Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
- Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
- For page related calls use realtime updates to subscribe to changes in data.
- Field expansion allows ton "join" multiple graph queries into a single call.
- Etags to check if the data querying has changed since the last check.
- For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.
Finally, the docs give the following informational tips:
- Batching calls will not reduce the number of api calls.
- Making parallel calls will not reduce the number of api calls.
You can use Sentenza for make applications for iPhone, on Windows. Tested with success. It's not a solution but a good alternative !
Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet
to List
, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator
:
List<Object> list =
DSL.using(connection)
.fetch("SELECT col1, col2, col3, ...")
.stream()
.flatMap(r -> Arrays.stream(r.intoArray()))
.collect(Collectors.toList());
List<Object> list =
DSL.using(connection)
.fetch("SELECT col1, col2, col3, ...")
.stream()
.flatMap(Record::intoStream)
.collect(Collectors.toList());
(Disclaimer, I work for the company behind jOOQ)
I use an immediately invoked lambda for these scenarios:
const config = (() => {
try {
return JSON.parse(fs.readFileSync('config.json'));
} catch (error) {
return {};
}
})();
async
version:
const config = await (async () => {
try {
return JSON.parse(await fs.readFileAsync('config.json'));
} catch (error) {
return {};
}
})();
This is what I did after reading all of the answers above.
spring.jpa.hibernate.ddl-auto=update
with other simple properties to application.propertiesFrom https://github.com/Homebrew/brew/issues/4436#issuecomment-403194892
Issue solved by setting this env variable:
export HOMEBREW_FORCE_BREWED_CURL=1
Inspired by the other answers (and so I can pick it up whenever I need it!), but with naming/style aligned with F# (which has a standard singleton
function per data structure*):
namespace System.Collections.Generic
{
public static class List
{
public static List<T> Singleton<T>(T value) => new List<T>(1) { value };
}
}
* except for ResizeArray
itself of course, hence this question :)
In practice I actually name it Create
to align with other helpers I define such as Tuple.Create
, Lazy.Create
[2], LazyTask.Create
etc:
namespace System.Collections.Generic
{
public static class List
{
public static List<T> Create<T>(T value) => new List<T>(1) { value };
}
}
[2]
namespace System
{
public static class Lazy
{
public static Lazy<T> Create<T>(Func<T> factory) => new Lazy<T>(factory);
}
}
You must feed the DOMDocument a version of your HTML with a header that make sense. Just like HTML5.
$profile ='<?xml version="1.0" encoding="'.$_encoding.'"?>'. $html;
maybe is a good idea to keep your html as valid as you can, so you don't get into issues when you'll start query... around :-) and stay away from htmlentities
!!!! That's an an necessary back and forth wasting resources.
keep your code insane!!!!
When cloning, by default it will not clone the events. The added rows do not have an event handler attached to them. If you call clone(true)
then it should handle them as well.
The general format, from the @link section of the javadoc documentation, is:
Method in the same class:
/** See also {@link #myMethod(String)}. */
void foo() { ... }
Method in a different class, either in the same package or imported:
/** See also {@link MyOtherClass#myMethod(String)}. */
void foo() { ... }
Method in a different package and not imported:
/** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
void foo() { ... }
Label linked to method, in plain text rather than code font:
/** See also this {@linkplain #myMethod(String) implementation}. */
void foo() { ... }
A chain of method calls, as in your question. We have to specify labels for the links to methods outside this class, or we get getFoo().Foo.getBar().Bar.getBaz()
. But these labels can be fragile during refactoring -- see "Labels" below.
/**
* A convenience method, equivalent to
* {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
* @return baz
*/
public Baz fooBarBaz()
Automated refactoring may not affect labels. This includes renaming the method, class or package; and changing the method signature.
Therefore, provide a label only if you want different text than the default.
For example, you might link from human language to code:
/** You can also {@linkplain #getFoo() get the current foo}. */
void setFoo( Foo foo ) { ... }
Or you might link from a code sample with text different than the default, as shown above under "A chain of method calls." However, this can be fragile while APIs are evolving.
If the method signature includes parameterized types, use the erasure of those types in the javadoc @link. For example:
int bar( Collection<Integer> receiver ) { ... }
/** See also {@link #bar(Collection)}. */
void foo() { ... }
In my case, the issue was unrelated to CORS since I was issuing a jQuery POST to the same web server. The data was JSON but I had omitted the dataType: 'json' parameter.
I did not have (nor did I add) a contentType parameter as shown in David Lopes' answer above.
Linux is now officially supported in brew - see the Homebrew 2.0.0 blog post. As shown on https://brew.sh, just copy/paste this into a command prompt:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
You can download the xgboost package to your local computer, and you better place the xgboost source file under D:\ or C:\ (ps: download address: http://www.lfd.uci.edu/~gohlke/pythonlibs/#xgboost, and select "xgboost-0.6-cp35-cp35m-win_amd64.whl",but it is up to your operation system), and you open the Anaconda prompt, type in pip install D:\xgboost-0.6-cp35-cp35m-win_amd64.whl
, then you can successful install xgboost into your anaconda
Is there a command that does?
thread apply all where
It is hard to say without knowing your code. My best guess is that the onchange
event is not firing when you change your textbox value from JavaScript code.
There are two ways for this to work; the first is to call onchange
by yourself, and the second is to wait for the textbox to lose focus.
Check this question; same issue, different framework.
Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.
You have to decide if:
If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)
If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:
If you give more details about your stack, it's easier to provide examples or resources.
EDIT: For client side JS highlighting you can try higlight.js, for instance.
In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).
you have to call set and add functions on chart object before calling redraw.
chart.xAxis[0].setCategories([2,4,5,6,7], false);
chart.addSeries({
name: "acx",
data: [4,5,6,7,8]
}, false);
chart.redraw();
If I have the class:
public class MyClass
{
public void MyMethod()
{
}
}
and I then do:
MyClass myClass = null;
myClass.MyMethod();
The second line throws this exception becuase I'm calling a method on a reference type object that is null
(I.e. has not been instantiated by calling myClass = new MyClass()
)
If you have date as a datetime.datetime
(or a datetime.date
) instance and want to combine it via a time from a datetime.time
instance, then you can use the classmethod datetime.datetime.combine
:
import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)
IMPORTANT NOTE: You should not concatenate SQL queries unless you trust the user completely. Query concatenation involves risk of SQL Injection being used to take over the world, ...khem, your database.
If you don't want to go into details how to execute query using SqlCommand
then you could call the same command line like this:
string userInput = "Brian";
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = string.Format(@"sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS
-s ; -W -w 100 -Q "" SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName,
tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = '{0}' """, userInput);
process.StartInfo = startInfo;
process.Start();
Just ensure that you escape each double quote "
with ""
I use $response->getBody()->getContents()
to get JSON from response.
Guzzle version 6.3.0.
you can make a jQuery onChange event to get the text from the combobox when the user select one of them:
<script>
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$('#EvaluationName').val(str);
})
.change();
</script>
When you select an option, it will save the text in an Input hidde
<input type="hidden" id="EvaluationName" name="EvaluationName" value="<?= $Evaluation ?>" />
After that, when you submit the form, just catch up the value of the input
$Evaluation = $_REQUEST['EvaluationName'];
Then you can do wathever you want with the text, for instance save it in a session variable and send it to other page. etc.
According to this website, it's a reference to this
, mostly in loops.
$_ (dollar underscore) 'THIS' token. Typically refers to the item inside a foreach loop. Task: Print all items in a collection. Solution. ... | foreach { Write-Host $_ }
app = Flask(__name__, static_folder="your path to static")
If you have templates in your root directory, placing the app=Flask(name) will work if the file that contains this also is in the same location, if this file is in another location, you will have to specify the template location to enable Flask to point to the location
Similar to mangledorf's solution, but shorter and layman friendly
:%s/.*/\L&/g
There are two simple ways to convert stdClass Object to an Array
$array = get_object_vars($obj);
and other is
$array = json_decode(json_encode($obj), true);
or you can simply create array using foreach loop
$array = array();
foreach($obj as $key){
$array[] = $key;
}
print_r($array);
Edit 2018-02-06: revision based on this comment
Edit: forgot to mention that this works on Python 2.7.x
There's multiprocesing.pool, and the following sample illustrates how to use one of them:
from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool
pool_size = 5 # your "parallelness"
# define worker function before a Pool is instantiated
def worker(item):
try:
api.my_operation(item)
except:
print('error with item')
pool = Pool(pool_size)
for item in items:
pool.apply_async(worker, (item,))
pool.close()
pool.join()
Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers
To create/change a root password in a running container
docker exec -itu root {containerName} passwd
Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.
Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House.
The above two are forms of containment (hence the parent-child relationships).
Dependency is a weaker form of relationship and in code terms indicates that a class uses another by parameter or return type.
Dependency is a form of association.
cballou's solution will work if you are using an old version of jquery. In newer versions you can also try:
$.ajax({
type: 'POST',
url:'url.do',
data: formData,
success: function(data, textStatus, request){
alert(request.getResponseHeader('some_header'));
},
error: function (request, textStatus, errorThrown) {
alert(request.getResponseHeader('some_header'));
}
});
According to docs the XMLHttpRequest object is available as of jQuery 1.4.
You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.
HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);
Materialized views are disk based and are updated periodically based upon the query definition.
Views are virtual only and run the query definition each time they are accessed.
I find this works easier. readonly the input field, then style it so the end user knows it's read only. inputs placed here (from AJAX for example) can still submit, without extra code.
<input readonly style="color: Grey; opacity: 1; ">
Add -confirm:$false to suppress confirmation.
Through this you can get absolute path of any file located in any directory.
File.join(Dir.pwd,'some-dir','some-file-name')
This will return
=> "/User/abc/xyz/some-dir/some-file-name"
In case anyone likes it, here is a .NET 4+ only solution formed as an extension method without the needless Dispose call on the MemoryStream. This is a hopelessly trivial optimization, but it is worth noting that failing to Dispose a MemoryStream is not a real failure.
public static class StreamHelpers
{
public static byte[] ReadFully(this Stream input)
{
var ms = new MemoryStream();
input.CopyTo(ms);
return ms.ToArray();
}
}
This is a press down button example I've made:
<div>
<form id="forminput" action="action" method="POST">
...
</form>
<div style="right: 0px;bottom: 0px;position: fixed;" class="thumbnail">
<div class="image">
<a onclick="document.getElementById('forminput').submit();">
<img src="images/button.png" alt="Some awesome text">
</a>
</div>
</div>
</div>
the CSS file:
.thumbnail {
width: 128px;
height: 128px;
}
.image {
width: 100%;
height: 100%;
}
.image img {
-webkit-transition: all .25s ease; /* Safari and Chrome */
-moz-transition: all .25s ease; /* Firefox */
-ms-transition: all .25s ease; /* IE 9 */
-o-transition: all .25s ease; /* Opera */
transition: all .25s ease;
max-width: 100%;
max-height: 100%;
}
.image:hover img {
-webkit-transform:scale(1.05); /* Safari and Chrome */
-moz-transform:scale(1.05); /* Firefox */
-ms-transform:scale(1.05); /* IE 9 */
-o-transform:scale(1.05); /* Opera */
transform:scale(1.05);
}
.image:active img {
-webkit-transform:scale(.95); /* Safari and Chrome */
-moz-transform:scale(.95); /* Firefox */
-ms-transform:scale(.95); /* IE 9 */
-o-transform:scale(.95); /* Opera */
transform:scale(.95);
}
Enjoy it!
You can format the jquery date with this line:
moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");
Minor difference to accepted answer, but I was having a lot of difficulty squashing and finally got it.
$ git rebase -i HEAD~4
esc --> :wq
Push to the remote using:
$ git push origin branch-name --force
If you read the help file for ?boxplot
, you'll see there is a names=
parameter.
boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))
Have a look at the following database schema, reverse engineered by Anatoly Lubarsky:
Building on @stankovski's answer, a more precise way of doing it which will work for all use cases (for example, when a tab is loading via ajax and so the anchor's href attribute doesn't correspond with the hash), the id in any case will correspond with the li element's "aria-controls" attribute. So for example if you are trying to activate a tab based on the location.hash, which is set to the tab id, then it is better to look for "aria-controls" than for "href".
With jQuery UI >= 1.9:
var index = $('#tabs > ul > li[aria-controls="simple-tab-2"]').parent().index();
$("#tabs").tabs("option", "active", index);
In the case of setting and checking the url hash:
When creating the tabs, use the 'activate' event to set the location.hash to the panel id:
$('#tabs').tabs({
activate: function(event, ui) {
var scrollTop = $(window).scrollTop(); // save current scroll position
window.location.hash = ui.newPanel.attr('id');
$(window).scrollTop(scrollTop); // keep scroll at current position
}
});
Then use the window hashchange event to compare the location.hash to the panel id (do this by looking for the li element's aria-controls attribute):
$(window).on('hashchange', function () {
if (!location.hash) {
$('#tabs').tabs('option', 'active', 0);
return;
}
$('#tabs > ul > li').each(function (index, li) {
if ('#' + $(li).attr('aria-controls') == location.hash) {
$('#tabs').tabs('option', 'active', index);
return;
}
});
});
This will handle all cases, even where tabs use ajax. Also if you have nested tabs, it isn't too difficult to handle that either using a little more logic.
There's a slightly shorter method that can be used similar to one of the ones above. That is:
[ $(date -d +1day +%d) -eq 1 ] && echo "last day of month"
Also, the crontab entry could be update to only check on the 28th to 31st as it's pointless running it the other days of the month. Which would give you:
0 23 28-31 * * [ $(date -d +1day +%d) -eq 1 ] && myscript.sh
I followed the link shared by lisachenko and found another link to this blog: http://guilhembichot.blogspot.co.uk/2013/11/with-recursive-and-mysql.html
The post lays out ways of emulating the 2 uses of SQL WITH. Really good explanation on how these work to do a similar query as SQL WITH.
1) Use WITH so you don't have to perform the same sub query multiple times
CREATE VIEW D AS (SELECT YEAR, SUM(SALES) AS S FROM T1 GROUP BY YEAR);
SELECT D1.YEAR, (CASE WHEN D1.S>D2.S THEN 'INCREASE' ELSE 'DECREASE' END) AS TREND
FROM
D AS D1,
D AS D2
WHERE D1.YEAR = D2.YEAR-1;
DROP VIEW D;
2) Recursive queries can be done with a stored procedure that makes the call similar to a recursive with query.
CALL WITH_EMULATOR(
"EMPLOYEES_EXTENDED",
"
SELECT ID, NAME, MANAGER_ID, 0 AS REPORTS
FROM EMPLOYEES
WHERE ID NOT IN (SELECT MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID IS NOT NULL)
",
"
SELECT M.ID, M.NAME, M.MANAGER_ID, SUM(1+E.REPORTS) AS REPORTS
FROM EMPLOYEES M JOIN EMPLOYEES_EXTENDED E ON M.ID=E.MANAGER_ID
GROUP BY M.ID, M.NAME, M.MANAGER_ID
",
"SELECT * FROM EMPLOYEES_EXTENDED",
0,
""
);
And this is the code or the stored procedure
# Usage: the standard syntax:
# WITH RECURSIVE recursive_table AS
# (initial_SELECT
# UNION ALL
# recursive_SELECT)
# final_SELECT;
# should be translated by you to
# CALL WITH_EMULATOR(recursive_table, initial_SELECT, recursive_SELECT,
# final_SELECT, 0, "").
# ALGORITHM:
# 1) we have an initial table T0 (actual name is an argument
# "recursive_table"), we fill it with result of initial_SELECT.
# 2) We have a union table U, initially empty.
# 3) Loop:
# add rows of T0 to U,
# run recursive_SELECT based on T0 and put result into table T1,
# if T1 is empty
# then leave loop,
# else swap T0 and T1 (renaming) and empty T1
# 4) Drop T0, T1
# 5) Rename U to T0
# 6) run final select, send relult to client
# This is for *one* recursive table.
# It would be possible to write a SP creating multiple recursive tables.
delimiter |
CREATE PROCEDURE WITH_EMULATOR(
recursive_table varchar(100), # name of recursive table
initial_SELECT varchar(65530), # seed a.k.a. anchor
recursive_SELECT varchar(65530), # recursive member
final_SELECT varchar(65530), # final SELECT on UNION result
max_recursion int unsigned, # safety against infinite loop, use 0 for default
create_table_options varchar(65530) # you can add CREATE-TABLE-time options
# to your recursive_table, to speed up initial/recursive/final SELECTs; example:
# "(KEY(some_column)) ENGINE=MEMORY"
)
BEGIN
declare new_rows int unsigned;
declare show_progress int default 0; # set to 1 to trace/debug execution
declare recursive_table_next varchar(120);
declare recursive_table_union varchar(120);
declare recursive_table_tmp varchar(120);
set recursive_table_next = concat(recursive_table, "_next");
set recursive_table_union = concat(recursive_table, "_union");
set recursive_table_tmp = concat(recursive_table, "_tmp");
# Cleanup any previous failed runs
SET @str =
CONCAT("DROP TEMPORARY TABLE IF EXISTS ", recursive_table, ",",
recursive_table_next, ",", recursive_table_union,
",", recursive_table_tmp);
PREPARE stmt FROM @str;
EXECUTE stmt;
# If you need to reference recursive_table more than
# once in recursive_SELECT, remove the TEMPORARY word.
SET @str = # create and fill T0
CONCAT("CREATE TEMPORARY TABLE ", recursive_table, " ",
create_table_options, " AS ", initial_SELECT);
PREPARE stmt FROM @str;
EXECUTE stmt;
SET @str = # create U
CONCAT("CREATE TEMPORARY TABLE ", recursive_table_union, " LIKE ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
SET @str = # create T1
CONCAT("CREATE TEMPORARY TABLE ", recursive_table_next, " LIKE ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
if max_recursion = 0 then
set max_recursion = 100; # a default to protect the innocent
end if;
recursion: repeat
# add T0 to U (this is always UNION ALL)
SET @str =
CONCAT("INSERT INTO ", recursive_table_union, " SELECT * FROM ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# we are done if max depth reached
set max_recursion = max_recursion - 1;
if not max_recursion then
if show_progress then
select concat("max recursion exceeded");
end if;
leave recursion;
end if;
# fill T1 by applying the recursive SELECT on T0
SET @str =
CONCAT("INSERT INTO ", recursive_table_next, " ", recursive_SELECT);
PREPARE stmt FROM @str;
EXECUTE stmt;
# we are done if no rows in T1
select row_count() into new_rows;
if show_progress then
select concat(new_rows, " new rows found");
end if;
if not new_rows then
leave recursion;
end if;
# Prepare next iteration:
# T1 becomes T0, to be the source of next run of recursive_SELECT,
# T0 is recycled to be T1.
SET @str =
CONCAT("ALTER TABLE ", recursive_table, " RENAME ", recursive_table_tmp);
PREPARE stmt FROM @str;
EXECUTE stmt;
# we use ALTER TABLE RENAME because RENAME TABLE does not support temp tables
SET @str =
CONCAT("ALTER TABLE ", recursive_table_next, " RENAME ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
SET @str =
CONCAT("ALTER TABLE ", recursive_table_tmp, " RENAME ", recursive_table_next);
PREPARE stmt FROM @str;
EXECUTE stmt;
# empty T1
SET @str =
CONCAT("TRUNCATE TABLE ", recursive_table_next);
PREPARE stmt FROM @str;
EXECUTE stmt;
until 0 end repeat;
# eliminate T0 and T1
SET @str =
CONCAT("DROP TEMPORARY TABLE ", recursive_table_next, ", ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# Final (output) SELECT uses recursive_table name
SET @str =
CONCAT("ALTER TABLE ", recursive_table_union, " RENAME ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# Run final SELECT on UNION
SET @str = final_SELECT;
PREPARE stmt FROM @str;
EXECUTE stmt;
# No temporary tables may survive:
SET @str =
CONCAT("DROP TEMPORARY TABLE ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# We are done :-)
END|
delimiter ;
Problem could occur if you have changed the namespace of your project.
Change the Namespace from Project Properties and also replace all old Namespace with new ones. Renaming to correct namespace might fix the issue.
Make sure the value in the child's project/parent/version node matches its parent's project/version value
Small change to the recursion to so you can for example find the child tab control of a tab control.
public static DependencyObject FindInVisualTreeDown(DependencyObject obj, Type type)
{
if (obj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child.GetType() == type)
{
return child;
}
DependencyObject childReturn = FindInVisualTreeDown(child, type);
if (childReturn != null)
{
return childReturn;
}
}
}
return null;
}
With question 3, this article states that RESTful Services are appropiate in this scenarios:
While SOAP is the way to go when:
Give permission in .htaccess as follows:
<Directory "Your directory path/uploads/">
Allow from all
</Directory>
You'll also get this exception if you try to save to an invalid path or if there's a permissions issue.
If you're not 100% sure that the file path is available and permissions are correct then try writing a to a text file. This takes just a few seconds to rule out what would be a very simple fix.
var img = System.Drawing.Image.FromStream(incomingStream);
// img.Save(path);
System.IO.File.WriteAllText(path, "Testing valid path & permissions.");
And don't forget to clean up your file.
As you said, in MySQL USAGE
is synonymous with "no privileges". From the MySQL Reference Manual:
The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.
USAGE
is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE
. It corresponds to a row in the `mysql`.`user`
table with no privileges set.
The IDENTIFIED BY
clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.
A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user`
table. If the user does not have any other privileges ON *.*
, they are granted USAGE ON *.*
and their password hash is displayed there. This is often a side effect of a CREATE USER
statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE
.
Following @Javier's answer. I have decided to go with "patching up the external IP" for my load balancer.
$ kubectl patch service my-loadbalancer-service-name \
-n lb-service-namespace \
-p '{"spec": {"type": "LoadBalancer", "externalIPs":["192.168.39.25"]}}'
This will replace that 'pending' with a new patched up IP address you can use for your cluster.
For more on this. Please see karthik's post on LoadBalancer support with Minikube for Kubernetes
Not the cleanest way to do it. I needed a temporary solution. Hope this helps somebody.
Pyperclip seems to be up to the task.
You're looking for keydown/press/up
$("#inputID").keydown(function(event) {
alert(event.keyCode);
});
or using bind $("#inputID").bind('onkeydown', ...
You can run IIS on any port you like, as long as it does not conflict with other applications. I am using 88, 8888 and other easy to remember ports.
You can find the common used port here: PORT NUMBERS, and it is safer to choose an unassigned TCP port.
Quote:
The Dynamic and/or Private Ports are those from 49152 through 65535
If IIS is working and you have troubles with an ASP.NET applications, those links might be helpful:
If you are still having troubles, it would be helpful to provide more information about your environment, the steps taken so far to solve the problem, and retagging the question (append asp.net for example)
Thanks a lot guys for your quick comments.
This is what i will be using now. Posting the function here so that somebody may use it.
public function getDayOfWeek($pTimezone)
{
$userDateTimeZone = new DateTimeZone($pTimezone);
$UserDateTime = new DateTime("now", $userDateTimeZone);
$offsetSeconds = $UserDateTime->getOffset();
//echo $offsetSeconds;
return gmdate("l", time() + $offsetSeconds);
}
Report if you find any corrections.
On click it can be done using below code
$('.dropdown-toggle').click(function() {
$(this).next('.dropdown-menu').slideToggle(500);
});
I wanted to to print one single line in a different color.
Use ANSI Escape Sequences.
Windows before 10 - no native support for ANSI colors on the console
For Windows version below 10, the Windows command console doesn't support output coloring by default. You could install either Cmder, ConEmu, ANSICON or Mintty (used by default in GitBash and Cygwin) to add coloring support to your Windows command console.
Windows 10 - Command Line Colors
Starting from Windows 10 the Windows console support ANSI Escape Sequences and some colors by default. The feature shipped with the Threshold 2 Update in Nov 2015.
Update (05-2019): The ColorTool enables you to change the color scheme of the console. It's part of the Microsoft Terminal project.
Demo
Batch Command
The win10colors.cmd
was written by Michele Locati:
The text below is stripped of special characters and will not work. You must copy it from here.
@echo off
cls
echo [101;93m STYLES [0m
echo ^<ESC^>[0m [0mReset[0m
echo ^<ESC^>[1m [1mBold[0m
echo ^<ESC^>[4m [4mUnderline[0m
echo ^<ESC^>[7m [7mInverse[0m
echo.
echo [101;93m NORMAL FOREGROUND COLORS [0m
echo ^<ESC^>[30m [30mBlack[0m (black)
echo ^<ESC^>[31m [31mRed[0m
echo ^<ESC^>[32m [32mGreen[0m
echo ^<ESC^>[33m [33mYellow[0m
echo ^<ESC^>[34m [34mBlue[0m
echo ^<ESC^>[35m [35mMagenta[0m
echo ^<ESC^>[36m [36mCyan[0m
echo ^<ESC^>[37m [37mWhite[0m
echo.
echo [101;93m NORMAL BACKGROUND COLORS [0m
echo ^<ESC^>[40m [40mBlack[0m
echo ^<ESC^>[41m [41mRed[0m
echo ^<ESC^>[42m [42mGreen[0m
echo ^<ESC^>[43m [43mYellow[0m
echo ^<ESC^>[44m [44mBlue[0m
echo ^<ESC^>[45m [45mMagenta[0m
echo ^<ESC^>[46m [46mCyan[0m
echo ^<ESC^>[47m [47mWhite[0m (white)
echo.
echo [101;93m STRONG FOREGROUND COLORS [0m
echo ^<ESC^>[90m [90mWhite[0m
echo ^<ESC^>[91m [91mRed[0m
echo ^<ESC^>[92m [92mGreen[0m
echo ^<ESC^>[93m [93mYellow[0m
echo ^<ESC^>[94m [94mBlue[0m
echo ^<ESC^>[95m [95mMagenta[0m
echo ^<ESC^>[96m [96mCyan[0m
echo ^<ESC^>[97m [97mWhite[0m
echo.
echo [101;93m STRONG BACKGROUND COLORS [0m
echo ^<ESC^>[100m [100mBlack[0m
echo ^<ESC^>[101m [101mRed[0m
echo ^<ESC^>[102m [102mGreen[0m
echo ^<ESC^>[103m [103mYellow[0m
echo ^<ESC^>[104m [104mBlue[0m
echo ^<ESC^>[105m [105mMagenta[0m
echo ^<ESC^>[106m [106mCyan[0m
echo ^<ESC^>[107m [107mWhite[0m
echo.
echo [101;93m COMBINATIONS [0m
echo ^<ESC^>[31m [31mred foreground color[0m
echo ^<ESC^>[7m [7minverse foreground ^<-^> background[0m
echo ^<ESC^>[7;31m [7;31minverse red foreground color[0m
echo ^<ESC^>[7m and nested ^<ESC^>[31m [7mbefore [31mnested[0m
echo ^<ESC^>[31m and nested ^<ESC^>[7m [31mbefore [7mnested[0m
You can't create an array immediately because you need to know the number of rows from the beginning (and this would require to read the csv file twice)
You can store values in two List<T>
and then use them or convert into an array using List<T>.ToArray()
Very simple example:
var column1 = new List<string>();
var column2 = new List<string>();
using (var rd = new StreamReader("filename.csv"))
{
while (!rd.EndOfStream)
{
var splits = rd.ReadLine().Split(';');
column1.Add(splits[0]);
column2.Add(splits[1]);
}
}
// print column1
Console.WriteLine("Column 1:");
foreach (var element in column1)
Console.WriteLine(element);
// print column2
Console.WriteLine("Column 2:");
foreach (var element in column2)
Console.WriteLine(element);
N.B.
Please note that this is just a very simple example. Using string.Split
does not account for cases where some records contain the separator ;
inside it.
For a safer approach, consider using some csv specific libraries like CsvHelper on nuget.
The experiment was: EXPERIMENT
Add a method to Card that creates a full deck of cards, with one card of each combination of rank and suit.
So without modifying or enhancing the given code other than adding the method (and without using stuff that hasn't been taught yet), I came up with this solution:
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
func createDeck() -> [Card] {
var deck: [Card] = []
for rank in Rank.Ace.rawValue...Rank.King.rawValue {
for suit in Suit.Spades.rawValue...Suit.Clubs.rawValue {
let card = Card(rank: Rank(rawValue: rank)!, suit: Suit(rawValue: suit)!)
//println(card.simpleDescription())
deck += [card]
}
}
return deck
}
}
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
let deck = threeOfSpades.createDeck()
How to use google app engine with ajax (json)?
Code Javascript with JQuery:
$.ajax({
url: '/ajax',
dataType : 'json',
cache: false,
success: function(data) {
alert('Load was performed.'+data.ajax_resp);
}
});
Code Python
class Ajax(webapp2.RequestHandler):
def get(self):
my_response = {'ajax_resp':'Hello, webapp World!'}
datos = json.dumps(my_response)
self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
self.response.out.write(datos)
If you really don't want to use any server controls, you should put the Response.Write
in the place you want the string to be written:
<body>
<% Response.Write(stringVariable); %>
</body>
A shorthand for this syntax is:
<body>
<%= stringVariable %>
</body>
I would like to add that
We have to set theme before calling 'super.onCreate()' and 'setContentView()' method.
Check out this link for applying new theme to whole application at runtime.
Not like the @staticmethod
but class variables are static method of class and are shared with all the instances.
Now you can access it like
instance = MyClass()
print(instance.i)
or
print(MyClass.i)
you have to assign the value to these variables
I was trying
class MyClass:
i: str
and assigning the value in one method call, in that case it will not work and will throw an error
i is not attribute of MyClass
In my case there were uncommitted changes from the previous branch lingering around. I used following commands and then delete worked.
git checkout *
git checkout master
git branch -D
You can use reduce
which works in all browser except IE8 and lower.
["20","40","80","400"].reduce(function(a, b) {
return parseInt(a, 10) + parseInt(b, 10);
})
I tried this and worked for me.
Date = (long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds
Microsoft have a proprietary CSS method of including embedded fonts (http://msdn.microsoft.com/en-us/library/ms533034(VS.85).aspx), but this probably shouldn't be recommended.
I've used sIFR before as this works great - it uses Javascript and Flash to dynamically replace normal text with some Flash containing the same text in the font you want (the font is embedded in a Flash file). This does not affect the markup around the text (it works by using a CSS class), you can still select the text, and if the user doesn't have Flash or has it disabled, it will degrade gracefully to the text in whatever font you specify in CSS (e.g. Arial).
For Windows,
You cannot capture packets for Local Loopback in Wireshark however, you can use a very tiny but useful program called RawCap;
Run RawCap on command prompt and select the Loopback Pseudo-Interface (127.0.0.1) then just write the name of the packet capture file (.pcap)
A simple demo is as below;
C:\Users\Levent\Desktop\rawcap>rawcap
Interfaces:
0. 169.254.125.51 Local Area Connection* 12 Wireless80211
1. 192.168.2.254 Wi-Fi Wireless80211
2. 169.254.214.165 Ethernet Ethernet
3. 192.168.56.1 VirtualBox Host-Only Network Ethernet
4. 127.0.0.1 Loopback Pseudo-Interface 1 Loopback
Select interface to sniff [default '0']: 4
Output path or filename [default 'dumpfile.pcap']: test.pcap
Sniffing IP : 127.0.0.1
File : test.pcap
Packets : 48^C
Or you could just do it that way:
public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
....
}
That works for example for forms like this:
<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />
This is the simplest solution :)
You can upload documents to SharePoint libraries using the Object Model or SharePoint Webservices.
Upload using Object Model:
String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/Research/";
String documentLibraryName = "Shared Documents";
using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
// Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
// Commit
myLibrary.Update();
}
}
You can call virtualenv
with python version you want. For example:
python3 -m virtualenv venv
Or alternatively directly point to your virtualenv path. e.g. for windows:
c:\Python34\Scripts\virtualenv.exe venv
And by running:
venv/bin/python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
you can see the python version installed in virtual environment
Following code returns full months between two dates by taking nr of days of partial months into account as well.
var monthDiff = function(d1, d2) {
if( d2 < d1 ) {
var dTmp = d2;
d2 = d1;
d1 = dTmp;
}
var months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
if( d1.getDate() <= d2.getDate() ) months += 1;
return months;
}
monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 20))
> 1
monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 19))
> 0
monthDiff(new Date(2015, 01, 20), new Date(2015, 01, 22))
> 0
First you have to ensure that there is a SMTP server listening on port 25.
To look whether you have the service, you can try using TELNET client, such as:
C:\> telnet localhost 25
(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.
$ telnet localhost 25
If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.
If you don't have the service, you can use these:
If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.
You can actually define your template class inside a .template file rather than a .cpp file. Whoever is saying you can only define it inside a header file is wrong. This is something that works all the way back to c++ 98.
Don't forget to have your compiler treat your .template file as a c++ file to keep the intelli sense.
Here is an example of this for a dynamic array class.
#ifndef dynarray_h
#define dynarray_h
#include <iostream>
template <class T>
class DynArray{
int capacity_;
int size_;
T* data;
public:
explicit DynArray(int size = 0, int capacity=2);
DynArray(const DynArray& d1);
~DynArray();
T& operator[]( const int index);
void operator=(const DynArray<T>& d1);
int size();
int capacity();
void clear();
void push_back(int n);
void pop_back();
T& at(const int n);
T& back();
T& front();
};
#include "dynarray.template" // this is how you get the header file
#endif
Now inside you .template file you define your functions just how you normally would.
template <class T>
DynArray<T>::DynArray(int size, int capacity){
if (capacity >= size){
this->size_ = size;
this->capacity_ = capacity;
data = new T[capacity];
}
// for (int i = 0; i < size; ++i) {
// data[i] = 0;
// }
}
template <class T>
DynArray<T>::DynArray(const DynArray& d1){
//clear();
//delete [] data;
std::cout << "copy" << std::endl;
this->size_ = d1.size_;
this->capacity_ = d1.capacity_;
data = new T[capacity()];
for(int i = 0; i < size(); ++i){
data[i] = d1.data[i];
}
}
template <class T>
DynArray<T>::~DynArray(){
delete [] data;
}
template <class T>
T& DynArray<T>::operator[]( const int index){
return at(index);
}
template <class T>
void DynArray<T>::operator=(const DynArray<T>& d1){
if (this->size() > 0) {
clear();
}
std::cout << "assign" << std::endl;
this->size_ = d1.size_;
this->capacity_ = d1.capacity_;
data = new T[capacity()];
for(int i = 0; i < size(); ++i){
data[i] = d1.data[i];
}
//delete [] d1.data;
}
template <class T>
int DynArray<T>::size(){
return size_;
}
template <class T>
int DynArray<T>::capacity(){
return capacity_;
}
template <class T>
void DynArray<T>::clear(){
for( int i = 0; i < size(); ++i){
data[i] = 0;
}
size_ = 0;
capacity_ = 2;
}
template <class T>
void DynArray<T>::push_back(int n){
if (size() >= capacity()) {
std::cout << "grow" << std::endl;
//redo the array
T* copy = new T[capacity_ + 40];
for (int i = 0; i < size(); ++i) {
copy[i] = data[i];
}
delete [] data;
data = new T[ capacity_ * 2];
for (int i = 0; i < capacity() * 2; ++i) {
data[i] = copy[i];
}
delete [] copy;
capacity_ *= 2;
}
data[size()] = n;
++size_;
}
template <class T>
void DynArray<T>::pop_back(){
data[size()-1] = 0;
--size_;
}
template <class T>
T& DynArray<T>::at(const int n){
if (n >= size()) {
throw std::runtime_error("invalid index");
}
return data[n];
}
template <class T>
T& DynArray<T>::back(){
if (size() == 0) {
throw std::runtime_error("vector is empty");
}
return data[size()-1];
}
template <class T>
T& DynArray<T>::front(){
if (size() == 0) {
throw std::runtime_error("vector is empty");
}
return data[0];
}
A simple way to check if an element exist can be done through one-line code of jQuery.
Here is the code below:
if ($('#elementId').length > 0) {
// Do stuff here if the element exists
} else {
// Do stuff here if the element does not exist
}
Open .dll
file with visual studio. Or resource editor.
You could add the following VBA code to your sheet:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("A1") > 0.5 Then
MsgBox "Discount too high"
End If
End Sub
Every time a cell is changed on the sheet, it will check the value of cell A1.
Notes:
Widor uses a different approach (Worksheet_Calculate
instead of Worksheet_Change
):
Conclusion: use Worksheet_Change
if A1 only depends on data located on the same sheet, use Worksheet_Calculate
if not.
Check out setParseBigDecimal
in DecimalFormat. With this setter, parse
will return a BigDecimal for you.
You can also store the initial value in a data attribute and check it against the current value.
<input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" />
$("#id_someid").keyup(function() {
return $(this).val() == $(this).data().initial;
});
Would return true if the initial value has not changed.
This works too and you dont have to use join or anything:
DROP VIEW IF EXISTS yourview;
CREATE VIEW yourview AS
SELECT table1.column1,
table2.column2
FROM
table1, table2
WHERE table1.column1 = table2.column1;
The SSL certificates are going to be bound to hostname rather than IP if they are setup in the standard way. Hence why it works at one site rather than the other.
Even if the servers share the same hostname they may well have two different certificates and hence WebSphere will have a certificate trust issue as it won't be able to recognise the certificate on the second server as it is different to the first.
Use below command to create a package.json file.
npm init
npm init --yes or -y flag
[This method will generate a default package.json using information extracted from the current directory.]
<?php header("Access-Control-Allow-Origin: http://example.com"); ?>
This command disables only first console warning info
Result: console result
A lot of tutorials/references were written for Python 2 and tell you to use pip install somename. If you're using Python 3 you want to change that to pip3 install somename.
If you're looking for a list of these attributes though, XPath will be your friend
print_r($xml->xpath('@token'));
From the terminal run:
sudo apt-get install python3-numpy
This package contains Numpy for Python 3.
For scipy:
sudo apt-get install python3-scipy
For for plotting graphs use pylab:
sudo apt-get install python3-matplotlib
You missed single quote sign:
SELECT *
FROM TABLENAME
WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM'
Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.
SELECT *
FROM TABLENAME
WHERE
DateTime >= '2011-04-12T00:00:00.000' AND
DateTime <= '2011-05-25T03:53:04.000'
In my case Win 10. the file applicationHost.config is corrupted by VS 2012. And you can get the copy the history of this file under C:\inetpub\history. Then restart IIS and it works properly.
Facebook does not allow you to change the "What's on your mind?" text box, unless of course you're developing an application for use on Facebook.
This is completely new working code with sample AJAX call.
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<div>
<div id="project-label">Select a project (type "j" for a start):</div>
<img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="" />
<input id="project" />
<input type="hidden" id="project-i" />
</div>
@*Auto Complete*@
<script>
$(function () {
$("#project").autocomplete({
minLength: 0,
source : function( request, response ) {
$.ajax({
url: "http://jsonplaceholder.typicode.com/posts/1/comments",
dataType: "jsonp",
data: {
q: request.term
},
success: function (data) {
response( data );
}
});
},
focus: function (event, ui) {
$("#project").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#project").val(ui.item.name);
$("#project-id").val(ui.item.email);
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a> " + item.name + "<br>" + item.email + "</a>")
.appendTo(ul);
};
});
</script>
You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:
$query = DB::table('category_issue')
->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
->where('category_id', '=', 1)
->join('issues', 'category_issue.issue_id', '=', 'issues.id')
->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
->group_by('issues.id')
->order_by('followers', 'desc')
->get();
Simple ways to check an empty dict are below:
a= {}
1. if a == {}:
print ('empty dict')
2. if not a:
print ('empty dict')
Although method 1st is more strict as when a = None, method 1 will provide correct result but method 2 will give an incorrect result.
Instead of nohup
, you should use screen
. It achieves the same result - your commands are running "detached". However, you can resume screen sessions and get back into their "hidden" terminal and see recent progress inside that terminal.
screen
has a lot of options. Most often I use these:
To start first screen session or to take over of most recent detached one:
screen -Rd
To detach from current session: Ctrl+ACtrl+D
You can also start multiple screens - read the docs.
Same basic solution as others, but I personally prefer to use map instead of the list comprehension:
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'
After making above improvement such as checking if mysql service
is running or not, you just need to give a small password while creating connection, it is ' '
or 1 time press on space-bar in case of GUI or workbench. After which you just need to validate your machine with server (validated HOST). For that purpose click on 'New Server Instance'
and it will configure server/HOST on your behalf itself.
I have done this successfully just a few couple of minutes ago. My workbench software is able to show all pre-installed databases
etc now.
hope it will work for you as well.
Thanks!!!
You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3)
. If you get an error, you don't have the right version.
For example, DATETIME(3)
will give you millisecond resolution in your timestamps, and TIMESTAMP(6)
will give you microsecond resolution on a *nix-style timestamp.
Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html
NOW(3)
will give you the present time from your MySQL server's operating system with millisecond precision.
If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value
FROM_UNIXTIME(ms * 0.001)
Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.
(Notice that MySQL internal fractional arithmetic, like * 0.001
, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)
If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.
If, for some reason you can't upgrade, you could consider using BIGINT
or DOUBLE
columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001)
will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000
The function you're after is numpy.linalg.norm
. (I reckon it should be in base numpy as a property of an array -- say x.norm()
-- but oh well).
import numpy as np
x = np.array([1,2,3,4,5])
np.linalg.norm(x)
You can also feed in an optional ord
for the nth order norm you want. Say you wanted the 1-norm:
np.linalg.norm(x,ord=1)
And so on.
$config['cricket'] = 'bat';
in config.php file
$this->config->item('cricket')
use this in view
div.section > div
When you pass the the System.Drawing.Image
type object to a method you are actually passing a copy of reference to that object.
So if inside that method you are loading a new image you are loading using new/copied reference. You are not making change in original.
YourMethod(System.Drawing.Image image)
{
//now this image is a new reference
//if you load a new image
image = new Image()..
//you are not changing the original reference you are just changing the copy of original reference
}
The key here is the name
attribute of the f
object representing the opened file. You get it like that:
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> f.name
'/Users/Desktop/febROSTER2012.xls'
Does it help?
int screenResolution = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(""+screenResolution);
Use the strong element, that is it's purpose:
<div id="content">
<p><strong>First Word</strong> rest of paragraph.</p>
</div>
Then create a style for it in your style sheet.
#content p strong
{
font-size: 14pt;
}
I found a problem: considering the next situation: 2.1 or 1.2 or -6.4
What if you want always 3 decimals or two or wharever, so, you have to complete the leading zeros to the right
// 3 decimals numbers
0.5 => 0.500
// 6 decimals
0.1 => 0.10000
// 4 decimales
-2.1 => -2.1000
// truncate to 3 decimals
3.11568 => 3.115
This is the fixed function of Nick Knowlson
function truncateDecimals (num, digits)
{
var numS = num.toString();
var decPos = numS.indexOf('.');
var substrLength = decPos == -1 ? numS.length : 1 + decPos + digits;
var trimmedResult = numS.substr(0, substrLength);
var finalResult = isNaN(trimmedResult) ? 0 : trimmedResult;
// adds leading zeros to the right
if (decPos != -1){
var s = trimmedResult+"";
decPos = s.indexOf('.');
var decLength = s.length - decPos;
while (decLength <= digits){
s = s + "0";
decPos = s.indexOf('.');
decLength = s.length - decPos;
substrLength = decPos == -1 ? s.length : 1 + decPos + digits;
};
finalResult = s;
}
return finalResult;
};
I suggest that you add
#!/usr/bin/env python
instead of #!/usr/bin/python
at the top of the file. The reason for this is that the python installation may be in different folders in different distros or different computers. By using env
you make sure that the system finds python and delegates the script's execution to it.
As said before to make the script executable, something like:
chmod u+x name_of_script.py
should do.
I found this question when searching for You are in 'detached HEAD' state.
After analyzing what I had done to get here, as compared with what I had done in the past, I discovered that I had made a mistake.
My normal flow is:
git checkout master
git fetch
git checkout my-cool-branch
git pull
This time I did:
git checkout master
git fetch
git checkout origin/my-cool-branch
# You are in 'detached HEAD' state.
The problem is that I accidentally did:
git checkout origin/my-cool-branch
Rather than:
git checkout my-cool-branch
The fix (in my situation) was simply to run the above command and then continue the flow:
git checkout my-cool-branch
git pull
In React all you need is:
<img
src={}
onMouseDown={(e) => {
e.preventDefault();
// other code
}}
/>
ActiveWorkbook.FullName would be better I think, in case you have the VBA Macro stored in another Excel Workbook, but you want to get the details of the Excel you are editing, not where the Macro resides.
If they reside in the same file, then it does not matter, but if they are in different files, and you want the file where the Data is rather than where the Macro is, then ActiveWorkbook is the one to go for, because it deals with both scenarios.
thank you, your first error guides me here and the solution solve mine too!
for permission error, f = open('output', 'w+')
, change it into f = open(output+'output', 'w+')
.
or something else, but the way you are now using is having access to the installation directory of Python which normally in Program Files, and it probably needs administrator permission.
for sure, you could probably running python/your script as administrator to pass permission error though
Use -1
index (negative indices count backward from the end of the array):
a[-1] # => 5
b[-1] # => 6
or Array#last
method:
a.last # => 5
b.last # => 6
And for those of you using an anonymous expression:
await Task.Run(async () =>
{
SQLLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupname);
});
I recommend trying the Java OCR project on sourceforge.net. I originally developed it, and I have a blog posting on it.
Since I put it up on sourceforge, its functionality been expanded and improved quite a bit through the great work of a volunteer researcher/developer.
Give it a try, and if you don't like it, you can always improve it!
From my experience, I used GridLayout.
thePanel.setLayout(new GridLayout(a,b,c,d));
a = row number, b = column number, c = horizontal gap, d = vertical gap.
For example, if I want to create panel with:
The code is below:
thePanel.setLayout(new GridLayout(0,1,0,3));
This method is useful when you want to add JScrollPane to your JPanel. Size of the JPanel inside JScrollPane will automatically changes when you add some components on it, so the JScrollPane will automatically reset the scroll bar.
You can use
adb shell ps | grep apps | awk '{print $9}'
to produce an output like:
com.google.process.gapps
com.google.android.apps.uploader
com.google.android.apps.plus
com.google.android.apps.maps
com.google.android.apps.maps:GoogleLocationService
com.google.android.apps.maps:FriendService
com.google.android.apps.maps:LocationFriendService
adb shell ps returns a list of all running processes on the android device, grep apps searches for any row with contains "apps", as you can see above they are all com.google.android.APPS. or GAPPS, awk extracts the 9th column which in this case is the package name.
To search for a particular package use
adb shell ps | grep PACKAGE.NAME.HERE | awk '{print $9}'
i.e adb shell ps | grep com.we7.player | awk '{print $9}'
If it is running the name will appear, if not there will be no result returned.
In my case the sqlite db file db.sqlite3
was stored in the DocumentRoot
of apache. So, even after setting the following permissions it didn't work:
sudo chown www-data:www-data /path/to/db-folder
sudo chown www-data:www-data /path/to/db-folder/sqlite-db.db
Finally when i moved db.sqlite3
to a newly created folder dbfolder
under DocumentRoot
and gave the above permissions, and it worked.
I would suggest not to use list-style-image
, as it behaves quite differently in different browsers, especially the image position
instead, you can use something like this
ol.widgets,
ol.widgets li { list-style: none; }
ol.widgets li { padding-left: 20px; backgroud: transparent ("image") no-repeat x y; }
it works in all browsers and would give you the identical result in different browsers.
Click "query tool" button in the list of "tool".
And then click the "open file" image button in the tool bar.
If you're running Linux I would suggest two tools:
align_image_stack from package hugin-tools - is a commandline program that can automatically correct rotation, scaling, and other distortions (it's mostly intended for compositing HDR photography, but works for video frames and other documents too). More information: http://hugin.sourceforge.net/docs/manual/Align_image_stack.html
compare from package imagemagick - a program that can find and count the amount of different pixels in two images. Here's a neat tutorial: http://www.imagemagick.org/Usage/compare/ uising the -fuzz N% you can increase the error tolerance. The higher the N the higher the error tolerance to still count two pixels as the same.
align_image_stack should correct any offset so the compare command will actually have a chance of detecting same pixels.
Use the method setAnimation(null) to stop an animation, it exposed as public method in
View.java, it is the base class for all widgets, which are used to create interactive UI components (buttons, text fields, etc.).
/**
* Sets the next animation to play for this view.
* If you want the animation to play immediately, use
* {@link #startAnimation(android.view.animation.Animation)} instead.
* This method provides allows fine-grained
* control over the start time and invalidation, but you
* must make sure that 1) the animation has a start time set, and
* 2) the view's parent (which controls animations on its children)
* will be invalidated when the animation is supposed to
* start.
*
* @param animation The next animation, or null.
*/
public void setAnimation(Animation animation)
Another simple solution is to add jackson-databind dependency in POM.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
Keep Rest of the code as it is.
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
I've created a bit of an adaptation of script @devnull69 submitted. I felt for my application it would be more useful as a function that returned the value that I could, then use as a variable.
HTML
<input type="text" id="time_field" />
<button>Submit</submit>
jQuery
$(document).ready(function() {
function convertTime(time) {
var hours = Number(time.match(/^(\d\d?)/)[1]);
var minutes = Number(time.match(/:(\d\d?)/)[1]);
var AMPM = time.match(/\s(AM|PM)$/i)[1];
if((AMPM == 'PM' || AMPM == 'pm') && hours < 12) {
hours = hours + 12;
}
else if((AMPM == 'AM' || AMPM == "am") && hours == 12) {
hours = hours - 12;
}
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours < 10) {
sHours = "0" + sHours;
}
else if(minutes < 10) {
sMinutes = "0" + sMinutes;
}
return sHours + ":" + sMinutes;
}
$('button').click(function() {
alert(convertTime($('#time_field').val()));
});
});
While padding programmatically, convert to density related values by converting pixel to Dp.
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
I like Keith Hill's answer except it has a bug that prevents it from recursing past two levels. These commands manifest the bug:
New-Item level1/level2/level3/level4/foobar.txt -Force -ItemType file
cd level1
GetFiles . xyz | % { $_.fullname }
With Hill's original code you get this:
...\level1\level2
...\level1\level2\level3
Here is a corrected, and slightly refactored, version:
function GetFiles($path = $pwd, [string[]]$exclude)
{
foreach ($item in Get-ChildItem $path)
{
if ($exclude | Where {$item -like $_}) { continue }
$item
if (Test-Path $item.FullName -PathType Container)
{
GetFiles $item.FullName $exclude
}
}
}
With that bug fix in place you get this corrected output:
...\level1\level2
...\level1\level2\level3
...\level1\level2\level3\level4
...\level1\level2\level3\level4\foobar.txt
I also like ajk's answer for conciseness though, as he points out, it is less efficient. The reason it is less efficient, by the way, is because Hill's algorithm stops traversing a subtree when it finds a prune target while ajk's continues. But ajk's answer also suffers from a flaw, one I call the ancestor trap. Consider a path such as this that includes the same path component (i.e. subdir2) twice:
\usr\testdir\subdir2\child\grandchild\subdir2\doc
Set your location somewhere in between, e.g. cd \usr\testdir\subdir2\child
, then run ajk's algorithm to filter out the lower subdir2
and you will get no output at all, i.e. it filters out everything because of the presence of subdir2
higher in the path. This is a corner case, though, and not likely to be hit often, so I would not rule out ajk's solution due to this one issue.
Nonetheless, I offer here a third alternative, one that does not have either of the above two bugs. Here is the basic algorithm, complete with a convenience definition for the path or paths to prune--you need only modify $excludeList
to your own set of targets to use it:
$excludeList = @("stuff","bin","obj*")
Get-ChildItem -Recurse | % {
$pathParts = $_.FullName.substring($pwd.path.Length + 1).split("\");
if ( ! ($excludeList | where { $pathParts -like $_ } ) ) { $_ }
}
My algorithm is reasonably concise but, like ajk's, it is less efficient than Hill's (for the same reason: it does not stop traversing subtrees at prune targets). However, my code has an important advantage over Hill's--it can pipeline! It is therefore amenable to fit into a filter chain to make a custom version of Get-ChildItem while Hill's recursive algorithm, through no fault of its own, cannot. ajk's algorithm can be adapted to pipeline use as well, but specifying the item or items to exclude is not as clean, being embedded in a regular expression rather than a simple list of items that I have used.
I have packaged my tree pruning code into an enhanced version of Get-ChildItem. Aside from my rather unimaginative name--Get-EnhancedChildItem--I am excited about it and have included it in my open source Powershell library. It includes several other new capabilities besides tree pruning. Furthermore, the code is designed to be extensible: if you want to add a new filtering capability, it is straightforward to do. Essentially, Get-ChildItem is called first, and pipelined into each successive filter that you activate via command parameters. Thus something like this...
Get-EnhancedChildItem –Recurse –Force –Svn
–Exclude *.txt –ExcludeTree doc*,man -FullName -Verbose
... is converted internally into this:
Get-ChildItem | FilterExcludeTree | FilterSvn | FilterFullName
Each filter must conform to certain rules: accepting FileInfo and DirectoryInfo objects as inputs, generating the same as outputs, and using stdin and stdout so it may be inserted in a pipeline. Here is the same code refactored to fit these rules:
filter FilterExcludeTree()
{
$target = $_
Coalesce-Args $Path "." | % {
$canonicalPath = (Get-Item $_).FullName
if ($target.FullName.StartsWith($canonicalPath)) {
$pathParts = $target.FullName.substring($canonicalPath.Length + 1).split("\");
if ( ! ($excludeList | where { $pathParts -like $_ } ) ) { $target }
}
}
}
The only additional piece here is the Coalesce-Args function (found in this post by Keith Dahlby), which merely sends the current directory down the pipe in the event that the invocation did not specify any paths.
Because this answer is getting somewhat lengthy, rather than go into further detail about this filter, I refer the interested reader to my recently published article on Simple-Talk.com entitled Practical PowerShell: Pruning File Trees and Extending Cmdlets where I discuss Get-EnhancedChildItem at even greater length. One last thing I will mention, though, is another function in my open source library, New-FileTree, that lets you generate a dummy file tree for testing purposes so you can exercise any of the above algorithms. And when you are experimenting with any of these, I recommend piping to % { $_.fullname }
as I did in the very first code fragment for more useful output to examine.
I created a more developed jQuery plugin that allows you to lock or unlock the map with a nice button.
This plugin disables the Google Maps iframe with a transparent overlay div and adds a button for unlockit. You must press for 650 milliseconds to unlock it.
You can change all the options for your convenience. Check it at https://github.com/diazemiliano/googlemaps-scrollprevent
Here's some example.
(function() {_x000D_
$(function() {_x000D_
$("#btn-start").click(function() {_x000D_
$("iframe[src*='google.com/maps']").scrollprevent({_x000D_
printLog: true_x000D_
}).start();_x000D_
return $("#btn-stop").click(function() {_x000D_
return $("iframe[src*='google.com/maps']").scrollprevent().stop();_x000D_
});_x000D_
});_x000D_
return $("#btn-start").trigger("click");_x000D_
});_x000D_
}).call(this);
_x000D_
.embed-container {_x000D_
position: relative !important;_x000D_
padding-bottom: 56.25% !important;_x000D_
height: 0 !important;_x000D_
overflow: hidden !important;_x000D_
max-width: 100% !important;_x000D_
}_x000D_
.embed-container iframe {_x000D_
position: absolute !important;_x000D_
top: 0 !important;_x000D_
left: 0 !important;_x000D_
width: 100% !important;_x000D_
height: 100% !important;_x000D_
}_x000D_
.mapscroll-wrap {_x000D_
position: static !important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.rawgit.com/diazemiliano/googlemaps-scrollprevent/v.0.6.5/dist/googlemaps-scrollprevent.min.js"></script>_x000D_
<div class="embed-container">_x000D_
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d12087.746318586604!2d-71.64614110000001!3d-40.76341959999999!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x9610bf42e48faa93%3A0x205ebc786470b636!2sVilla+la+Angostura%2C+Neuqu%C3%A9n!5e0!3m2!1ses-419!2sar!4v1425058155802"_x000D_
width="400" height="300" frameborder="0" style="border:0"></iframe>_x000D_
</div>_x000D_
<p><a id="btn-start" href="#">"Start Scroll Prevent"</a> <a id="btn-stop" href="#">"Stop Scroll Prevent"</a>_x000D_
</p>
_x000D_
Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.
I had the same problem and solved by using Newtonsoft.Json;
var list = JsonConvert.SerializeObject(model,
Formatting.None,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return Content(list, "application/json");
I've found a way to pass parent data to component scope in Vue, i think it's a little a bit of a hack but maybe this will help you.
1) Reference data in Vue Instance as an external object (data : dataObj)
2) Then in the data return function in the child component just return parentScope = dataObj
and voila. Now you cann do things like {{ parentScope.prop }}
and will work like a charm.
Good Luck!
You are converting cert into BKS Keystore, why aren't you using .cert
directly, from https://developer.android.com/training/articles/security-ssl.html:
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream instream = context.getResources().openRawResource(R.raw.gtux_cert);
Certificate ca;
try {
ca = cf.generateCertificate(instream);
} finally {
caInput.close();
}
KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
kStore.load(null, null);
kStore.setCertificateEntry("ca", ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(););
tmf.init(kStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
okHttpClient.setSslSocketFactory(context.getSocketFactory());
Here is another alternative that shouldn't perform too badly (because of deferred execution):
new string(mystring.Reverse().Take(4).Reverse().ToArray());
Although an extension method for the purpose mystring.Last(4)
is clearly the cleanest solution, albeit a bit more work.
This is difficult with worksheet functions because dates in excel are simply formatted numbers - only CELL
function lets you investigate the format of a cell (and you can't apply that to a range, so a helper column would be required).......or, if you only have dates and blanks.....or dates and text then it would be sufficient to use COUNT
function, i.e.
=COUNT(range)
That counts numbers so it won't be adequate if you want to distinguish dates from numbers. If you do then the number range could be utilised, e.g. if you have numbers in a range and dates but the numbers will all be lower than 10,000 and the dates will all be relatively recent then you could use this version to exclude the numbers
=COUNTIF(range,">10000")
according to High Performance MySQL book:
VARCHAR stores variable-length character strings and is the most common string data type. It can require less storage space than fixed-length types, because it uses only as much space as it needs (i.e., less space is used to store shorter values). The exception is a MyISAM table created with ROW_FORMAT=FIXED, which uses a fixed amount of space on disk for each row and can thus waste space. VARCHAR helps performance because it saves space.
CHAR is fixed-length: MySQL always allocates enough space for the specified number of characters. When storing a CHAR value, MySQL removes any trailing spaces. (This was also true of VARCHAR in MySQL 4.1 and older versions—CHAR and VAR CHAR were logically identical and differed only in storage format.) Values are padded with spaces as needed for comparisons.
I had the same error which was coming and dont need to worry about this error, just restart the server and restart the SQL services. This issue comes when there is low disk space issue and system will go into hung state and then the sql services will stop automatically.
I simulate the actual string replacement that's about to happen to calculate that future string's length:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if([newString length] > maxLength)
return NO;
return YES;
}
You can use closures to pass parameters:
iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);
However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):
document.getElementById("myFrame").contentDocument.addEventListener(...);
Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio
# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
# Grab the image size and initialize dimensions
dim = None
(h, w) = image.shape[:2]
# Return original image if no need to resize
if width is None and height is None:
return image
# We are resizing height if width is none
if width is None:
# Calculate the ratio of the height and construct the dimensions
r = height / float(h)
dim = (int(w * r), height)
# We are resizing width if height is none
else:
# Calculate the ratio of the width and construct the dimensions
r = width / float(w)
dim = (width, int(h * r))
# Return the resized image
return cv2.resize(image, dim, interpolation=inter)
Usage
import cv2
image = cv2.imread('1.png')
cv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))
cv2.imshow('width_300', maintain_aspect_ratio_resize(image, width=300))
cv2.waitKey()
Using this example image
Simply downscale to width=100
(left) or upscale to width=300
(right)
I want to contribute an answer here as I too have faced the same issue - we want the $_FILES element available as part of the same post as another form. My answer is based on @mrtnmgs however notes the comments added to that question.
Firstly: Dropzone posts its data via ajax
Just because you use the formData.append
option still means that you must tackle the UX actions - i.e. this all happens behind the scenes and isn't a typical form post. Data is posted to your url
parameter.
Secondly: If you therefore want to mimic a form post you will need to store the posted data
This requires server side code to store your $_POST
or $_FILES
in a session which is available to the user on another page load as the user will not go to the page where the posted data is received.
Thirdly: You need to redirect the user to the page where this data is actioned
Now you have posted your data, stored it in a session, you need to display/action it for the user in an additional page. You need to send the user to that page as well.
So for my example:
[Dropzone code: Uses Jquery]
$('#dropArea').dropzone({
url: base_url+'admin/saveProject',
maxFiles: 1,
uploadMultiple: false,
autoProcessQueue:false,
addRemoveLinks: true,
init: function(){
dzClosure = this;
$('#projectActionBtn').on('click',function(e) {
dzClosure.processQueue(); /* My button isn't a submit */
});
// My project only has 1 file hence not sendingmultiple
dzClosure.on('sending', function(data, xhr, formData) {
$('#add_user input[type="text"],#add_user textarea').each(function(){
formData.append($(this).attr('name'),$(this).val());
})
});
dzClosure.on('complete',function(){
window.location.href = base_url+'admin/saveProject';
})
},
});
When you call notify() from an object t, java notifies a particular t.wait() method. But, how does java search and notify a particular wait method.
java only looks into the synchronized block of code which was locked by object t. java cannot search the whole code to notify a particular t.wait().
Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.
The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.
Using the google maps projection api to draw the polylines on an overlay view enables us to do a lot of things. Check this repo that has an example.
When you need to debug, use printf with %p
option is really helpful. You see 0x0 when you have a NULL value.
I know this is already answered, but none of the current answers make any mention of namespacing and how it affects constants and defines.
As of PHP 5.3, consts and defines are similar in most respects. There are still, however, some important differences:
const FOO = 4 * 3;
doesn't work, but define('CONST', 4 * 3);
does. define
must include the namespace to be defined within that namespace.The code below should illustrate the differences.
namespace foo
{
const BAR = 1;
define('BAZ', 2);
define(__NAMESPACE__ . '\\BAZ', 3);
}
namespace {
var_dump(get_defined_constants(true));
}
The content of the user sub-array will be ['foo\\BAR' => 1, 'BAZ' => 2, 'foo\\BAZ' => 3]
.
=== UPDATE ===
The upcoming PHP 5.6 will allow a bit more flexibility with const
. You will now be able to define consts in terms of expressions, provided that those expressions are made up of other consts or of literals. This means the following should be valid as of 5.6:
const FOOBAR = 'foo ' . 'bar';
const FORTY_TWO = 6 * 9; // For future editors: THIS IS DELIBERATE! Read the answer comments below for more details
const ULTIMATE_ANSWER = 'The ultimate answer to life, the universe and everything is ' . FORTY_TWO;
You still won't be able to define consts in terms of variables or function returns though, so
const RND = mt_rand();
const CONSTVAR = $var;
will still be out.
I could not find an exact solution to this question so i'll post my solution in case it may be of any help using stantard Calendar and datetime libs. this works for add and substract months, and accounts for month-end rolls and cases where the final month has less days than the initial one. I also have a more generalized solution if you are looking for more complex manipulation, it adds regular intervals (days, months, years, quarters, semeters, etc) like: '1m', '-9m', '-1.5y', '-3q', '1s' etc.
from datetime import datetime
from calendar import monthrange
def date_bump_months(start_date, months):
"""
bumps months back and forth.
--> if initial date is end-of-month, i will move to corresponding month-end
--> ir inital date.day is greater than end of month of final date, it casts it to momth-end
"""
signbit = -1 if months < 0 else 1
d_year, d_month = divmod(abs(months),12)
end_year = start_date.year + d_year*signbit
end_month = 0
if signbit ==-1:
if d_month < start_date.month:
end_month = start_date.month - d_month
else:
end_year -=1
end_month = 12 - (d_month - start_date.month)
else:
end_month +=start_date.month
if end_month > 12:
end_year +=1
end_month -=12
# check if we are running end-of-month dates
eom_run = monthrange(start_date.year, start_date.month)[1]==start_date.day
eom_month = monthrange((end_year), (end_month))[1]
if eom_run:
end_day = eom_month
else:
end_day = min(start_date.day, eom_month )
return date(end_year, end_month, end_day)
There is a correct way of uploading a file with its name with Retrofit 2, without any hack:
Define API interface:
@Multipart
@POST("uploadAttachment")
Call<MyResponse> uploadAttachment(@Part MultipartBody.Part filePart);
// You can add other parameters too
Upload file like this:
File file = // initialize file here
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
Call<MyResponse> call = api.uploadAttachment(filePart);
This demonstrates only file uploading, you can also add other parameters in the same method with @Part
annotation.
Select select = new Select(driver.findElement(By.id("searchDropdownBox")));
select.getOptions();//will get all options as List<WebElement>
The json module is a good solution here. It has the advantages over pickle that it only produces plain text output, and is cross-platform and cross-version.
import json
json.dumps(dict)
Don't forget to go to your device and enable Settings->Developer Options->USB debugging.
There was an error in understanding of return Type Just add Header and it will solve your problem
@Headers("Content-Type: application/json")
AFAIK, you have to convert it to grayscale and then threshold it to binary.
1. Read the image as a grayscale image If you're reading the RGB image from disk, then you can directly read it as a grayscale image, like this:
// C
IplImage* im_gray = cvLoadImage("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);
// C++ (OpenCV 2.0)
Mat im_gray = imread("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);
2. Convert an RGB image im_rgb
into a grayscale image: Otherwise, you'll have to convert the previously obtained RGB image into a grayscale image
// C
IplImage *im_rgb = cvLoadImage("image.jpg");
IplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);
cvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);
// C++
Mat im_rgb = imread("image.jpg");
Mat im_gray;
cvtColor(im_rgb,im_gray,CV_RGB2GRAY);
3. Convert to binary You can use adaptive thresholding or fixed-level thresholding to convert your grayscale image to a binary image.
E.g. in C you can do the following (you can also do the same in C++ with Mat and the corresponding functions):
// C
IplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);
cvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
// C++
Mat img_bw = im_gray > 128;
In the above example, 128 is the threshold.
4. Save to disk
// C
cvSaveImage("image_bw.jpg",img_bw);
// C++
imwrite("image_bw.jpg", img_bw);
SUM is used to sum the value in a column for multiple rows. You can just add your columns together:
select tblExportVertexCompliance.TotalDaysOnIncivek + tblExportVertexCompliance.IncivekDaysOtherSource AS [Total Days on Incivek]
Along with the _countof() macro you can refer to the array size using pointer notation, where the array name by itself refers to the row, the indirection operator appended by the array name refers to the column.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int beans[3][4]{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
cout << "Row size = " << _countof(beans) // Output row size
<< "\nColumn size = " << _countof(*beans); // Output column size
cout << endl;
// Used in a for loop with a pointer.
int(*pbeans)[4]{ beans };
for (int i{}; i < _countof(beans); ++i) {
cout << endl;
for (int j{}; j < _countof(*beans); ++j) {
cout << setw(4) << pbeans[i][j];
}
};
cout << endl;
}
Online index rebuilds are less intrusive when it comes to locking tables. Offline rebuilds cause heavy locking of tables which can cause significant blocking issues for things that are trying to access the database while the rebuild takes place.
"Table locks are applied for the duration of the index operation [during an offline rebuild]. An offline index operation that creates, rebuilds, or drops a clustered, spatial, or XML index, or rebuilds or drops a nonclustered index, acquires a Schema modification (Sch-M) lock on the table. This prevents all user access to the underlying table for the duration of the operation. An offline index operation that creates a nonclustered index acquires a Shared (S) lock on the table. This prevents updates to the underlying table but allows read operations, such as SELECT statements."
http://msdn.microsoft.com/en-us/library/ms188388(v=sql.110).aspx
Additionally online index rebuilds are a enterprise (or developer) version only feature.
var decPlaces = (int)(((decimal)number % 1) * 100);
This presumes your number only has two decimal places.
Maybe you should have a look at Mapquests Traffic API: http://www.mapquestapi.com/traffic/
The webservice is unfortunately only available for some citys in the US, I think. But probably it solves your problem.
I will put a small comparison table here (just to have it somewhere):
Servlet is mapped as /test%3F/*
and the application is deployed under /app
.
http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a
Method URL-Decoded Result
----------------------------------------------------
getContextPath() no /app
getLocalAddr() 127.0.0.1
getLocalName() 30thh.loc
getLocalPort() 8480
getMethod() GET
getPathInfo() yes /a?+b
getProtocol() HTTP/1.1
getQueryString() no p+1=c+d&p+2=e+f
getRequestedSessionId() no S%3F+ID
getRequestURI() no /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL() no http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme() http
getServerName() 30thh.loc
getServerPort() 8480
getServletPath() yes /test?
getParameterNames() yes [p 2, p 1]
getParameter("p 1") yes c d
In the example above the server is running on the localhost:8480
and the name 30thh.loc
was put into OS hosts
file.
Comments
"+" is handled as space only in the query string
Anchor "#a" is not transferred to the server. Only the browser can work with it.
If the url-pattern
in the servlet mapping does not end with *
(for example /test
or *.jsp
), getPathInfo()
returns null
.
If Spring MVC is used
Method getPathInfo()
returns null
.
Method getServletPath()
returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b
Be careful with URL encoded parts of @RequestMapping
and @RequestParam
in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.
This is made to assign a default value, in this case the value of y
, if the x
variable is falsy.
The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.
The Logical OR operator (||
) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.
For example:
"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"
Falsy values are those who coerce to false
when used in boolean context, and they are 0
, null
, undefined
, an empty string, NaN
and of course false
.
In my specific case I had to stop ENTER from submitting the form and also simulate the clicking of the submit button. This is because the submit button had a click handler on it because we were within a modal window (inherited old code). In any case here's my combo solutions for this case.
$('input,select').keypress(function(event) {
// detect ENTER key
if (event.keyCode == 13) {
// simulate submit button click
$("#btn-submit").click();
// stop form from submitting via ENTER key press
event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
});
This use case is specifically useful for people working with IE8.
Its just to save a byte of data when we do javascript minification.
consider the below anonymous function
function (){}
To make the above as self invoking function we will generally change the above code as
(function (){}())
Now we added two extra characters (,)
apart from adding ()
at the end of the function which necessary to call the function. In the process of minification we generally focus to reduce the file size. So we can also write the above function as
!function (){}()
Still both are self invoking functions and we save a byte as well. Instead of 2 characters (,)
we just used one character !
Try making a boot directory in PHP, as in
<?PHP
$ip = $_SERVER['REMOTE_ADDR'];
$privacy = ['BOOTSTRAP_CONFIG'];
$shell = ['BOOTSTRAP_OUTPUT'];
enter code here
if $ip == $privacy {
function $privacy int $ip = "https://";
} endif {
echo $shell
}
?>
Thats mainly it!
There are pre-release (beta) versions of NCover available for free. They work fine for most cases, especially when combined with NCoverExplorer.
If you are using more animation attributes the shorthand is:
animation: bubble 2s linear 0.5s 1 normal forwards;
This gives:
bubble
animation name2s
durationlinear
timing-function0.5s
delay1
iteration-count (can be 'infinite
')normal
directionforwards
fill-mode (set 'backwards' if you want to have compatibility to use the end position as the final state[this is to support browsers that has animations turned off]{and to answer only the title, and not your specific case})This reply is on a very old question to help others facing this issue.
I face this failed error while I were working on my Java
project using IntelliJ IDEA
IDE.
Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-cli) on project getpassword: The packaging for this project did not assign a file to the build artifact
this failed happens, when I choose install:install
under Plugins - install
, as pointed with red arrow in below image.
Once I run the selected install
under Lifecycle
as illustrated above, the issue gone, and my maven install compile build successfully.
passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.
no, you need to do something like:
$('input.sitebg').val('000000');
but you should really be using unique IDs if you can.
You can also get more specific, such as:
$('input[type=text].sitebg').val('000000');
EDIT:
do this to find your input based on the name attribute:
$('input[name=sitebg]').val('000000');
Python is not purely lexically scoped.
See this: Using global variables in a function
and this: https://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/
I could be mistaken, but I think Applescript Terminal integration is a one-shot deal...That is, each do script
call is like opening a different terminal window, so I don't think you can interact with it at all.
You could copy over the SSH public keys to prevent the password prompt, then execute all the commands joined together (warning: the following is totally untested):
tell application "Terminal"
activate
do script "ssh [email protected] '/home/jdoe/dosomestuff.sh && /home/jdoe/dosomemorestuff.sh'"
end tell
Alternatively, you could wrap the ssh and subsequent commands in a shell script using Expect, and then call said shell script from your Applescript.
So far best solution that I've made:
function convertHtmlToJQueryObject(html){
var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
return $(htmlDOMObject.documentElement);
}
I have the same problem on my virtual environment after upgrade python installation from 3.6 to 3.7 but only on vent globally pip work fine, to solve it I deactivate and delete my virtual environment after recreate again and now is fine, on venv:
deactivate
rm -rvf venv
and after recreate the virtual environment. I use mac OS 10.11, and python 3
Alternatively, I would suggest turning interactive on in the beginning and at the very last plot, turn it off. All will show up, but they will not disappear as your program will stay around until you close the figures.
import matplotlib.pyplot as plt
from matplotlib import interactive
plt.figure(1)
... code to make figure (1)
interactive(True)
plt.show()
plt.figure(2)
... code to make figure (2)
plt.show()
plt.figure(3)
... code to make figure (3)
interactive(False)
plt.show()
\includegraphics<1>{A}%
\includegraphics<2>{B}%
\includegraphics<3>{C}%
The % is important. This will keep all the images fixed.
There is no (standard) cross-platform way to do this. On windows, try using conio.h
.
It has the:
textcolor(); // and
textbackground();
functions.
For example:
textcolor(RED);
cprintf("H");
textcolor(BLUE);
cprintf("e");
// and so on.
Yes, you either need to do this onload
or in a <script>
tag after the closing </body>
tag, when the lc
element is already found in the document's DOM tree.
You can always escape the reserved keyword if you still want to make your query work!!
Just replace end with `end`
Here is the list of reserved keywords https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL
CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
"dynamodb.column.mapping" = "cid:cid,end:end,category:category");
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country()
{
Cities = new List<City>();
}
}
public class City
{
public string Name { get; set; }
}
List<Country> Countries = new List<Country>
{
new Country
{
Name = "Germany",
Cities =
{
new City {Name = "Berlin"},
new City {Name = "Hamburg"}
}
},
new Country
{
Name = "England",
Cities =
{
new City {Name = "London"},
new City {Name = "Birmingham"}
}
}
};
bindingSource1.DataSource = Countries;
member_CountryComboBox.DataSource = bindingSource1.DataSource;
member_CountryComboBox.DisplayMember = "Name";
member_CountryCombo
Box.ValueMember = "Name";
This is the code I am using now.
The official support page should answer your question.
So in your .gitignore
you might ignore the files ending with .iws
, and the workspace.xml
and tasks.xml
files.
the Correct Solution Would be like this
QString k;
k = "CRAZYYYQT";
char ab[16];
sprintf(ab,"%s",(const char *)((QByteArray)(k.toLatin1()).data()) );
sprintf(ab,"%s",(const char *)((QByteArray)(k.toStdString()).data()));
sprintf(ab,"%s",(const char *)k.toStdString().c_str() );
qDebug()<<"--->"<<ab<<"<---";
Maybe a more simple solution.
if ($(document).height() > $(window).height()) {
// scrollbar
}
What's probably happening is that React thinks that only one MyInput
(unemployment-duration
) is added between the renders. As such, the job-title
never gets replaced with the unemployment-reason
, which is also why the predefined values are swapped.
When React does the diff, it will determine which components are new and which are old based on their key
property. If no such key is provided in the code, it will generate its own.
The reason why the last code snippet you provide works is because React essentially needs to change the hierarchy of all elements under the parent div
and I believe that would trigger a re-render of all children (which is why it works). Had you added the span
to the bottom instead of the top, the hierarchy of the preceding elements wouldn't change, and those element's wouldn't re-render (and the problem would persist).
Here's what the official React documentation says:
The situation gets more complicated when the children are shuffled around (as in search results) or if new components are added onto the front of the list (as in streams). In these cases where the identity and state of each child must be maintained across render passes, you can uniquely identify each child by assigning it a key.
When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).
You should be able to fix this by providing a unique key
element yourself to either the parent div
or to all MyInput
elements.
For example:
render(){
if (this.state.employed) {
return (
<div key="employed">
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div key="notEmployed">
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
OR
render(){
if (this.state.employed) {
return (
<div>
<MyInput key="title" ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<MyInput key="reason" ref="unemployment-reason" name="unemployment-reason" />
<MyInput key="duration" ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
Now, when React does the diff, it will see that the divs
are different and will re-render it including all of its' children (1st example). In the 2nd example, the diff will be a success on job-title
and unemployment-reason
since they now have different keys.
You can of course use any keys you want, as long as they are unique.
Update August 2017
For a better insight into how keys work in React, I strongly recommend reading my answer to Understanding unique keys in React.js.
Update November 2017
This update should've been posted a while ago, but using string literals in ref
is now deprecated. For example ref="job-title"
should now instead be ref={(el) => this.jobTitleRef = el}
(for example). See my answer to Deprecation warning using this.refs for more info.
IMHO the better solution is to combine two answers by @RamboNo5 and @Jason
I mean overridding addClass function and adding a custom event called cssClassChanged
// Create a closure
(function(){
// Your base, I'm in it!
var originalAddClassMethod = jQuery.fn.addClass;
jQuery.fn.addClass = function(){
// Execute the original method.
var result = originalAddClassMethod.apply( this, arguments );
// trigger a custom event
jQuery(this).trigger('cssClassChanged');
// return the original result
return result;
}
})();
// document ready function
$(function(){
$("#YourExampleElementID").bind('cssClassChanged', function(){
//do stuff here
});
});
I have added reCaptcha to a project I'm currently working on. I needed it to use the AJAX API as the reCaptcha element was loaded into the page dynamically. I couldn't find any existing controls and the API is simple so I created my own.
I'll post my code here in case anyone finds it useful.
1: Add the script tag to the master page headers
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
2: Add your keys to the web.config
<appSettings>
<add key="ReCaptcha.PrivateKey" value="[key here]" />
<add key="ReCaptcha.PublicKey" value="[key here]" />
</appSettings>
3: Create the Action Attribute and Html Helper extensions
namespace [Your chosen namespace].ReCaptcha
{
public enum Theme { Red, White, BlackGlass, Clean }
[Serializable]
public class InvalidKeyException : ApplicationException
{
public InvalidKeyException() { }
public InvalidKeyException(string message) : base(message) { }
public InvalidKeyException(string message, Exception inner) : base(message, inner) { }
}
public class ReCaptchaAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var userIP = filterContext.RequestContext.HttpContext.Request.UserHostAddress;
var privateKey = ConfigurationManager.AppSettings.GetString("ReCaptcha.PrivateKey", "");
if (string.IsNullOrWhiteSpace(privateKey))
throw new InvalidKeyException("ReCaptcha.PrivateKey missing from appSettings");
var postData = string.Format("&privatekey={0}&remoteip={1}&challenge={2}&response={3}",
privateKey,
userIP,
filterContext.RequestContext.HttpContext.Request.Form["recaptcha_challenge_field"],
filterContext.RequestContext.HttpContext.Request.Form["recaptcha_response_field"]);
var postDataAsBytes = Encoding.UTF8.GetBytes(postData);
// Create web request
var request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataAsBytes.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(postDataAsBytes, 0, postDataAsBytes.Length);
dataStream.Close();
// Get the response.
var response = request.GetResponse();
using (dataStream = response.GetResponseStream())
{
using (var reader = new StreamReader(dataStream))
{
var responseFromServer = reader.ReadToEnd();
if (!responseFromServer.StartsWith("true"))
((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Captcha words typed incorrectly");
}
}
}
}
public static class HtmlHelperExtensions
{
public static MvcHtmlString GenerateCaptcha(this HtmlHelper helper, Theme theme, string callBack = null)
{
const string htmlInjectString = @"<div id=""recaptcha_div""></div>
<script type=""text/javascript"">
Recaptcha.create(""{0}"", ""recaptcha_div"", {{ theme: ""{1}"" {2}}});
</script>";
var publicKey = ConfigurationManager.AppSettings.GetString("ReCaptcha.PublicKey", "");
if (string.IsNullOrWhiteSpace(publicKey))
throw new InvalidKeyException("ReCaptcha.PublicKey missing from appSettings");
if (!string.IsNullOrWhiteSpace(callBack))
callBack = string.Concat(", callback: ", callBack);
var html = string.Format(htmlInjectString, publicKey, theme.ToString().ToLower(), callBack);
return MvcHtmlString.Create(html);
}
}
}
4: Add the captcha to your view
@using (Html.BeginForm("MyAction", "MyController"))
{
@Html.TextBox("EmailAddress", Model.EmailAddress)
@Html.GenerateCaptcha(Theme.White)
<input type="submit" value="Submit" />
}
5: Add the attribute to your action
[HttpPost]
[ReCaptcha]
public ActionResult MyAction(MyModel model)
{
if (!ModelState.IsValid) // Will have a Model Error "ReCaptcha" if the user input is incorrect
return Json(new { capthcaInvalid = true });
... other stuff ...
}
6: Note you will need to reload the captcha after each post even if it was valid and another part of the form was invalid. Use Recaptcha.reload();
Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.