I had this same error. I had everything written in correctly, including the Listing 10.13 from the tutorial.
Rails.application.configure do
.
.
.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delevery_method :test
host = 'example.com'
config.action_mailer.default_url_options = { host: host }
.
.
.
end
obviously with "example.com" replaced with my server url.
What I had glossed over in the tutorial was this line:
After restarting the development server to activate the configuration...
So the answer for me was to turn the server off and back on again.
This question is an old one, but it shows up at the top of Google when searching for how to run a single test. I don't know if it's a recent addition, but to run a single test out of a spec you can do the following:
rspec path/to/spec:<line number>
where -line number- is a line number that contains part of your test. For example, if you had a spec like:
1:
2: it "should be awesome" do
3: foo = 3
4: foo.should eq(3)
5: end
6:
Let's say it's saved in spec/models/foo_spec.rb. Then you would run:
rspec spec/models/foo_spec.rb:2
and it would just run that one spec. In fact, that number could be anything from 2 to 5.
Hope this helps!
Simple and easy to way to do this.
# set some variable on success like :success => true in your controller
controller.rb
render :json => {:success => true, :data => data} # on success
spec_controller.rb
parse_json = JSON(response.body)
parse_json["success"].should == true
The below should work
describe "#foo"
it "should call 'bar' with appropriate arguments" do
subject.stub(:bar)
subject.foo
expect(subject).to have_received(:bar).with("Invalid number of arguments")
end
end
Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments
A solution that I like, because it keeps rspec output separate from actual rails log output, is to do the following:
$ tail -f $RAILS_APP_DIR/logs/test.log
or tail -f $RAILS_APP_DIR\logs\test.log
for Window usersIf you are running a multi-pane terminal like iTerm, this becomes even more fun and you have rspec
and the test.log
output side by side.
I always prefer let
to an instance variable for a couple of reasons:
nil
, which can lead to subtle bugs and false positives. Since let
creates a method, you'll get a NameError
when you misspell it, which I find preferable. It makes it easier to refactor specs, too.before(:each)
hook will run before each example, even if the example doesn't use any of the instance variables defined in the hook. This isn't usually a big deal, but if the setup of the instance variable takes a long time, then you're wasting cycles. For the method defined by let
, the initialization code only runs if the example calls it.@
).let
and keeping my it
block nice and short.A related link can be found here: http://www.betterspecs.org/#let
Usually I do:
rspec ./spec/controllers/groups_controller_spec.rb:42
Where 42
represents the line of the test I want to run.
EDIT1:
You could also use tags. See here.
EDIT 2:
Try:
bundle exec rspec ./spec/controllers/groups_controller_spec.rb:42
To scrolldown from any position in the recyclerview to bottom
edittext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rv.postDelayed(new Runnable() {
@Override
public void run() {
rv.scrollToPosition(rv.getAdapter().getItemCount() - 1);
}
}, 1000);
}
});
The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
http://docs.python.org/library/logging.handlers.html#filehandler
The
FileHandler
class, located in the corelogging
package, sends logging output to a disk file.
You can use org.apache.commons.lang.Validate
's "notEmpty" method:
Validate.notEmpty(myCollection)
-> Validate that the specified argument collection is neither null nor a size of zero (no elements); otherwise throwing an exception.
There is now a an approach to do this, using Doctrine's Criteria.
A full example can be seen in How to use a findBy method with comparative criteria, but a brief answer follows.
use \Doctrine\Common\Collections\Criteria;
// Add a not equals parameter to your criteria
$criteria = new Criteria();
$criteria->where(Criteria::expr()->neq('prize', 200));
// Find all from the repository matching your criteria
$result = $entityRepository->matching($criteria);
If your start and end datetimes are on different days use TIMEDIFF.
SELECT TIMEDIFF(datetime1,datetime2)
if datetime1 > datetime2 then
SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")
gives: 24:01:00
and datetime1 < datetime2
SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")
gives: -24:01:00
Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie. Try that:
$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );
then when you get your cookie next time:
$cookie = json_decode( $_COOKIE[ "cookiename" ] );
you can simply extract the expiry time, which was inserted as data inside the cookie itself..
$expiry = $cookie->expiry;
and additionally the data which will come out as a usable object :)
$data = $cookie->data;
$value1 = $cookie->data->value1;
etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!
I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.
//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
context.executeQueryAsync(function(){
alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
}, function(){alert(":(");});
Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.
My .bash_profile file and how I used grep:
If the PATH environment variable includes my two bin
directories, don't append them,
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
U=~/.local.bin:~/bin
if ! echo "$PATH" | grep -q "home"; then
export PATH=$PATH:${U}
fi
If you want to store the result in one file outside the container, in your local machine, you can do something like this.
RES_FILE=$(readlink -f /tmp/result.txt)
docker run --rm -v ${RES_FILE}:/result.txt img bash -c "cat /etc/passwd | grep root > /result.txt"
The result of your commands will be available in /tmp/result.txt
in your local machine.
The else
keyword can be confusing here, and as many people have pointed out, something like nobreak
, notbreak
is more appropriate.
In order to understand for ... else ...
logically, compare it with try...except...else
, not if...else...
, most of python programmers are familiar with the following code:
try:
do_something()
except:
print("Error happened.") # The try block threw an exception
else:
print("Everything is find.") # The try block does things just find.
Similarly, think of break
as a special kind of Exception
:
for x in iterable:
do_something(x)
except break:
pass # Implied by Python's loop semantics
else:
print('no break encountered') # No break statement was encountered
The difference is python
implies except break
and you can not write it out, so it becomes:
for x in iterable:
do_something(x)
else:
print('no break encountered') # No break statement was encountered
Yes, I know this comparison can be difficult and tiresome, but it does clarify the confusion.
I have used the below code and it is working fine as describing->
CKEDITOR.instances.mail_msg.insertText(obj["template"]);
Here->
CKEDITOR
->Your editor Name,
mail_msg
-> Id of your textarea(to which u bind the ckeditor),
obj["template"]
->is the value that u want to bind
An __init__.py
file makes imports easy. When an __init__.py
is present within a package, function a()
can be imported from file b.py
like so:
from b import a
Without it, however, you can't import directly. You have to amend the system path:
import sys
sys.path.insert(0, 'path/to/b.py')
from b import a
Try this:
var frm = document.getElementById('search-theme-form') || null;
if(frm) {
frm.action = 'whatever_you_need.ext'
}
TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
getResource()
directly on the class.There is no difference between the two, one is just a shorthand for the second.
The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.
<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>
Source: official documentation.
I got the same issue and this solved it for me. Perhaps this might be a fix for your problem too.
Here is the fix. Follow this link http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/
Go to "Fixed curl extensions" and download the extension that matches your PHP version.
Extract and copy "php_curl.dll" to the extension directory of your wamp installation. (i.e. C:\wamp\bin\php\php5.3.13\ext)
Restart Apache
Done!
Refer to: http://blog.nterms.com/2012/07/php-curl-issues-with-wamp-server-on.html
Cheers!
Problem: You're trying to import data (using mysqldump file) to your mysql database ,but it seems you don't have permission to perform that operation.
Solution: Assuming you data is migrated ,seeded and updated in your mysql database, take snapshot using mysqldump and export it to file
mysqldump -u [username] -p [databaseName] --set-gtid-purged=OFF > [filename].sql
From mysql documentation:
GTID - A global transaction identifier (GTID) is a unique identifier created and associated with each transaction committed on the server of origin (master). This identifier is unique not only to the server on which it originated, but is unique across all servers in a given replication setup. There is a 1-to-1 mapping between all transactions and all GTIDs.
--set-gtid-purged=OFF SET @@GLOBAL.gtid_purged is not added to the output, and SET @@SESSION.sql_log_bin=0 is not added to the output. For a server where GTIDs are not in use, use this option or AUTO. Only use this option for a server where GTIDs are in use if you are sure that the required GTID set is already present in gtid_purged on the target server and should not be changed, or if you plan to identify and add any missing GTIDs manually.
Afterwards connect to your mysql with user root ,give permissions , flush them ,and verify that your user privileges were updated correctly.
mysql -u root -p
UPDATE mysql.user SET Super_Priv='Y' WHERE user='johnDoe' AND host='%';
FLUSH PRIVILEGES;
mysql> SHOW GRANTS FOR 'johnDoe';
+------------------------------------------------------------------+
| Grants for johnDoe |
+------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `johnDoe` |
| GRANT ALL PRIVILEGES ON `db1`.* TO `johnDoe` |
+------------------------------------------------------------------+
now reload the data and the operation should be permitted.
mysql -h [host] -u [user] -p[pass] [db_name] < [mysql_dump_name].sql
That means that your consumer is expecting XML from the webservice but the webservice, as your error shows, returns HTML because it's failing due to a timeout.
So you need to talk to the remote webservice provider to let them know it's failing and take corrective action. Unless you are the provider of the webservice in which case you should catch the exceptions and return XML telling the consumer which error occurred (the 'remote provider' should probably do that as well).
You can use Array.ForEach()
Array.ForEach(employees, employee => {
Array.ForEach(employee.Departments, department => department.SomeProperty = null);
Collection.AddRange(employee.Departments);
});
var statuses = new[] { "A", "B", "C" };
var filteredOrders = from order in orders.Order
where statuses.Contains(order.StatusCode)
select order;
This may help someone, put UTC at the end of what you pass in to the new constructor
At least in chrome you can say var date = new Date("2014-01-01 11:00:00 UTC")
For me the issue wasn't six
but rst2pdf
itself. head -1 $(which rst2pdf)
(3.8) didn't match python3 --version
(3.9). My solution:
pip3 install rst2pdf
dplyr >= 1.0.0
In newer versions of dplyr
you can use rowwise()
along with c_across
to perform row-wise aggregation for functions that do not have specific row-wise variants, but if the row-wise variant exists it should be faster.
Since rowwise()
is just a special form of grouping and changes the way verbs work you'll likely want to pipe it to ungroup()
after doing your row-wise operation.
To select a range of rows:
df %>%
dplyr::rowwise() %>%
dplyr::mutate(sumrange = sum(dplyr::c_across(x1:x5), na.rm = T))
# %>% dplyr::ungroup() # you'll likely want to ungroup after using rowwise()
To select rows by type:
df %>%
dplyr::rowwise() %>%
dplyr::mutate(sumnumeric = sum(c_across(where(is.numeric)), na.rm = T))
# %>% dplyr::ungroup() # you'll likely want to ungroup after using rowwise()
In your specific case a row-wise variant exists so you can do the following (note the use of across
instead):
df %>%
dplyr::mutate(sumrow = rowSums(dplyr::across(x1:x5), na.rm = T))
For more information see the page on rowwise.
You could do something like this:
> +(Math.floor(y/x)*x).toFixed(15);
1.2
It's possible, you can simply use jQuery to substitute the 'meta tag' that references the cache status with an event handler / button, and then refresh, easy,
$('.button').click(function() {
$.ajax({
url: "",
context: document.body,
success: function(s,x){
$('html[manifest=saveappoffline.appcache]').attr('content', '');
$(this).html(s);
}
});
});
NOTE: This solution relies on the Application Cache that is implemented as part of the HTML 5 spec. It also requires server configuration to set up the App Cache manifest. It does not describe a method by which one can clear the 'traditional' browser cache via client- or server-side code, which is nigh impossible to do.
Another solution if you want to keep this column as index.
pd.read_csv('filename.csv', index_col='Unnamed: 0')
With gnuplot using gplot.py
from gplot import *
l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
gplot.log('y')
gplot(*zip(*l))
DBCC OPENTRAN helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the transaction log of the specified database. Results are displayed only if there is an active transaction that exists in the log or if the database contains replication information.
An informational message is displayed if there are no active transactions in the log.
In my case ; what solved my issue was.....
You may had json like this, the keys without " double quotations....
{ name: "test", phone: "2324234" }
So try any online Json Validator to make sure you have right syntax...
You can use with this format (tested on Laravel 5.5). In my case I used it for gettting the data of database connections and use on Controller:
$User = env('DB_USERNAMEchild','');
$Pass = env('DB_PASSWORDchild','');
The second parameter can be null, or set any default in case of DB_USERNAMEchild is null.
Your .env file can be the same:
DB_HOST=localhost
DB_DATABASE=FATHERBD
DB_USERNAME=root
DB_PASSWORD=password
DB_DATABASEchild=ZTEST
DB_USERNAMEchild=root
DB_PASSWORDchild=passwordofchild
Using Replace Function and FOR JSON PATH
SELECT T3.DEPT, REPLACE(REPLACE(T3.ENAME,'{"ENAME":"',''),'"}','') AS ENAME_LIST
FROM (
SELECT DEPT, (SELECT ENAME AS [ENAME]
FROM EMPLOYEE T2
WHERE T2.DEPT=T1.DEPT
FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) ENAME
FROM EMPLOYEE T1
GROUP BY DEPT) T3
For sample data and more ways click here
Don't use wait()
, use either android.os.SystemClock.sleep(1000);
or Thread.sleep(1000);
.
The main difference between them is that Thread.sleep()
can be interrupted early -- you'll be told, but it's still not the full second. The android.os
call will not wake early.
you can swipe the key and the value. For example
String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
int[] v = {341, 273, 278, 329, 445};
TreeMap<Integer,String>a=new TreeMap();
for (int i = 0; i < k.length; i++)
a.put(v[i],k[i]);
System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
a.remove(a.firstEntry().getKey());
System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
You can use one of the following methods:
document.getElementById('log').innerHTML = "text";
document.getElementById('log').innerText = "text";
document.getElementById('log').textContent = "text";
For Jquery:
$("#log").text("text");
$("#log").html("text");
Use CSS position: absolute;
followed by top: 0px; left 0px;
in the style
attribute of each DIV. Replace the pixel values with whatever you want.
You can use z-index: x;
to set the vertical "order" (which one is "on top"). Replace x
with a number, higher numbers are on top of lower numbers.
Here is how your new code would look:
<div>
<div id="backdrop" style="z-index: 1; position: absolute; top: 0px; left: 0px;"><img alt="" src='/backdrop.png' /></div>
<div id="curtain" style="z-index: 2; position: absolute; top: 0px; left: 0px; background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;"> </div>
</div>
Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB
, which mimics Linux' SO_REUSEPORT
behaviour - it balances the load; see setsockopt(2)
An image of how to in Android Studio 1.5.1.
Within the "Android" project (see the drop-down in the topleft of my image), Right-click on the app...
like dwn said, Performance was one of its benefits during the rise of complex processors, MSDN blog Non-classical processor behavior: How doing something can be faster than not doing it gives an example which clearly says the difference between ternary (conditional) operator and if/else statement.
give the following code:
#include <windows.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
int array[10000];
int countthem(int boundary)
{
int count = 0;
for (int i = 0; i < 10000; i++) {
if (array[i] < boundary) count++;
}
return count;
}
int __cdecl wmain(int, wchar_t **)
{
for (int i = 0; i < 10000; i++) array[i] = rand() % 10;
for (int boundary = 0; boundary <= 10; boundary++) {
LARGE_INTEGER liStart, liEnd;
QueryPerformanceCounter(&liStart);
int count = 0;
for (int iterations = 0; iterations < 100; iterations++) {
count += countthem(boundary);
}
QueryPerformanceCounter(&liEnd);
printf("count=%7d, time = %I64d\n",
count, liEnd.QuadPart - liStart.QuadPart);
}
return 0;
}
the cost for different boundary are much different and wierd (see the original material). while if change:
if (array[i] < boundary) count++;
to
count += (array[i] < boundary) ? 1 : 0;
The execution time is now independent of the boundary value, since:
the optimizer was able to remove the branch from the ternary expression.
but on my desktop intel i5 cpu/windows 10/vs2015, my test result is quite different with msdn blog.
when using debug mode, if/else cost:
count= 0, time = 6434
count= 100000, time = 7652
count= 200800, time = 10124
count= 300200, time = 12820
count= 403100, time = 15566
count= 497400, time = 16911
count= 602900, time = 15999
count= 700700, time = 12997
count= 797500, time = 11465
count= 902500, time = 7619
count=1000000, time = 6429
and ternary operator cost:
count= 0, time = 7045
count= 100000, time = 10194
count= 200800, time = 12080
count= 300200, time = 15007
count= 403100, time = 18519
count= 497400, time = 20957
count= 602900, time = 17851
count= 700700, time = 14593
count= 797500, time = 12390
count= 902500, time = 9283
count=1000000, time = 7020
when using release mode, if/else cost:
count= 0, time = 7
count= 100000, time = 9
count= 200800, time = 9
count= 300200, time = 9
count= 403100, time = 9
count= 497400, time = 8
count= 602900, time = 7
count= 700700, time = 7
count= 797500, time = 10
count= 902500, time = 7
count=1000000, time = 7
and ternary operator cost:
count= 0, time = 16
count= 100000, time = 17
count= 200800, time = 18
count= 300200, time = 16
count= 403100, time = 22
count= 497400, time = 16
count= 602900, time = 16
count= 700700, time = 15
count= 797500, time = 15
count= 902500, time = 16
count=1000000, time = 16
the ternary operator is slower than if/else statement on my machine!
so according to different compiler optimization techniques, ternal operator and if/else may behaves much different.
To just download a commit using the 7-digit SHA1 short form do:
Working Example:
https://github.com/python/cpython/archive/31af650.zip
Description:
`https://github.com/username/projectname/archive/commitshakey.zip`
If you have the long hash key
31af650ee25f65794b75d4dfefed6fe4758781c1
, just get the first 7 chars31af650
. It's the default for GitHub.
Unfortunately, JavaScript doesn't provide an async functionality. It works only in a single one thread. But the most of the modern browsers provide Worker
s, that are second scripts which gets executed in background and can return a result.
So, I reached a solution I think it's useful to asynchronously run a function, which creates a worker for each async call.
The code below contains the function async
to call in background.
Function.prototype.async = function(callback) {
let blob = new Blob([ "self.addEventListener('message', function(e) { self.postMessage({ result: (" + this + ").apply(null, e.data) }); }, false);" ], { type: "text/javascript" });
let worker = new Worker(window.URL.createObjectURL(blob));
worker.addEventListener("message", function(e) {
this(e.data.result);
}.bind(callback), false);
return function() {
this.postMessage(Array.from(arguments));
}.bind(worker);
};
This is an example for usage:
(function(x) {
for (let i = 0; i < 999999999; i++) {}
return x * 2;
}).async(function(result) {
alert(result);
})(10);
This executes a function which iterate a for
with a huge number to take time as demonstration of asynchronicity, and then gets the double of the passed number.
The async
method provides a function
which calls the wanted function in background, and in that which is provided as parameter of async
callbacks the return
in its unique parameter.
So in the callback function I alert
the result.
All answers assume the starting array is unique. OP did not specify how to handle arrays with duplicate entries, which result in duplicate keys.
Let's look at:
a = ["item 1", "item 2", "item 3", "item 4", "item 1", "item 5"]
You will lose the item 1 => item 2
pair as it is overridden bij item 1 => item 5
:
Hash[*a]
=> {"item 1"=>"item 5", "item 3"=>"item 4"}
All of the methods, including the reduce(&:merge!)
result in the same removal.
It could be that this is exactly what you expect, though. But in other cases, you probably want to get a result with an Array
for value instead:
{"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}
The naïve way would be to create a helper variable, a hash that has a default value, and then fill that in a loop:
result = Hash.new {|hash, k| hash[k] = [] } # Hash.new with block defines unique defaults.
a.each_slice(2) {|k,v| result[k] << v }
a
=> {"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}
It might be possible to use assoc
and reduce
to do above in one line, but that becomes much harder to reason about and read.
From some reason most of the answers here didn't help me (maybe it's related to my FROM image in the Dockerfile)
So I preferred to create a bash script
in my workspace combined with --build-arg
in order to handle if statement while Docker build by checking if the argument is empty or not
Bash script:
#!/bin/bash -x
if test -z $1 ; then
echo "The arg is empty"
....do something....
else
echo "The arg is not empty: $1"
....do something else....
fi
Dockerfile:
FROM ...
....
ARG arg
COPY bash.sh /tmp/
RUN chmod u+x /tmp/bash.sh && /tmp/bash.sh $arg
....
Docker Build:
docker build --pull -f "Dockerfile" -t $SERVICE_NAME --build-arg arg="yes" .
Remark: This will go to the else (false) in the bash script
docker build --pull -f "Dockerfile" -t $SERVICE_NAME .
Remark: This will go to the if (true)
Edit 1:
After several tries I have found the following article and this one which helped me to understand 2 things:
1) ARG before FROM is outside of the build
2) The default shell is /bin/sh which means that the if else is working a little bit different in the docker build. for example you need only one "=" instead of "==" to compare strings.
So you can do this inside the Dockerfile
ARG argname=false #default argument when not provided in the --build-arg
RUN if [ "$argname" = "false" ] ; then echo 'false'; else echo 'true'; fi
and in the docker build
:
docker build --pull -f "Dockerfile" --label "service_name=${SERVICE_NAME}" -t $SERVICE_NAME --build-arg argname=true .
Sometimes it's nice to be explicit (for readability) that the variable doesn't change. Here's a simple example where using final
can save some possible headaches:
public void setTest(String test) {
test = test;
}
If you forget the 'this' keyword on a setter, then the variable you want to set doesn't get set. However, if you used the final
keyword on the parameter, then the bug would be caught at compile time.
create a folder inside htdocs, place your website there, access it via localhost or Internal IP (if you're behind a router) - check out this video demo here
slide modification changed Helper
public static IHtmlString ActionImageLink(this HtmlHelper html, string action, object routeValues, string styleClass, string alt)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
anchorBuilder.AddCssClass(styleClass);
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return new HtmlString(anchorHtml);
}
CSS Class
.Edit {
background: url('../images/edit.png') no-repeat right;
display: inline-block;
height: 16px;
width: 16px;
}
Create the link just pass the class name
@Html.ActionImageLink("Edit", new { id = item.ID }, "Edit" , "Edit")
Try this Code
var app = angular.module('myapp', []);
app.controller('testController', function ($scope, $http) {
$scope.init = function(){
alert($scope.testInput);
};});
<body ng-app="myapp">_x000D_
<div ng-controller='testController' data-ng-init="testInput='value'; init();" class="col-sm-9 col-lg-9" >_x000D_
</div>_x000D_
</body>
_x000D_
Pro Git 8.2 explains it: http://git-scm.com/book/en/Git-and-Other-Systems-Migrating-to-Git
The problem could be in Flex's SOAP encoder. Try extending the SOAP encoder in your Flex application and debug the program to see how the null value is handled.
My guess is, it's passed as NaN (Not a Number). This will mess up the SOAP message unmarshalling process sometime (most notably in the JBoss 5 server...). I remember extending the SOAP encoder and performing an explicit check on how NaN is handled.
To get the current working directory, you can use:
process.cwd()
However, be aware that some scripts, notably gulp, will change the current working directory with process.chdir()
.
You can get the path of the current module with:
__filename
__dirname
If you are running a script from the command line, and you want the original directory from which the script was run, regardless of what directory the script is currently operating in, you can use:
process.env.INIT_CWD
It's sometimes desirable to run an NPM script in the current directory, rather than the root of the project.
This variable is available inside npm package scripts as:
$INIT_CWD.
You must be running a recent version of NPM. If this variable is not available, make sure NPM is up to date.
This will allow you access the current path in your package.json, e.g.:
scripts: {
"customScript": "gulp customScript --path $INIT_CWD"
}
To avoid doing indexing from inside lambda, like:
rval = dict(map(lambda kv : (kv[0], ' '.join(kv[1])), rval.iteritems()))
You can also do:
rval = dict(map(lambda(k,v) : (k, ' '.join(v)), rval.iteritems()))
I know it's an old thread, but I just looked into schemas myself and think the following could be another good candidate for schema usage:
In a Datawarehouse, with data coming from different sources, you can use a different schema for each source, and then e.g. control access based on the schemas. Also avoids the possible naming collisions between the various source, as another poster replied above.
OAuth v2 specs indicates:
Access token attributes and the methods used to access protected resources are beyond the scope of this specification and are defined by companion specifications.
My Authorisation Server has a webservice (SOAP) endpoint that allows the Resource Server to know whether the access_token is valid.
I'm so frustrated that this question can't just be answered. Every other question is in relation to how to revert correctly and preserve history. This question says "I want the head of the branch to point to A, i.e. I want B, C, D, and HEAD to disappear and I want head to be synonymous with A."
git checkout <branch_name>
git reset --hard <commit Hash for A>
git push -f
I learned a lot reading Jakub's post, but some guy in the company (with access to push to our "testing" branch without Pull-Request) pushed like 5 bad commits trying to fix and fix and fix a mistake he made 5 commits ago. Not only that, but one or two Pull Requests were accepted, which were now bad. So forget it, I found the last good commit (abc1234) and just ran the basic script:
git checkout testing
git reset --hard abc1234
git push -f
I told the other 5 guys working in this repo that they better make note of their changes for the last few hours and Wipe/Re-Branch from the latest testing. End of the story.
how to remove all the blanks lines
:%s,\n\n,^M,g
(do this multiple times util all the empty lines went gone)
how to remove all the blanks lines leaving SINGLE empty line
:%s,\n\n\n,^M^M,g
(do this multiple times)
how to remove all the blanks lines leaving TWO empty lines AT MAXIMUM,
:%s,\n\n\n\n,^M^M^M,g
(do this multiple times)
in order to input ^M, I have to control-Q and control-M in windows
You could use dplyr
:
df %>% group_by("Amount") %>% slice(which.min(x))
These are extended operations (e.g., sort, reverse) for one dimensional and two dimensional arrays in Twig framework:
{% for key, value in array_one_dimension %}
<div>{{ key }}</div>
<div>{{ value }}</div>
{% endfor %}
{% for key, value in array_one_dimension|keys|sort %}
<div>{{ key }}</div>
<div>{{ value }}</div>
{% endfor %}
{% for key, value in array_one_dimension|keys|sort|reverse %}
<div>{{ key }}</div>
<div>{{ value }}</div>
{% endfor %}
{% for key_a, value_a in array_two_dimension %}
{% for key_b, value_b in array_two_dimension[key_a] %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort %}
{% for key_b, value_b in array_two_dimension[key_a] %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
It's Ctrl+Shift+O / Cmd+Shift+O on mac. You can see it if you close all tabs
If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok
Another solution, you can do it using ResourceLoader
like this:
import org.springframework.core.io.Resource;
import org.apache.commons.io.FileUtils;
@Autowire
private ResourceLoader resourceLoader;
...
Resource resource = resourceLoader.getResource("classpath:/path/to/you/dir");
File file = resource.getFile();
Iterator<File> fi = FileUtils.iterateFiles(file, null, true);
while(fi.hasNext()) {
load(fi.next())
}
According to the docs:
"If the onPressed callback is null, then the button will be disabled and by default will resemble a flat button in the disabledColor."
https://docs.flutter.io/flutter/material/RaisedButton-class.html
So, you might do something like this:
RaisedButton(
onPressed: calculateWhetherDisabledReturnsBool() ? null : () => whatToDoOnPressed,
child: Text('Button text')
);
First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.
The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "
Source and example of polyfill here:
http://www.programmerinterview.com/index.php/html5/html5-polyfill/
All you need is a ADODB.Connection
Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset ' Microsoft ActiveX Data Objects Library
Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"
Set rs = cnn.Execute(SQLQuery) ' Retrieve the data
You can use Decode
as well:
SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item
Setting html { height: 100%}
can wreak havoc with IE. Here's an example (png). But you know what works great? Just set your background on the <html>
tag.
html {
-moz-linear-gradient(top, #fff, #000);
/* etc. */
}
Background extends to the bottom and no weird scrolling behavior occurs. You can skip all of the other fixes. And this is broadly supported. I haven't found a browser that doesn't let you apply a background to the html tag. It's perfectly valid CSS and has been for a while. :)
cls
implies that method belongs to the class while self implies that the method is related to instance of the class,therefore member with cls
is accessed by class name where as the one with self is accessed by instance of the class...it is the same concept as static member
and non-static members
in java if you are from java background.
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
An alternative solution is to use marker, a tool I've created recently that allows you to "bookmark" command templates and easily place cursor at command place-holders:
I found that most of time, I'm using shell functions so I don't have to write frequently used commands again and again in the command-line. The issue of using functions for this use case, is adding new terms to my command vocabulary and having to remember what functions parameters refer to in the real-command. Marker goal is to eliminate that mental burden.
Acutally, it gives several examples of compile commands used for pthreads codes are listed in the table below, if you continue reading the following tutorial:
If all hours must be displayed (more than 24) and if '0' before hours is not necessary, then formatting can be done with a short line of code:
Math.floor(duration.as('h')) + moment.utc(duration.as('ms')).format(':mm:ss')
These regexes are equivalent (for matching purposes):
/^(7|8|9)\d{9}$/
/^[789]\d{9}$/
/^[7-9]\d{9}$/
The explanation:
(a|b|c)
is a regex "OR" and means "a or b or c", although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code (?:7|8|9)
to make it a non capturing group.
[abc]
is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d]
= [abcd]
)
The reason these regexes are similar is that a character class is a shorthand for an "or" (but only for single characters). In an alternation, you can also do something like (abc|def)
which does not translate to a character class.
~
flips the bits in the value.
Why ~2
is -3
has to do with how numbers are represented bitwise. Numbers are represented as two's complement.
So, 2 is the binary value
00000010
And ~2 flips the bits so the value is now:
11111101
Which, is the binary representation of -3.
It's working
Try below code
$('#example').dataTable({
"bProcessing": true,
"sAutoWidth": false,
"bDestroy":true,
"sPaginationType": "bootstrap", // full_numbers
"iDisplayStart ": 10,
"iDisplayLength": 10,
"bPaginate": false, //hide pagination
"bFilter": false, //hide Search bar
"bInfo": false, // hide showing entries
})
You can do that using at. You can try out the following simple example:
const size_t N = 20;
std::vector<int> vec(N);
try {
vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);
Notice that method at
returns an allocator_type::reference
, which is that case is a int&
. Using at
is equivalent to assigning values like vec[i]=...
.
There is a difference between at
and insert as it can be understood with the following example:
const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
vec[i] = i + 1;
}
vec.insert(vec.begin()+2, 10);
If we now print out vec
we will get:
1 2 10 3 4 5 0 0 0
If, instead, we did vec.at(2) = 10
, or vec[2]=10
, we would get
1 2 10 4 5 0 0 0
If you want to change socket to non blocking , precisely accept() to NON-Blocking state then
int flags=fcntl(master_socket, F_GETFL);
fcntl(master_socket, F_SETFL,flags| O_NONBLOCK); /* Change the socket into non-blocking state F_SETFL is a command saying set flag and flag is 0_NONBLOCK */
while(1){
if((newSocket = accept(master_socket, (struct sockaddr *) &address, &addr_size))<0){
if(errno==EWOULDBLOCK){
puts("\n No clients currently available............ \n");
continue;
}
}else{
puts("\nClient approched............ \n");
}
}
Nicer code for this:
yourstring = yourstring.Replace(System.Environment.NewLine, string.Empty);
Simon, I suppose there's a reason none of the other answers is accepted so far. Thus I believe this could be a Grails issue nevertheless - Especially if you're using the 'Resources Plugin'.
If your plugins provide a favicon (which - illogically - many do), they might override the one you desired to use - given yours is in a plugin itself.
If deleting the favicon from all your plugins temporary resolves the issue then you're very likely experiencing this:
Here’s another quickie way to get the unique value count, as well as to get the unique values. Copy the column you care about into another worksheet, then select the entire column. Click on Data -> Remove Duplicates -> OK. This removes all duplicated values.
1.) Check here. Basically do this:
Function FileExists(ByVal FileToTest As String) As Boolean
FileExists = (Dir(FileToTest) <> "")
End Function
I'll leave it to you to figure out the various error handling needed but these are among the error handling things I'd be considering:
2.) How To Delete a File. Look at this. Basically use the Kill command but you need to allow for the possibility of a file being read-only. Here's a function for you:
Sub DeleteFile(ByVal FileToDelete As String)
If FileExists(FileToDelete) Then 'See above
' First remove readonly attribute, if set
SetAttr FileToDelete, vbNormal
' Then delete the file
Kill FileToDelete
End If
End Sub
Again, I'll leave the error handling to you and again these are the things I'd consider:
Should this behave differently for a directory vs. a file? Should a user have to explicitly have to indicate they want to delete a directory?
Do you want the code to automatically reset the read-only attribute or should the user be given some sort of indication that the read-only attribute is set?
EDIT: Marking this answer as community wiki so anyone can modify it if need be.
All the solutions above are looks good and elegant, but the FormData() object does not expect any parameter, but use append() after instantiate it, like what one wrote above:
formData.append(val.name, val.value);
Make sure that you've installed php-mysql, the pdo needs php-mysql to operate properly. If not you could simply type
sudo apt install php-mysql
java.util.Date
is independent of the timezone. When you print cal_Two
though the Calendar
instance has got its timezone set to UTC
, cal_Two.getTime()
would return a Date
instance which does not have a timezone (and is always in the default timezone)
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
System.out.println(cal_Two.getTimeZone());
Output:
Sat Jan 25 16:40:28 IST 2014
sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
From the javadoc of TimeZone.setDefault()
Sets the TimeZone that is returned by the getDefault method. If zone is null, reset the default to the value it had originally when the VM first started.
Hence, moving your setDefault()
before cal_Two
is instantiated you would get the correct result.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());
Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());
Output:
Sat Jan 25 11:15:29 UTC 2014
Sat Jan 25 11:15:29 UTC 2014
When you do not provide mapDispatchToProps
as a second argument, like this:
export default connect(mapStateToProps)(Checkbox)
then you are automatically getting the dispatch to component's props, so you can just:
class SomeComp extends React.Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
this.props.dispatch(ACTION GOES HERE);
}
....
without any mapDispatchToProps
This command will help to pull from the repository as the different user:
git pull https://[email protected]/projectfolder/projectname.git master
It is a workaround, when you are using same machine that someone else used before you, and had saved credentials
SOURCE: https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#Integrating-Contributed-Work
The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this:
If you want to pull commit e43a6 into your master branch, you can run
$ git cherry-pick e43a6
Finished one cherry-pick.
[master]: created a0a41a9: "More friendly message when locking the index fails."
3 files changed, 17 insertions(+), 3 deletions(-)
This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this:
Now you can remove your topic branch and drop the commits you didn’t want to pull in.
If the variable required to be final, cannot be then you can assign the value of the variable to another variable and make THAT final so you can use it instead.
As an additional info to Joey's answer, which isn't described in the help of set /?
nor for /?
.
%~0
expands to the name of the own batch, exactly as it was typed.
So if you start your batch it will be expanded as
%~0 - mYbAtCh
%~n0 - mybatch
%~nx0 - mybatch.bat
But there is one exception, expanding in a subroutine could fail
echo main- %~0
call :myFunction
exit /b
:myFunction
echo func - %~0
echo func - %~n0
exit /b
This results to
main - myBatch
Func - :myFunction
func - mybatch
In a function %~0
expands always to the name of the function, not of the batch file.
But if you use at least one modifier it will show the filename again!
you can use your method by this way
var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();
$http({
url: '/api/apiControllerName/methodName',
method: 'POST',
params: {application:app, from:d1, to:d2},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
//timeout: 1,
//cache: false,
//transformRequest: false,
//transformResponse: false
}).then(function (results) {
return results;
}).catch(function (e) {
});
You have to loop through the array and printf()
each element:
for(int i=0;i<10;++i) {
printf("%.2f ", foo[i]);
}
printf("\n");
You could try using a $_SESSION
variable to make sure that a request was made from a browser. Otherwise, you could have the request sent through a database or file [server-side].
Easiest is to use strftime
(docs).
If it's for use on the view side, better to wrap it in a helper, though.
df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
does already return a dataframe, so you cannot loop over the groups anymore.
In general:
df.groupby(...)
returns a GroupBy
object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:
grouped = df.groupby('A')
for name, group in grouped:
...
When you apply a function on the groupby, in your example df.groupby(...).agg(...)
(but this can also be transform
, apply
, mean
, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).
Microsoft has listened to the cry for supporting installers (MSI) in Visual Studio and release the Visual Studio Installer Projects Extension. You can now create installers in VS2013, download the extension here from the visualstudiogallery.
Easy way
from IPython.display import Image
Image(filename ="Covid.jpg" size )
My approach with jQuery to just make all of the embedded anchor links slide instead of jump instantly
It's really similar to the answer by Santi Nunez but it's more reliable.
<a href="#myid">Go to</a>
<div id="myid"></div>
// Slow scroll with anchors
(function($){
$(document).on('click', 'a[href^=#]', function(e){
e.preventDefault();
var id = $(this).attr('href');
$('html,body').animate({scrollTop: $(id).offset().top}, 500);
});
})(jQuery);
Both System.Timers.Timer
and System.Threading.Timer
will work for services.
The timers you want to avoid are System.Web.UI.Timer
and System.Windows.Forms.Timer
, which are respectively for ASP applications and WinForms. Using those will cause the service to load an additional assembly which is not really needed for the type of application you are building.
Use System.Timers.Timer
like the following example (also, make sure that you use a class level variable to prevent garbage collection, as stated in Tim Robinson's answer):
using System;
using System.Timers;
public class Timer1
{
private static System.Timers.Timer aTimer;
public static void Main()
{
// Normally, the timer is declared at the class level,
// so that it stays in scope as long as it is needed.
// If the timer is declared in a long-running method,
// KeepAlive must be used to prevent the JIT compiler
// from allowing aggressive garbage collection to occur
// before the method ends. (See end of method.)
//System.Timers.Timer aTimer;
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
//GC.KeepAlive(aTimer);
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
}
/* This code example produces output similar to the following:
Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
*/
If you choose System.Threading.Timer
, you can use as follows:
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(10);
// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate =
new TimerCallback(statusChecker.CheckStatus);
// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Console.WriteLine("{0} Creating timer.\n",
DateTime.Now.ToString("h:mm:ss.fff"));
Timer stateTimer =
new Timer(timerDelegate, autoEvent, 1000, 250);
// When autoEvent signals, change the period to every
// 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period.\n");
// When autoEvent signals the second time, dispose of
// the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}
class StatusChecker
{
int invokeCount, maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if(invokeCount == maxCount)
{
// Reset the counter and signal Main.
invokeCount = 0;
autoEvent.Set();
}
}
}
Both examples comes from the MSDN pages.
string[] lines = File.ReadLines("c:\\file.txt").ToArray();
Although one wonders why you'll want to do that when ReadAllLines
works just fine.
Or perhaps you just want to enumerate with the return value of File.ReadLines
:
var lines = File.ReadAllLines("c:\\file.txt");
foreach (var line in lines)
{
Console.WriteLine("\t" + line);
}
The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:
The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.
You should use python Explicit Conversion Flag PEP-3101
'My name is {0!s:10} {1}'.format('Dunkin', 'Donuts')
'My name is Dunkin Donuts'
or
'My name is %-10s %s' % ('Dunkin', 'Donuts')
'My name is Dunkin Donuts'
Make sure your id_rsa file doesn't have any extension like .txt or .rtf. Rich Text Format adds additional characters to your file and those gets added to byte array. Which eventually causes invalid private key error. Long story short, Copy the file, not content.
If you press CTRL + I it will just format tabs/whitespaces in code and pressing CTRL + SHIFT + F format all code that is format tabs/whitespaces and also divide code lines in a way that it is visible without horizontal scroll.
The reason you don't have permissions to open file is because you didn't grant other apps to open or view the file on your intent. To grant other apps to open the downloaded file, include the flag(as shown below): FLAG_GRANT_READ_URI_PERMISSION
Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(getUriFromFile(localFile), "application/pdf");
browserIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|
Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(browserIntent);
And for function:
getUriFromFile(localFile)
private Uri getUriFromFile(File file){
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
return Uri.fromFile(file);
}else {
return FileProvider.getUriForFile(itemView.getContext(), itemView.getContext().getApplicationContext().getPackageName() + ".provider", file);
}
}
<bean id="benchmarkDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
in angular-2 attribute syntax is
<div [attr.role]="myAriaRole">
Binds attribute role to the result of expression myAriaRole.
so can use like
[attr.role]="myAriaRole ? true: null"
In my case looking in the servers window only showed a tomcat server that I had never used for this project. My SpringBoot project used an embedded tomcat server and it did not stop when my application finished. This button which I indicate with a red arrow will stop the application and the Tomcat server so next time I run the application I will not get the error that an Instance of Tomcat is already running on port 8080.
actual error messages:
Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.
Caused by: java.net.BindException: Address already in use Caused by: org.apache.catalina.LifecycleException: service.getName(): "Tomcat"; Protocol handler start failed
I will now be looking into a way to shut down all services on completion of my SpringBoot Consuming Rest application in this tutorial https://spring.io/guides/gs/consuming-rest/
To see both of the structure and location (directory) of an any (internal or external)table, we can use table's create statment-
show create table table_name;
Wanted to add a solution for IE8 and below (as low as IE5.5 I think), which cannot use background-size
div{
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=
'/path/to/img.jpg', sizingMethod='scale');
}
I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)
public static bool IsStringType(object data)
{
return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
}
You can change the listen port as per your requirement. This task can be accomplished in two diffrent ways. By changing config.xml file By changing in admin console Change the listen port in config.xml as per your requirement and bounce the domain. Admin Console Login to AdminConsole->Server->Configuration->ListenPort (Change it) Note: It is a bad practice to edit config.xml and try to edit in admin console(It's a good practise as well)
If you know the type will never be null
or undefined
, you should declare it as foo: Bar
without the ?
. Declaring a type with the ? Bar
syntax means it could potentially be undefined, which is something you need to check for.
In other words, the compiler is doing exactly what you're asking it to. If you want it to be optional, you'll need to the check later.
Same as above. Use double quote to start the comment and without the closing quote.
Example:
set cul "Highlight current line
I had the exact same issue, found this fix on another site: powershell.exe "Get-Process processname| Stop-Process" it worked for me and I was in the same boat where I had to restart, the /T would not work.
According to Reddit, more options icon and kabob menu are popular names. I prefer the latter as it goes well with hamburger menu.
I prefer this, because this is simple, but maybe somehow inefficient and buggy. You must check the exit code of shell command if you want a strongly error-proof program.
os.system('date +%Y-%m-%d')
If you use Excel, then the command would be Find and MID. Here is what it would look like in Powershell.
$text = "asdfNAME=PC123456<>Diweursejsfdjiwr"
asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456
$text.IndexOf("E=")
7 - this is the "FIND" command for Powershell
$text.substring(10,5)
C1234 - this is the "MID" command for Powershell
$text.substring($text.IndexOf("E=")+2,8)
PC123456 - tada it has found and cut our text
-RavonTUS
(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :
Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.
This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).
If Len(Dir(ThisWorkbook.Path & "\YOUR_DIRECTORY", vbDirectory)) = 0 Then
MkDir ThisWorkbook.Path & "\YOUR_DIRECTORY"
End If
why not use flexbox ? so wrap them into another div like that
.flexContainer { _x000D_
_x000D_
margin: 2px 10px;_x000D_
display: flex;_x000D_
} _x000D_
_x000D_
.left {_x000D_
flex-basis : 30%;_x000D_
}_x000D_
_x000D_
.right {_x000D_
flex-basis : 30%;_x000D_
}
_x000D_
<form id="new_production" class="simple_form new_production" novalidate="novalidate" method="post" action="/projects/1/productions" accept-charset="UTF-8">_x000D_
<div style="margin:0;padding:0;display:inline">_x000D_
<input type="hidden" value="?" name="utf8">_x000D_
<input type="hidden" value="2UQCUU+tKiKKtEiDtLLNeDrfBDoHTUmz5Sl9+JRVjALat3hFM=" name="authenticity_token">_x000D_
</div>_x000D_
<div class="flexContainer">_x000D_
<div class="left">Proj Name:</div>_x000D_
<div class="right">must have a name</div>_x000D_
</div>_x000D_
<div class="input string required"> </div>_x000D_
</form>
_x000D_
feel free to play with flex-basis percentage to get more customized space.
It means exactly what it says: "The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path"
The library referred to is bundled into an OS specific dll (tcnative-1.dll) loaded via JNI. It allows tomcat to use OS functionalities not provided in the Java Runtime (such as sendfile, epoll, OpenSSL, system status, etc.). Tomcat will run just fine without it, but for some use cases, it will be faster with the native libraries.
If you really want it, download the tcnative-1.dll
(or libtcnative.so
for Linux) and put it in the bin folder, and add a system property to the launch configuration of the tomcat server in eclipse.
-Djava.library.path=c:\dev\tomcat\bin
This is an old question maybe even before actual Optional type was introduced but these days you can consider few things: - use method overloading - use Optional type which has advantage of avoiding passing NULLs around Optional type was introduced in Java 8 before it was usually used from third party lib such as Google's Guava. Using optional as parameters / arguments can be consider as over-usage as the main purpose was to use it as a return time.
Ref: https://itcodehub.blogspot.com/2019/06/using-optional-type-in-java.html
I've just started using Java on Eclipse (Juno) after a 15 year break from Java. I was using the ADK on a 1.6GHz Atom N270 with 4Gb RAM on W7 32bit on a nearly empty disk. Not sure if it is the Atom or whether Java is as bad as it used to be 15 years ago but it takes over 2 minutes for Eclipse to even start. The emulator does turn up eventually but is extremely sluggish. Even without the emulator, Eclipse is sluggish.
On a 1.6GHz Core i7 or a 2GHz Core 2 Duo, operation is reasonable. Emulator works, Eclipse takes about 5 to 10 seconds to be ready for work. Moral of the story: don't use an Atom or any other low powered processor. It is sluggish even with 4Gb memory and having the same clock speed as a high end processor.
I've also tried it in a VMWare VM on the 1.6GHz Core i7 and on the Core 2. It is reasonably fast until the the emulator is started. It then slows down to the point of no return. Redraws is now very much like that of the Atom but at least it responds when the buttons are clicked. Note that it is now running an emulator within an emulator. The only problem with VMs is that every so often W7 does what W7 does. There is a wait cursor and whole machine is totally unresponsive for a minute or two then it springs back to life. This was with VMWare V3. V4/V5 might be different. Varying the number of cores/processors did not make any difference to eclipse or the emulator.
Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.
In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.
Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!
Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).
Install Homebrew first :
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Then run this : brew install gdb
You can try the following:
function InitOverviewDataTable() {
oOverviewTable = $('#HelpdeskOverview').dataTable({
"bPaginate": true,
"bJQueryUI": true, // ThemeRoller-stöd
"bLengthChange": false,
"bFilter": false,
"bSort": false,
"bInfo": true,
"bAutoWidth": true,
"bProcessing": true,
"iDisplayLength": 10,
"sAjaxSource": '/Helpdesk/ActiveCases/noacceptancetest'
});
}
function RefreshTable(tableId, urlData) {
$.getJSON(urlData, null, function(json) {
table = $(tableId).dataTable();
oSettings = table.fnSettings();
table.fnClearTable(this);
for (var i = 0; i < json.aaData.length; i++) {
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
// Edited by Prasad
function AutoReload() {
RefreshTable('#HelpdeskOverview', '/Helpdesk/ActiveCases/noacceptancetest');
setTimeout(function() {
AutoReload();
}, 30000);
}
$(document).ready(function() {
InitOverviewDataTable();
setTimeout(function() {
AutoReload();
}, 30000);
});
If youR data was in A1:C100
then:
Excel - all versions
=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))
Excel - 2007 onwards
=COUNTIFS(A1:A100,"M",C1:C100,"Yes")
Other way which I found useful is:
git checkout <wildcard>
Example:
git checkout *.html
More generally:
git checkout <branch> <filename/wildcard>
In Code behind you can achieve it only by doing this.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
txtIndex.Focusable = true;
txtIndex.Focus();
}
Note: It wont work before window is loaded
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
yes you can do it. write this code on your typescript component and enjoy!
import { Location } from '@angular/common'
import { Component, Input } from '@angular/core'
@Component({
selector: 'return_page',
template: `<button mat-button (click)="onReturn()">Back</button>`,
})
export class ReturnPageComponent {
constructor(private location: Location) { }
onReturn() {
this.location.back();
}
}
base64 is the way to go for your simple needs. There is no need to import anything:
>>> 'your string'.encode('base64')
'eW91ciBzdHJpbmc=\n'
>>> _.decode('base64')
'your string'
Try these:
sudo modprobe vboxnetadp
sudo modprobe vboxnetflt
sudo modprobe vboxdrv
I just timed some functions out of curiosity. In these tests I'm removing non-alphanumeric characters from the string string.printable
(part of the built-in string
module). The use of compiled '[\W_]+'
and pattern.sub('', str)
was found to be fastest.
$ python -m timeit -s \
"import string" \
"''.join(ch for ch in string.printable if ch.isalnum())"
10000 loops, best of 3: 57.6 usec per loop
$ python -m timeit -s \
"import string" \
"filter(str.isalnum, string.printable)"
10000 loops, best of 3: 37.9 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]', '', string.printable)"
10000 loops, best of 3: 27.5 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]+', '', string.printable)"
100000 loops, best of 3: 15 usec per loop
$ python -m timeit -s \
"import re, string; pattern = re.compile('[\W_]+')" \
"pattern.sub('', string.printable)"
100000 loops, best of 3: 11.2 usec per loop
Generally speaking,
$('#startdate').data('date')
is best because
$('#startdate').val()
not work if you have a datepicker "inline"
There are several options. You can use the WebMethod attribute, for your purpose.
If MySQLdb's now distributed in a way that requires setuptools
, your choices are either to download the latter (e.g. from here) or refactor MySQLdb's setup.py to bypass setuptools
(maybe just importing setup
and Extension
from plain distutils
instead might work, but you may also need to edit some of the setup_*.py
files in the same directory).
Depending on how your site's Python installation is configured, installing extensions for your own individual use without requiring sysadm rights may be hard, but it's never truly impossible if you have shell access. You'll need to tweak your Python's sys.path to start with a directory of your own that's your personal equivalent of the system-wide site pacages directory, e.g. by setting PYTHONPATH
persistently in your own environment, and then manually place in said personal directory what normal installs would normally place in site-packages (and/or subdirectories thereof).
If this is happening to you with Android 6 and compile target >= 23, don't forget that we are now using runtime permissions. So giving permissions in the manifest is not enough anymore.
I was working on a dataframe and having no luck with the provided answers, it always returned 0 rows, so I found and used grepl:
df = df[grepl("downlink",df$Transmit.direction),]
Which basically trimmed my dataframe to only the rows that contained "downlink" in the Transmit direction column. P.S. If anyone can guess as to why I'm not seeing the expected behavior, please leave a comment.
Specifically to the original question:
expr[grepl("hesc",expr$cell_type),]
expr[grepl("bj fibroblast|hesc",expr$cell_type),]
from ..gen_py.lib import MyService
or
from main.gen_py.lib import MyService
Make sure you have a (at least empty) __init__.py
file on each directory.
I'm not sure why you'd be getting subscript out of range unless your sheets weren't actually called Sheet1
or Sheet2
. When I rename my Sheet2
to Sheet_2
, I get that same problem.
In addition, some of your code seems the wrong way about (you paste before selecting the second sheet). This code works fine for me.
Sub OneCell()
Sheets("Sheet1").Select
Range("A1:A3").Copy
Sheets("Sheet2").Select
Range("b1:b3").Select
ActiveSheet.Paste
End Sub
If you don't want to know about what the sheets are called, you can use integer indexes as follows:
Sub OneCell()
Sheets(1).Select
Range("A1:A3").Copy
Sheets(2).Select
Range("b1:b3").Select
ActiveSheet.Paste
End Sub
When installing npm packages (both globally or locally) you can define a specific version by using the @version
syntax to define a version to be installed.
In other words, doing:
npm install -g [email protected]
will ensure that only 0.9.2 is installed and won't reinstall if it already exists.
As a word of a advice, I would suggest avoiding global npm installs wherever you can. Many people don't realize that if a dependency defines a bin file, it gets installed to ./node_modules/.bin/. Often, its very easy to use that local version of an installed module that is defined in your package.json. In fact, npm scripts will add the ./node_modules/.bin onto your path.
As an example, here is a package.json that, when I run npm install && npm test
will install the version of karma defined in my package.json, and use that version of karma (installed at node_modules/.bin/karma) when running the test
script:
{
"name": "myApp",
"main": "app.js",
"scripts": {
"test": "karma test/*",
},
"dependencies": {...},
"devDependencies": {
"karma": "0.9.2"
}
}
This gives you the benefit of your package.json defining the version of karma to use and not having to keep that config globally on your CI box.
Here's a version using only the features available in a bare-bones shell (ie it'd work in sh
), and with one less process than using grep
:
if expr "$var" : '[0-9][0-9]*$'>/dev/null; then
echo yes
else
echo no
fi
This checks that the $var
represents only an integer; adjust the regexp to taste, and note that the expr
regexp argument is implicitly anchored at the beginning.
If your task is performing some kind of action in a loop there is a way to pause/restart processing, but I think it would have to be outside what the Thread API currently offers. If its a single shot process I am not aware of any way to suspend/restart without running into API that has been deprecated or is no longer allowed.
As for looped processes, the easiest way I could think of is that the code that spawns the Task instantiates a ReentrantLock and passes it to the task, as well as keeping a reference itself. Every time the Task enters its loop it attempts a lock on the ReentrantLock instance and when the loop completes it should unlock. You may want to encapsulate all this try/finally, making sure you let go of the lock at the end of the loop, even if an exception is thrown.
If you want to pause the task simply attempt a lock from the main code (since you kept a reference handy). What this will do is wait for the loop to complete and not let it start another iteration (since the main thread is holding a lock). To restart the thread simply unlock from the main code, this will allow the task to resume its loops.
To permanently stop the thread I would use the normal API or leave a flag in the Task and a setter for the flag (something like stopImmediately). When the loop encountered a true value for this flag it stops processing and completes the run method.
to make this work in both FF and IE you must write both ways:
button_element.setAttribute('onclick','doSomething();'); // for FF
button_element.onclick = function() {doSomething();}; // for IE
thanks to this post.
UPDATE: This is to demonstrate that sometimes it is necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:
// get old onclick attribute
var onclick = button_element.getAttribute("onclick");
// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") {
button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome
// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
button_element.onclick = function() {
doSomething();
onclick();
}; // for IE7
}
A solution that is viable for both Linux and Windows is to just get used to using console ffmpeg in your code. I stack up threads, write a simple thread controller class, then you can easily make use of what ever functionality of ffmpeg you want to use.
As an example, this contains sections use ffmpeg to create a thumbnail from a time that I specify.
In the thread controller you have something like
List<ThrdFfmpeg> threads = new List<ThrdFfmpeg>();
Which is the list of threads that you are running, I make use of a timer to Pole these threads, you can also set up an event if Pole'ing is not suitable for your application. In this case thw class Thrdffmpeg contains,
public class ThrdFfmpeg
{
public FfmpegStuff ffm { get; set; }
public Thread thrd { get; set; }
}
FFmpegStuff contains the various ffmpeg functionality, thrd is obviously the thread.
A property in FfmpegStuff is the class FilesToProcess, which is used to pass information to the called process, and receive information once the thread has stopped.
public class FileToProcess
{
public int videoID { get; set; }
public string fname { get; set; }
public int durationSeconds { get; set; }
public List<string> imgFiles { get; set; }
}
VideoID (I use a database) tells the threaded process which video to use taken from the database. fname is used in other parts of my functions that use FilesToProcess, but not used here. durationSeconds - is filled in by the threads that just collect video duration. imgFiles is used to return any thumbnails that were created.
I do not want to get bogged down in my code when the purpose of this is to encourage the use of ffmpeg in easily controlled threads.
Now we have our pieces we can add to our threads list, so in our controller we do something like,
AddThread()
{
ThrdFfmpeg thrd;
FileToProcess ftp;
foreach(FileToProcess ff in `dbhelper.GetFileNames(txtCategory.Text))`
{
//make a thread for each
ftp = new FileToProcess();
ftp = ff;
ftp.imgFiles = new List<string>();
thrd = new ThrdFfmpeg();
thrd.ffm = new FfmpegStuff();
thrd.ffm.filetoprocess = ftp;
thrd.thrd = new `System.Threading.Thread(thrd.ffm.CollectVideoLength);`
threads.Add(thrd);
}
if(timerNotStarted)
StartThreadTimer();
}
Now Pole'ing our threads becomes a simple task,
private void timerThreads_Tick(object sender, EventArgs e)
{
int runningCount = 0;
int finishedThreads = 0;
foreach(ThrdFfmpeg thrd in threads)
{
switch (thrd.thrd.ThreadState)
{
case System.Threading.ThreadState.Running:
++runningCount;
//Note that you can still view data progress here,
//but remember that you must use your safety checks
//here more than anywhere else in your code, make sure the data
//is readable and of the right sort, before you read it.
break;
case System.Threading.ThreadState.StopRequested:
break;
case System.Threading.ThreadState.SuspendRequested:
break;
case System.Threading.ThreadState.Background:
break;
case System.Threading.ThreadState.Unstarted:
//Any threads that have been added but not yet started, start now
thrd.thrd.Start();
++runningCount;
break;
case System.Threading.ThreadState.Stopped:
++finishedThreads;
//You can now safely read the results, in this case the
//data contained in FilesToProcess
//Such as
ThumbnailsReadyEvent( thrd.ffm );
break;
case System.Threading.ThreadState.WaitSleepJoin:
break;
case System.Threading.ThreadState.Suspended:
break;
case System.Threading.ThreadState.AbortRequested:
break;
case System.Threading.ThreadState.Aborted:
break;
default:
break;
}
}
if(flash)
{//just a simple indicator so that I can see
//that at least one thread is still running
lbThreadStatus.BackColor = Color.White;
flash = false;
}
else
{
lbThreadStatus.BackColor = this.BackColor;
flash = true;
}
if(finishedThreads >= threads.Count())
{
StopThreadTimer();
ShowSample();
MakeJoinedThumb();
}
}
Putting your own events onto into the controller class works well, but in video work, when my own code is not actually doing any of the video file processing, poling then invoking an event in the controlling class works just as well.
Using this method I have slowly built up just about every video and stills function I think I will ever use, all contained in the one class, and that class as a text file is useable on the Lunux and Windows version, with just a small number of pre-process directives.
I have solved as plist file.
For Nginx, the only thing that worked for me was adding this header:
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
Along with the Access-Control-Allow-Origin header:
add_header 'Access-Control-Allow-Origin' '*';
Then reloaded the nginx config and it worked great. Credit https://gist.github.com/algal/5480916.
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
Lets say to want to make default version as 10.19.0.
nvm alias default v10.19.0
But it will give following error
! WARNING: Version 'v10.19.0' does not exist.
default -> v10.19.0 (-> N/A)
In That case you need to run two commands in the following order
# Install the version that you would like
nvm install 10.19.0
# Set 10.19.0 (or another version) as default
nvm alias default 10.19.0
Take a look at the Commons CLI project, lots of good stuff in there.
You may use clone()
which works well if your object has immutable objects and/or primitives, but it may be a little problematic when you don't have these ( such as collections ) for which you may need to perform a deep clone.
User userCopy = (User) user.clone();//make a copy
for(...) {
user.age = 1;
user.id = -1;
UserDao.update(user)
user = userCopy;
}
It seems like you just want to preserve the attributes: age
and id
which are of type int
so, why don't you give it a try and see if it works.
For more complex scenarios you could create a "copy" method:
publc class User {
public static User copy( User other ) {
User newUser = new User();
newUser.age = other.age;
newUser.id = other.id;
//... etc.
return newUser;
}
}
It should take you about 10 minutes.
And then you can use that instead:
User userCopy = User.copy( user ); //make a copy
// etc.
To read more about clone read this chapter in Joshua Bloch "Effective Java: Override clone judiciously"
@dibrovsd: Solution will not work if the xml have more than one tag with same name
On your line of thought, I have modified the code a bit and written it for general node instead of root:
from collections import defaultdict
def xml2dict(node):
d, count = defaultdict(list), 1
for i in node:
d[i.tag + "_" + str(count)]['text'] = i.findtext('.')[0]
d[i.tag + "_" + str(count)]['attrib'] = i.attrib # attrib gives the list
d[i.tag + "_" + str(count)]['children'] = xml2dict(i) # it gives dict
return d
I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!
Download the Visual C++ Redistributable 2015
Updated links to VC++ file:
type -a PROG
in order to find all the places where PROG is available, usually somewhere in ~/bin rather than the one in /usr/bin/PROG that might have been expected.
Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.
Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().
Let's say that your input field has an id and name of "city":
<input type="text" name="city" id="city" />
Have a global variable named "city":
var city = "";
Add this to your page initialization:
setInterval(lookForCityChange, 100);
Then define a lookForCityChange() function:
function lookForCityChange()
{
var newCity = document.getElementById("city").value;
if (newCity != city) {
city = newCity;
doSomething(city); // do whatever you need to do
}
}
In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.
If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.
You can use the phone alias with Inputmask v3
$('#phone').inputmask({ alias: "phone", "clearIncomplete": true });
$(function() {_x000D_
$('input[type="tel"]').inputmask({ alias: "phone", "clearIncomplete": true });_x000D_
});
_x000D_
<label for="phone">Phone</label>_x000D_
<input name="phone" type="tel">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.numeric.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.date.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/inputmask.phone.extensions.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/jquery.inputmask.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/[email protected]/dist/inputmask/phone-codes/phone.js"></script>
_x000D_
for Oracle Database 10g users:
alter table mytable modify(mycolumn null);
You get "ORA-01735: invalid ALTER TABLE option" when you try otherwise
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
In my case, I created a new "Solution Configuration" like shown in the image. So when I select my custom one as "Prod", it doesnt recognize TestMehods for some reason. Changing back to "Debug" solves the problem
A better way to handle all of these suggestions in one command is
LC_ALL=C GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"
This will set the last commit's commit and author date to "right now."
The .selectedIndex
of the select
object has an index; you can use that to index into the .options
array.
The query below demonstrates use of the package and some of the information you can get.
select sys_context ( 'USERENV', 'DB_NAME' ) db_name,
sys_context ( 'USERENV', 'SESSION_USER' ) user_name,
sys_context ( 'USERENV', 'SERVER_HOST' ) db_host,
sys_context ( 'USERENV', 'HOST' ) user_host
from dual
NOTE: The parameter ‘SERVER_HOST’ is available in 10G only.
Any Oracle User that can connect to the database can run a query against “dual”. No special permissions are required and SYS_CONTEXT provides a greater range of application-specific information than “sys.v$instance”.
Best way to use UserDefaults
Steps
Sample
extension UserDefaults{
//MARK: Check Login
func setLoggedIn(value: Bool) {
set(value, forKey: UserDefaultsKeys.isLoggedIn.rawValue)
//synchronize()
}
func isLoggedIn()-> Bool {
return bool(forKey: UserDefaultsKeys.isLoggedIn.rawValue)
}
//MARK: Save User Data
func setUserID(value: Int){
set(value, forKey: UserDefaultsKeys.userID.rawValue)
//synchronize()
}
//MARK: Retrieve User Data
func getUserID() -> Int{
return integer(forKey: UserDefaultsKeys.userID.rawValue)
}
}
enum for Keys used to store data
enum UserDefaultsKeys : String {
case isLoggedIn
case userID
}
Save in UserDefaults where you want
UserDefaults.standard.setLoggedIn(value: true) // String
UserDefaults.standard.setUserID(value: result.User.id!) // String
Retrieve data anywhere in app
print("ID : \(UserDefaults.standard.getUserID())")
UserDefaults.standard.getUserID()
Remove Values
UserDefaults.standard.removeObject(forKey: UserDefaultsKeys.userID)
This way you can store primitive data in best
Update You need no use synchronize() to store the values. As @Moritz pointed out the it unnecessary and given the article about it.Check comments for more detail
To your secondary question
var elem1 = $('#elem1'),
elem2 = $('#elem2'),
elem3 = $('#elem3');
You can use the variable as the replacement of selector.
elem1.css({'display':'none'}); //will work
In the below case selector is already stored in a variable.
$(elem1,elem2,elem3).css({'display':'none'}); // will not work
The following is more Drupal-ish:
url(current_path(), array('absolute' => true));
@Furqan Could you please let me know whether you tested this with HTTP POST method,
Since I am also working on the same kind of situation, but I am not able to POST the data to different domain.
But after reading this it was quite simple...only thing is you have to forget about OLD browsers. I am giving code to send with POST method from same above URL for quick reference
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("POST", "http://www.sanshark.com/");
var content = "name=sandesh&lastname=daddi";
if (request){
request.onload = function(){
//do something with request.responseText
alert(request.responseText);
};
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", content.length);
request.send(content);
}
Your are probably looking for eval $var
.
wininet.dll
returns both standard and non-standard status codes that are listed below.
401 - Unauthorized file
403 - Forbidden file
404 - File Not Found
500 - some inclusion or functions may missed
200 - Completed
12002 - Server timeout
12029,12030, 12031 - dropped connections (either web server or DB server)
12152 - Connection closed by server.
13030 - StatusText properties are unavailable, and a query attempt throws an exception
For the status code "zero" are you trying to do a request on a local webpage running on a webserver or without a webserver?
XMLHttpRequest status = 0 and XMLHttpRequest statusText = unknown can help you if you are not running your script on a webserver.
In Swift 4 or 4.2
You can add on your vc
preferredStatusBarStyle
and set return value to
.lightContent or .default
ex:
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
I come across this all the time, so supplemental information regarding branches:
If you're working with multiple branches, shelvesets are tied to the specific branch in which you created them. So, if you let a changeset rust on the shelf for too long and have to unshelve to a different branch, then you have to do that with the July release of the power tools.
tfpt unshelve /migrate
zeros=[0]*4
you can replace 4
in the above example with whatever number you want.
unset()
and initialization:unset($_POST);
$_POST = array();
Or in a single statement:
unset($_POST) ? $_POST = array() : $_POST = array();
But what is the reason you want to do this?
Console.Read()
reads a single key, where Console.Readline()
waits for the Enter key.
JSONObject jsonobject=new JSONObject();
jsonobject.put("error","Invalid username");
response.getWriter().write(jsonobject.toString());
in javascript:
f(data!=success){
var errorMessage=jQuery.parseJson(data);
alert(errorMessage.error);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
Example
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)
Install
Available on npm as escape-string-regexp
npm install --save escape-string-regexp
Note
See MDN: Javascript Guide: Regular Expressions
Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.
.
.
.
.
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// \ ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn't matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
// I choose to escape every character with '\'
// even though only some strictly require it when inside of []
, regex = RegExp('[' + specials.join('\\') + ']', 'g')
;
escapeRegExp = function (str) {
return str.replace(regex, "\\$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());
I had to restart the rails application on the production so I looked for an another answer. I have found it below:
http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger
As stated before you can use -p to pass the password to the server.
But I recommend this:
mysql -h "hostaddress" -u "username" -p "database-name" < "sqlfile.sql"
Notice the password is not there. It would then prompt your for the password. I would THEN type it in. So that your password doesn't get logged into the servers command line history.
This is a basic security measure.
If security is not a concern, I would just temporarily remove the password from the database user. Then after the import - re-add it.
This way any other accounts you may have that share the same password would not be compromised.
It also appears that in your shell script you are not waiting/checking to see if the file you are trying to import actually exists. The perl script may not be finished yet.
We can use FlexBox for Sticky Footer and Header without using POSITIONS in CSS.
.container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
height: 50px;_x000D_
flex-shrink: 0;_x000D_
background-color: #037cf5;_x000D_
}_x000D_
_x000D_
footer {_x000D_
height: 50px;_x000D_
flex-shrink: 0;_x000D_
background-color: #134c7d;_x000D_
}_x000D_
_x000D_
main {_x000D_
flex: 1 0 auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<header>HEADER</header>_x000D_
<main class="content">_x000D_
_x000D_
</main>_x000D_
<footer>FOOTER</footer>_x000D_
</div>
_x000D_
DEMO - JSFiddle
Note : Check browser supports for FlexBox. caniuse
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
tl;dr What to do in modern (2018) times? Assume tel:
is supported, use it and forget about anything else.
The tel:
URI scheme RFC5431 (as well as sms:
but also feed:
, maps:
, youtube:
and others) is handled by protocol handlers (as mailto:
and http:
are).
They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto:
protocol handler with same meaning and behaviour of tel:
but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.
What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler()
and related functions) simplifying also the check for their support through isProtocolHandlerRegistered()
function.
There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).
In general what I suggest is:
tel:
is supported (yes, it's not true for very old devices but IMO you can ignore them).tel:
isn't supported then change links to use callto:
and repeat check desctibed in 3.tel:
and callto:
aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href
with javascript:void(0)
and (if number isn't repeated in text span) putting, telephone number in title
. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto:
and tel:
.Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:
tel:
is supported.tel:
with callto:
.tel:
or leave it as is (assuming there are good chances Skype is installed).Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
you can actually do it with numpy:
import numpy as np
a = np.fromstring('hi', dtype=np.uint8)
print(a)
//function to find vowel
const vowel = (str)=>{
//these are vowels we want to check for
const check = ['a','e','i','o','u'];
//keep track of vowels
var count = 0;
for(let char of str.toLowerCase())
{
//check if each character in string is in vowel array
if(check.includes(char)) count++;
}
return count;
}
console.log(vowel("hello there"));
After a long time suffering from it in PHPunit...
For those using namespace, which is very common with Frameworks or CMS, a good check in addition to seeing if php-xml is installed and active, is to remember to declare the DOMDocument after the namespace:
namespace YourNameSpace\YourNameSpace;
use DOMDocument; //<--- here, check this!
@InjectMocks annotation can be used to inject mock fields into a test object automatically.
In below example @InjectMocks has used to inject the mock dataMap into the dataLibrary .
@Mock
Map<String, String> dataMap ;
@InjectMocks
DataLibrary dataLibrary = new DataLibrary();
@Test
public void whenUseInjectMocksAnnotation_() {
Mockito.when(dataMap .get("aData")).thenReturn("aMeaning");
assertEquals("aMeaning", dataLibrary .getMeaning("aData"));
}
In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date
(usually GNU date).
As such:
# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal
In bash (<4.2):
# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directly
echo $(date '+%Y-%m-%d')
Other available date formats can be viewed from the date man pages (for external non-bash specific command):
man date
There are three ways to switch to the frame
1)Can use id
2)Can use name of the frame
3)Can use WebElement of the frame
2->driver.switchTo().frame("name of the frame");
_counter = 0 def foo(): global _counter _counter += 1 print 'counter is', _counter
Python customarily uses underscores to indicate private variables. The only reason in C to declare the static variable inside the function is to hide it outside the function, which is not really idiomatic Python.
Some addition to previous comments: 'firstboot' won't be available until you run 'mount_root' command.
So here is a full recap of what needs to be done. All manipulations I did on Windows 8.1.
netsh interface ip set address name="Ethernet" static 192.168.1.2 255.255.255.0 192.168.1.1
Now you can enter to the router console from a browser. Also don't forget to return your PC from static to DHCP address assignment. Example: netsh interface ip set address name="Ethernet" source=dhcp
Simplest NodeJS
const http = require('http');
const server = http.createServer((req, res) => {
SomeVeryLongAction(res);
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);
// the long running task - simplified to setTimeout here
// but can be async, wait from websocket service - whatever really
function SomeVeryLongAction(response) {
setTimeout(response.end, 10000);
}
Production wise scenario in Express for exmaple you would get response
in the middleware. Do you what you need to do, can scope out all of the long polled methods to Map or something (that is visible to other flows), and invoke <Response> response.end()
whenever you are ready. There is nothing special about long polled connections. Rest is just how you normally structure your application.
If you dont know what i mean by scoping out, this should give you idea
const http = require('http');
var responsesArray = [];
const server = http.createServer((req, res) => {
// not dealing with connection
// put it on stack (array in this case)
responsesArray.push(res);
// end this is where normal api flow ends
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
// and eventually when we are ready to resolve
// that if is there just to ensure you actually
// called endpoint before the timeout kicks in
function SomeVeryLongAction() {
if ( responsesArray.length ) {
let localResponse = responsesArray.shift();
localResponse.end();
}
}
// simulate some action out of endpoint flow
setTimeout(SomeVeryLongAction, 10000);
server.listen(8000);
As you see, you could really respond to all connections, one, do whatever you want. There is id
for every request so you should be able to use map and access specific out of api call.
If your looking to format into a string.
statusUpdate = "time " + new Date(Date.now()).toLocaleTimeString();
output "time 11:30:53 AM"
The post marked as answer gives a workaround, not a solution.
This solution works for me:
Window - Preferences - PyDev - Interpreters - Python Interpreter
Forced builtins
tabNew...
multiprocessing
in my case) and click OK
Not only will the error messages disappear, the module members will also be recognized.
Completely untested, but this should work:
View positiveButton = findViewById(R.id.positiveButton);
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
positiveButton.setLayoutParams(layoutParams);
add android:configChanges="orientation|screenSize"
inside your activity in your manifest
Hi I'm also new to react and I also faced this problem after so many trouble I found solution: Just run in your command prompt or terminal :
npm config set registry http://registry.npmjs.org/
This will resolve your problem. Reference link: http://blog.csdn.net/zhalcie2011/article/details/78726679
For downloading you can use multiple ways as been explained above, moreover I will also provide my strategy for this scenario.
npm install --save react-download-link
import DownloadLink from "react-download-link";
<DownloadLink
label="Download"
filename="fileName.txt"
exportFile={() => "Client side cache data here…"}
/>
<DownloadLink
label="Download with Promise"
filename="fileName.txt"
exportFile={() => Promise.resolve("cached data here …")}
/>
getDataFromURL = (url) => new Promise((resolve, reject) => {
setTimeout(() => {
fetch(url)
.then(response => response.text())
.then(data => {
resolve(data)
});
});
}, 2000);
<DownloadLink
label=”Download”
filename=”filename.txt”
exportFile={() => Promise.resolve(this. getDataFromURL (url))}
/>
Go for the simplest and shortest if you can -- DISTINCT seems to be more what you are looking for only because it will give you EXACTLY the answer you need and only that!
Mostly, I've seen it used to encode binary data in contexts that can only handle ascii - or a simple - character sets.