You don't really need to use the @staticmethod
decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)
Mostly, you just use functions though...
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
As far as I can tell, at this point it is not possible to set click_action in the console.
While not a strict answer to how to get the click_action set in the console, you can use curl as an alternative:
curl --header "Authorization: key=<YOUR_KEY_GOES_HERE>" --header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"/topics/news\",\"notification\": {\"title\": \"Click Action Message\",\"text\": \"Sample message\",\"click_action\":\"OPEN_ACTIVITY_1\"}}"
This is an easy way to test click_action mapping. It requires an intent filter like the one specified in the FCM docs:
<intent-filter>_x000D_
<action android:name="OPEN_ACTIVITY_1" />_x000D_
<category android:name="android.intent.category.DEFAULT" />_x000D_
</intent-filter>
_x000D_
This also makes use of topics to set the audience. In order for this to work you will need to subscribe to a topic called "news".
FirebaseMessaging.getInstance().subscribeToTopic("news");
Even though it takes several hours to see a newly-created topic in the console, you may still send messages to it through the FCM apis.
Also, keep in mind, this will only work if the app is in the background. If it is in the foreground you will need to implement an extension of FirebaseMessagingService. In the onMessageReceived method, you will need to manually navigate to your click_action target:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//This will give you the topic string from curl request (/topics/news)
Log.d(TAG, "From: " + remoteMessage.getFrom());
//This will give you the Text property in the curl request(Sample Message):
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//This is where you get your click_action
Log.d(TAG, "Notification Click Action: " + remoteMessage.getNotification().getClickAction());
//put code here to navigate based on click_action
}
As I said, at this time I cannot find a way to access notification payload properties through the console, but I thought this work around might be helpful.
A better solution is to set the doc width/height using the aspect ratio of your image.
var ExportModule = {_x000D_
// Member method to convert pixels to mm._x000D_
pxTomm: function(px) {_x000D_
return Math.floor(px / $('#my_mm').height());_x000D_
},_x000D_
ExportToPDF: function() {_x000D_
var myCanvas = document.getElementById("exportToPDF");_x000D_
_x000D_
html2canvas(myCanvas, {_x000D_
onrendered: function(canvas) {_x000D_
var imgData = canvas.toDataURL(_x000D_
'image/jpeg', 1.0);_x000D_
//Get the original size of canvas/image_x000D_
var img_w = canvas.width;_x000D_
var img_h = canvas.height;_x000D_
_x000D_
//Convert to mm_x000D_
var doc_w = ExportModule.pxTomm(img_w);_x000D_
var doc_h = ExportModule.pxTomm(img_h);_x000D_
//Set doc size_x000D_
var doc = new jsPDF('l', 'mm', [doc_w, doc_h]);_x000D_
_x000D_
//set image height similar to doc size_x000D_
doc.addImage(imgData, 'JPG', 0, 0, doc_w, doc_h);_x000D_
var currentTime = new Date();_x000D_
doc.save('Dashboard_' + currentTime + '.pdf');_x000D_
_x000D_
}_x000D_
});_x000D_
},_x000D_
}
_x000D_
<script src="Scripts/html2canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/jsPDF.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/addimage.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/fileSaver.js"></script>_x000D_
<div id="my_mm" style="height: 1mm; display: none"></div>_x000D_
_x000D_
<div id="exportToPDF">_x000D_
Your html here._x000D_
</div>_x000D_
_x000D_
<button id="export_btn" onclick="ExportModule.ExportToPDF();">Export</button>
_x000D_
I think in this case you want something like this:
$(window).resize(resize=function resize(){ some code...}
Now u can call resize() within some other nested functions:
$(window).scroll(function(){ resize();}
After applying : Tools > preferences > Graphics > Backend > Automatic Just restart the kernel
And you will surely get Interactive Plot. Happy Coding!
You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;
05/12/2015
In ANSI C:
char* strings[3];
strings[0] = "foo";
strings[1] = "bar";
strings[2] = "baz";
You can format the jquery date with this line:
moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");
Drawing an image using a QLabel
seems like a bit of a kludge to me. With newer versions of Qt you can use a QGraphicsView
widget. In Qt Creator, drag a Graphics View
widget onto your UI and name it something (it is named mainImage
in the code below). In mainwindow.h
, add something like the following as private
variables to your MainWindow
class:
QGraphicsScene *scene;
QPixmap image;
Then just edit mainwindow.cpp
and make the constructor something like this:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
image.load("myimage.png");
scene = new QGraphicsScene(this);
scene->addPixmap(image);
scene->setSceneRect(image.rect());
ui->mainImage->setScene(scene);
}
In windows:
java -cp C:/.../jardir1/*;C:/.../jardir2/* class_with_main_method
make sure that the class with the main function is in one of the included jars
You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session
(cookie) variable before redirecting and then get the variable before rendering the template. For example:
from flask import session, url_for
def do_baz():
messages = json.dumps({"main":"Condition failed on page baz"})
session['messages'] = messages
return redirect(url_for('.do_foo', messages=messages))
@app.route('/foo')
def do_foo():
messages = request.args['messages'] # counterpart for url_for()
messages = session['messages'] # counterpart for session
return render_template("foo.html", messages=json.loads(messages))
(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
Or you could probably just use Flask Message Flashing if you just need to show simple messages.
When you have the expression:
a % b = c
It really means there exists an integer n
that makes c
as small as possible, but non-negative.
a - n*b = c
By hand, you can just subtract 2
(or add 2
if your number is negative) over and over until the end result is the smallest positive number possible:
3.14 % 2
= 3.14 - 1 * 2
= 1.14
Also, 3.14 % 2 * pi
is interpreted as (3.14 % 2) * pi
. I'm not sure if you meant to write 3.14 % (2 * pi)
(in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).
The standard techniques to filter a list apply, although they are not as efficient as the split/join
or translate
methods.
We need a set of whitespaces:
>>> import string
>>> ws = set(string.whitespace)
The filter
builtin:
>>> "".join(filter(lambda c: c not in ws, "strip my spaces"))
'stripmyspaces'
A list comprehension (yes, use the brackets: see benchmark below):
>>> import string
>>> "".join([c for c in "strip my spaces" if c not in ws])
'stripmyspaces'
A fold:
>>> import functools
>>> "".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))
'stripmyspaces'
Benchmark:
>>> from timeit import timeit
>>> timeit('"".join("strip my spaces".split())')
0.17734256500003198
>>> timeit('"strip my spaces".translate(ws_dict)', 'import string; ws_dict = {ord(ws):None for ws in string.whitespace}')
0.457635745999994
>>> timeit('re.sub(r"\s+", "", "strip my spaces")', 'import re')
1.017787621000025
>>> SETUP = 'import string, operator, functools, itertools; ws = set(string.whitespace)'
>>> timeit('"".join([c for c in "strip my spaces" if c not in ws])', SETUP)
0.6484303600000203
>>> timeit('"".join(c for c in "strip my spaces" if c not in ws)', SETUP)
0.950212219999969
>>> timeit('"".join(filter(lambda c: c not in ws, "strip my spaces"))', SETUP)
1.3164566040000523
>>> timeit('"".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))', SETUP)
1.6947649049999995
Actually you can fix it with following steps -
cls.__dict__
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.del cls.__dict__['isFilled']
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
In Java you would do something similar to:
Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.
Just adding so you don't have to click-through:
curl --user name:password http://www.example.com
or if you're trying to do send authentication for OAuth 2:
curl -H "Authorization: OAuth <ACCESS_TOKEN>" http://www.example.com
I thought I would share my research on this. I needed to be able to detect if a specific extension was installed for some file:/// links to work. I came across this article here This explained a method of getting the manifest.json of an extension.
I adjusted the code a bit and came up with:
function Ext_Detect_NotInstalled(ExtName, ExtID) {
console.log(ExtName + ' Not Installed');
if (divAnnounce.innerHTML != '')
divAnnounce.innerHTML = divAnnounce.innerHTML + "<BR>"
divAnnounce.innerHTML = divAnnounce.innerHTML + 'Page needs ' + ExtName + ' Extension -- to intall the LocalLinks extension click <a href="https://chrome.google.com/webstore/detail/locallinks/' + ExtID + '">here</a>';
}
function Ext_Detect_Installed(ExtName, ExtID) {
console.log(ExtName + ' Installed');
}
var Ext_Detect = function (ExtName, ExtID) {
var s = document.createElement('script');
s.onload = function () { Ext_Detect_Installed(ExtName, ExtID); };
s.onerror = function () { Ext_Detect_NotInstalled(ExtName, ExtID); };
s.src = 'chrome-extension://' + ExtID + '/manifest.json';
document.body.appendChild(s);
}
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if (is_chrome == true) {
window.onload = function () { Ext_Detect('LocalLinks', 'jllpkdkcdjndhggodimiphkghogcpida'); };
}
With this you should be able to use Ext_Detect(ExtensionName,ExtensionID) to detect the installation of any number of extensions.
If you want to list categories, I think you should explicitly state your intention in the view.
<select ng-model="orderProp" >
<option ng-repeat="category in categories"
value="{{category}}">
{{category}}
</option>
</select>
in the controller:
$scope.categories = $scope.places.reduce(function(sum, place) {
if (sum.indexOf( place.category ) < 0) sum.push( place.category );
return sum;
}, []);
To avoid adding extra div
s when clicking on the link multiple times, and avoid problems when using the script to display forms, you could try a variation of @jek's code.
$('a.ajax').live('click', function() {
var url = this.href;
var dialog = $("#dialog");
if ($("#dialog").length == 0) {
dialog = $('<div id="dialog" style="display:hidden"></div>').appendTo('body');
}
// load remote content
dialog.load(
url,
{},
function(responseText, textStatus, XMLHttpRequest) {
dialog.dialog();
}
);
//prevent the browser to follow the link
return false;
});`
In order to be on the safe side, i would suggest to use also method
NetworkInfo.isConnected()
/**
* Checking whether network is connected
* @param context Context to get {@link ConnectivityManager}
* @return true if Network is connected, else false
*/
public static boolean isConnected(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
int networkType = activeNetwork.getType();
return networkType == ConnectivityManager.TYPE_WIFI || networkType == ConnectivityManager.TYPE_MOBILE;
} else {
return false;
}
}
This should do it:
HTML
<input name="Name" value="Enter Your Name" onClick="blankDefault('Enter Your Name', this)">
JavaScript
function blankDefault(_text, _this) {
if(_text == _this.value)
_this.value = '';
}
There are better/less obtrusive ways though, but this will get the job done.
You can add an extension method to javascript.
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}
This is piggy backing off of other answers. It's just a thought I had for managing the query strings.
Person.cs
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public static string Select()
{
return $"select top 1 person_id {nameof(PersonId)}, first_name {nameof(FirstName)}, last_name {nameof(LastName)}from Person";
}
}
API Method
using (var conn = ConnectionFactory.GetConnection())
{
var person = conn.Query<Person>(Person.Select()).ToList();
return person;
}
I write following function which convert base64 in direct way (without conversion to string at the middlestep). IDEA
=
char, remove one/two numbers from output arrayBelow solution allows to process large input base64 strings. Similar function for convert bytes to base64 without btoa is HERE
function base64ToBytesArr(str) {
const abc = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"]; // base64 alphabet
let result = [];
for(let i=0; i<str.length/4; i++) {
let chunk = [...str.slice(4*i,4*i+4)]
let bin = chunk.map(x=> abc.indexOf(x).toString(2).padStart(6,0)).join('');
let bytes = bin.match(/.{1,8}/g).map(x=> +('0b'+x));
result.push(...bytes.slice(0,3 - (str[4*i+2]=="=") - (str[4*i+3]=="=")));
}
return result;
}
// --------
// TEST
// --------
let test = "Alice's Adventure in Wonderland.";
console.log('test string:', test.length, test);
let b64_btoa = btoa(test);
console.log('encoded string:', b64_btoa);
let decodedBytes = base64ToBytesArr(b64_btoa); // decode base64 to array of bytes
console.log('decoded bytes:', JSON.stringify(decodedBytes));
let decodedTest = decodedBytes.map(b => String.fromCharCode(b) ).join``;
console.log('Uint8Array', JSON.stringify(new Uint8Array(decodedBytes)));
console.log('decoded string:', decodedTest.length, decodedTest);
_x000D_
What you could do is, create the "function" as another template file and then include that file passing the parameters to it.
Inside index.html
<h3> Latest Songs </h3>
{% include "song_player_list.html" with songs=latest_songs %}
Inside song_player_list.html
<ul>
{% for song in songs %}
<li>
<div id='songtile'>
<a href='/songs/download/{{song.id}}/'><i class='fa fa-cloud-download'></i> Download</a>
</div>
</li>
{% endfor %}
</ul>
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
In Swift 5, in order to sort Dictionary by KEYS
let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.0 < $1.0 })
In order to sort Dictionary by VALUES
let sortedYourArray = YOURDICTIONARY.sorted( by: { $0.1 < $1.1 })
You would need to install pip3.
On Linux, the command would be: sudo apt install python3-pip
On Mac, using brew, first brew install python3
Then brew postinstall python3
Try calling pip3 -V
to see if it worked.
I solved it 100% I had this problem with gulp version: 3.5.6.
You should clean the package-lock.js and then run npm install
and It worked form
POJO : It is a java file(class) which doesn't extend or implement any other java file(class).
Bean: It is a java file(class) in which all variables are private, methods are public and appropriate getters and setters are used for accessing variables.
Normal class: It is a java file(class) which may consist of public/private/default/protected variables and which may or may not extend or implement another java file(class).
Using the scatter
method of the matplotlib.pyplot
module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1
rather than numpoints=1
in the legend call to have only one point for each legend entry.
In the code below I've used random values rather than plotting the same range over and over, making all the plots visible (i.e. not overlapping each other).
import matplotlib.pyplot as plt
from numpy.random import random
colors = ['b', 'c', 'y', 'm', 'r']
lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])
plt.legend((lo, ll, l, a, h, hh, ho),
('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
scatterpoints=1,
loc='lower left',
ncol=3,
fontsize=8)
plt.show()
To plot a scatter in 3D, use the plot
method, as the legend does not support Patch3DCollection
as is returned by the scatter
method of an Axes3D
instance. To specify the markerstyle you can include this as a positional argument in the method call, as seen in the example below. Optionally one can include argument to both the linestyle
and marker
parameters.
import matplotlib.pyplot as plt
from numpy.random import random
from mpl_toolkits.mplot3d import Axes3D
colors=['b', 'c', 'y', 'm', 'r']
ax = plt.subplot(111, projection='3d')
ax.plot(random(10), random(10), random(10), 'x', color=colors[0], label='Low Outlier')
ax.plot(random(10), random(10), random(10), 'o', color=colors[0], label='LoLo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[1], label='Lo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[2], label='Average')
ax.plot(random(10), random(10), random(10), 'o', color=colors[3], label='Hi')
ax.plot(random(10), random(10), random(10), 'o', color=colors[4], label='HiHi')
ax.plot(random(10), random(10), random(10), 'x', color=colors[4], label='High Outlier')
plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))
plt.show()
I think the simple way is to use DateOffset from Pandas like so:
import pandas as pd
date_1 = pd.to_datetime("2013-03-31", format="%Y-%m-%d") - pd.DateOffset(months=1)
The result will be a Timestamp object
For opening a URL in the browser through the terminal, CentOS 7 users can use gio open command. For example, if you want to open google.com then gio open https://www.google.com
will open google.com URL in the browser.
xdg-open https://www.google.com
will also work but this tool has been deprecated, Use gio open
instead. I prefer this as this is the easiest way to open a URL using a command from the terminal.
As a slight improvement over the other answers, you can do the mkdir
and chmod
as a single operation using mkdir
's -m
switch.
$ mkdir -m 700 ${HOME}/.ssh
From a Linux system
$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.
Mandatory arguments to long options are mandatory for short options too.
-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask
...
...
For me, the revelation came when I realized that they all work the same way: by running something once, storing the value they get, and then cough up that same stored value when referenced through dependency injection.
Say we have:
app.factory('a', fn);
app.service('b', fn);
app.provider('c', fn);
The difference between the three is that:
a
's stored value comes from running fn
.b
’s stored value comes from new
ing fn
.c
’s stored value comes from first getting an instance by new
ing fn
, and then running a $get
method of the instance.Which means there’s something like a cache object inside AngularJS, whose value of each injection is only assigned once, when they've been injected the first time, and where:
cache.a = fn()
cache.b = new fn()
cache.c = (new fn()).$get()
This is why we use this
in services, and define a this.$get
in providers.
In addition to the very many excellent answers above you could also implement the following two functions in your projects. They will catch every non-syntax error before application/script exit. Inside the functions you can do a backtrace and log or render a pleasant 'Site is under maintenance' message to the public.
Fatal Errors:
register_shutdown_function
http://php.net/manual/en/function.register-shutdown-function.php
Errors:
set_error_handler
http://php.net/manual/en/function.set-error-handler.php
Backtracing:
debug_backtrace
Latest version works with:
console.log(socket.handshake.address);
The builtin command for properly indenting the code has already been mentioned (gg=G
). If you want to beautify the code, you'll need to use an external application like indent. Since %
denotes the current file in ex mode, you can use it like this:
:!indent %
You can use the sprintf
method, however the arg
method is preferred as it supports unicode.
QString str;
str.sprintf("%s %d", "string", 213);
I was using Jupyter notebook and tried almost all of the above solutions (adapting to my scenario) to no use. I then went line by line, deleted all spaces for each line and replaced with tab. That solved the issue.
String.prototype.startsWith
is a standard method in the most recent version of JavaScript, ES6.
Looking at the compatibility table below, we can see that it is supported on all current major platforms, except versions of Internet Explorer.
+-------------------------------------------------------------------------------+
¦ Feature ¦ Chrome ¦ Firefox ¦ Edge ¦ Internet Explorer ¦ Opera ¦ Safari ¦
¦---------------+--------+---------+-------+-------------------+-------+--------¦
¦ Basic Support ¦ 41+ ¦ 17+ ¦ (Yes) ¦ No Support ¦ 28 ¦ 9 ¦
+-------------------------------------------------------------------------------+
You'll need to implement .startsWith
yourself. Here is the polyfill:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
Just tell request that you are using json:true and forget about header and parse
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'GET',
json:true
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
and the same for post
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'POST',
json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
An eclipse specific alternative limited to the java.library.path JVM parameter allows to set it for a specific source folder rather than for the whole jdk as proposed in another response:
For those interested on detail on why maven argline tag should be preferred to the systemProperties one, look, for example:
One possibility is to delete to cookie you are looking for the expiration date from and rewrite it. Then you'll know the expiration date.
They are the same concepts, apart from the NULL value returned.
See below:
declare @table1 table( col1 int, col2 int );
insert into @table1 select 1, 11 union all select 2, 22;
declare @table2 table ( col1 int, col2 int );
insert into @table2 select 10, 101 union all select 2, 202;
select
t1.*,
t2.*
from @table1 t1
full outer join @table2 t2 on t1.col1 = t2.col1
order by t1.col1, t2.col1;
/* full outer join
col1 col2 col1 col2
----------- ----------- ----------- -----------
NULL NULL 10 101
1 11 NULL NULL
2 22 2 202
*/
select
t1.*,
t2.*
from @table1 t1
cross join @table2 t2
order by t1.col1, t2.col1;
/* cross join
col1 col2 col1 col2
----------- ----------- ----------- -----------
1 11 2 202
1 11 10 101
2 22 2 202
2 22 10 101
*/
The only way to ensure code is executed is to place your setTimeout logic in a different process.
Use the child process module to spawn a new node.js program that does your logic and pass data to that process through some kind of a stream (maybe tcp).
This way even if some long blocking code is running in your main process your child process has already started itself and placed a setTimeout in a new process and a new thread and will thus run when you expect it to.
Further complication are at a hardware level where you have more threads running then processes and thus context switching will cause (very minor) delays from your expected timing. This should be neglible and if it matters you need to seriously consider what your trying to do, why you need such accuracy and what kind of real time alternative hardware is available to do the job instead.
In general using child processes and running multiple node applications as separate processes together with a load balancer or shared data storage (like redis) is important for scaling your code.
Negatives are your friend here:
SELECT Col1
FROM TABLE
WHERE Col1 like '%[^a-Z0-9]%'
Which says that you want any rows where Col1
consists of any number of characters, then one character not in the set a-Z0-9, and then any number of characters.
If you have a case sensitive collation, it's important that you use a range that includes both upper and lower case A
, a
, Z
and z
, which is what I've given (originally I had it the wrong way around. a
comes before A
. Z
comes after z
)
Or, to put it another way, you could have written your original WHERE
as:
Col1 LIKE '[!@#$%]'
But, as you observed, you'd need to know all of the characters to include in the []
.
original answer
Yes.
window.screen.availHeight
window.screen.availWidth
update 2017-11-10
From Tsunamis in the comments:
To get the native resolution of i.e. a mobile device you have to multiply with the device pixel ratio:
window.screen.width * window.devicePixelRatio
andwindow.screen.height * window.devicePixelRatio
. This will also work on desktops, which will have a ratio of 1.
And from Ben in another answer:
In vanilla JavaScript, this will give you the AVAILABLE width/height:
window.screen.availHeight window.screen.availWidth
For the absolute width/height, use:
window.screen.height window.screen.width
A list comprehension is absolutely the way to do this. Another way that should be faster is map
and itemgetter
.
import operator
new_list = map(operator.itemgetter(1), old_list)
In response to the comment that the OP couldn't find an answer on google, I'll point out a super naive way to do it.
new_list = []
for item in old_list:
new_list.append(item[1])
This uses:
append
method on a list.If somebody is trying to learn a language and can't put together these basic pieces for themselves, then they need to view it as an exercise and do it themselves even if it takes twenty hours.
One needs to learn how to think about what one wants and compare that to the available tools. Every element in my second answer should be covered in a basic tutorial. You cannot learn to program without reading one.
To check Clustered Index exist on particular table or not:
SELECT * FROM SYS.indexes
WHERE index_id = 1 AND name IN (SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'Table_Name')
Good question, but it seems to have confused people. The answers are almost equally divided between those who thought Dave (the OP) was saving his HTML pages without the .html
extension, and those who thought he was saving them as normal (with .html
), but wanting the URL to show up without. While the question could have been worded a little better, I think it’s clear what he meant. If he was saving pages without .html
, his two question (‘how to remove .html') and (how to ‘redirect any url with .html’) would be exactly the same question! So that interpretation doesn’t make much sense. Also, his first comment (about avoiding an infinite loop) and his own answer seem to confirm this.
So let’s start by rephrasing the question and breaking down the task. We want to accomplish two things:
.html
if it’s part of the requested URL (e.g. /page.html
)/page
) back to the actual file (/page.html
).There’s nothing difficult about doing either of these things. (We could achieve the second one simply by enabling MultiViews.) The challenge here is doing them both without creating an infinite loop.
Dave’s own answer got the job done, but it’s pretty convoluted and not at all portable. (Sorry Dave.) Lukasz Habrzyk seems to have cleaned up Anmol’s answer, and finally Amit Verma improved on them both. However, none of them explained how their solutions solved the fundamental problem—how to avoid an infinite loop. As I understand it, they work because THE_REQUEST
variable holds the original request from the browser. As such, the condition (RewriteCond %{THE_REQUEST}
) only gets triggered once. Since it doesn’t get triggered upon a rewrite, you avoid the infinite loop scenario. But then you're dealing with the full HTTP request—GET
, HTTP
and all—which partly explains some of the uglier regex examples on this page.
I’m going to offer one more approach, which I think is easier to understand. I hope this helps future readers understand the code they’re using, rather than just copying and pasting code they barely understand and hoping for the best.
RewriteEngine on
# Remove .html (or htm) from visible URL (permanent redirect)
RewriteCond %{REQUEST_URI} ^/(.+)\.html?$ [nocase]
RewriteRule ^ /%1 [L,R=301]
# Quietly point back to the HTML file (temporary/undefined redirect):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [END]
Let’s break it down…
The first rule is pretty simple. The condition matches any URL ending in .html
(or .htm
) and redirects to the URL without the filename extension. It's a permanent redirect to indicate that the cropped URL is the canonical one.
The second rule is simple too. The first condition will only pass if the requested filename is not a valid directory (!-d
). The second will only pass if the filename refers to a valid file (-f
) with the .html extension added. If both conditions pass, the rewrite rule simply adds ‘.html’ to the filename. And then the magic happens… [END]
. Yep, that’s all it takes to prevent an infinite loop. The Apache RewriteRule Flags documentation explains it:
Using the [END] flag terminates not only the current round of rewrite processing (like [L]) but also prevents any subsequent rewrite processing from occurring in per-directory (htaccess) context.
You can use split
Reference: http://www.w3schools.com/jsref/jsref_split.asp
"0,1".split(',')
I have test project A and B. Tests in Project A where discovered but the Discovery never stopped for B. I had to manually kill TestHost to make stop.
I did a lot of things this page describes even to the point that I'm unsure as to wheter this was the solution.
Now it worked and the thing I did was to open the Solution and NOT have the Test Explorer up. Instead I just checked the Output window for Tests and I could see the discovery process end and the number of test where equal to A+B. After this, I opened the Test Explorer and then both A and B where present. So:
Uninstall and Install the latest xUnit stuff correctly. Delete the %temp% as mentioned above, Add NuGet Package "Microsoft.TestPlatform.TestHost" Add NuGet Package "Microsoft.NET.Test.Sdk", restart but only check the Tests Output. If it works u'll see
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
/** eworkyou **//
$('#navigation a').bind('click',function(e){
var $this = $(this);
var prev = current;
current = $this.parent().index() + 1; //
if (current == 1){
$("#navigation a:eq(1)").unbind("click"); //
}
if (current >= 2){
$("#navigation a:eq(1)").bind("click"); //
}
Make sure you're not sending a '#' at the end of your URL. In my case, that was preventing window.location.href from working.
[UPDATED privacy keys list to iOS 13 - see below]
There is a list of all Cocoa Keys
that you can specify in your Info.plist
file:
(Xcode: Target -> Info -> Custom iOS Target Properties)
iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).
Privacy keys with example description:
Alternatively, you can open Info.plist
as source code:
And add privacy keys like this:
<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>
List of all privacy keys: [UPDATED to iOS 13]
NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription
In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.
I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo
to ${PRODUCT_NAME} need access to the camera to update your avatar
even though the app context was obvious (user tapped on the avatar).
It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.
Please try below code :
public T? GetParsedOrDefaultValue<T>(string valueToParse) where T : struct, IComparable
{
if(string.EmptyOrNull(valueToParse))return null;
try
{
// return parsed value
return (T) Convert.ChangeType(valueToParse, typeof(T));
}
catch(Exception)
{
//default as null value
return null;
}
return null;
}
Use this:
static int RandomNumber(int min, int max)
{
Random random = new Random(); return random.Next(min, max);
}
This is example for you to modify and use in your application.
Just keep going with your code - you're on the right track:
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("NewColumn", typeof(System.Int32));
foreach(DataRow row in dt.Rows)
{
//need to set value to NewColumn column
row["NewColumn"] = 0; // or set it to some other value
}
// possibly save your Dataset here, after setting all the new values
I would strongly recommend using a library like PHPMailer to send emails.
It's easier and handles most of the issues automatically for you.
Regarding displaying embedded (inline) images, here's what's on their documentation:
Inline Attachments
There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with
<img src="cid:my-photo" alt="my-photo" />
.In detail, here is the function to add an inline attachment:
$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');
To give you a more complete example of how it would work:
<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->Port = 25; // set the SMTP port
$mail->SetFrom('[email protected]', 'First Last');
$mail->AddAddress('[email protected]', 'John Doe');
$mail->Subject = 'PHPMailer Test';
$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';
$mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
$mail->Send();
echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Regarding your comment, you asked how to send HTML email with embedded images, so I gave you an example of how to do that.
The library I told you about can send emails using a lot of methods other than SMTP.
Take a look at the PHPMailer Example page for other examples.
One way or the other, if you don't want to send the email in the ways supported by the library, you can (should) still use the library to build the message, then you send it the way you want.
For example:
You can replace the line that send the email:
$mail->Send();
With this:
$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want
Hope that helps. Let me know if you run into trouble using it.
sed
is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.
There are various versions of sed
with different levels of support for command line options and language features.
awk
is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if
/else
, while
, do
/while
and for
(C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf
and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk
.
GNU awk
(gawk
) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk
including mawk
and nawk
.
Both programs use regular expressions for selecting and processing text.
I would tend to use sed
where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):
sed 's/-\([0-9.]\+\)/(\1)/g' inputfile
I would use awk
when the text looks more like rows and columns or, as awk
refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:
awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile
Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.
You also have CSS Grid and CSS Flex, both can give you columns that keep their position and size ratios depending on screen size, and flex can also easily rearrange the columns if screen size is too small so they can maintain a minimum width nicely.
See these guides for full details:
Grid:
.container {
display: grid | inline-grid;
}
Flex:
.container {
display: flex | inline-flex;
}
Select from the table, use the ORDER BY __ DESC to sort in reverse order, then limit your results to 10.
SELECT * FROM big_table ORDER BY A DESC LIMIT 10
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block
Using a Android clientId (no client_secret) I was getting the following error response:
{
"error": "invalid_grant",
"error_description": "Missing code verifier."
}
I cannot find any documentation for the field 'code_verifier' but I discovered if you set it to equal values in both the authorization and token requests it will remove this error. I'm not sure what the intended value should be or if it should be secure. It has some minimum length (16? characters) but I found setting to null
also works.
I am using AppAuth for the authorization request in my Android client which has a setCodeVerifier()
function.
AuthorizationRequest authRequest = new AuthorizationRequest.Builder(
serviceConfiguration,
provider.getClientId(),
ResponseTypeValues.CODE,
provider.getRedirectUri()
)
.setScope(provider.getScope())
.setCodeVerifier(null)
.build();
Here is an example token request in node:
request.post(
'https://www.googleapis.com/oauth2/v4/token',
{ form: {
'code': '4/xxxxxxxxxxxxxxxxxxxx',
'code_verifier': null,
'client_id': 'xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
'client_secret': null,
'redirect_uri': 'com.domain.app:/oauth2redirect',
'grant_type': 'authorization_code'
} },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Success!');
} else {
console.log(response.statusCode + ' ' + error);
}
console.log(body);
}
);
I tested and this works with both https://www.googleapis.com/oauth2/v4/token
and https://accounts.google.com/o/oauth2/token
.
If you are using GoogleAuthorizationCodeTokenRequest
instead:
final GoogleAuthorizationCodeTokenRequest req = new GoogleAuthorizationCodeTokenRequest(
TRANSPORT,
JSON_FACTORY,
getClientId(),
getClientSecret(),
code,
redirectUrl
);
req.set("code_verifier", null);
GoogleTokenResponse response = req.execute();
CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.
first we read data in csv format and then convert to data frame and create a temp view
Reading data in csv format
val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")
printing the schema
data.printSchema
data.createOrReplaceTempView("Data")
Now we can run sql queries on top the table view we just created
%sql select Week as Date,Campaign Type,Engagements,Country from Data order by Date asc
Access has some sort of system tables You can read about it a little here you can fire the folowing query to see if it exists ( 1 = it exists, 0 = it doesnt ;))
SELECT Count([MSysObjects].[Name]) AS [Count]
FROM MSysObjects
WHERE (((MSysObjects.Name)="TblObject") AND ((MSysObjects.Type)=1));
Try using this:
var x:Int!
var xTimesTwo:Int {
get {
return x * 2
}
set {
x = newValue / 2
}
}
This is basically Jack Wu's answer, but the difference is that in Jack Wu's answer his x variable is var x: Int
, in mine, my x variable is like this: var x: Int!
, so all I did was make it an optional type.
you cannot add a background image to an html
newsletter which is to be viewed in outlook. It just wont work, as they ignore the property.
You can only have block colours (background-color
) behind text.
Outlook doesn't support the following CSS:
azimuth
background-attachment
background-image
background-position
background-repeat
border-spacing
bottom
caption-side
clear
clip
content
counter-increment
counter-reset
cue-before, cue-after, cue
cursor
display
elevation
empty-cells
float
font-size-adjust
font-stretch
left
line-break
list-style-image
list-style-position
marker-offset
max-height
max-width
min-height
min-width
orphans
outline
outline-color
outline-style
outline-width
overflow
overflow-x
overflow-y
pause-before, pause-after, pause
pitch
pitch-range
play-during
position
quotes
richness
right
speak
speak-header
speak-numeral
speak-punctuation
speech-rate
stress
table-layout
text-shadow
text-transform
top
unicode-bidi
visibility
voice-family
volume
widows
word-spacing
z-index
Source: http://msdn.microsoft.com/en-us/library/aa338201.aspx
UPDATE - July 2015
I thought it best to update this list as it gets the odd upvote every now and then - a great link to current email client support is available here: https://www.campaignmonitor.com/css/
:nth-last-child(-n+2)
should do the trick
public class ThreadClass {
volatile int i = 1;
volatile boolean state=true;
synchronized public void printOddNumbers(){
try {
while (!state) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+i);
state = false;
i++;
notifyAll();
}
synchronized public void printEvenNumbers(){
try {
while (state) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+i);
state = true;
i++;
notifyAll();
}
}
Then call the above class like this
// I am ttying to print 10 values.
ThreadClass threadClass=new ThreadClass();
Thread t1=new Thread(){
int k=0;
@Override
public void run() {
while (k<5) {
threadClass.printOddNumbers();
k++;
}
}
};
t1.setName("Thread1");
Thread t2=new Thread(){
int j=0;
@Override
public void run() {
while (j<5) {
threadClass.printEvenNumbers();
j++;
}
}
};
t2.setName("Thread2");
t1.start();
t2.start();
out put:
System.out: Thread1 1
System.out: Thread2 2
System.out: Thread1 3
System.out: Thread2 4
System.out: Thread1 5
System.out: Thread2 6
System.out: Thread1 7
System.out: Thread2 8
System.out: Thread1 9
System.out: Thread2 10
When an element, such as a div
is floated
, its parent container no longer considers its height, i.e.
<div id="main">
<div id="child" style="float:left;height:40px;"> Hi</div>
</div>
The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.
So the clearfix
class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.
Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.
Can read more here
I tried the procedures of your posts but with no success.
This is what I get from debugger:
Original string that I save into sqlite database was b\r\na
.. when I read them, I get b\\r\\na
(length in debugger is 6: "b" "\" "\r" "\" "\n" "a"
) then I try replace this string and I get string with length 6 again (you can see in picture above).
I run this short script in my test form with only one text box:
private void Form_Load(object sender, EventArgs e)
{
string x = "b\\r\\na";
string y = x.Replace(@"\\", @"\");
this.textBox.Text = y + "\r\n\r\nLength: " + y.Length.ToString();
}
and I get this in text box (so, no new line characters between "b" and "a":
b\r\na
Length: 6
What can I do with this string to unescape backslash? (I expect new line between "b" and "a".)
Solution:
OK, this is not possible to do with standard replace, because of \r
and \n
is one character. Is possible to replace part of string character by character but not possible to replace "half part" of one character. So, I must replace any special character separatelly, like this:
private void Form_Load(object sender, EventArgs e) {
...
string z = x.Replace(@"\r\n", Environment.NewLine);
...
This produce correct result for me:
b
a
A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.
Before JavaScript 1.5: ^[a-zA-Z_$][0-9a-zA-Z_$]*$
In English: It must start with a dollar sign, underscore or one of letters in the 26-character alphabet, upper or lower case. Subsequent characters (if any) can be one of any of those or a decimal digit.
JavaScript 1.5 and later * : ^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$
This is more difficult to express in English, but it is conceptually similar to the older syntax with the addition that the letters and digits can be from any language. After the first character, there are also allowed additional underscore-like characters (collectively called “connectors”) and additional character combining marks (“modifiers”). (Other currency symbols are not included in this extended set.)
JavaScript 1.5 and later also allows Unicode escape sequences, provided that the result is a character that would be allowed in the above regular expression.
Identifiers also must not be a current reserved word or one that is considered for future use.
There is no practical limit to the length of an identifier. (Browsers vary, but you’ll safely have 1000 characters and probably several more orders of magnitude than that.)
Links to the character categories:
*n.b. This Perl regex is intended to describe the syntax only — it won’t work in JavaScript, which doesn’t (yet) include support for Unicode Properties. (There are some third-party packages that claim to add such support.)
This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.
typedef void (*functiontype)();
Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:
void dosomething() { }
functiontype func = &dosomething;
func();
For a function that returns an int and takes a char you would do
typedef int (*functiontype2)(char);
and to use it
int dosomethingwithchar(char a) { return 1; }
functiontype2 func2 = &dosomethingwithchar
int result = func2('a');
There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!
boost::function<int (char a)> functiontype2;
is so much nicer than the above.
It was very tedious when I get same problem. When I got this problem, I uninstall my SQL Server 2008 but after installing the SQL Server 2008 again,I got the same problem. I was so tensed plus, I had not gotten any help from any site.
To over come this problem. Simply You Need to go on SQL Server Configuration Manager and then click On Protocols on left panel. If you running Network service just disable 'VIA' Protocol. And after that try to start your SQL service it will run successfully.
Give parent layout of ViewPager as NestedScrollView
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:fillViewport="true">
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.viewpager.widget.ViewPager>
</androidx.core.widget.NestedScrollView>
Don't forget to set android:fillViewport="true"
This will stretch scrollview and its child's content to fill the viewport.
https://developer.android.com/reference/android/widget/ScrollView.html#attr_android:fillViewport
I found similar error it was located to C:\Users\sony\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@schematics\angular\workspace\files
it is installed in windows try to search in c drive angular.json you will view the file
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
Your code is way more cluttered than necessary.
Replace (Not (X Is Nothing))
with X IsNot Nothing
and omit the outer parentheses:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For i As Integer = 0 To comp.Container.Components.Count() - 1
fixUIIn(comp.Container.Components(i), style)
Next
End If
Much more readable. … Also notice that I’ve removed the redundant Step 1
and the probably redundant .Item
.
But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each
instead:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For Each component In comp.Container.Components
fixUIIn(component, style)
Next
End If
Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)
function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
Hi Jack,
your function design is fine, but this function always misses the first dataset in the array. I tested that.
Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.
The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.
You can avoid that by moving the if condition above the second foreach loop like this:
function display_data($data) {
$output = "<table>";
foreach($data as $key => $var) {
//$output .= '<tr>';
if($key===0) {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= "<td>" . $col . '</td>';
}
$output .= '</tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
else {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
}
$output .= '</table>';
echo $output;
}
Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016
and another update that removes redundant code blocks that hurt maintainability of the code.
function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
This is my quick trick:
from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'
For more info Visit: https://humanfriendly.readthedocs.io/en/latest/#humanfriendly.format_timespan
I just installed Jest as global, ran jest myFileToTest.spec.js
, and it worked.
if you are using an IDE like visual studio and it is open while you sending commands close IDE and try again
git add .
and other commands, it will workout
The exception states that your result is closed. You should examine your code and look for all location where you issue a ResultSet.close()
call. Also look for Statement.close()
and Connection.close()
. For sure, one of them gets called before rs.next()
is called.
Problem 1
You mentioned it was your private docker registry, so you probably need to check Registry API instead of Hub registry API doc, which is the link you provided.
Problem 2
docker registry API is a client/server protocol, it is up to the server's implementation on whether to remove the images in the back-end. (I guess)
DELETE /v1/repositories/(namespace)/(repository)/tags/(tag*)
Detailed explanation
Below I demo how it works now from your description as my understanding for your questions.
I run a private docker registry.
I use the default one, and listen on port 5000
.
docker run -d -p 5000:5000 registry
Then I tag the local image and push into it.
$ docker tag ubuntu localhost:5000/ubuntu
$ docker push localhost:5000/ubuntu
The push refers to a repository [localhost:5000/ubuntu] (len: 1)
Sending image list
Pushing repository localhost:5000/ubuntu (1 tags)
511136ea3c5a: Image successfully pushed
d7ac5e4f1812: Image successfully pushed
2f4b4d6a4a06: Image successfully pushed
83ff768040a0: Image successfully pushed
6c37f792ddac: Image successfully pushed
e54ca5efa2e9: Image successfully pushed
Pushing tag for rev [e54ca5efa2e9] on {http://localhost:5000/v1/repositories/ubuntu/tags/latest}
After that I can use Registry API to check it exists in your private docker registry
$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags
{"latest": "e54ca5efa2e962582a223ca9810f7f1b62ea9b5c3975d14a5da79d3bf6020f37"}
Now I can delete the tag using that API !!
$ curl -X DELETE localhost:5000/v1/repositories/ubuntu/tags/latest
true
Check again, the tag doesn't exist in my private registry server
$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags/latest
{"error": "Tag not found"}
It's been some time since I used node.js, but I think I might be able to help.
Firstly, in node, you only have a single thread and are supposed to use callbacks. What will happen with your code, is that base.getID
query will get queued up by for execution, but the while
loop will continusouly run as a busy loop pointlessly.
You should be able to solve your issue with a callback as follows:
function generate(count, k) {
var _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
var str = '';
for(var i = 0; i < count; i++) {
str += _sym[parseInt(Math.random() * (_sym.length))];
}
base.getID(str, function(err, res) {
if(!res.length) {
k(str) // use the continuation
} else generate(count, k) // otherwise, recurse on generate
});
}
And use it as such
generate(10, function(uniqueId){
// have a uniqueId
})
I haven't coded any node/js in around 2 years and haven't tested this, but the basic idea should hold – don't use a busy loop, and use callbacks. You might want to have a look at the node async package.
continue
simply skips the rest of the code in the loop until next iteration
?modestbranding=1&autohide=1&showinfo=0&controls=0
autohide=1
is something that I never found... but it was the key :) I hope it's help
Route::get('/', function()
{
return View::make('home.index');
});
Route::get('user', function()
{
return View::make('user.index');
});
change above to
Route::get('user', function()
{
return View::make('user.index');
});
Route::get('/', function()
{
return View::make('home.index');
});
You have to use '/'(home/default) at the end in your routes
A simple way of using one instance of logging library in multiple modules for me was following solution:
import logging
logger = logging
logger.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
from base_logger import logger
if __name__ == '__main__':
logger.info("This is an info message")
I've used flex-grow
property to achieve this goal. You'll have to set display: flex
for parent container, then you need to set flex-grow: 1
for the block you want to fill remaining space, or just flex: 1
as tanius mentioned in the comments.
Change the wrapping from "onload
" to "No wrap - in <body>
"
The function defined has a different scope.
Taken from the example on this site, I think this would be the most natural way of doing it, by filling in the header value and passing the header to the template.
This is to fill in the header Authorization
:
String plainCreds = "willie:p@ssword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
And this is to pass the header to the REST template:
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();
Tasks are stored in 3 locations: 1 file system location and 2 registry locations.
C:\Windows\System32\Tasks
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree
So, you need to delete a corrupted task in these 3 locations.
String permutaions using Es6
Using reduce() method
const permutations = str => {_x000D_
if (str.length <= 2) _x000D_
return str.length === 2 ? [str, str[1] + str[0]] : [str];_x000D_
_x000D_
return str_x000D_
.split('')_x000D_
.reduce(_x000D_
(acc, letter, index) =>_x000D_
acc.concat(permutations(str.slice(0, index) + str.slice(index + 1)).map(val => letter + val)),_x000D_
[] _x000D_
);_x000D_
};_x000D_
_x000D_
console.log(permutations('STR'));
_x000D_
No, it is better practice to leave them out.
Without strip(), you can have empty keys and values:
apples<tab>round, fruity things
oranges<tab>round, fruity things
bananas<tab>
Without strip(), bananas is present in the dictionary but with an empty string as value. With strip(), this code will throw an exception because it strips the tab of the banana line.
I don't think there is a way to ignore adding DEFINER
s to the dump. But there are ways to remove them after the dump file is created.
Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost
with an empty string ""
Edit the dump (or pipe the output) using perl
:
perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
Apple has changed the rules on this. I read through all the Apple docs and as many of the US export regs as I could find.
My view on this was until recently even using HTTPS for most apps meant Apple would require the export certificate. Some apps such as banking would be OK but for many apps they did not fall into the excempt category which is very, very broad.
However Apple has now introduced a getout under the exempt category for apps that JUST use https. I do not know when they did this but I think it was either Dec 2016 or Jan 2017. We are now submitting our apps without the certificate from the US Govt.
If you are using Python 2, the following will be the solution:
import io
for line in io.open("u.item", encoding="ISO-8859-1"):
# Do something
Because the encoding
parameter doesn't work with open()
, you will be getting the following error:
TypeError: 'encoding' is an invalid keyword argument for this function
To add to the good answer by @Tomalak:
Here are some unmentioned and important differences:
xsl:apply-templates
is much richer and deeper than xsl:call-templates
and even from xsl:for-each
, simply because we don't know what code will be applied on the nodes of
the selection -- in the general case this code will be different for
different nodes of the node-list.
The code that will be applied
can be written way after the xsl:apply template
s was written and by
people that do not know the original author.
The FXSL library's implementation of higher-order functions (HOF) in XSLT wouldn't be possible if XSLT didn't have the <xsl:apply-templates>
instruction.
Summary: Templates and the <xsl:apply-templates>
instruction is how XSLT implements and deals with polymorphism.
Reference: See this whole thread: http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/200411/msg00546.html
I think that CodeRush has a free, limited version, too. I ended up going with ReSharper, and I still recommend it, even though some of the functionality is in Visual Studio 2010. There are just some things that make it worth it.
Keep in mind that you don't need the full ReSharper license if you only code in one language. I have the C# version, and it's cheaper.
Another solution is to use output buffering, you can collect everything that is being outputted/echoed and store it in a variable.
<?php
ob_start();
?>line1
line2
line3<?php
$xml = ob_get_clean();
Please note that output buffering might not be the best solution in terms of performance and code cleanliness for this exact case but worth leaving it here for reference.
Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)
Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.
If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:
my %new_hash = %hash1; # make a copy; leave %hash1 alone
foreach my $key2 ( keys %hash2 )
{
if( exists $new_hash{$key2} )
{
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else
{
$new_hash{$key2} = $hash2{$key2};
}
}
If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.
foreach my $key2 ( keys %hash2 )
{
if( exists $hash1{$key2} )
{
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else
{
$hash1{$key2} = $hash2{$key2};
}
}
If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:
@hash1{ keys %hash2 } = values %hash2;
Do this:
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
Context initialContext = new InitialContext(props);
Also add this to the libraries of the project:
C:\installs\glassfish\glassfish-4.1\glassfish\lib\gf-client.jar
adjust path accordingly
I was having the same problem. I installed with
adb shell pm install --user <userId> test.apk
For some reason, there was no icon on the screen. It was a debug build and all other consecutive installs were not working. Simply uninstalling the package helped.
adb uninstall com.package.name
DECLARE @t TABLE (ID UNIQUEIDENTIFIER DEFAULT NEWID(),myid UNIQUEIDENTIFIER
, friendid UNIQUEIDENTIFIER, time1 Datetime, time2 Datetime)
insert into @t (myid,friendid,time1,time2)
values
( CONVERT(uniqueidentifier,'0C6A36BA-10E4-438F-BA86-0D5B68A2BB15'),
CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E'),
'2014-01-05 02:04:41.953','2014-01-05 12:04:41.953')
SELECT * FROM @t
Result Set With out any errors
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
¦ ID ¦ myid ¦ friendid ¦ time1 ¦ time2 ¦
¦--------------------------------------+--------------------------------------+--------------------------------------+-------------------------+-------------------------¦
¦ CF628202-33F3-49CF-8828-CB2D93C69675 ¦ 0C6A36BA-10E4-438F-BA86-0D5B68A2BB15 ¦ DF215E10-8BD4-4401-B2DC-99BB03135F2E ¦ 2014-01-05 02:04:41.953 ¦ 2014-01-05 12:04:41.953 ¦
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:
document.body.onclick = function( e ) {
// Cross-browser handling
var evt = e || window.event,
target = evt.target || evt.srcElement;
// If the element clicked is an anchor
if ( target.nodeName === 'A' ) {
// Add the confirm box
return confirm( 'Are you sure?' );
}
};
This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.
You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.
To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):
SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.
String input = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date);
...
JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
For the disabled buttons you can use the :disabled
pseudo-element. It works for all the elements.
For browsers/devices supporting CSS2 only, you can use the [disabled]
selector.
As with the image, don't put an image in the button. Use CSS background-image
with background-position
and background-repeat
. That way, the image dragging will not occur.
Selection problem: here is a link to the specific question:
Example for the disabled selector:
button {_x000D_
border: 1px solid #0066cc;_x000D_
background-color: #0099cc;_x000D_
color: #ffffff;_x000D_
padding: 5px 10px;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
border: 1px solid #0099cc;_x000D_
background-color: #00aacc;_x000D_
color: #ffffff;_x000D_
padding: 5px 10px;_x000D_
}_x000D_
_x000D_
button:disabled,_x000D_
button[disabled]{_x000D_
border: 1px solid #999999;_x000D_
background-color: #cccccc;_x000D_
color: #666666;_x000D_
}_x000D_
_x000D_
div {_x000D_
padding: 5px 10px;_x000D_
}
_x000D_
<div>_x000D_
<button> This is a working button </button>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<button disabled> This is a disabled button </button>_x000D_
</div>
_x000D_
Just for the record, I wanted to know the answer to this question, so I used a PHP method:
<script>
var jGets = new Array ();
<?
if(isset($_GET)) {
foreach($_GET as $key => $val)
echo "jGets[\"$key\"]=\"$val\";\n";
}
?>
</script>
That way all my javascript/jquery that runs after this can access everything in the jGets. Its an nice elegant solution I feel.
Yes, via extensions. Try Bookmarks extension on marketplace.visualstudio.com
Hit Ctrl+Shift+P and type the install extensions
and press enter, then type Bookmark
and press enter.
Next you may wish to customize what keys are used to make a bookmark and move to it. For that see this question.
If you use nano with a language like python (as in your example) it's also a good idea to convert tabs to spaces.
Edit your ~/.nanorc file (or create it) and add:
set tabsize 4
set tabstospaces
If you already got a file with tabs and want to convert them to spaces i recommend the expand
command (shell):
expand -4 input.py > output.py
When this happens the easiest solution is to make the virtual directory manually.
First of all, you need to make sure you have the right version of ASP.Net installed and that you have installed the IIS extensions.
To do this, go to the relevant .net version's folder in C:\(Windows)\Microsoft.NET\Framework\(dotnetver)\ (substituting the bracketed folders for the right folders on your PC) and run this command
aspnet_regiis.exe -i
Next once that's run and finished, sometimes running
iisreset
from the command line helps, sometimes you don't need to.
Next, go to your IIS Manager and find you localhost website and choose add a folder. Browse to the folder in your project that contains the actual ASP.Net project and add that.
Finally, right click on the folder you added and you should have an option that says 'convert to application' or 'create virtual directory' or something similar.
!!Make sure the Virtual directory has the name 'MyWebApp'!!
Reload your solution and it should work.
Please be wary; this isn't a programming question (and shouldn't really be posted here) but I've posted this guidance as it's a common problem, but the advice I've posted is generic; the commands I've listed are correct but the steps you need to do in IIS may vary, it depends on your version and your account privileges.
Good luck!
Use the --prefix
or -p
option to specify where to write the environment files. For example:
conda create --prefix /tmp/test-env python=2.7
Will create the environment named /tmp/test-env
which resides in /tmp/
instead of the default .conda
.
I love the answer from @Bert F but this is the way my brain sees it.
I have an X in my hand. If I want to write my X into a List, that List needs to be either a List of X or a List of things that my X can be upcast to as I write them in i.e. any superclass of X...
List<? super X>
If I get a List and I want to read an X out of that List, that better be a List of X or a List of things that can be upcast to X as I read them out, i.e. anything that extends X
List<? extends X>
Hope this helps.
TLDR; MySql does not have an equivalent concept of varchar(max)
, this is a MS SQL Server feature.
varchar(max)
is a feature of Microsoft SQL Server.
The amount of data that a column could store in Microsoft SQL server versions prior to version 2005 was limited to 8KB. In order to store more than 8KB you would have to use TEXT
, NTEXT
, or BLOB
columns types, these column types stored their data as a collection of 8K pages separate from the table data pages; they supported storing up to 2GB per row.
The big caveat to these column types was that they usually required special functions and statements to access and modify the data (e.g. READTEXT
, WRITETEXT
, and UPDATETEXT
)
In SQL Server 2005, varchar(max)
was introduced to unify the data and queries used to retrieve and modify data in large columns. The data for varchar(max)
columns is stored inline with the table data pages.
As the data in the MAX column fills an 8KB data page an overflow page is allocated and the previous page points to it forming a linked list. Unlike TEXT
, NTEXT
, and BLOB
the varchar(max)
column type supports all the same query semantics as other column types.
So varchar(MAX)
really means varchar(AS_MUCH_AS_I_WANT_TO_STUFF_IN_HERE_JUST_KEEP_GROWING)
and not varchar(MAX_SIZE_OF_A_COLUMN)
.
In order to get the same amount of storage as a varchar(max)
in MySql you would still need to resort to a BLOB
column type. This article discusses a very effective method of storing large amounts of data in MySql efficiently.
a sample can be
script-loader.service.ts file
import {Injectable} from '@angular/core';
import * as $ from 'jquery';
declare let document: any;
interface Script {
src: string;
loaded: boolean;
}
@Injectable()
export class ScriptLoaderService {
public _scripts: Script[] = [];
/**
* @deprecated
* @param tag
* @param {string} scripts
* @returns {Promise<any[]>}
*/
load(tag, ...scripts: string[]) {
scripts.forEach((src: string) => {
if (!this._scripts[src]) {
this._scripts[src] = {src: src, loaded: false};
}
});
let promises: any[] = [];
scripts.forEach((src) => promises.push(this.loadScript(tag, src)));
return Promise.all(promises);
}
/**
* Lazy load list of scripts
* @param tag
* @param scripts
* @param loadOnce
* @returns {Promise<any[]>}
*/
loadScripts(tag, scripts, loadOnce?: boolean) {
loadOnce = loadOnce || false;
scripts.forEach((script: string) => {
if (!this._scripts[script]) {
this._scripts[script] = {src: script, loaded: false};
}
});
let promises: any[] = [];
scripts.forEach(
(script) => promises.push(this.loadScript(tag, script, loadOnce)));
return Promise.all(promises);
}
/**
* Lazy load a single script
* @param tag
* @param {string} src
* @param loadOnce
* @returns {Promise<any>}
*/
loadScript(tag, src: string, loadOnce?: boolean) {
loadOnce = loadOnce || false;
if (!this._scripts[src]) {
this._scripts[src] = {src: src, loaded: false};
}
return new Promise((resolve, reject) => {
// resolve if already loaded
if (this._scripts[src].loaded && loadOnce) {
resolve({src: src, loaded: true});
}
else {
// load script tag
let scriptTag = $('<script/>').
attr('type', 'text/javascript').
attr('src', this._scripts[src].src);
$(tag).append(scriptTag);
this._scripts[src] = {src: src, loaded: true};
resolve({src: src, loaded: true});
}
});
}
}
and usage
first inject
constructor(
private _script: ScriptLoaderService) {
}
then
ngAfterViewInit() {
this._script.loadScripts('app-wizard-wizard-3',
['assets/demo/default/custom/crud/wizard/wizard.js']);
}
or
this._script.loadScripts('body', [
'assets/vendors/base/vendors.bundle.js',
'assets/demo/default/base/scripts.bundle.js'], true).then(() => {
Helpers.setLoading(false);
this.handleFormSwitch();
this.handleSignInFormSubmit();
this.handleSignUpFormSubmit();
this.handleForgetPasswordFormSubmit();
});
When you share for Facebook, you have to add in your html into the head section next meta tags:
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
And that's it!
Add the button as you should according to what FB tells you.
All the info you need is in www.facebook.com/share/
A really good way to make a tooltip is described here: Simple D3 tooltip example
You have to append a div
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("a simple tooltip");
Then you can just toggle it using
.on("mouseover", function(){return tooltip.style("visibility", "visible");})
.on("mousemove", function(){return tooltip.style("top",
(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");});
d3.event.pageX
/ d3.event.pageY
is the current mouse coordinate.
If you want to change the text you can use tooltip.text("my tooltip text");
From Apple Docs
You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."
If you want to target a specific class and ID in CSS, then use a format like div.x#y {}
.
it seems that
python -m pip install XXX
will work anyway (worked for me) (see link by user474491)
SSH doesn't use the :
syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config
file and add:
Host git.host.de Port 4019
Then specify just git.host.de
without a port number.
I was a bit puzzled that norm.fit
apparently only worked with the expanded list of sampled values. I tried giving it two lists of numbers, or lists of tuples, but it only appeared to flatten everything and threat the input as individual samples. Since I already have a histogram based on millions of samples, I didn't want to expand this if I didn't have to. Thankfully, the normal distribution is trivial to calculate, so...
# histogram is [(val,count)]
from math import sqrt
def normfit(hist):
n,s,ss = univar(hist)
mu = s/n
var = ss/n-mu*mu
return (mu, sqrt(var))
def univar(hist):
n = 0
s = 0
ss = 0
for v,c in hist:
n += c
s += c*v
ss += c*v*v
return n, s, ss
I'm sure this must be provided by the libraries, but as I couldn't find it anywhere, I'm posting this here instead. Feel free to point to the correct way to do it and downvote me :-)
This is as simple as this.
window.open('_link is here_', 'name');
Function description:
name
is a name of the window. Following names are supported:
_blank
- URL is loaded into a new tab. This is default._parent
- URL is loaded into the parent frame_self
- URL replaces the current page_top
- URL replaces any framesets that may be loadedAssuming you have a JSON hash hanging around somewhere, to automatically convert it into something like WarHog's version, wrap your JSON hash contents in %q{hsh}
tags.
This seems to automatically add all the necessary escaped text like in WarHog's answer.
Like the accepted answer well explained by lhunath, you can use
command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)
Beware than if you use bash you could have some issue.
Let me take the matthew-wilcoxson exemple.
And for those who "seeing is believing", a quick test:
(echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)
Personally, when I try, I have this result :
user@computer:~$ (echo "Test Out";>&2 echo "Test Err") > >(tee stdout.log) 2> >(tee stderr.log >&2)
user@computer:~$ Test Out
Test Err
Both message does not appear at the same level. Why Test Out
seem to be put like if it is my previous command ?
Prompt is on a blank line, let me think the process is not finished, and when I press Enter
this fix it.
When I check the content of the files, it is ok, redirection works.
Let take another test.
function outerr() {
echo "out" # stdout
echo >&2 "err" # stderr
}
user@computer:~$ outerr
out
err
user@computer:~$ outerr >/dev/null
err
user@computer:~$ outerr 2>/dev/null
out
Trying again the redirection, but with this function.
function test_redirect() {
fout="stdout.log"
ferr="stderr.log"
echo "$ outerr"
(outerr) > >(tee "$fout") 2> >(tee "$ferr" >&2)
echo "# $fout content :"
cat "$fout"
echo "# $ferr content :"
cat "$ferr"
}
Personally, I have this result :
user@computer:~$ test_redirect
$ outerr
# stdout.log content :
out
out
err
# stderr.log content :
err
user@computer:~$
No prompt on a blank line, but I don't see normal output, stdout.log content seem to be wrong, only stderr.log seem to be ok. If I relaunch it, output can be different...
So, why ?
Because, like explained here :
Beware that in bash, this command returns as soon as [first command] finishes, even if the tee commands are still executed (ksh and zsh do wait for the subprocesses)
So, if you use bash, prefer use the better exemple given in this other answer :
{ { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2
It will fix the previous issues.
Now, the question is, how to retrieve exit status code ?
$?
does not works.
I have no found better solution than switch on pipefail with set -o pipefail
(set +o pipefail
to switch off) and use ${PIPESTATUS[0]}
like this
function outerr() {
echo "out"
echo >&2 "err"
return 11
}
function test_outerr() {
local - # To preserve set option
! [[ -o pipefail ]] && set -o pipefail; # Or use second part directly
local fout="stdout.log"
local ferr="stderr.log"
echo "$ outerr"
{ { outerr | tee "$fout"; } 2>&1 1>&3 | tee "$ferr"; } 3>&1 1>&2
# First save the status or it will be lost
local status="${PIPESTATUS[0]}" # Save first, the second is 0, perhaps tee status code.
echo "==="
echo "# $fout content :"
echo "<==="
cat "$fout"
echo "===>"
echo "# $ferr content :"
echo "<==="
cat "$ferr"
echo "===>"
if (( status > 0 )); then
echo "Fail $status > 0"
return "$status" # or whatever
fi
}
user@computer:~$ test_outerr
$ outerr
err
out
===
# stdout.log content :
<===
out
===>
# stderr.log content :
<===
err
===>
Fail 11 > 0
You can use the upper() function in your query, and to increase performance you can use a function-base index
CREATE INDEX upper_index_name ON table(upper(name))
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
This can also be done as follows for a list of dataframes df_list
:
df = df_list[0]
for df_ in df_list[1:]:
df = df.merge(df_, on='join_col_name')
or if the dataframes are in a generator object (e.g. to reduce memory consumption):
df = next(df_list)
for df_ in df_list:
df = df.merge(df_, on='join_col_name')
On Selenium >= 3.41 (C#) the rigth syntax is:
webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));
From official documentation. Maybe you can use it in your case.
When you need equal height, add .h-100 to the cards.
<div class="row row-cols-1 row-cols-md-3 g-4">
<div class="col">
<div class="card h-100">
<div>.....</div>
</div>
<div class="col">
<div class="card h-100">
<div>.....</div>
</div>
Hardware -> Erase all content and settings did the job for me (other things didn't).
This is a good article about the subject.
To summarize,
An application program that is executed within a runtime engine installed in the same machine. The application cannot run without it. The runtime environment provides the general library of software routines that the program uses and typically performs memory management. It may also provide just-in-time (JIT) conversion from source code to executable code or from an intermediate language to executable code. Java, Visual Basic and .NET's Common Language Runtime (CLR) are examples of runtime engines. (Read more)
An executable program that runs by itself. Launched from the operating system, the program calls upon and uses the software routines in the operating system, but does not require another software system to be used. Assembly language programs that have been assembled into machine language and C/C++ programs compiled into machine language for a particular platform are examples of unmanaged code.(Read more)
The best I can find is to set input[type="password"] {font:small-caption;font-size:16px}
Demo:
input {_x000D_
font: small-caption;_x000D_
font-size: 16px;_x000D_
}
_x000D_
<input type="password">
_x000D_
Say you have a child_method()
in the child component:
export default {
methods: {
child_method () {
console.log('I got clicked')
}
}
}
Now you want to execute the child_method
from parent component:
<template>
<div>
<button @click="exec">Execute child component</button>
<child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
</div>
</template>
export default {
methods: {
exec () { //accessing the child component instance through $refs
this.$refs.child.child_method() //execute the method belongs to the child component
}
}
}
If you want to execute a parent component method from child component:
this.$parent.name_of_method()
NOTE: It is not recommended to access the child and parent component like this.
Instead as best practice use Props & Events for parent-child communication.
If you want communication between components surely use vuex or event bus
Please read this very helpful article
getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.
The simplest method is using the tac
command. tac
is cat
's inverse.
Example:
$ cat order.txt
roger shah
armin van buuren
fpga vhdl arduino c++ java gridgain
$ tac order.txt > inverted_file.txt
$ cat inverted_file.txt
fpga vhdl arduino c++ java gridgain
armin van buuren
roger shah
Assuming your row number is in B1
, you can use INDIRECT
:
=INDIRECT("A" & B1)
This takes a cell reference as a string (in this case, the concatenation of A
and the value of B1
- 5), and returns the value at that cell.
You could just declare a DBMS_SQL.VARCHAR2_TABLE to hold an in-memory variable length array indexed by a BINARY_INTEGER:
DECLARE
name_array dbms_sql.varchar2_table;
BEGIN
name_array(1) := 'Tim';
name_array(2) := 'Daisy';
name_array(3) := 'Mike';
name_array(4) := 'Marsha';
--
FOR i IN name_array.FIRST .. name_array.LAST
LOOP
-- Do something
END LOOP;
END;
You could use an associative array (used to be called PL/SQL tables) as they are an in-memory array.
DECLARE
TYPE employee_arraytype IS TABLE OF employee%ROWTYPE
INDEX BY PLS_INTEGER;
employee_array employee_arraytype;
BEGIN
SELECT *
BULK COLLECT INTO employee_array
FROM employee
WHERE department = 10;
--
FOR i IN employee_array.FIRST .. employee_array.LAST
LOOP
-- Do something
END LOOP;
END;
The associative array can hold any make up of record types.
Hope it helps, Ollie.
You can do this with JQuery
Simply:
<form name='add'>
Age: <select id="age" name='age'>
<option value='1' stud_name='sre'>23</option>
<option value='2' stud_name='sam'>24</option>
<option value='5' stud_name='john'>25</option>
</select>
<input type='hidden' id="name" name="name" value=""/>
<input type='submit' name='submit'/>
</form>
Add this code in Header section:
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
Now JQuery function
<script type="text/javascript" language="javascript">
$(function() {
$("#age").change(function(){
var studentNmae= $('option:selected', this).attr('stud_name');
$('#name').val(studentNmae);
});
});
</script>
you can use both values as
$name = $_POST['name'];
$value = $_POST['age'];
Yes you can put the break-point on client side page in Visual studio
First Put the debugger in java-script code and run the page in browser
debugger
After that open your page in browser and view the inspect element you see the following view
Another alternative is the old school NET USER commands:
NET USER username "password" /ADD
OK - you can't set all the options but it's a lot less convoluted for simple user creation & easy to script up in Powershell.
NET LOCALGROUP "group" "user" /add
to set group membership.
The element.style
property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle
property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle
method.
The two ways have differences, for example, the IE element.currentStyle
property expect that you access the CCS property names composed of two or more words in camelCase (e.g. maxHeight
, fontSize
, backgroundColor
, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height
, font-size
, background-color
, etc).
Also, the IE element.currentStyle
will return all the sizes in the unit that they were specified, (e.g. 12pt, 50%, 5em), the standard way will compute the actual size in pixels always.
I made some time ago a cross-browser function that allows you to get the computed styles in a cross-browser way:
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
The above function is not perfect for some cases, for example for colors, the standard method will return colors in the rgb(...) notation, on IE they will return them as they were defined.
I'm currently working on an article in the subject, you can follow the changes I make to this function here.
Use org.hibernate.annotations
for doing Cascade
, if the hibernate
and JPA
are used together , its somehow complaining on saving the child objects.
The answer has been given by Faisal Khurshid and Michael_B already.
This is just an attempt to make a possible solution more obvious.
For IE11 and below you need to enable grid's older specification in the parent div e.g. body or like here "grid" like so:
.grid-parent{display:-ms-grid;}
then define the amount and width of the columns and rows like e.g. so:
.grid-parent{
-ms-grid-columns: 1fr 3fr;
-ms-grid-rows: 4fr;
}
finally you need to explicitly tell the browser where your element (item) should be placed in e.g. like so:
.grid-item-1{
-ms-grid-column: 1;
-ms-grid-row: 1;
}
.grid-item-2{
-ms-grid-column: 2;
-ms-grid-row: 1;
}
I had the same problem. When I ran the code on another computer, it worked fine. On mine, however, it displayed "The application may be doing too much work on its main thread".
I solved my problem by restarting Android studio [File -> Invalidated caches / Restart -> click on "Invalidate and Restart"].
(March 2012)
Beware: that default "matching
" policy might change soon
(sometimes after git1.7.10+):
See "Please discuss: what "git push" should do when you do not say what to push?"
In the current setting (i.e.
push.default=matching
),git push
without argument will push all branches that exist locally and remotely with the same name.
This is usually appropriate when a developer pushes to his own public repository, but may be confusing if not dangerous when using a shared repository.The proposal is to change the default to '
upstream
', i.e. push only the current branch, and push it to the branch git pull would pull from.
Another candidate is 'current
'; this pushes only the current branch to the remote branch of the same name.What has been discussed so far can be seen in this thread:
http://thread.gmane.org/gmane.comp.version-control.git/192547/focus=192694
Previous relevant discussions include:
To join the discussion, send your messages to: [email protected]
Here is what I use to convert to the XSD datetime format:
from datetime import datetime
datetime.now().replace(microsecond=0).isoformat()
# You get your ISO string
I came across this question when looking for the XSD date time format (xs:dateTime
). I needed to remove the microseconds from isoformat
.
string s2 = s1.Replace(",", ",\r\n");
If you have a double array named numbers
, you can use:
firstNum = numbers[0];
lastNum = numbers[numbers.length-1];
or with ArrayList
firstNum = numbers.get(0);
lastNum = numbers.get(numbers.size() - 1);
V8 is an implementation of JavaScript. It lets you run standalone JavaScript applications (among other things).
Node.js is simply a library written for V8 which does evented I/O. This concept is a bit trickier to explain, and I'm sure someone will answer with a better explanation than I... The gist is that rather than doing some input or output and waiting for it to happen, you just don't wait for it to finish. So for example, ask for the last edited time of a file:
// Pseudo code
stat( 'somefile' )
That might take a couple of milliseconds, or it might take seconds. With evented I/O you simply fire off the request and instead of waiting around you attach a callback that gets run when the request finishes:
// Pseudo code
stat( 'somefile', function( result ) {
// Use the result here
} );
// ...more code here
This makes it a lot like JavaScript code in the browser (for example, with Ajax style functionality).
For more information, you should check out the article Node.js is genuinely exciting which was my introduction to the library/platform... I found it quite good.
If you need to respond to changes, you can try this:
document.getElementById('select-meal-type').addEventListener('change', function(e) {
let values = [].slice.call(e.target.selectedOptions).map(a => a.value));
})
The [].slice.call(e.target.selectedOptions)
is needed because e.target.selectedOptions
returns a HTMLCollection
, not an Array
. That call converts it to Array
so that we can then apply the map
function, which extract the values.
The answer of Uttam didnt work for me. I just got null when I do:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:
//Create bitmap with width, height, and 4 bytes color (RGBA)
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);
Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options
you can format date just making this type of the code.In javascript.
// for eg.
var inputdate=document.getElementById("getdate").value);
var datecomp= inputdate.split('.');
Var Date= new Date(datecomp[2], datecomp[1]-1, datecomp[0]);
//new date( Year,Month,Date)
Another answer is:
Try checking the View dimensions at onWindowFocusChanged
.
No, you can't change file upload input's text. But there are some tricks to overlay an image over the button.
What you are possibly looking for is map()
. You can "convert" the objects in a stream to another by mapping this way:
...
.map(userMeal -> new UserMealExceed(...))
...
This works too, with the semi-colon.
NAME=sam; echo $NAME
On .Net Core 3.1 just follow Microsoft Doc that it is pretty simple: kestrel-aspnetcore-3.1
To summarize:
Add the below ConfigureServices section to CreateDefaultBuilder on Program.cs
:
// using Microsoft.Extensions.DependencyInjection;
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
services.Configure<KestrelServerOptions>(
context.Configuration.GetSection("Kestrel"));
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Add the below basic config to appsettings.json
file (more config options on Microsoft article):
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://0.0.0.0:5002"
}
}
}
Open CMD or Console on your project Publish/Debug/Release binaries folder and run:
dotnet YourProject.dll
Enjoy exploring your site/api at your http://localhost:5002
The solution is already answered here above (long ago).
But the implicit question "why does it work in FF and IE but not in Chrome and Safari" is found in the error text "Not allowed to load local resource": Chrome and Safari seem to use a more strict implementation of sandboxing (for security reasons) than the other two (at this time 2011).
This applies for local access. In a (normal) server environment (apache ...) the file would simply not have been found.
Before the days of jQuery you would use:
document.getElementById('findmebyid');
If this one line will save you an entire jQuery library, it might be worth while using it instead.
For those concerned about performance: Beginning your selector with an ID is always best as it uses native function document.getElementById.
// Fast:
$( "#container div.robotarm" );
// Super-fast:
$( "#container" ).find( "div.robotarm" );
You don't need to pass the parameter, you can get it using .attr()
method
$(function(){
$('elements-to-match').click(function(){
alert("The id is "+ $(this).attr("id") );
});
});
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
I think this is the better way to keep backwards compatibility if we go with this approach, it is working for my case and hope will work for you. Also pretty easy to understand.
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
}
Alternatively you can use cmder
which lets you add aliases just like linux:
alias subl="C:\Program Files\Sublime Text 3\subl.exe" $*
This is the code I'm using to disable refresh on IE and firefox which works for the following key combinations:
F5 | Ctrl + F5 | Ctrl + R
//this code handles the F5/Ctrl+F5/Ctrl+R
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
// Mozilla firefox
if ($.browser.mozilla) {
if (keycode == 116 ||(e.ctrlKey && keycode == 82)) {
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}
}
// IE
else if ($.browser.msie) {
if (keycode == 116 || (window.event.ctrlKey && keycode == 82)) {
window.event.returnValue = false;
window.event.keyCode = 0;
window.status = "Refresh is disabled";
}
}
}
If you don't want to use useragent to detect what type of browser it is ($.browser
uses navigator.userAgent
to determine the platform), you can use
if('MozBoxSizing' in document.documentElement.style)
which returns true for firefox
Call super.OnMessageReceived()
in the Overriden method. This worked for me!
Finally!
If you're using xml.etree.ElementTree.parse
to parse from a file, then you can use xml.etree.ElementTree.fromstring
to parse from text.
You can used this line of code : url()->current()
In blade file : {{url()->current()}}
This example reads 6 bytes into a byte array and writes it to another byte array. It does an XOR operation with the bytes so that the result written to the file is the same as the original starting values. The file is always 6 bytes in size, since it writes at position 0.
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
byte[] b1 = { 1, 2, 4, 8, 16, 32 };
byte[] b2 = new byte[6];
byte[] b3 = new byte[6];
byte[] b4 = new byte[6];
FileStream f1;
f1 = new FileStream("test.txt", FileMode.Create, FileAccess.Write);
// write the byte array into a new file
f1.Write(b1, 0, 6);
f1.Close();
// read the byte array
f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);
f1.Read(b2, 0, 6);
f1.Close();
// make changes to the byte array
for (int i = 1; i < b2.Length; i++)
{
b2[i] = (byte)(b2[i] ^ (byte)10); //xor 10
}
f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);
// write the new byte array into the file
f1.Write(b2, 0, 6);
f1.Close();
f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Read);
// read the byte array
f1.Read(b3, 0, 6);
f1.Close();
// make changes to the byte array
for (int i = 1; i < b3.Length; i++)
{
b4[i] = (byte)(b3[i] ^ (byte)10); //xor 10
}
f1 = new FileStream("test.txt", FileMode.Open, FileAccess.Write);
// b4 will have the same values as b1
f1.Write(b4, 0, 6);
f1.Close();
}
}
}
Regular grammar:- grammar containing production as follows is RG:
V->TV or VT
V->T
where V=variable and T=terminal
RG may be Left Linear Grammar or Right Liner Grammar, but not Middle linear Grammar.
As we know all RG are Linear Grammar but only Left Linear or Right Linear Grammar are RG.
A regular grammar can be ambiguous.
S->aA|aB
A->a
B->a
Ambiguous Grammar:- for a string x their exist more than one LMD or More than RMD or More than one Parse tree or One LMD and One RMD but both Produce different Parse tree.
S S
/ \ / \
a A a B
\ \
a a
this Grammar is ambiguous Grammar because two parse tree.
CFG:- A grammar said to be CFG if its Production is in form:
V->@ where @ belongs to (V+T)*
DCFL:- as we know all DCFL are LL(1) Grammar and all LL(1) is LR(1) so it is Never be ambiguous. so DCFG is Never be ambiguous.
We also know all RL are DCFL so RL never be ambiguous. Note that RG may be ambiguous but RL not.
CFL: CFl May or may not ambiguous.
Note: RL never be Inherently ambiguous.
For instance you can use
update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'
You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.
I don't see any problem with that. Pre-ARC, I've always made my IBOutlets assign
, as they're already retained by their superviews. If you make them weak
, you shouldn't have to nil them out in viewDidUnload, as you point out.
One caveat: You can support iOS 4.x in an ARC project, but if you do, you can't use weak
, so you'd have to make them assign
, in which case you'd still want to nil the reference in viewDidUnload
to avoid a dangling pointer. Here's an example of a dangling pointer bug I've experienced:
A UIViewController has a UITextField for zip code. It uses CLLocationManager to reverse geocode the user's location and set the zip code. Here's the delegate callback:
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
Class geocoderClass = NSClassFromString(@"CLGeocoder");
if (geocoderClass && IsEmpty(self.zip.text)) {
id geocoder = [[geocoderClass alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (self.zip && IsEmpty(self.zip.text)) {
self.zip.text = [[placemarks objectAtIndex:0] postalCode];
}
}];
}
[self.locationManager stopUpdatingLocation];
}
I found that if I dismissed this view at the right time and didn't nil self.zip in viewDidUnload
, the delegate callback could throw a bad access exception on self.zip.text.
Also, if your PATH's dir is enclosed in quotes, it will work from the command prompt but you'll get the same error message
I.e. this causes an issue with Process.Start() not finding your exe:
PATH="C:\my program\bin";c:\windows\system32
Maybe it helps someone.
ALTER TABLE <table_name> MODIFY <column_name> DEFAULT <defult_value>
EX: ALTER TABLE AAA MODIFY ID DEFAULT AAA_SEQUENCE.nextval
Tested on Oracle Database 12c Enterprise Edition Release 12.2.0.1.0
For truly fastest solution with sufficiently large N would be to download a pre-calculated list of primes, store it as a tuple and do something like:
for pos,i in enumerate(primes):
if i > N:
print primes[:pos]
If N > primes[-1]
only then calculate more primes and save the new list in your code, so next time it is equally as fast.
Always think outside the box.
Initially used only ViewDidLoad with tableView. On testing with loss of Wifi, by setting device to airplane mode, realized that the table did not refresh with return of Wifi. In fact, there appears to be no way to refresh tableView on the device even by hitting the home button with background mode set to YES in -Info.plist.
My solution:
-(void) viewWillAppear: (BOOL) animated { [self.tableView reloadData];}
Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).
This library files should be under cygwin\usr\include
Regards.
I believe in your case something like
sort -t@ -k1.1,1.4 -k1.5,1.7 ... <inputfile
will work better. @ is the field separator, make sure it is a character that appears nowhere. then your input is considered as consisting of one column.
Edit: apparently clintp already gave a similar answer, sorry. As he points out, the flags 'n' and 'r' can be added to every -k.... option.
The difference is in which lock is being acquired:
synchronized method acquires a lock on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread.
synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword. Meaning no other thread can acquire a lock on the locked object until the synchronized block exits.
So if you want to lock the whole object, use a synchronized method. If you want to keep other parts of the object accessible to other threads, use synchronized block.
If you choose the locked object carefully, synchronized blocks will lead to less contention, because the whole object/class is not blocked.
This applies similarly to static methods: a synchronized static method will acquire a lock in the whole class object, while a synchronized block inside a static method will acquire a lock in the object between parentheses.
$ git remote remove <name>
ie.
$ git remote remove upstream
that should do the trick
I have several library projects with the same package name specified in the AndroidManifest (so no duplicate field names are generated by R.java). I had to remove any permissions and activities from the AndroidManifest.xml for all library projects to remove the error so Manifest.java wasn't created multiple times. Hopefully this can help someone.
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
Add this CSS reset to your CSS code: (From here)
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
It'll reset the CSS effectively, getting rid of the padding and margins.
Regex is unnecessary for this. Just use some_string.split(' ', 1)[0]
or some_string.partition(' ')[0]
.
Found the code that I referred to in my comment above. To test it, do this:
Sheet1
change the cell height and width of say A1
as shown in the snapshot below. Start Timer
button on the sheet and click on Assign Macros
. Select StartTimer
macro.End Timer
button on the sheet and click on Assign Macros
. Select EndTimer
macro.Now click on Start Timer button and you will see the time getting updated in cell A1
. To stop time updates, Click on End Timer button.
Code (TRIED AND TESTED)
Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long
'~~> Start Timer
Sub StartTimer()
'~~ Set the timer for 1 second
TimerSeconds = 1
TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub
'~~> End Timer
Sub EndTimer()
On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
'~~> Update value in Sheet 1
Sheet1.Range("A1").Value = Time
End Sub
SNAPSHOT
as per @anaximander s answer but your signup action should look more like
[HttpPost]
public ActionResult SignUp(Account account)
{
if(ModelState.IsValid){
//do something with account
return RedirectToAction("Index");
}
return View("SignUp");
}
This URL format worked like a charm:
http://maps.google.com/maps?&z={INSERT_MAP_ZOOM}&mrt={INSERT_TYPE_OF_SEARCH}&t={INSERT_MAP_TYPE}&q={INSERT_MAP_LAT_COORDINATES}+{INSERT_MAP_LONG_COORDINATES}
Example for Mount Everest:
http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=27.9879012+86.9253141
Full reference here:
https://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
-- EDIT --
Apparently the zoom parameter stopped working, here's the updated format.
Format
https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite¢er={LAT},{LONG}&zoom={ZOOM}
Example
I had this concern when working on a Rails application with Docker.
My most preferred approach is to generally not use quotes. This includes not using quotes for:
${RAILS_ENV}
postgres-log:/var/log/postgresql
I, however, use double-quotes for integer
values that need to be converted to strings like:
version: "3.8"
"8080:8080"
However, for special cases like booleans
, floats
, integers
, and other cases, where using double-quotes for the entry values could be interpreted as strings
, please do not use double-quotes.
Here's a sample docker-compose.yml
file to explain this concept:
version: "3"
services:
traefik:
image: traefik:v2.2.1
command:
- --api.insecure=true # Don't do that in production
- --providers.docker=true
- --providers.docker.exposedbydefault=false
- --entrypoints.web.address=:80
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
That's all.
I hope this helps
This seemed to do the trick for me:
conda remove certifi
conda install certifi
Then you can do whatever you were trying to do before, e.g.
conda update --all
In the manifest, set this for all your activities:
<activity android:name=".YourActivity"
android:configChanges="orientation"
android:screenOrientation="portrait"/>
Let me explain:
android:configChanges="orientation"
you tell Android that you will be responsible of the changes of orientation.android:screenOrientation="portrait"
you set the default orientation mode.Here's my solution:
//**** scroll to bottom if at bottom
function scrollbottom() {
if (typeof(scr1)!='undefined') clearTimeout(scr1)
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
if((scrollTop + window.innerHeight) >= scrollHeight-50) window.scrollTo(0,scrollHeight+50)
scr1=setTimeout(function(){scrollbottom()},200)
}
scr1=setTimeout(function(){scrollbottom()},200)
You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm
My own standard loop looks something like this:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")
'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst 'Unnecessary in this case, but still a good habit
Do Until rs.EOF = True
'Perform an edit
rs.Edit
rs!VendorYN = True
rs("VendorYN") = True 'The other way to refer to a field
rs.Update
'Save contact name into a variable
sContactName = rs!FirstName & " " & rs!LastName
'Move to the next record. Don't ever forget to do this.
rs.MoveNext
Loop
Else
MsgBox "There are no records in the recordset."
End If
MsgBox "Finished looping through records."
rs.Close 'Close the recordset
Set rs = Nothing 'Clean up
If this is a submit button, use <input type="image" src="..." ... />
.
http://www.htmlcodetutorial.com/forms/_INPUT_TYPE_IMAGE.html
If you want to specify the image with CSS, you'll have to use type="submit"
.