For iOS13+ there are withTintColor(__:) and withTintColor(_:renderingMode:) methods.
Example usage:
let newImage = oldImage.withTintColor(.red)
or
let newImage = oldImage.withTintColor(.red, renderingMode: .alwaysTemplate)
This would print the files in those directories line by line.
array=(ww/* ee/* qq/*)
printf "%s\n" "${array[@]}"
Slightly off-topic: But here is if you have an Array of Dictionaries i.e: [ [String : String] ]
var array_has_dictionary = [ // Start of array
// Dictionary 1
[
"name" : "xxxx",
"age" : "xxxx",
"last_name":"xxx"
],
// Dictionary 2
[
"name" : "yyy",
"age" : "yyy",
"last_name":"yyy"
],
] // end of array
cell.textLabel?.text = Array(array_has_dictionary[1])[1].key
// Output: age -> yyy
//Client
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String hostname = "localhost";
int port = 6789;
// declaration section:
// clientSocket: our client socket
// os: output stream
// is: input stream
Socket clientSocket = null;
DataOutputStream os = null;
BufferedReader is = null;
// Initialization section:
// Try to open a socket on the given port
// Try to open input and output streams
try {
clientSocket = new Socket(hostname, port);
os = new DataOutputStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + hostname);
}
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on the given port
if (clientSocket == null || os == null || is == null) {
System.err.println( "Something is wrong. One variable is null." );
return;
}
try {
while ( true ) {
System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String keyboardInput = br.readLine();
os.writeBytes( keyboardInput + "\n" );
int n = Integer.parseInt( keyboardInput );
if ( n == 0 || n == -1 ) {
break;
}
String responseLine = is.readLine();
System.out.println("Server returns its square as: " + responseLine);
}
// clean up:
// close the output stream
// close the input stream
// close the socket
os.close();
is.close();
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
//Server
import java.io.*;
import java.net.*;
public class Server1 {
public static void main(String args[]) {
int port = 6789;
Server1 server = new Server1( port );
server.startServer();
}
// declare a server socket and a client socket for the server
ServerSocket echoServer = null;
Socket clientSocket = null;
int port;
public Server1( int port ) {
this.port = port;
}
public void stopServer() {
System.out.println( "Server cleaning up." );
System.exit(0);
}
public void startServer() {
// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(port);
}
catch (IOException e) {
System.out.println(e);
}
System.out.println( "Waiting for connections. Only one connection is allowed." );
// Create a socket object from the ServerSocket to listen and accept connections.
// Use Server1Connection to process the connection.
while ( true ) {
try {
clientSocket = echoServer.accept();
Server1Connection oneconnection = new Server1Connection(clientSocket, this);
oneconnection.run();
}
catch (IOException e) {
System.out.println(e);
}
}
}
}
class Server1Connection {
BufferedReader is;
PrintStream os;
Socket clientSocket;
Server1 server;
public Server1Connection(Socket clientSocket, Server1 server) {
this.clientSocket = clientSocket;
this.server = server;
System.out.println( "Connection established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
String line;
try {
boolean serverStop = false;
while (true) {
line = is.readLine();
System.out.println( "Received " + line );
int n = Integer.parseInt(line);
if ( n == -1 ) {
serverStop = true;
break;
}
if ( n == 0 ) break;
os.println("" + n*n );
}
System.out.println( "Connection closed." );
is.close();
os.close();
clientSocket.close();
if ( serverStop ) server.stopServer();
} catch (IOException e) {
System.out.println(e);
}
}
}
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
fireTableStructureChanged();
will default the resize behavior ! If this method is called somewhere in your code AFTER you did set the column resize properties all your settings will be reset. This side effect can happen indirectly. F.e. as a consequence of the linked data model being changed in a way this method is called, after properties are set.
svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt
You may also do the following in Python 3.6.1
from Object import Object as Parent
and your class definition to:
class Visitor(Parent):
With bootstrap
<div class="table-responsive">
<table class="table">
...
</table>
</div>
I restarted my computer (Mac Mountain Lion) and the problem fixed itself. Something having to do with the shell thinking it was disconnected from the internet I think.
Restarting your shell in some definite way may solve this problem as well. Simply opening up a new session/window however did not work.
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'
Prefixing the string with an @ indicates that it should be treated as a literal, i.e. no escaping.
For example if your string contains a path you would typically do this:
string path = "c:\\mypath\\to\\myfile.txt";
The @ allows you to do this:
string path = @"c:\mypath\to\myfile.txt";
Notice the lack of double slashes (escaping)
For completeness sake, on a Swedish keyboard it's CTRL + å .
Also, I guess logical, but worth mentioning CTRL + shift + å (for capital Å), selects everything inside the braces and goes to the matching one.
You'd first wanna make sure you have the JSDT installed.
Next thing is to install some dedicated tools for the job, so check out AngularJS Eclipse Tools. The AngularJS Eclipse Templates might be of help, too, and here's a visual guide written for it to get you started.
Also see the AngularJS Eclipse getting started page.
Since this answer had been posted, the AngularJS Eclipse plugin was released, as other answers stated. You might wanna check it out first.
This is the code I use for creating an index sheet.
Sub CreateIndexSheet()
Dim wSheet As Worksheet
ActiveWorkbook.Sheets.Add(Before:=Worksheets(1)).Name = "Contents" 'Call whatever you like
Range("A1").Select
Application.ScreenUpdating = False 'Prevents seeing all the flashing as it updates the sheet
For Each wSheet In Worksheets
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'" & wSheet.Name & "'" & "!A1", TextToDisplay:=wSheet.Name
ActiveCell.Offset(1, 0).Select 'Moves down a row
Next
Range("A1").EntireColumn.AutoFit
Range("A1").EntireRow.Delete 'Remove content sheet from content list
Application.ScreenUpdating = True
End Sub
Please use an ISO8601 parsing library for doing this. There are too many ways how the string could be encoded. Don't rely on a specific format and don't rely on the server sending always the same. The problems start with the 'Z' at the end and it will extend through all varieties of the standard. A parsing library will handle all cases and will always provide a safe conversion - whereas a fixed formatting string is likely to fail in the future.
You could use one of these libraries. They are also available on CococaPods:
https://github.com/boredzo/iso-8601-date-formatter/
https://github.com/malcommac/SwiftDate
Take a look at the implementations. They are both several hundred lines long - for good reason.
With regards to the question: You can pull out the date components from the date using NSDateComponents. The example on the website covers exactly your case.
https://developer.apple.com/documentation/foundation/nscalendar/1414841-components?language=objc
Please be aware, that converting your date will take into account the time zone. You might want to set the 'locale' of the NSCalendar explicitly.
The Problem is Windows and Microsoft applications put byte order marks at the beginning of all your files so other applications often break or don't read these UTF-8 encoding marks. I perfect example of this problem was triggering quirsksmode in old IE web browsers when encoding in UTF-8 as browsers often display web pages based on what encoding falls at the start of the page. It makes a mess when other applications view those UTF-8 Visual Studio pages.
I usually do not recommend Visual Studio Extensions, but I do this one to fix that issue:
Fix File Encoding: https://vlasovstudio.com/fix-file-encoding/
The FixFileEncoding above install REMOVES the byte order mark and forces VS to save ALL FILES without signature in UTF-8. After installing go to Tools > Option then choose "FixFileEncoding". It should allow you to set all saves as UTF-8 . Add "cshtml to the list of files to always save in UTF-8 without the byte order mark as so: ".(htm|html|cshtml)$)".
Now open one of your files in Visual Studio. To verify its saving as UTF-8 go to File > Save As, then under the Save button choose "Save With Encoding". It should choose "UNICODE (Save without Signature)" by default from the list of encodings. Now when you save that page it should always save as UTF-8 without byte order mark at the beginning of the file when saving in Visual Studio.
It does allow you (well, the compiler) to catch when you've used the wrong spelling on a method name you are overriding.
Your config file does not include any references to "origin" remote. That section looks like this:
[remote "origin"]
url = [email protected]:repository.git
fetch = +refs/heads/*:refs/remotes/origin/*
You need to add the remote using git remote add
before you can use it.
If the XML module is not installed, install it.
Current version 5.6 on ubuntu 14.04:
sudo apt-get install php5.6-xml
And don't forget to run sudo service apache2 restart command after it
Zulhilmi Zainudi
As other answers mentioned you can use ajaxStop()
to wait until all ajax request are completed.
$(document).ajaxStop(function() {
// This function will be triggered every time any ajax request is requested and completed
});
If you want do it for an specific ajax()
request the best you can do is use complete()
method inside the certain ajax request:
$.ajax({
type: "POST",
url: "someUrl",
success: function(data) {
// This function will be triggered when ajax returns a 200 status code (success)
},
complete: function() {
// This function will be triggered always, when ajax request is completed, even it fails/returns other status code
},
error: function() {
// This will be triggered when ajax request fail.
}
});
But, If you need to wait only for a few and certain ajax request to be done? Use the wonderful javascript promises to wait until the these ajax you want to wait are done. I made a shortly, easy and readable example to show you how does promises works with ajax.
Please take a look to the next example. I used setTimeout
to clarify the example.
// Note:_x000D_
// resolve() is used to mark the promise as resolved_x000D_
// reject() is used to mark the promise as rejected_x000D_
_x000D_
$(document).ready(function() {_x000D_
$("button").on("click", function() {_x000D_
_x000D_
var ajax1 = new Promise((resolve, reject) => {_x000D_
$.ajax({_x000D_
type: "GET",_x000D_
url: "https://miro.medium.com/max/1200/0*UEtwA2ask7vQYW06.png",_x000D_
xhrFields: { responseType: 'blob'},_x000D_
success: function(data) {_x000D_
setTimeout(function() {_x000D_
$('#image1').attr("src", window.URL.createObjectURL(data));_x000D_
resolve(" Promise ajax1 resolved");_x000D_
}, 1000);_x000D_
},_x000D_
error: function() {_x000D_
reject(" Promise ajax1 rejected");_x000D_
},_x000D_
});_x000D_
});_x000D_
_x000D_
var ajax2 = new Promise((resolve, reject) => {_x000D_
$.ajax({_x000D_
type: "GET",_x000D_
url: "https://cdn1.iconfinder.com/data/icons/social-media-vol-1-1/24/_github-512.png",_x000D_
xhrFields: { responseType: 'blob' },_x000D_
success: function(data) {_x000D_
setTimeout(function() {_x000D_
$('#image2').attr("src", window.URL.createObjectURL(data));_x000D_
resolve(" Promise ajax2 resolved");_x000D_
}, 1500);_x000D_
},_x000D_
error: function() {_x000D_
reject(" Promise ajax2 rejected");_x000D_
},_x000D_
});_x000D_
});_x000D_
_x000D_
var ajax3 = new Promise((resolve, reject) => {_x000D_
$.ajax({_x000D_
type: "GET",_x000D_
url: "https://miro.medium.com/max/632/1*LUfpOf7teWvPdIPTBmYciA.png",_x000D_
xhrFields: { responseType: 'blob' },_x000D_
success: function(data) {_x000D_
setTimeout(function() {_x000D_
$('#image3').attr("src", window.URL.createObjectURL(data));_x000D_
resolve(" Promise ajax3 resolved");_x000D_
}, 2000);_x000D_
},_x000D_
error: function() {_x000D_
reject(" Promise ajax3 rejected");_x000D_
},_x000D_
});_x000D_
});_x000D_
_x000D_
Promise.all([ajax1, ajax2, ajax3]).then(values => {_x000D_
console.log("We waited until ajax ended: " + values);_x000D_
console.log("My few ajax ended, lets do some things!!")_x000D_
}, reason => {_x000D_
console.log("Promises failed: " + reason);_x000D_
});_x000D_
_x000D_
// Or if you want wait for them individually do it like this_x000D_
// ajax1.then(values => {_x000D_
// console.log("Promise 1 resolved: " + values)_x000D_
// }, reason => {_x000D_
// console.log("Promise 1 failed: " + reason)_x000D_
// });_x000D_
});_x000D_
_x000D_
});
_x000D_
img {_x000D_
max-width: 200px;_x000D_
max-height: 100px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<button>Make AJAX request</button>_x000D_
<div id="newContent">_x000D_
<img id="image1" src="">_x000D_
<img id="image2" src="">_x000D_
<img id="image3" src="">_x000D_
</div>
_x000D_
Hope this tip will save someone else's life. In my case the problem was that I ran out of memory, but only slightly, was hard to think about it. Wasted 3hrs on that. I recommend running:
sudo htop
or
sudo free -m
...along with running problematic requests on the server to see if your memory doesn't run out. And if it does like in my case, you need to create swap file (unless you already have one).
I have followed this tutorial to create swap file on Ubuntu Server 14.04 and it worked just fine: http://www.cyberciti.biz/faq/ubuntu-linux-create-add-swap-file/
The simplest solution that I can think of is using Properties class.
Saving the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
properties.store(new FileOutputStream("data.properties"), null);
Loading the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));
for (String key : properties.stringPropertyNames()) {
ldapContent.put(key, properties.get(key).toString());
}
EDIT:
if your map contains plaintext values, they will be visible if you open file data via any text editor, which is not the case if you serialize the map:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();
EDIT2:
instead of for loop (as suggested by OldCurmudgeon) in saving example:
properties.putAll(ldapContent);
however, for the loading example this is the best that can be done:
ldapContent = new HashMap<Object, Object>(properties);
"but does that mean it should just be an example of the sort of expression you could use, or should it be an actual expression, that can be executed (eval etc..) to recreate the object? Or... should it be just a rehasing of the actual expression which was used, for pure information purposes?"
Wow, that's a lot of hand-wringing.
An "an example of the sort of expression you could use" would not be a representation of a specific object. That can't be useful or meaningful.
What is the difference between "an actual expression, that can ... recreate the object" and "a rehasing of the actual expression which was used [to create the object]"? Both are an expression that creates the object. There's no practical distinction between these. A repr call could produce either a new expression or the original expression. In many cases, they're the same.
Note that this isn't always possible, practical or desirable.
In some cases, you'll notice that repr() presents a string which is clearly not an expression of any kind. The default repr() for any class you define isn't useful as an expression.
In some cases, you might have mutual (or circular) references between objects. The repr() of that tangled hierarchy can't make sense.
In many cases, an object is built incrementally via a parser. For example, from XML or JSON or something. What would the repr be? The original XML or JSON? Clearly not, since they're not Python. It could be some Python expression that generated the XML. However, for a gigantic XML document, it might not be possible to write a single Python expression that was the functional equivalent of parsing XML.
apt-cache policy <package-name>
$ apt-cache policy redis-server
redis-server:
Installed: (none)
Candidate: 2:2.8.4-2
Version table:
2:2.8.4-2 0
500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages
apt-get install -s <package-name>
$ apt-get install -s redis-server
NOTE: This is only a simulation!
apt-get needs root privileges for real execution.
Keep also in mind that locking is deactivated,
so don't depend on the relevance to the real current situation!
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
libjemalloc1 redis-tools
The following NEW packages will be installed:
libjemalloc1 redis-server redis-tools
0 upgraded, 3 newly installed, 0 to remove and 3 not upgraded.
Inst libjemalloc1 (3.5.1-2 Ubuntu:14.04/trusty [amd64])
Inst redis-tools (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Inst redis-server (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Conf libjemalloc1 (3.5.1-2 Ubuntu:14.04/trusty [amd64])
Conf redis-tools (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Conf redis-server (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
apt-cache show <package-name>
$ apt-cache show redis-server
Package: redis-server
Priority: optional
Section: universe/misc
Installed-Size: 744
Maintainer: Ubuntu Developers <[email protected]>
Original-Maintainer: Chris Lamb <[email protected]>
Architecture: amd64
Source: redis
Version: 2:2.8.4-2
Depends: libc6 (>= 2.14), libjemalloc1 (>= 2.1.1), redis-tools (= 2:2.8.4-2), adduser
Filename: pool/universe/r/redis/redis-server_2.8.4-2_amd64.deb
Size: 267446
MD5sum: 066f3ce93331b876b691df69d11b7e36
SHA1: f7ffbf228cc10aa6ff23ecc16f8c744928d7782e
SHA256: 2d273574f134dc0d8d10d41b5eab54114dfcf8b716bad4e6d04ad8452fe1627d
Description-en: Persistent key-value database with network interface
Redis is a key-value database in a similar vein to memcache but the dataset
is non-volatile. Redis additionally provides native support for atomically
manipulating and querying data structures such as lists and sets.
.
The dataset is stored entirely in memory and periodically flushed to disk.
Description-md5: 9160ed1405585ab844f8750a9305d33f
Homepage: http://redis.io/
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Origin: Ubunt
dpkg -l <package-name>
$ dpkg -l nginx
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name Version Architecture Description
+++-========================================-=========================-=========================-=====================================================================================
ii nginx 1.6.2-1~trusty amd64 high performance web server
I have created a more general function, that sorts more than two lists based on another one, inspired by @Whatang's answer.
def parallel_sort(*lists):
"""
Sorts the given lists, based on the first one.
:param lists: lists to be sorted
:return: a tuple containing the sorted lists
"""
# Create the initially empty lists to later store the sorted items
sorted_lists = tuple([] for _ in range(len(lists)))
# Unpack the lists, sort them, zip them and iterate over them
for t in sorted(zip(*lists)):
# list items are now sorted based on the first list
for i, item in enumerate(t): # for each item...
sorted_lists[i].append(item) # ...store it in the appropriate list
return sorted_lists
How to resolve this problem in Angular8
polyfills.ts uncomment import 'classlist.js';
and import 'web-animations-js';
then install two dependency using npm install --save classlist.js
and npm install --save web-animations-js
.
update tsconfig.json
with "target":"es5",
then ng serve
run the application and open in IE, it will work
import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);
Source: https://docs.oracle.com/javase/tutorial/essential/io/copy.html
In wamp/alias/mySite.conf, be careful to add a slash "/" at the end of the alias' adress :
Replace :
Alias /mySite/ "D:/Work/Web/mySite/www"
By :
Alias /mySite/ "D:/Work/Web/mySite/www/"
Or the index.php is not read correctly.
If you want to see how much space each folder ocuppes:
du -sh *
s
– summarizeh
– human readable*
– list of foldersMake both divs like this. This will align both divs side-by-side.
.my-class {
display : inline-flex;
}
Use 'q'
as the the optional argument to getline
.
#include <iostream>
#include <sstream>
int main() {
std::string numbers_str;
getline( std::cin, numbers_str, 'q' );
int number;
for ( std::istringstream numbers_iss( numbers_str );
numbers_iss >> number; ) {
std::cout << number << ' ';
}
}
I used andrew joslin's answer, which works great but triggered an angular route change, which created a jumpy looking scroll for me. If you want to avoid triggering a route change,
myApp.directive('scrollOnClick', function() {
return {
restrict: 'A',
link: function(scope, $elm, attrs) {
var idToScroll = attrs.href;
$elm.on('click', function(event) {
event.preventDefault();
var $target;
if (idToScroll) {
$target = $(idToScroll);
} else {
$target = $elm;
}
$("body").animate({scrollTop: $target.offset().top}, "slow");
return false;
});
}
}
});
The use of the package \usepackage{fancyvrb}
allows the definition of the fontsize argument inside Verbatim:
\begin{Verbatim}[fontsize=\small]
print "Hello, World"
\end{Verbatim}
The fontsize that you can specify are the common
\tiny
\scriptsize
\footnotesize
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
"Clear" JavaScript:
function myKeyPress(e){
var keynum;
if(window.event) { // IE
keynum = e.keyCode;
} else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
alert(String.fromCharCode(keynum));
}
_x000D_
<input type="text" onkeypress="return myKeyPress(event)" />
_x000D_
JQuery:
$("input").keypress(function(event){
alert(String.fromCharCode(event.which));
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
_x000D_
Try:
C:\Users\USERNAME\.nuget\packages\
That worked for me.
<input type="text" autocomplete="off" />
I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.
It is evident to me that GitLens is the most popular extension for Git history.
What I like the most it can provide you side annotations when some line has been changed the last time and by whom.
import os
externalIp = os.popen("ipconfig").read().split(":")[15][1:14]
some numbers may need to be changed but this works for me
Further more to the Above Accepted Answer
For those who were wondering about :=
& =
Significant difference between :=
and =
, and that is that :=
works as a variable-assignment operator everywhere, while =
only works that way in SET statements, and is a comparison operator everywhere else.
So SELECT @var = 1 + 1;
will leave @var
unchanged and return a boolean (1 or 0 depending on the current value of @var), while SELECT @var := 1 + 1;
will change @var
to 2, and return 2.
[Source]
You can easily create your own extension method on IEnumerable or IQueryable:
public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}
public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
(this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}
Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:
var query = dataList.OrderByWithDirection(x => x.Property, direction);
From Errors and Exceptions # Handling exceptions - docs.python.org
The
try ... except
statement has an optionalelse
clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close()
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.
Above screenshot taken from this live example: https://regex101.com/r/cU5lC2/1
I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match
Start phpsh, put some content into a variable, match on word.
el@apollo:~/foo$ phpsh
php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'
php> echo preg_match('(\w+)', $content1);
1
php> echo preg_match('(\w+)', $content2);
1
php> echo preg_match('(\w+)', $content3);
0
The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1
, $content2
and $content3
with the (\w)+
pattern.
$content1 and $content2 contain at least one word, $content3 does not.
el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(dart|fart)', $gun1);
1
php> echo preg_match('(dart|fart)', $gun2);
1
php> echo preg_match('(dart|fart)', $gun3);
1
php> echo preg_match('(dart|fart)', $gun4);
0
Variables gun1
and gun2
contain the string dart
or fart
which is correct, but gun3 contains darty
and still matches, that is the problem. So onto the next example.
Word Boundaries can be force matched with \b
, see:
Regex Visual Image acquired from http://jex.im/regulex and https://github.com/JexCheng/regulex Example:
el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0
php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0
The \b
asserts that we have a word boundary, making sure " dart " is matched, but " darty " isn't.
If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.
The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.
For me / had to be in a new line.
For example
create type emp_t;/
didn't work
but
create type emp_t;
/
worked.
Well a fix for you could be to put it on the UpdatedDate field and have a trigger that updates the AddedDate field with the UpdatedDate value only if AddedDate is null.
Here's another approach using Vuetify grid
system available in Vuetify 2.x
: https://vuetifyjs.com/en/components/grids
<v-container>
<v-row align="center">
Hello I am center to vertically using "grid".
</v-row>
</v-container>
What is the "Visual C#"? There is no such thing. Just C#, or .NET C# :)
Also, Python's convention for constants CONSTANT_NAME
is not very common in C#. We are usually using CamelCase according to MSDN standards, e.g. public const string ExtractedMagicString = "vs2019";
Source: Defining constants in C#
If you'd like to redirect to another domain without the user having to do anything you can use a link with the property:
target="_parent"
as said previously, and then use:
document.getElementById('link').click();
to have it automatically redirect.
Example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<a id="link" target="_parent" href="outsideDomain.html"></a>
<script type="text/javascript">
document.getElementById('link').click();
</script>
</body>
</html>
Note: The javascript click() command must come after you declare the link.
My issue was that end users would start typing in a textbox and receive autocomplete (ACP) suggestions and update the calling control if a suggestion was selected as the ACP is designed by default. However, I also needed to update multiple other controls (textboxes, DropDowns, etc...) with data specific to the end user's selection. I have been trying to figure out an elegant solution to the issue and I feel the one I developed is worth sharing and hopefully will save you at least some time.
WebMethod (SampleWM.aspx):
PURPOSE:
NOTES:
//Call to custom function to return SP results as a DataTable
// DataTable will consist of Field0 - Field5
Dim params As ArrayList = New ArrayList
params.Add("@QueryFilter|" & QueryFilter)
Dim dt As DataTable = Data.GetDataTableFromSP("AutoComplete", params, [ConnStr])
//Create a StringBuilder Obj to hold the JSON
//IE: [{"Field0":"0","Field1":"Test","Field2":"Jason","Field3":"Smith","Field4":"32","Field5":"888-555-1212"},{"Field0":"1","Field1":"Test2","Field2":"Jane","Field3":"Doe","Field4":"25","Field5":"888-555-1414"}]
Dim jStr As StringBuilder = New StringBuilder
//Loop the DataTable and convert row into JSON String
If dt.Rows.Count > 0 Then
jStr.Append("[")
Dim RowCnt As Integer = 1
For Each r As DataRow In dt.Rows
jStr.Append("{")
Dim ColCnt As Integer = 0
For Each c As DataColumn In dt.Columns
If ColCnt = 0 Then
jStr.Append("""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
Else
jStr.Append(",""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
End If
ColCnt += 1
Next
If Not RowCnt = dt.Rows.Count Then
jStr.Append("},")
Else
jStr.Append("}")
End If
RowCnt += 1
Next
jStr.Append("]")
End If
//Return JSON to WebMethod Caller
Return jStr.ToString
AutoComplete jQuery (AutoComplete.aspx):
$(function() {
$("#LookUp").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SampleWM.aspx/GetAutoCompleteData",
dataType: "json",
data:'{QueryFilter: "' + request.term + '"}',
success: function (data) {
response($.map($.parseJSON(data.d), function (item) {
var AC = new Object();
//autocomplete default values REQUIRED
AC.label = item.Field0;
AC.value = item.Field1;
//extend values
AC.FirstName = item.Field2;
AC.LastName = item.Field3;
AC.Age = item.Field4;
AC.Phone = item.Field5;
return AC
}));
}
});
},
minLength: 3,
select: function (event, ui) {
$("#txtFirstName").val(ui.item.FirstName);
$("#txtLastName").val(ui.item.LastName);
$("#ddlAge").val(ui.item.Age);
$("#txtPhone").val(ui.item.Phone);
}
});
});
Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.
Promise with jQuery 1.8+
Promise.resolve(
$.ajax({
url: '/getData',
timeout:3000 //3 second timeout
})
).then(function(){
//do something
}).catch(function(e) {
if(e.statusText == 'timeout')
{
alert('Native Promise: Failed from timeout');
//do something. Try again perhaps?
}
});
jQuery 1.8+
$.ajax({
url: '/getData',
timeout:3000 //3 second timeout
}).done(function(){
//do something
}).fail(function(jqXHR, textStatus){
if(textStatus === 'timeout')
{
alert('Failed from timeout');
//do something. Try again perhaps?
}
});?
jQuery <= 1.7.2
$.ajax({
url: '/getData',
error: function(jqXHR, textStatus){
if(textStatus === 'timeout')
{
alert('Failed from timeout');
//do something. Try again perhaps?
}
},
success: function(){
//do something
},
timeout:3000 //3 second timeout
});
Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.
error(jqXHR, textStatus, errorThrown)
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.
Can be done via changing the Collation. By default it is case insensitive.
Excerpt from the link:
SELECT 1
FROM dbo.Customers
WHERE CustID = @CustID COLLATE SQL_Latin1_General_CP1_CS_AS
AND CustPassword = @CustPassword COLLATE SQL_Latin1_General_CP1_CS_AS
For Windows HTTP, you can't beat Fiddler. You can use it as a reverse proxy for port-forwarding on a web server. It doesn't necessarily need IE, either. It can use other clients.
This problem appeared for me when I was creating folders in the filesystem (not in my solution) and moved some projects around.
Turns out that the package paths are relative from the csproj files. So I had to change the "HintPath" of my references:
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
<Private>True</Private>
</Reference>
To:
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
<Private>True</Private>
</Reference>
Notice the double "..\" in 'HintPath'.
I also had to change my error conditions, for example I had to change:
<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />
To:
<Error Condition="!Exists('..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />
Again, notice the double "..\".
Import the FormsModule in those modules where you want to use the [(ngModel)]
Try both queries (the one with inner and left join) with OPTION (FORCE ORDER)
at the end and post the results. OPTION (FORCE ORDER)
is a query hint that forces the optimizer to build the execution plan with the join order you provided in the query.
If INNER JOIN
starts performing as fast as LEFT JOIN
, it's because:
INNER JOIN
s, the join order doesn't matter. This gives freedom for the query optimizer to order the joins as it sees fit, so the problem might rely on the optimizer.LEFT JOIN
, that's not the case because changing the join order will alter the results of the query. This means the engine must follow the join order you provided on the query, which might be better than the optimized one.Don't know if this answers your question but I was once in a project that featured highly complex queries making calculations, which completely messed up the optimizer. We had cases where a FORCE ORDER
would reduce the execution time of a query from 5 minutes to 10 seconds.
There's a really good paper by Microsoft Research called To Blob or Not To Blob.
Their conclusion after a large number of performance tests and analysis is this:
if your pictures or document are typically below 256K in size, storing them in a database VARBINARY column is more efficient
if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)
in between those two, it's a bit of a toss-up depending on your use
If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.
For filegroups, check out Files and Filegroup Architecture for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".
Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:
CREATE TABLE dbo.YourTable
(....... define the fields here ......)
ON Data -- the basic "Data" filegroup for the regular data
TEXTIMAGE_ON LARGE_DATA -- the filegroup for large chunks of data
Check out the MSDN intro on filegroups, and play around with it!
If you install the composer as global on Ubuntu, you just need to find the composer location.
Use command
type composer
or
where composer
For Mac users, use command:
which composer
and then just remove the folder using rm
command.
For JavaScript arrays, you use Both push() and concat() function.
var array = [1, 2, 3];
array.push(4, 5); //use push for appending a single array.
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2); //It is better use concat for appending more then one array.
for superclasses with many members I would suggest you to use @Delegate
@Data
public class A {
@Delegate public class AInner{
private final int x;
private final int y;
}
}
@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
private final int z;
public B(A.AInner a, int z) {
super(a);
this.z = z;
}
}
If your implementation provides a 64-bit integer type, you may get a different (incorrect) answer by using fmin or fmax. Your 64-bit integers will be converted to doubles, which will (at least usually) have a significand that's smaller than 64-bits. When you convert such a number to a double, some of the least significant bits can/will be lost completely.
This means that two numbers that were really different could end up equal when converted to double -- and the result will be that incorrect number, that's not necessarily equal to either of the original inputs.
This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12
but Excel.XlFileFormat.xlOpenXMLWorkbook
. The actual C# command was
excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
I hope this helps someone else in the future.
Missing.Value
is found in the System.Reflection
namespace.
Think about it. When your client makes a GET request to an URI X, what it's saying to the server is: "I want a representation of the resource located at X, and this operation shouldn't change anything on the server." A PUT request is saying: "I want you to replace whatever is the resource located at X with the new entity I'm giving you on the body of this request". A DELETE request is saying: "I want you to delete whatever is the resource located at X". A PATCH is saying "I'm giving you this diff, and you should try to apply it to the resource at X and tell me if it succeeds." But a POST is saying: "I'm sending you this data subordinated to the resource at X, and we have a previous agreement on what you should do with it."
If you don't have it documented somewhere that the resource expects a POST and does something with it, it doesn't make sense to send a POST to it expecting it to act like a GET.
REST relies on the standardized behavior of the underlying protocol, and POST is precisely the method used for an action that isn't standardized. The result of a GET, PUT and DELETE requests are clearly defined in the standard, but POST isn't. The result of a POST is subordinated to the server, so if it's not documented that you can use POST to do something, you have to assume that you can't.
To understand the use of "SET SERVEROUTPUT ON" I will take an example
DECLARE
a number(10) :=10;
BEGIN
dbms_output.put_line(a) ;
dbms_output.put_line('Hello World ! ') ;
END ;
With an output : PL/SQl procedure successfully completed i.e without the expected output
And the main reason behind is that ,whatever we pass inside dbms_output.put_line(' ARGUMENT '/VALUES) i.e. ARGUMENT/VALUES , is internally stored inside a buffer in SGA(Shared Global Area ) memory area upto 2000 bytes .
*NOTE :***However one should note that this buffer is only created when we use **dbms_output package. And we need to set the environment variable only once for a session !!
And in order to fetch it from that buffer we need to set the environment variable for the session . It makes a lot of confusion to the beginners that we are setting the server output on ( because of its nomenclature ) , but unfortunately its nothing like that . Using SET SERVER OUTPUT ON are just telling the PL/SQL engine that
*Hey please print the ARGUMENT/VALUES that I will be passing inside dbms_output.put_line
and in turn PL/SQl run time engine prints the argument on the main console .
I think I am clear to you all . Wish you all the best . To know more about it with the architectural structure of Oracle Server Engine you can see my answer on Quora http://qr.ae/RojAn8
And to answer your question "One should use SET SERVER OUTPUT in the beginning of the session. "
It may also be, that you by mistake commented out such a line like require_once __DIR__.'/../vendor/autoload.php';
--- your namespaces are not loaded.
Or you forget to add a classmap to the composer, thus classes are not autoloaded and are not available. For example,
"autoload": {
"psr-4": {
"": "src/"
},
"classmap": [
"dir/YourClass.php",
]
},
"require": {
"php": ">=5.3.9",
"symfony/symfony": "2.8.*",
Code posted by you is correct and should have worked. But check exactly what you have in the char*
. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL
. Check what you have in the char*
against maximum values that float
and double
can represent on your computer.
Check this page for strtod
reference and this page for atof
reference.
I have tried the example you provided in both Windows and Linux and it worked fine.
You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:
body{
min-width:1000px; /* Suppose you want minimum width of 1000px */
width: auto !important; /* Firefox will set width as auto */
width:1000px; /* As IE6 ignores !important it will set width as 1000px; */
}
Or:
body{
min-width:1000px; // Suppose you want minimum width of 1000px
_width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}
File->Project Structure->Project pane->"Android plugin version".
Make sure you don't confuse the Gradle version with the Android plugin version. The former is the build system itself, the latter is the plugin to the build system that knows how to build Android projects
To your first question:
I would go with Paul R's comment and terminate with '\0'
. But the value 0
itself works also fine. A matter of taste. But don't use the MACRO NULL
which is meant for pointers.
To your second question:
If your string is not terminated with\0
, it might still print the expected output because following your string is a non-printable character in your memory. This is a really nasty bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'
.
In my case the problem occured from php
file.
It gave unwanted characters.That is why a json parsing
problem occured.
Then I paste my php code
in Notepad++
and select Encode in utf-8 without BOM
from Encoding
tab and running this code-
My problem gone away.
Put this code in the <head></head>
tags:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
Just add this line
sFileName = "C:\someotherfilelocation"
right before this line
Open sFileName For Output As iFileNum
The idea is to open and write to a different file than the one you read earlier (C:\filelocation
).
If you want to get fancy and show a real "Save As" dialog box, you could do this instead:
sFileName = Application.GetSaveAsFilename()
I feel this question need a bit more details. My answer is inspired from the Android Programming, The Big Nerd Ranch Guide (2nd edition).
By default, JavaScript is off in WebView. You do not always need to have it on, but for some apps, might do require it.
Loading the URL has to be done after configuring the WebView, so you do that last. Before that, you turn JavaScript on by calling getSettings()
to get an instance of WebSettings and calling WebSettings.setJavaScriptEnabled(true)
. WebSettings is the first of the three ways you can modify your WebView. It has various properties you can set, like the user agent string and text size.
After that, you configure your WebViewClient. WebViewClient is an event interface. By providing your own implementation of WebViewClient, you can respond to rendering events. For example, you could detect when the renderer starts loading an image from a particular URL or decide whether to resubmit a POST request to the server.
WebViewClient has many methods you can override, most of which you will not deal with. However, you do need to replace the default WebViewClient’s implementation of shouldOverrideUrlLoading(WebView, String)
. This method determines what will happen when a new URL is loaded in the WebView, like by pressing a link. If you return true, you are saying, “Do not handle this URL, I am handling it myself.” If you return false, you are saying, “Go ahead and load this URL, WebView, I’m not doing anything with it.”
The default implementation fires an implicit intent with the URL, just like you did earlier. Now, though, this would be a severe problem. The first thing some Web Applications does is redirect you to the mobile version of the website. With the default WebViewClient, that means that you are immediately sent to the user’s default web browser. This is just what you are trying to avoid. The fix is simple – just override the default implementation and return false.
Use WebChromeClient to spruce things up Since you are taking the time to create your own WebView, let’s spruce it up a bit by adding a progress bar and updating the toolbar’s subtitle with the title of the loaded page.
To hook up the ProgressBar, you will use the second callback on WebView: WebChromeClient
.
WebViewClient is an interface for responding to rendering events; WebChromeClient is an event interface for reacting to events that should change elements of chrome around the browser. This includes JavaScript alerts, favicons, and of course updates for loading progress and the title of the current page.
Hook it up in onCreateView(…)
. Using WebChromeClient to spruce things up
Progress updates and title updates each have their own callback method,
onProgressChanged(WebView, int)
and onReceivedTitle(WebView, String)
. The progress you receive from onProgressChanged(WebView, int)
is an integer from 0 to 100. If it is 100, you know
that the page is done loading, so you hide the ProgressBar by setting its visibility to View.GONE
.
Disclaimer: This information was taken from Android Programming: The Big Nerd Ranch Guide with permission from the authors. For more information on this book or to purchase a copy, please visit bignerdranch.com.
Use Match() function in excel VBA to check whether the value exists in an array.
Sub test()
Dim x As Long
vars1 = Array("Abc", "Xyz", "Examples")
vars2 = Array("Def", "IJK", "MNO")
If IsNumeric(Application.Match(Range("A1").Value, vars1, 0)) Then
x = 1
ElseIf IsNumeric(Application.Match(Range("A1").Value, vars2, 0)) Then
x = 1
End If
MsgBox x
End Sub
I wanted to do the same thing as, but I wanted to do it in the one file.
So the logic would be:
I modified the answer by Bakuriu and came up with this:
from os import getpid
from sys import argv, exit
import psutil ## pip install psutil
myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
if process.pid != mypid:
for path in process.cmdline():
if myname in path:
print "process found"
process.terminate()
exit()
## your program starts here...
Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.
I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.
There does not seem to be any answer which addresses the very common beginner problem of failing to install the required library in the first place.
On Debianish platforms, if libfoo
is missing, you can frequently install it with something like
apt-get install libfoo-dev
The -dev
version of the package is required for development work, even trivial development work such as compiling source code to link to the library.
The package name will sometimes require some decorations (libfoo0-dev
? foo-dev
without the lib
prefix? etc), or you can simply use your distro's package search to find out precisely which packages provide a particular file.
(If there is more than one, you will need to find out what their differences are. Picking the coolest or the most popular is a common shortcut, but not an acceptable procedure for any serious development work.)
For other architectures (most notably RPM) similar procedures apply, though the details will be different.
If you are simply testing a local dev version of WordPress as I was an hitting timeouts when WordPress tries to update itself you can always disable updates for your local version like so: https://www.wpbeginner.com/wp-tutorials/how-to-disable-automatic-updates-in-wordpress/
Don't do this for a production site!
If you are using jQuery you can use $('#mydiv').append('html content')
and it will keep the existing content.
Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:
- Install Visual Studio 2008
- Install the service Package 1 (SP1)
- Install SQL Server 2008 r2
<div id="calendar"></div>
<script>
$(document).ready(function() {
var days = [];
$('#calendar').datepicker({
dateFormat: 'yymmdd',
showWeek: true, showOtherMonths: false, selectOtherMonths: false,
navigationAsDateFormat: true, prevText: 'MM', nextText: 'MM',
onSelect: function(d) {
var i = $.inArray(d, days);
if (i == -1)
days.push(d);
else
days.splice(i, 1);
},
beforeShowDay: function(d) {
return ([true, $.inArray($.datepicker.formatDate('yymmdd', d), days) == -1 ? 'ui-state-free' : 'ui-state-busy']);
}
});
});
</script>
NOTE: You can prefill days
with a list of dates like '20190101'
with a piece of code in PHP.
Add 2 lines to your CSS:
#calendar .ui-state-busy a {background:#e6e6e6 !important;}
#calendar .ui-state-free a {background:none !important;}
To get the list of days selected by the calendar in a <form>
:
<div id="calendar"></div>
<form method="post">
<input type="submit" name="calendar_get" id="calendar_get" value="Validate" />
</form>
Add this to the <script>
:
$('#calendar_get').click(function() {
$(this).append('<input type="hidden" name="calendar_days" value="' + days.join(',') + '" />');
});
Apply implode
on the string in $_POST['calendar_days']
and map strtotime
to all the formatted dates.
var i=0,length=2;
for(i; i<=length;i++)
{
$('#footer-div'+[i]).append($('<div class="ui-footer ui-bar-b ui-footer-fixed slideup" data-theme="b" data-position="fixed" data-role="footer" role="contentinfo" ><h3 class="ui-title" role="heading" aria-level="1">Advertisement </h3></div>'));
}
This will convert an integer to a 2 digit hex string with the 0x prefix:
strHex = "0x%0.2X" % 255
allow from all will not work along with Require local. Instead, try Require ip xxx.xxx.xxx.xx
For Example:
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Require local
Require ip 10.0.0.1
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
Check this Link it contains a java-script code that you can use to refresh your page only once
There are more than one way to refresh your page:
solution1:
To refresh a page once each time it opens use:
<head>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
</head>
sollution2:
<script language=" JavaScript" >
<!--
function LoadOnce()
{
window.location.reload();
}
//-->
</script>
Then change your to say
<Body onLoad=" LoadOnce()" >
solution3:
response.setIntHeader("Refresh", 1);
But this solution will refresh the page more than one time depend on the time you specifying
I hope that will help you
It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.
Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.
DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj
...
The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.
var DyObjectsList = new List<dynamic>;
if (condition1) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = true;
DyObj.Message = "Message 1";
DyObjectsList .Add(DyObj);
}
if (condition2) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = false;
DyObj.Message = "Message 2";
DyObjectsList .Add(DyObj);
}
your resulting List essentially looks like this
DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj
Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.
However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.
Query all users and filter by the list from your text file:
$Users = Get-Content 'C:\scripts\Users.txt'
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users -contains $_.SamAccountName } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
Get-ADUser -Filter '*'
returns all AD user accounts. This stream of user objects is then piped into a Where-Object
filter, which checks for each object if its SamAccountName
property is contained in the user list from your input file ($Users
). Only objects with a matching account name are passed forward to the next step of the pipeline. The output can be limited by selecting the relevant properties before exporting the data.
You can further optimize the code by replacing the -contains
operator with hashtable lookups:
$Users = @{}
Get-Content 'C:\scripts\Users.txt' | ForEach-Object { $Users[$_] = $true }
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users.ContainsKey($_.SamAccountName) } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
You can use include
/include_once
or require
/require_once
require_once('class.php');
Alternatively, use autoloading
by adding to page.php
<?php
function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
$vars = new IUarts();
print($vars->data);
?>
It also works adding that __autoload
function in a lib that you include on every file like utils.php
.
There is also this post that has a nice and different approach.
1)event.stopPropagation():
=>It is used to stop executions of its corresponding parent handler only.
2) event.stopImmediatePropagation():
=> It is used to stop the execution of its corresponding parent handler and also handler or function attached to itself except the current handler.
=> It also stops all the handler attached to the current element of entire DOM.
Here is the example: Jsfiddle!
Thanks, -Sahil
In Python 2:
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a, list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
In Python 3:
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> list(zip(list_a, list_b))
[(1, 5), (2, 6), (3, 7), (4, 8)]
To directly answer your question if you want to return a view that belongs to another controller you simply have to specify the name of the view and its folder name.
public class CommentsController : Controller
{
public ActionResult Index()
{
return View("../Articles/Index", model );
}
}
and
public class ArticlesController : Controller
{
public ActionResult Index()
{
return View();
}
}
Also, you're talking about using a read and write method from one controller in another. I think you should directly access those methods through a model rather than calling into another controller as the other controller probably returns html.
This is usually happens when the remote is down/unavailable; or the remote machine doesn't have ssh installed; or a firewall doesn't allow a connection to be established to the remote host.
ssh
returns 255 when an error occurred or 255 is returned by the remote script:
EXIT STATUS
ssh exits with the exit status of the remote command or
with 255 if an error occurred.
Usually you would an error message something similar to:
ssh: connect to host host.domain.com port 22: No route to host
Or
ssh: connect to host HOSTNAME port 22: Connection refused
Check-list:
What happens if you run the ssh command directly from the command line?
Are you able to ping
that machine?
Does the remote has ssh installed?
If installed, then is the ssh service running?
With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt
in the root of your project. Then from the root of your project:
mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..
make
And for Debug
(again from the root of your project):
mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make
Release
/ Debug
will add the appropriate flags for your compiler. There are also RelWithDebInfo
and MinSizeRel
build configurations.
You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT
variables, e.g.:
set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")
See CMAKE_BUILD_TYPE for more details.
As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.
What you've got (according to the debug image) is an object array containing a string array. So you need something like:
Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];
You haven't shown the type of values
- if this is already Object[]
then you could just use (String[])values[0]
.
Of course even with the cast to Object[]
you could still do it in one statement, but it's ugly:
String[] strings = (String[]) ((Object[])values)[0];
You have mentioned "user" twice in your FROM clause. You must provide a table alias to at least one mention so each mention of user. can be pinned to one or the other instance:
FROM article INNER JOIN section
ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user **AS user1** ON article.author\_id = **user1**.id
LEFT JOIN user **AS user2** ON article.modified\_by = **user2**.id
WHERE article.id = '1'
(You may need something different - I guessed which user is which, but the SQL engine won't guess.)
Also, maybe you only needed one "user". Who knows?
The else
is only connected to the last if
. You want elif
:
if 'bad' in line:
pass
elif 'naughty' in line:
pass
else:
newopen.write(line)
Also note that I removed the line substitution, as you don't write those lines anyway.
$('#hello').hide('slide', {direction: 'left'}, 1000);
requires the jQuery-ui library. See http://www.jqueryui.com
Query syntax
var query = from p in context.People
group p by p.name into g
select new
{
name = g.Key,
count = g.Count()
};
Method syntax
var query = context.People
.GroupBy(p => p.name)
.Select(g => new { name = g.Key, count = g.Count() });
Well, I got a similar problem with large data set and trying to force the application to use so much data is not really the right option. The best tip I can give you is to process your data in small chunk if it is possible. Because dealing with so much data, the problem will come back sooner or later. Plus, you cannot know the configuration of each machine that will run your application so there's always a risk that the exception will happens on another pc.
All that the call to urlopen()
does (according to the docs) is return a file-like object. Once you have that, you need to call its read()
method to actually pull the JSON data across the network.
Something like:
jsonurl = urlopen(url)
text = json.loads(jsonurl.read())
print text
According to me the best way of dealing with such problems and avoiding couple of condition required for checking the the height of device, is using the relative frame for views or any UI element which you are adding to you view for example: if you are adding some UI element which you want should at the bottom of view or just above tab bar then you should take the y origin with respect to your view's height or with respect to tab bar (if present) and we have auto resizing property as well. I hope this will work for you
If the column already exists in your table and it is null, you can update the column with this command (replace id, tablename, and tablekey ):
UPDATE x
SET x.<Id> = x.New_Id
FROM (
SELECT <Id>, ROW_NUMBER() OVER (ORDER BY <tablekey>) AS New_Id
FROM <tablename>
) x
You can use the DataFrame method .apply()
to operate on the values in Mycol:
>>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
>>> df
Mycol
0 05SEP2014:00:00:00.000
>>> import datetime as dt
>>> df['Mycol'] = df['Mycol'].apply(lambda x:
dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
>>> df
Mycol
0 2014-09-05
This answer comes a little bit late, but I just was in a similar need.
Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.
For example, use the directive like this:
<my-directive class2add="special-class" />
And get the following html:
<div>
<ul>
<li class="special-class">Item 1</li>
<li class="special-class">Item 2</li>
</ul>
</div>
The solution found here applied with templateUrl, would be:
app.directive("myDirective", function() {
return {
template: function(element, attrs){
return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
},
link: function(scope, element, attrs) {
var list = element.find("ul");
}
}
});
Just tried it successfully with AngularJS 1.4.9.
Hope it helps.
I didn't want any image so i modified the answer given by @statmaster to make it simple entry along with the other columns.
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this entry?');">Delete </asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
The colour of the text can be changed using the Forecolor Property.
If you look at your XAMPP Control Panel, it's clearly stated that the port to the MySQL server is 3306
- you provided 3360
. The 3306
is default, and thus doesn't need to be specified. Even so, the 5th parameter of mysqli_connect()
is the port, which is where it should be specified.
You could just remove the port specification altogether, as you're using the default port, making it
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'test_db13';
References
Looks like I am late to the party, but try the below solution which I personally found the best solution:
var x = "testing sub string"
alert(x[0]);
alert(x[1]);
Output should show alert with below values: "t" "e"
They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"
On Windows add following lines to _vimrc
" store backup, undo, and swap files in temp directory
set directory=$HOME/temp//
set backupdir=$HOME/temp//
set undodir=$HOME/temp//
Thank you all! i managed to do what i wanted :D http://jsfiddle.net/Tfc9j/42/ here take a look
i wanted to have the opacity of an outer div to be different from the opacity of the internal div and that change with a click somwewhere ;) Thanks!
$('#ena').on('click', function () {
$('head').append("<style>#ena:before { opacity:0.3; }</style>");
});
$('#duop').on('click', function (e) {
$('head').append("<style>#ena:before { opacity:0.8; }</style>");
e.stopPropagation();
});
#ena{
width:300px;
height:300px;
border:1px black solid;
position:relative;
}
#duo{
opacity:1;
position:absolute;
top:50px;
width:300px;
height:100px;
background-color:white;
}
#ena:before {
content: attr(data-before);
color: white;
cursor: pointer;
position: absolute;
background-color:red;
opacity:0.9;
width:100%;
height:100%;
}
<div id="ena">
<div id="duo">
<p>ena p</p>
<p id="duop">duoyyyyyyyyyyyyyy p</p>
</div>
</div>
a very clean solution working in all browsers and without any framework is to asign a new Array and simply return it without the item you want to delete:
/**
* @param {Array} array the original array with all items
* @param {any} item the time you want to remove
* @returns {Array} a new Array without the item
*/
var removeItemFromArray = function(array, item){
/* assign a empty array */
var tmp = [];
/* loop over all array items */
for(var index in array){
if(array[index] !== item){
/* push to temporary array if not like item */
tmp.push(array[index]);
}
}
/* return the temporary array */
return tmp;
}
Use the phpinfo();
function to see the table of settings on your browser and look for the
Configuration File (php.ini) Path
and edit that file. Your computer can have multiple php.ini files, you want to edit the right one.
Also check display_errors = On
, html_errors = On
and error_reporting = E_ALL
inside that file
Restart Apache.
Just a note:
W3C has no problem with button inside of link tag, so it is just another MS sub-standard.
Answer:
Use surrogate button, unless you want to go for a full image.
Surrogate button can be put into tag (safer, if you use spans, not divs).
It can be styled to look like button, or anything else.
It is versatile - one piece of css code powers all instances - just define CSS once and from that point just copy and paste html instance wherever your code requires it.
Every button can have its own label - great for multi-lingual pages (easier that doing pictures for every language - I think) - also allows to propagate instances all over your script easier.
Adjusts its width to label length - also takes fixed width if it is how you want it.
IE7 is an exception to above - it must have width, or will make this button from edge to edge - alternatively to giving it width, you can float button left
- css for IE7:
a. .width:150px; (make note of dot before property, I usually target IE7 by adding such dot - remove dot and property will be read by all browsers)
b. text-align:center; - if you have fixed width, you have to have this to center text/label
c. cursor:pointer; - all IE must have this to show link pointer correctly - good browsers do not need it
You can go step forward with this code and use CSS3 to style it, instead of using images:
a. radius for round corners (limitation: IE will show them square)
b. gradient to make it "button like" (limitation: opera does not support gradients, so remember to set standard background colour for this browser)
c. use :hover pclass to change button states depending on mouse pointer position etc. - you can apply it to text label only, or whole button
.button_surrogate span { margin:0; display:block; height:25px; text-align:center; cursor:pointer; .width:150px; background:url(left_button_edge.png) left top no-repeat; }
.button_surrogate span span { display:block; padding:0 14px; height:25px; background:url(right_button_edge.png) right top no-repeat; }
.button_surrogate span span span { display:block; overflow:hidden; padding:5px 0 0 0; background:url(button_connector.png) left top repeat-x; }
HTML code below (button instance):
<a href="#">
<span class="button_surrogate">
<span><span><span>YOUR_BUTTON_LABEL</span></span></span>
</span>
</a>
This is how its working for me. The redirection used will redirect all the normal http as well.
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var request = require('request');
//For https
const https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('certificates/private.key'),
cert: fs.readFileSync('certificates/certificate.crt'),
ca: fs.readFileSync('certificates/ca_bundle.crt')
};
// API file for interacting with MongoDB
const api = require('./server/routes/api');
// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));
// API location
app.use('/api', api);
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(function(req,resp,next){
if (req.headers['x-forwarded-proto'] == 'http') {
return resp.redirect(301, 'https://' + req.headers.host + '/');
} else {
return next();
}
});
http.createServer(app).listen(80)
https.createServer(options, app).listen(443);
The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this:
f = open('test.txt','r')
g = open('test1.txt','w')
while True:
x = f.readline()
x = x.rstrip()
if not x: break
print >> g, int(x, 16)
On the other hand it would be better to use for x in f
instead of readline
. Do not forget to close your files or better to use with
that close them for you:
with open('test.txt','r') as f:
with open('test1.txt','w') as g:
for x in f:
x = x.rstrip()
if not x: continue
print >> g, int(x, 16)
Above answers are helpful, I'd just like to add an example that I think is demonstrating clearly what happens when we pass parameter without the ref keyword, even when that parameter is a reference type:
MyClass c = new MyClass(); c.MyProperty = "foo";
CNull(c); // only a copy of the reference is sent
Console.WriteLine(c.MyProperty); // still foo, we only made the copy null
CPropertyChange(c);
Console.WriteLine(c.MyProperty); // bar
private void CNull(MyClass c2)
{
c2 = null;
}
private void CPropertyChange(MyClass c2)
{
c2.MyProperty = "bar"; // c2 is a copy, but it refers to the same object that c does (on heap) and modified property would appear on c.MyProperty as well.
}
Instead of
style="width:100%"
try using
class="col-xs-12"
it will save you 1 character :)
MDN has a good example on the use of setTimeout preserving "this".
Like the following:
function doSomething() {
// use 'this' to handle the selected element here
}
$(".someSelector").each(function() {
setTimeout(doSomething.bind(this), 0);
});
Maybe you coul'd use UTF8 bold chars.
For examples: https://yaytext.com/bold-italic/
It works on Chromium 80.0, I don't know on other browsers...
You should really rethink your approach to this issue. Using a well crafted selector and attaching the class may be a more elegant solution to this approach. As far as I know you cannot modify external CSS.
If you are facing this issue in case of Sqlite then
. I think this is the problem with version of Sqlite,I had the same problem when I was using this versions of SqLite
Version 2.2.4:
After checking version here I changed the version then it worked.
No error after using this
Version 2.1.2:
i had this issue years back..but I got this. All you need to do is set the width and the height of the image to whatever you want..what i mean is your image in your carousel inner ...don't add the style attribut like "style:"(no not this) but something like this and make sure your codes ar correct its gonna work...Good luck
Normal answer for this question if you really want to get something like content//media/external/video/media/18576
(e.g. for your video mp4 absolute path) and not just file///storage/emulated/0/DCIM/Camera/20141219_133139.mp4
:
MediaScannerConnection.scanFile(this,
new String[] { file.getAbsolutePath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("onScanCompleted", uri.getPath());
}
});
Accepted answer is wrong (cause it will not return content//media/external/video/media/*
)
Uri.fromFile(file).toString()
only returns something like file///storage/emulated/0/*
which is a simple absolute path of a file on the sdcard but with file//
prefix (scheme)
You can also get content
uri using MediaStore
database of Android
TEST (what returns Uri.fromFile
and what returns MediaScannerConnection
):
File videoFile = new File("/storage/emulated/0/video.mp4");
Log.i(TAG, Uri.fromFile(videoFile).toString());
MediaScannerConnection.scanFile(this, new String[] { videoFile.getAbsolutePath() }, null,
(path, uri) -> Log.i(TAG, uri.toString()));
Output:
I/Test: file:///storage/emulated/0/video.mp4
I/Test: content://media/external/video/media/268927
type C:\temp\test.bat>C:\temp\test.log
Here are the simple ways to every date format confusions:
for current date:
var current_date=new Date();
to get the Timestamp of current date:
var timestamp=new Date().getTime();
to convert a particular Date into Timestamp:
var timestamp_formation=new Date('mm/dd/yyyy').getTime();
to convert timestamp into Date:
var timestamp=new Date('02/10/2016').getTime();
var todate=new Date(timestamp).getDate();
var tomonth=new Date(timestamp).getMonth()+1;
var toyear=new Date(timestamp).getFullYear();
var original_date=tomonth+'/'+todate+'/'+toyear;
OUTPUT:
02/10/2016
You could try giving an ID to the form, in order to get ahold of it, and then call form.submit() from a Javascript call.
Petruza,
Instead of using keystroke use key code.
The following example should work for you.
tell application "System Events"
tell application process "Terminal"
set frontmost to true
key code {2, 0, 17, 14}
keystroke return
end tell
end tell
The above example will send the characters {d a t e}
to Terminal and then
keystroke return will enter and run
the command. Use the above example
with whatever key codes you need
and you'll be able to do what you're trying to do.
For a cell to self-reference itself:
INDIRECT(ADDRESS(ROW(), COLUMN()))
For a cell to self-reference its column:
INDIRECT(ADDRESS(1,COLUMN()) & ":" & ADDRESS(65536, COLUMN()))
For a cell to self-reference its row:
INDIRECT(ADDRESS(ROW(),1) & ":" & ADDRESS(ROW(),256))
or
INDIRECT("A" & ROW() & ":IV" & ROW())
The numbers are for 2003 and earlier, use column:XFD and row:1048576 for 2007+.
Note: The INDIRECT function is volatile and should only be used when needed.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(range(10), 'r') #row=0, col=0
ax[1, 0].plot(range(10), 'b') #row=1, col=0
ax[0, 1].plot(range(10), 'g') #row=0, col=1
ax[1, 1].plot(range(10), 'k') #row=1, col=1
plt.show()
OK, so within minutes after posting the question, I found the answer myself here: https://github.com/npm/npm/issues/2119#issuecomment-5321857
The issue seems to be that npm is not that great with HTTPS over a proxy. Changing the registry URL from HTTPS to HTTP fixed it for me:
npm config set registry http://registry.npmjs.org/
I still have to provide the proxy config (through Authoxy in my case), but everything works fine now.
Seems to be a common issue, but not well documented. I hope this answer here will make it easier for people to find if they run into this issue.
First of all, Don't repeat yourself.
Then, please be careful not to overengineer, sometimes it is just a waste of time, and makes someone lose focus on what is important. Review the zen of python from time to time.
Take a look at active projects
the fabric repository is also a good one to look at.
yourapp/models/logicalgroup.py
User
, Group
and related models can go under yourapp/models/users.py
Poll
, Question
, Answer
... could go under yourapp/models/polls.py
__all__
inside of yourapp/models/__init__.py
request.GET
/ request.POST
...etctastypie
or piston
Take advantage of middleware / templatetags
Take advantage of model managers
User
can go in a UserManager(models.Manager)
.models.Model
.queryset
could go in a models.Manager
.User
one at a time, so you may think that it should live on the model itself, but when creating the object, you probably don't have all the details:Example:
class UserManager(models.Manager):
def create_user(self, username, ...):
# plain create
def create_superuser(self, username, ...):
# may set is_superuser field.
def activate(self, username):
# may use save() and send_mail()
def activate_in_bulk(self, queryset):
# may use queryset.update() instead of save()
# may use send_mass_mail() instead of send_mail()
Make use of forms where possible
A lot of boilerplate code can be eliminated if you have forms that map to a model. The ModelForm documentation
is pretty good. Separating code for forms from model code can be good if you have a lot of customization (or sometimes avoid cyclic import errors for more advanced uses).
Use management commands when possible
yourapp/management/commands/createsuperuser.py
yourapp/management/commands/activateinbulk.py
if you have business logic, you can separate it out
django.contrib.auth
uses backends, just like db has a backend...etc.setting
for your business logic (e.g. AUTHENTICATION_BACKENDS
)django.contrib.auth.backends.RemoteUserBackend
yourapp.backends.remote_api.RemoteUserBackend
yourapp.backends.memcached.RemoteUserBackend
backend example:
class User(db.Models):
def get_present_name(self):
# property became not deterministic in terms of database
# data is taken from another service by api
return remote_api.request_user_name(self.uid) or 'Anonymous'
could become:
class User(db.Models):
def get_present_name(self):
for backend in get_backends():
try:
return backend.get_present_name(self)
except: # make pylint happy.
pass
return None
more about design patterns
more about interface boundaries
yourapp.models
yourapp.vendor
yourapp.libs
yourapp.libs.vendor
or yourapp.vendor.libs
In short, you could have
yourapp/core/backends.py
yourapp/core/models/__init__.py
yourapp/core/models/users.py
yourapp/core/models/questions.py
yourapp/core/backends.py
yourapp/core/forms.py
yourapp/core/handlers.py
yourapp/core/management/commands/__init__.py
yourapp/core/management/commands/closepolls.py
yourapp/core/management/commands/removeduplicates.py
yourapp/core/middleware.py
yourapp/core/signals.py
yourapp/core/templatetags/__init__.py
yourapp/core/templatetags/polls_extras.py
yourapp/core/views/__init__.py
yourapp/core/views/users.py
yourapp/core/views/questions.py
yourapp/core/signals.py
yourapp/lib/utils.py
yourapp/lib/textanalysis.py
yourapp/lib/ratings.py
yourapp/vendor/backends.py
yourapp/vendor/morebusinesslogic.py
yourapp/vendor/handlers.py
yourapp/vendor/middleware.py
yourapp/vendor/signals.py
yourapp/tests/test_polls.py
yourapp/tests/test_questions.py
yourapp/tests/test_duplicates.py
yourapp/tests/test_ratings.py
or anything else that helps you; finding the interfaces you need and the boundaries will help you.
According to this JSPerf test, they differ in speed. But unless you're going to use them in huge amounts, any of them should perform fine.
For completeness: As asawyer already mentioned, you can also use the .toString()
method.
If you pass the -v
flag to ansible-playbook on the command line, you'll see the stdout and stderr for each task executed:
$ ansible-playbook -v playbook.yaml
Ansible also has built-in support for logging. Add the following lines to your ansible configuration file:
[defaults]
log_path=/path/to/logfile
Ansible will look in several places for the config file:
ansible.cfg
in the current directory where you ran ansible-playbook
~/.ansible.cfg
/etc/ansible/ansible.cfg
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
now it is:
this.activatedRoute.queryParams.subscribe((params: Params) => {
console.log(params);
});
I was able to came up with a couple of "one line" solutions, for example:
obj.map(o -> (Runnable) () -> o.setAvailable(true))
.orElse(() -> logger.fatal("Object not available"))
.run();
or
obj.map(o -> (Consumer<Object>) c -> o.setAvailable(true))
.orElse(o -> logger.fatal("Object not available"))
.accept(null);
or
obj.map(o -> (Supplier<Object>) () -> {
o.setAvailable(true);
return null;
}).orElse(() () -> {
logger.fatal("Object not available")
return null;
}).get();
It doesn't look very nice, something like orElseRun
would be much better, but I think that option with Runnable is acceptable if you really want one line solution.
This is the class I wrote for this purpose:
public class Base64Image
{
public static Base64Image Parse(string base64Content)
{
if (string.IsNullOrEmpty(base64Content))
{
throw new ArgumentNullException(nameof(base64Content));
}
int indexOfSemiColon = base64Content.IndexOf(";", StringComparison.OrdinalIgnoreCase);
string dataLabel = base64Content.Substring(0, indexOfSemiColon);
string contentType = dataLabel.Split(':').Last();
var startIndex = base64Content.IndexOf("base64,", StringComparison.OrdinalIgnoreCase) + 7;
var fileContents = base64Content.Substring(startIndex);
var bytes = Convert.FromBase64String(fileContents);
return new Base64Image
{
ContentType = contentType,
FileContents = bytes
};
}
public string ContentType { get; set; }
public byte[] FileContents { get; set; }
public override string ToString()
{
return $"data:{ContentType};base64,{Convert.ToBase64String(FileContents)}";
}
}
var base64Img = new Base64Image {
FileContents = File.ReadAllBytes("Path to image"),
ContentType="image/png"
};
string base64EncodedImg = base64Img.ToString();
A possibility is that the git server you are pushing to is down/crashed, and the solution lies in restarting the git server.
Take a look at SimpleDateFormat
:
java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));
You may well want to use JSON-P instead (see below). First a quick explanation.
The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest
) rather than the standard XMLHttpRequest
that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com
).
To get the JSON data you're requesting, you basically have three options:
If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)
Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax
call (just set dataType
to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:
{"weather": "Dreary start but soon brightening into a fine summer day."}
Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:
jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
That's it. JSON-P is very broadly compatible (because it works via JavaScript script
tags). JSON-P is only for GET
, though, not POST
(again because it works via script
tags).
Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:
A. The browser will send your server a "preflight" message using the OPTIONS
HTTP verb (method). It will contain the various headers it would send with the GET
or POST
as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET
or POST
), and "Access-Control-Request-Headers" (the headers it wants to send).
B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.
C. The browser will look at your response and see whether it's allowed to send you the actual GET
or POST
. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.
D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.
In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):
// Find out what the request is asking for
corsOrigin = get_request_header("Origin")
corsMethod = get_request_header("Access-Control-Request-Method")
corsHeaders = get_request_header("Access-Control-Request-Headers")
if corsOrigin is null or "null" {
// Requests from a `file://` path seem to come through without an
// origin or with "null" (literally) as the origin.
// In my case, for testing, I wanted to allow those and so I output
// "*", but you may want to go another way.
corsOrigin = "*"
}
// Decide whether to accept that request with those headers
// If so:
// Respond with headers saying what's allowed (here we're just echoing what they
// asked for, except we may be using "*" [all] instead of the actual origin for
// the "Access-Control-Allow-Origin" one)
set_response_header("Access-Control-Allow-Origin", corsOrigin)
set_response_header("Access-Control-Allow-Methods", corsMethod)
set_response_header("Access-Control-Allow-Headers", corsHeaders)
if the HTTP request method is "OPTIONS" {
// Done, no body in response to OPTIONS
stop
}
// Process the GET or POST here; output the body of the response
Again stressing that this is pseudo-code.
Using a little different approach, you can use try catch
, with throw statement.
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
I recently had to do this to create half decent looking emails for an email client that did not support the CSS necessary. For an HTML only solution I use a wrapping table to provide the padding.
<table border="1" cellspacing="0" cellpadding="0">_x000D_
<tr><td height="5" colspan="3"></td></tr>_x000D_
<tr>_x000D_
<td width="5"></td>_x000D_
<td>_x000D_
This cells padding matches what you want._x000D_
<ul>_x000D_
<li>5px Left, Top, Bottom padding</li>_x000D_
<li>10px on the right</li>_x000D_
</ul> _x000D_
You can then put your table inside this_x000D_
cell with no spacing or padding set. _x000D_
</td>_x000D_
<td width="10"></td>_x000D_
</tr>_x000D_
<tr><td height="5" colspan="3"></td></tr>_x000D_
</table>
_x000D_
As of 2017 you would only do this for old email client support, it's pretty overkill.
In POSIX systems, you don't find -r
parameter for grep
and your grep -rn "stuff" .
won't run, but if you use find
command it will:
find . -type f -exec grep -n "stuff" {} \; -print
Agreed by Solaris
and HP-UX
.
object-fit
may help you, if you're playing with<img>
tag
The below code will crop your image for you. You can play around with object-fit
img {
object-fit: cover;
width: 300px;
height: 337px;
}
Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).
If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel
public class ThisViewModel : ViewModelBase
{
TypeOfAncestorViewModel Parent { get; set; }
}
and bind against that directly instead.
<TextBox Text="{Binding Parent}" />
To get the index by value, simply add .index[0] to the end of a query. This will return the index of the first row of the result...
So, applied to your dataframe:
In [1]: a[a['c2'] == 1].index[0] In [2]: a[a['c1'] > 7].index[0]
Out[1]: 0 Out[2]: 4
Where the query returns more than one row, the additional index results can be accessed by specifying the desired index, e.g. .index[n]
In [3]: a[a['c2'] >= 7].index[1] In [4]: a[(a['c2'] > 1) & (a['c1'] < 8)].index[2]
Out[3]: 4 Out[4]: 3
One line of code using jQuery which hides the 2nd column:
$('td:nth-child(2)').hide();
If your table has header(th), use this:
$('td:nth-child(2),th:nth-child(2)').hide();
Source: Hide a Table Column with a Single line of jQuery code
jsFiddle to test the code: http://jsfiddle.net/mgMem/1/
If you want to see a good use case, take a look at my blog post:
Hide a table column and colorize rows based on value with jQuery.
I couldn't get live or delegate to work on a div in a lightbox (tinybox).
I used setTimeout successfullly, in the following simple way:
$('#displayContact').click(function() {
TINY.box.show({html:'<form><textarea id="contactText"></textarea><div id="contactSubmit">Submit</div></form>', close:true});
setTimeout(setContactClick, 1000);
})
function setContactClick() {
$('#contactSubmit').click(function() {
alert($('#contactText').val());
})
}
Just use DROP TABLE IF EXISTS
:
DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );
Try searching the MySQL documentation first if you have any other problems.
A simple solution that works well, is to parse the double from the string representation of the float:
double val = Double.valueOf(String.valueOf(yourFloat));
Not super efficient, but it works!
When creating a function, a property object called prototype is being created automatically (you didn't create it yourself) and is being attached to the function object (the constructor
).
Note: This new prototype object also points to, or has an internal-private link to, the native JavaScript Object.
Example:
function Foo () {
this.name = 'John Doe';
}
// Foo has an object property called prototype.
// prototype was created automatically when we declared the function Foo.
Foo.hasOwnProperty('prototype'); // true
// Now, we can assign properties and methods to it:
Foo.prototype.myName = function () {
return 'My name is ' + this.name;
}
If you create a new object out of Foo
using the new
keyword, you are basically creating (among other things) a new object that has an internal or private link to the function Foo
's prototype we discussed earlier:
var b = new Foo();
b.[[Prototype]] === Foo.prototype // true
[[Prototype]]
. Many browsers are providing us a public linkage to it that called __proto__
!
To be more specific, __proto__
is actually a getter function that belong to the native JavaScript Object. It returns the internal-private prototype linkage of whatever the this
binding is (returns the [[Prototype]]
of b
):
b.__proto__ === Foo.prototype // true
It is worth noting that starting of ECMAScript5
, you can also use the getPrototypeOf method to get the internal private linkage:
Object.getPrototypeOf(b) === b.__proto__ // true
__proto__
, prototype
and [[Prototype]]
and how it works.
Lua doesn't provide a standard sleep
function, but there are several ways to implement one, see Sleep Function for detail.
For Linux, this may be the easiest one:
function sleep(n)
os.execute("sleep " .. tonumber(n))
end
In Windows, you can use ping
:
function sleep(n)
if n > 0 then os.execute("ping -n " .. tonumber(n+1) .. " localhost > NUL") end
end
The one using select
deserves some attention because it is the only portable way to get sub-second resolution:
require "socket"
function sleep(sec)
socket.select(nil, nil, sec)
end
sleep(0.2)
Try like this...
select CONVERT (varchar(10), getdate(), 103) AS [DD/MM/YYYY]
For more info : http://www.sql-server-helper.com/tips/date-formats.aspx
Remove it from the adapter and then notify the arrayadapter that data set has changed.
m_adapter.remove(o);
m_adapter.notifyDataSetChanged();
As suggested in a similar question, use JavaScript to call window.open
with the target
argument set to _system
, as per the InAppBrowser documentation:
<a href="#" onclick="window.open('http://www.kidzout.com', '_system'); return false;">www.kidzout.com</a>
This should work, though a better and more flexible solution would be to intercept all links' click
events, and call window.open
with arguments read from the link's attributes.
Remember you must install the InAppBrowser plugin for this to work:
cordova plugin add cordova-plugin-inappbrowser
As an addendum to the existing answers, none of which worked for me I found my solution HERE:
https://bundletransformer.codeplex.com/discussions/429707
The solution was to
Build Action
as Content
I did NOT need to remove extensionless handlers (as can be found in other solutions on the internet)
I did NOT have to add the <add name="BundleModule" type="System.Web.Optimization.BundleModule" />
web.config setting.
Hope this helps!
var isiOSSafari = (navigator.userAgent.match(/like Mac OS X/i)) ? true: false;
$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);
Since react-native eject is depreciated in 60.3 and I was getting diff errors trying to upgrade form 60.1 to 60.3 regenerating the android folder was not working.
I had to
rm -R node_modules
Then update react-native in package.json to 59.1 (remove package-lock.json)
Run
npm install
react-native eject
This will regenerate your android and ios folders Finally upgrade back to 60.3
react-native upgrade
react-native upgrade while back and 59.1 did not regenerate my android folder so the eject was necessary.
PHP has libraries: http://ca.php.net/ldap
PEAR also has a number of packages: http://pear.php.net/search.php?q=ldap&in=packages&x=0&y=0
I haven't used either, but I was going to at one point and they seemed like they should work.
$(this).closest('ul').attr('id');
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
On linux, /etc/apache2/mods-enabled/php5.conf dans php5.load
exists. If not, enables this modules (may require to sudo apt-get install libapache2-mod-php5
).
define function outerHTML based on support for element.outerHTML:
var temp_container = document.createElement("div"); // empty div not added to DOM
if (temp_container.outerHTML){
var outerHTML = function(el){return el.outerHTML||el.nodeValue} // e.g. textnodes do not have outerHTML
} else { // when .outerHTML is not supported
var outerHTML = function(el){
var clone = el.cloneNode(true);
temp_container.appendChild(clone);
outerhtml = temp_container.innerHTML;
temp_container.removeChild(clone);
return outerhtml;
};
};
You can still use HttpResponseMessage
. That capability will not go away. I felt the same way as you and argued extensively with the team that there was no need for an additional abstraction. There were a few arguments thrown around to try and justify its existence but nothing that convinced me that it was worthwhile.
That is, until I saw this sample from Brad Wilson. If you construct IHttpActionResult
classes in a way that can be chained, you gain the ability to create a "action-level" response pipeline for generating the HttpResponseMessage
. Under the covers, this is how ActionFilters
are implemented however, the ordering of those ActionFilters
is not obvious when reading the action method which is one reason I'm not a fan of action filters.
However, by creating an IHttpActionResult
that can be explicitly chained in your action method you can compose all kinds of different behaviour to generate your response.
The main difference is that state are private to a component and can be changed inside that component only while props are just static value and key for child component which is passed through parent component and can't be changed inside the child component
I'm somewhat surprised that no one has mentioned that the original poster might have liked rational numbers to result. Should you be interested in this, the Python-based program Sage has your back. (Currently still based on Python 2.x, though 3.x is under way.)
sage: (20-10) / (100-10)
1/9
This isn't a solution for everyone, because it does do some preparsing so these numbers aren't int
s, but Sage Integer
class elements. Still, worth mentioning as a part of the Python ecosystem.
With JavaScript:
//#region REGION_NAME
...code here
//#endregion
After a long research and different experiments the easiest way "FOR MAC USERS" is to create a script:
open -a "Visual Studio" \
"path to first sln" \
"path to second sln" \
...
:D
use double quotation marks around the values.
insert into Person (First, Last) Values("Joe","O'Brien")
Include the sunfire and jacoco plugins in the pom.xml and Run the maven command as given below.
mvn jacoco:prepare-agent jacoco:report sonar:sonar
<properties>
<surefire.version>2.17</surefire.version>
<jacoco.version>0.7.2.201409121644</jacoco.version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals><goal>prepare-agent</goal></goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals><goal>report</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
just insert the following line and use any color you like
echo "<body style='background-color:pink'>";
One caveat on using window.open()
is that if the url that you pass to it doesn't have http://
or https://
in front of it, angular treats it as a route.
To get around this, test if the url starts with http://
or https://
and append it if it doesn't.
let url: string = '';
if (!/^http[s]?:\/\//.test(this.urlToOpen)) {
url += 'http://';
}
url += this.urlToOpen;
window.open(url, '_blank');
An abstract class can be used instead of an interface (in C# 7.3).
// Like interface
abstract class IIO
{
public virtual async Task<string> DoOperation(string Name)
{
throw new NotImplementedException(); // throwing exception
// return await Task.Run(() => { return ""; }); // or empty do
}
}
// Implementation
class IOImplementation : IIO
{
public override async Task<string> DoOperation(string Name)
{
return await await Task.Run(() =>
{
if(Name == "Spiderman")
return "ok";
return "cancel";
});
}
}
An example on how to use that would be great. There is a couple of examples at the Qt forum, but you're right that the official documentation should be expanded.
QJsonDocument
on its own indeed doesn't produce anything, you will have to add the data to it. That's done through the QJsonObject
, QJsonArray
and QJsonValue
classes. The top-level item needs to be either an array or an object (because 1
is not a valid json document, while {foo: 1}
is.)
I would suggest you just evenly space them as shown in this answer here
.navbar ul {
list-style-type: none;
padding: 0;
display: flex;
flex-direction: row;
justify-content: space-around;
flex-wrap: nowrap; /* assumes you only want one row */
}
To begin with, it would be best to understand the measure of information
.
measure
the information?When something unlikely happens, we say it's a big news. Also, when we say something predictable, it's not really interesting. So to quantify this interesting-ness
, the function should satisfy
one bit
of information.One natural measure that satisfy the constraints is
I(X) = -log_2(p)
where p is the probability of the event X
. And the unit is in bit
, the same bit computer uses. 0 or 1.
Fair coin flip :
How much information can we get from one coin flip?
Answer : -log(p) = -log(1/2) = 1 (bit)
If a meteor strikes the Earth tomorrow, p=2^{-22}
then we can get 22 bits of information.
If the Sun rises tomorrow, p ~ 1
then it is 0 bit of information.
So if we take expectation on the interesting-ness
of an event Y
, then it is the entropy.
i.e. entropy is an expected value of the interesting-ness of an event.
H(Y) = E[ I(Y)]
More formally, the entropy is the expected number of bits of an event.
Y = 1 : an event X occurs with probability p
Y = 0 : an event X does not occur with probability 1-p
H(Y) = E[I(Y)] = p I(Y==1) + (1-p) I(Y==0)
= - p log p - (1-p) log (1-p)
Log base 2 for all log.
sum(d.values()) - "d" -> Your dictionary Variable
This should work
render(){_x000D_
_x000D_
var payments = [];_x000D_
_x000D_
for(let i = 0; i < noGuest; i++){_x000D_
_x000D_
payments.push(_x000D_
<View key = {i}>_x000D_
<View>_x000D_
<TextInput />_x000D_
</View>_x000D_
<View>_x000D_
<TextInput />_x000D_
</View>_x000D_
<View>_x000D_
<TextInput />_x000D_
</View>_x000D_
</View>_x000D_
)_x000D_
}_x000D_
_x000D_
return (_x000D_
<View>_x000D_
<View>_x000D_
<View><Text>No</Text></View>_x000D_
<View><Text>Name</Text></View>_x000D_
<View><Text>Preference</Text></View>_x000D_
</View>_x000D_
_x000D_
{ payments }_x000D_
</View>_x000D_
)_x000D_
}
_x000D_
I think the challenge here is not to call upon global()
I would personally define a list for your (dynamic) variables to be held and then append to it within a for loop. Then use a separate for loop to view each entry or even execute other operations.
Here is an example - I have a number of network switches (say between 2 and 8) at various BRanches. Now I need to ensure I have a way to determining how many switches are available (or alive - ping test) at any given branch and then perform some operations on them.
Here is my code:
import requests
import sys
def switch_name(branchNum):
# s is an empty list to start with
s = []
#this FOR loop is purely for creating and storing the dynamic variable names in s
for x in range(1,8,+1):
s.append("BR" + str(branchNum) + "SW0" + str(x))
#this FOR loop is used to read each of the switch in list s and perform operations on
for i in s:
print(i,"\n")
# other operations can be executed here too for each switch (i) - like SSH in using paramiko and changing switch interface VLAN etc.
def main():
# for example's sake - hard coding the site code
branchNum= "123"
switch_name(branchNum)
if __name__ == '__main__':
main()
Output is:
BR123SW01
BR123SW02
BR123SW03
BR123SW04
BR123SW05
BR123SW06
BR123SW07
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
Another solution is just using not
to get the opposite negation:
<h2 th:if="${potentially_complex_expression}">Hello!</h2>
<span class="xxx" th:if="${not potentially_complex_expression}">Something else</span>
As explained in the documentation, it's the same thing as using th:unless
. As other answers have explained:
Also,
th:if
has an inverse attribute,th:unless
, which we could have used in the previous example instead of using a not inside the OGNL expression
Using not
also works, but IMHO it is more readable to use th:unless
instead of negating the condition with not
.
This is really late to the party, but none of the solutions above worked for me. I didn't want the "Found total xxx records
" so I added info:false
to the config. When I removed that everything worked.
I should note that the first page loaded fine. When I hit next, the second page loaded, but immediately threw the above console error
For Swift 3 and XCode 8, this worked. Follow below steps to achieve this:-
viewDidLoad()
{
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
var width = UIScreen.main.bounds.width
layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
width = width - 10
layout.itemSize = CGSize(width: width / 2, height: width / 2)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
}
You can add a new remote URL for the other username using git remote add origin-username https://[email protected]/repository_name.git
After this, if you'll push using git push -u origin-username master
, this will prompt you for the password.
Windows.System.UserProfile.GlobalizationPreferences.Languages[0]
This is the correct way to obtain the currently set system language. System language setting is completely different than culture setting from which you all want to get the language.
For example: User may use "en-GB" language along with "en-US" culture at the same time. Using CurrentCulture and other cultures you will get "en-US", hope you get the difference (that may be innoticable with GB-US, but with other languages?)
Is it possible to simulate abstract base class in JavaScript?
Certainly. There are about a thousand ways to implement class/instance systems in JavaScript. Here is one:
// Classes magic. Define a new class with var C= Object.subclass(isabstract),
// add class members to C.prototype,
// provide optional C.prototype._init() method to initialise from constructor args,
// call base class methods using Base.prototype.call(this, ...).
//
Function.prototype.subclass= function(isabstract) {
if (isabstract) {
var c= new Function(
'if (arguments[0]!==Function.prototype.subclass.FLAG) throw(\'Abstract class may not be constructed\'); '
);
} else {
var c= new Function(
'if (!(this instanceof arguments.callee)) throw(\'Constructor called without "new"\'); '+
'if (arguments[0]!==Function.prototype.subclass.FLAG && this._init) this._init.apply(this, arguments); '
);
}
if (this!==Object)
c.prototype= new this(Function.prototype.subclass.FLAG);
return c;
}
Function.prototype.subclass.FLAG= new Object();
var cat = new Animal('cat');
That's not really an abstract base class of course. Do you mean something like:
var Animal= Object.subclass(true); // is abstract
Animal.prototype.say= function() {
window.alert(this._noise);
};
// concrete classes
var Cat= Animal.subclass();
Cat.prototype._noise= 'meow';
var Dog= Animal.subclass();
Dog.prototype._noise= 'bark';
// usage
var mycat= new Cat();
mycat.say(); // meow!
var mygiraffe= new Animal(); // error!
Doesn't provide much functionality, but you can use the title command for a couple of uses, like providing status on a long script in the task bar, or just to enhance user feedback.
@title Searching for ...
:: processing search
@title preparing search results
:: data processing
It can also be done the following way.
At first rename local branch, then remote branch.
Renaming the local branch:
If logged in another branch,
git branch -m old_branch new_branch
If logged in the same branch,
git branch -m new_branch
Renaming remote branch:
git push origin :old_branch // Delete the remote branch
git push --set-upstream origin new_branch // Create a new remote branch
The following technique worked for me:
1) Right click on the project Solution -> Click on Clean solution
2) Right click on the project Solution -> Click on Rebuild solution
normaly is better image store in public folder (because it has write permission already that you can use when I upload images to it)
public
upload_media
photos
image.png
$image = public_path() . '/upload_media/photos/image.png'; // destination path
view PHP
<img src="<?= $image ?>">
View blade
<img src="{{ $image }}">
You can absolutely do that, just remove the @RequestParam
annotation, Spring will cleanly bind your request parameters to your class instance:
public @ResponseBody List<MyObject> myAction(
@RequestParam(value = "page", required = false) int page,
MyObject myObject)
You can wrap it in your own function:
function isNullAndUndef(variable) {
return (variable !== null && variable !== undefined);
}
In Python, you wouldn't use indexes for this at all, but just deal with the values—[value for value in a if value > 2]
. Usually dealing with indexes means you're not doing something the best way.
If you do need an API similar to Matlab's, you would use numpy, a package for multidimensional arrays and numerical math in Python which is heavily inspired by Matlab. You would be using a numpy array instead of a list.
>>> import numpy
>>> a = numpy.array([1, 2, 3, 1, 2, 3])
>>> a
array([1, 2, 3, 1, 2, 3])
>>> numpy.where(a > 2)
(array([2, 5]),)
>>> a > 2
array([False, False, True, False, False, True], dtype=bool)
>>> a[numpy.where(a > 2)]
array([3, 3])
>>> a[a > 2]
array([3, 3])
Underscore.js or Lodash
if (_.has(x, "y")) ...
:)
You can set custom color using this-
check out this - click hear
XSSFWorkbook workbook = new XSSFWorkbook();
IndexedColorMap colorMap = workbook.getStylesSource().getIndexedColors();
Font tableHeadOneFontStyle = workbook.createFont();
tableHeadOneFontStyle.setBold( true );
tableHeadOneFontStyle.setColor( IndexedColors.BLACK.getIndex() );
XSSFCellStyle tableHeaderOneColOneStyle = workbook.createCellStyle();
tableHeaderOneColOneStyle.setFont( tableHeadOneFontStyle );
tableHeaderOneColOneStyle
.setFillForegroundColor( new XSSFColor( new java.awt.Color( 255, 231, 153 ), colorMap ) );
tableHeaderOneColOneStyle.setFillPattern( FillPatternType.SOLID_FOREGROUND );
tableHeaderOneColOneStyle = setLeftRightBorderColor( tableHeaderOneColOneStyle );
tableHeaderOneColOneStyle = alignCenter( tableHeaderOneColOneStyle );
What was working for me (ASP.NET Core), was to set return type ContentResult
, then wrap the HMTL into it and set the ContentType to "text/html; charset=UTF-8"
. That is important, because, otherwise it will not be interpreted as HTML and the HTML language would be displayed as text.
Here's the example, part of a Controller class:
/// <summary>
/// Startup message displayed in browser.
/// </summary>
/// <returns>HTML result</returns>
[HttpGet]
public ContentResult Get()
{
var result = Content("<html><title>DEMO</title><head><h2>Demo started successfully."
+ "<br/>Use <b><a href=\"http://localhost:5000/swagger\">Swagger</a></b>"
+ " to view API.</h2></head><body/></html>");
result.ContentType = "text/html; charset=UTF-8";
return result;
}
For me it was the apache server hosted on a t2.micro linux EC2 instance, not the EC2 instance itself.
I fixed it by doing:
sudo su
service httpd restart