I ended up finding it through the IntelliSense on the get()
function. So, I'll post it here for anyone who is looking for similar information.
Anyways, the syntax is nearly identical, but slightly different. Instead of using URLSearchParams()
the parameters need to be initialized as HttpParams()
and the property within the get()
function is now called params
instead of search
.
import { HttpClient, HttpParams } from '@angular/common/http';
getLogs(logNamespace): Observable<any> {
// Setup log namespace query parameter
let params = new HttpParams().set('logNamespace', logNamespace);
return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })
}
I actually prefer this syntax as its a little more parameter agnostic. I also refactored the code to make it slightly more abbreviated.
getLogs(logNamespace): Observable<any> {
return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, {
params: new HttpParams().set('logNamespace', logNamespace)
})
}
Multiple Parameters
The best way I have found thus far is to define a Params
object with all of the parameters I want to define defined within. As @estus pointed out in the comment below, there are a lot of great answers in This Question as to how to assign multiple parameters.
getLogs(parameters) {
// Initialize Params Object
let params = new HttpParams();
// Begin assigning parameters
params = params.append('firstParameter', parameters.valueOne);
params = params.append('secondParameter', parameters.valueTwo);
// Make the API call using the new parameters.
return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })
Multiple Parameters with Conditional Logic
Another thing I often do with multiple parameters is allow the use of multiple parameters without requiring their presence in every call. Using Lodash, it's pretty simple to conditionally add/remove parameters from calls to the API. The exact functions used in Lodash or Underscores, or vanilla JS may vary depending on your application, but I have found that checking for property definition works pretty well. The function below will only pass parameters that have corresponding properties within the parameters variable passed into the function.
getLogs(parameters) {
// Initialize Params Object
let params = new HttpParams();
// Begin assigning parameters
if (!_.isUndefined(parameters)) {
params = _.isUndefined(parameters.valueOne) ? params : params.append('firstParameter', parameters.valueOne);
params = _.isUndefined(parameters.valueTwo) ? params : params.append('secondParameter', parameters.valueTwo);
}
// Make the API call using the new parameters.
return this._HttpClient.get(`${API_URL}/api/v1/data/logs`, { params: params })
Because of the condition in while
, the loop might never break:
while (entry != null) {
// If entry never becomes null here, loop will never break.
}
Instead of the null
check there, you can try this:
ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
// Rest of your code
}
You have to drop it and recreate it, but you don't have to incur the cost of revalidating the data if you don't want to.
alter table t drop constraint ck ;
alter table t add constraint ck check (n < 0) enable novalidate;
The enable novalidate
clause will force inserts or updates to have the constraint enforced, but won't force a full table scan against the table to verify all rows comply.
Late, but:
In addition to the DEFAULT_FROM_EMAIL
fix others have mentioned, and allowing less-secure apps to access the account, I had to navigate to https://accounts.google.com/DisplayUnlockCaptcha while signed in as the account in question to get Django to finally authenticate.
I went to that URL through a SSH tunnel to the web server to make sure the IP address was the same; I'm not totally sure if that's necessary but it can't hurt. You can do that like so: ssh -D 8080 -fN <username>@<host>
, then set your web browser to use localhost:8080
as a SOCKS proxy.
editText.setFocusableInTouchMode(false);
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
editText.setFocusable(true);
EditText will lose focus, but can gain it again on a new touch event.
At the risk of getting negative marks, I want to suggest that the highest ranking solution (currently the first response) violates the latest SDK Agreement as of Nov 5, 2009. Our application was just rejected for using it. Here's the response from Apple:
"For security reasons, iPhone OS restricts an application (including its preferences and data) to a unique location in the file system. This restriction is part of the security feature known as the application's "sandbox." The sandbox is a set of fine-grained controls limiting an application's access to files, preferences, network resources, hardware, and so on."
The device's phone number is not available within your application's container. You will need to revise your application to read only within your directory container and resubmit your binary to iTunes Connect in order for your application to be reconsidered for the App Store.
This was a real disappointment since we wanted to spare the user having to enter their own phone number.
This is how you will add local dependencies:
npm install file:src/assets/js/FILE_NAME
Add it to package.json from NPM:
npm install --save file:src/assets/js/FILE_NAME
Directly add to package.json like this:
....
"angular2-autosize": "1.0.1",
"angular2-text-mask": "8.0.2",
"animate.css": "3.5.2",
"LIBRARY_NAME": "file:src/assets/js/FILE_NAME"
....
If you're using Cloudera 5.x, Here in this documentation is mentioned that Lily maintains the Real time updations and deletions also.
Configuring the Lily HBase NRT Indexer Service for Use with Cloudera Search
As HBase applies inserts, updates, and deletes to HBase table cells, the indexer keeps Solr consistent with the HBase table contents, using standard HBase replication.
Not sure iftruncate 'hTable'
is also supported in the same.
Else you create a Trigger or Service to clear up your data from both Solr and HBase on a particular Event or anything.
Received the same error , the problem was difference in the version of Android SDK which AVD was using and the version in AndroidManifest file. I could solve it by correcting the
android:minSdkVersion="16"
to match with AVD.
pip install --ignore-installed six
This will do the job, then you can try your first command.
Read many answers and posts and determined the most accurate solution. Tested in Safari, Chrome, Firefox (desktop and iOS versions). First we need to detect Apple
vendor and then exclude Chrome and Firefox (for iOS).
let isSafari = navigator.vendor.match(/apple/i) &&
!navigator.userAgent.match(/crios/i) &&
!navigator.userAgent.match(/fxios/i);
if (isSafari) {
//
} else {
//
}
After calling an request, set timeout to initialize slick slider.
var options = {
arrows: false,
slidesToShow: 1,
variableWidth: true,
centerPadding: '10px'
}
$.ajax({
type: "GET",
url: review_url+"?page="+page,
success: function(result){
setTimeout(function () {
$(".reviews-page-carousel").slick(options)
}, 500);
}
})
Do not initialize slick slider at start. Just initialize after an AJAX with timeout. That should work for you.
In my case the solutions above did not work I had to do the following:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));
I'll just leave this here for people interested in an implementation with no dependencies.
inline int
stringLength (char *String)
{
int Count = 0;
while (*String ++) ++ Count;
return Count;
}
inline int
stringToInt (char *String)
{
int Integer = 0;
int Length = stringLength(String);
for (int Caret = Length - 1, Digit = 1; Caret >= 0; -- Caret, Digit *= 10)
{
if (String[Caret] == '-') return Integer * -1;
Integer += (String[Caret] - '0') * Digit;
}
return Integer;
}
Works with negative values, but can't handle non-numeric characters mixed in between (should be easy to add though). Integers only.
From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;
<ul>
<li class='item col-md-12 panel' id='gameplay-title'>Title</li>
<li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>
And so on... To add more categories add another ul in there. Now, for the CSS you just need this;
ul {
list-style: none;
}
.item {
display: inline;
padding-right: 20px;
}
"Change to if (typeof $next == 'object' && $next.length) $next[0].offsetWidth" -did not help. if you convert Bootstrap 3 to php(for WordPress theme), when adding WP_Query ($loop = new WP_Query( $args );) insert $count = 0;. And and at the end before endwhile; add $count++;.
this type of error usually occur when you try to access data through the index in which data data has not been assign. for example
//assign of data in to array
for(int i=0; i<10; i++){
arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}
the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.
I still experience occasional black screens with latest Chrome 60 with GPU acceleration enabled by default (probably caused by lack of free memory for numerous tabs).
Sometimes it helps to kill GPU process in builtin Task manager (Shift+Esc) as @amit suggests. But sometimes this forces more Chrome windows to become black while some others may remain normal.
I've noticed that tabs headers and address bar of black windows remain funtional and tabs can be fully repaired just by dragging them out of black windows. But it's too tedious to do this one by one when their number is huge.
So here is quick completely restartless solution inspired by Merging windows of Google Chrome:
No, there is no difference. But I prefer using int[] array
as it is more readable.
For C++ (using cURL):
#include <curl/curl.h>
//// cURL to string
size_t curl_to_str(void *contents, size_t size, size_t nmemb, void *userp) {
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
};
//// Read Instance-id
curl_global_init(CURL_GLOBAL_ALL); // Initialize cURL
CURL *curl; // cURL handler
CURLcode res_code; // Result
string response;
curl = curl_easy_init(); // Initialize handler
curl_easy_setopt(curl, CURLOPT_URL, "http://169.254.169.254/latest/meta-data/instance-id");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_to_str);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res_code = curl_easy_perform(curl); // Perform cURL
if (res_code != CURLE_OK) { }; // Error
curl_easy_cleanup(curl); // Cleanup handler
curl_global_cleanup(); // Cleanup cURL
Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under "Apple", do the following:
>>> mydict["Apple"]
{'American': '16', 'Mexican': 10, 'Chinese': 5}
And getting how many of them are American (16), do like this:
>>> mydict["Apple"]["American"]
'16'
If you are using new version of Kafka e.g. 5.3.3, you can use
kafka-broker-api-versions --bootstrap-server BROKER | grep 9092
You just need to pass one of the brokers
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
or you can use this, the '-1' means you don't have to specify the number of the elements.
In [3]: a.view(1,-1)
Out[3]:
1 2 3 4 5
[torch.FloatTensor of size 1x5]
Alternatively you can also use CASE
for the same:
SELECT CASE WHEN field1 IS NULL OR field1 = ''
THEN 'empty'
ELSE field1 END AS field1
FROM tablename.
Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
a = 5
makes the variable name a
to refer to the integer 5. Later, a = "hello"
makes the variable name a
to refer to a string containing "hello". Static typed languages would have you declare int a
and then a = 5
, but assigning a = "hello"
would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a
refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.a = "5"
(the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5
to get "hello5"
.Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...
Based on a web search, I just found a Chrome plugin called SVG Export.
Available in the Chrome web store: https://chrome.google.com/webstore/detail/svg-export/naeaaedieihlkmdajjefioajbbdbdjgp
The home page is https://svgexport.io
unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.
So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.
Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.
Besides calling omp_get_num_threads()
outside of the parallel region in your case, calling omp_set_num_threads()
still doesn't guarantee that the OpenMP runtime will use exactly the specified number of threads. omp_set_num_threads()
is used to override the value of the environment variable OMP_NUM_THREADS
and they both control the upper limit of the size of the thread team that OpenMP would spawn for all parallel regions (in the case of OMP_NUM_THREADS
) or for any consequent parallel region (after a call to omp_set_num_threads()
). There is something called dynamic teams that could still pick smaller number of threads if the run-time system deems it more appropriate. You can disable dynamic teams by calling omp_set_dynamic(0)
or by setting the environment variable OMP_DYNAMIC
to false
.
To enforce a given number of threads you should disable dynamic teams and specify the desired number of threads with either omp_set_num_threads()
:
omp_set_dynamic(0); // Explicitly disable dynamic teams
omp_set_num_threads(4); // Use 4 threads for all consecutive parallel regions
#pragma omp parallel ...
{
... 4 threads used here ...
}
or with the num_threads
OpenMP clause:
omp_set_dynamic(0); // Explicitly disable dynamic teams
// Spawn 4 threads for this parallel region only
#pragma omp parallel ... num_threads(4)
{
... 4 threads used here ...
}
It may be called abc.py
from the main script as below:
#!/usr/bin/python
import abc
abc.py
may be something like this:
print'abc'
For apache look up SymLink or you can solve via the OS with Symbolic Links or on linux set up a library link/etc
My answer is one method specifically to windows 10.
So my method involves mapping a network drive to U:/ (e.g. I use G:/ for Google Drive)
open cmd
and type hostname
(example result: LAPTOP-G666P000
, you could use your ip instead, but using a static hostname for identifying yourself makes more sense if your network stops)
Press Windows_key + E
> right click 'This PC'
> press N
(It's Map Network drive, NOT add a network location)
If you are right clicking the shortcut on the desktop you need to press N then enter
Fill out U:
or G:
or Z:
or whatever you want
Example Address: \\LAPTOP-G666P000\c$\Users\username\
Then you can use <a href="file:///u:/2ndFile.html"><button type="submit">Local file</button>
like in your question
related: You can also use this method for FTPs, and setup multiple drives for different relative paths on that same network.
related2: I have used http://localhost/c$
etc before on some WAMP/apache servers too before, you can use .htaccess
for control/security but I recommend to not do so on a live/production machine -- or any other symlink documentroot example you can google
See:
'Quattro TT'
is a string.
Since string is a list of characters, this is the same as
['Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T']
Now...
['Quattro TT']
is a list with a string in the first position.
Also...
a = 'Quattro TT'
list(a)
is a string converted into a list.
Again, since string is a list of characters, there is not much change.
Another information...
tuple(something)
This convert something into tuple.
Understanding all of this, I think you can conclude that nothing fails.
Yes with Virtual Host you can have as many parallel programs as you want:
Open
/etc/httpd/conf/httpd.conf
Listen 81
Listen 82
Listen 83
<VirtualHost *:81>
ServerAdmin [email protected]
DocumentRoot /var/www/site1/html
ServerName site1.com
ErrorLog logs/site1-error_log
CustomLog logs/site1-access_log common
ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>
<VirtualHost *:82>
ServerAdmin [email protected]
DocumentRoot /var/www/site2/html
ServerName site2.com
ErrorLog logs/site2-error_log
CustomLog logs/site2-access_log common
ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>
<VirtualHost *:83>
ServerAdmin [email protected]
DocumentRoot /var/www/site3/html
ServerName site3.com
ErrorLog logs/site3-error_log
CustomLog logs/site3-access_log common
ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>
Restart apache
service httpd restart
You can now refer Site1 :
http://<ip-address>:81/
http://<ip-address>:81/cgi-bin/
Site2 :
http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/
Site3 :
http://<ip-address>:83/
http://<ip-address>:83/cgi-bin/
If path is not hardcoded in any script then your websites should work seamlessly.
In Windows 10, it's still 8191 characters...at least on my machine.
It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.
Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.
echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat
I was having a lot of problems with justify-content, and I figured out the problem was "margin: 0 auto"
The auto part overrides the justify-content so its always displayed according to the margin and not to the justify-content.
If you are just setting defaults for certain attributes of a database backed model I'd consider using sql default column values - can you clarify what types of defaults you are using?
There are a number of approaches to handle it, this plugin looks like an interesting option.
This is how I did it. This makes the images in the slideshow take up the full screen if it´s aspect ratio allows it, othervice it scales down.
.carousel {
height: 100vh;
width: 100%;
overflow:hidden;
}
.carousel .carousel-inner {
height:100%;
}
To allways get a full screen slideshow, no matter screen aspect ratio, you can also use object-fit: (doesn´t work in IE or Edge)
.carousel .carousel-inner img {
display:block;
object-fit: cover;
}
When you populate your fields, you can check for the value:
<input type="radio" name="sex" value="Male" <?php echo ($sex=='Male')?'checked':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=='Female')?'checked':'' ?> size="17">Female
Assuming that the value you return from your database is in the variable $sex
The checked property will preselect the value that match
Use Load function
load(filename)
You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.
Example : mongo localhost:27017/mydb myfile.js
This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.
For loading external js you can write
load("/data/db/scripts/myloadjs.js")
Suppose we have two js file myFileOne.js and myFileTwo.js
myFileOne.js
print('From file 1');
load('myFileTwo.js'); // Load other js file .
myFileTwo.js
print('From file 2');
MongoShell
>mongo myFileOne.js
Output
From file 1
From file 2
in the java src you can add a new tool like this:
public static String remplaceVirguleParpoint(String chaine) {
return chaine.replaceAll(",", "\\.");
}
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
Flexible approach to produce different outputs based on the request
public class AuctionsController : Controller
{
public ActionResult Auction(long id)
{
var db = new DataContext();
var auction = db.Auctions.Find(id);
// Respond to AJAX requests
if (Request.IsAjaxRequest())
return PartialView("Auction", auction);
// Respond to JSON requests
if (Request.IsJsonRequest())
return Json(auction);
// Default to a "normal" view with layout
return View("Auction", auction);
}
}
The Request.IsAjaxRequest()
method is quite simple: it merely checks the HTTP headers for the incoming request to see if the value of the X-Requested-With header is XMLHttpRequest
, which is automatically appended by most browsers and AJAX frameworks.
Custom extension method to check whether the request is for json or not so that we can call it from anywhere, just like the Request.IsAjaxRequest() extension method:
using System;
using System.Web;
public static class JsonRequestExtensions
{
public static bool IsJsonRequest(this HttpRequestBase request)
{
return string.Equals(request["format"], "json");
}
}
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
i once got the error too:
Cause: I was trying to update a Recycler View from an Async task while simultaneously trying to get old deleted viewHolders;
Code: I generate data at the press of a button, logic as follows
Problem: Whenever i scroll fast before generating my data i get
Inconsistency detected. Invalid view holder adapter positionViewHolder java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 20(offset:2).state:3
Solution: instead of clearing the RecyclerView before generating my data, i instead leave it and then Replace it with the New Data, the Call NotifyDatasetChanged, as shown below;
@Override
protected void onPostExecute(List<Objects> o) {
super.onPostExecute(o);
recyclerViewAdapter.setList(o);
mProgressBar.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
}
Two options:
Do the division after the multiplication:
int n = 25;
int v = 100;
int percent = n * 100 / v;
Convert an int
to a float
before dividing
int n = 25;
int v = 100;
float percent = n * 100f / v;
//Or:
// float percent = (float) n * 100 / v;
// float percent = n * 100 / (float) v;
To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:
Open Source:
Paid:
** - means I didn't try those so I can't really recommend it but other users suggested it..
SELECT employee_id
FROM (
SELECT employee_id, ROW_NUMBER() OVER (ORDER BY employee_id) AS rn
FROM V_EMPLOYEE
) q
WHERE rn > 0
ORDER BY
Employee_ID
Note that this filter is redundant: ROW_NUMBER()
starts from 1
and is always greater than 0
.
Try this
// UILabel *myLabel;
CGSize labelSize = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:myLabel.frame.size
lineBreakMode:NSLineBreakByWordWrapping];
CGFloat labelHeight = labelSize.height;
int lines = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:myLabel.frame.size
lineBreakMode:NSLineBreakByWordWrapping].height/16;
// '16' is font size
or
int lines = labelHeight/16;
NSLog(@"lines count : %i \n\n",lines);
or
int lines = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:myLabel.frame.size
lineBreakMode:UILineBreakModeWordWrap].height /myLabel.font.pointSize; //fetching font size from font
By Using Categories, Just Create the category class named as
UILabel+UILabelDynamicHeight.h
UILabel+UILabelDynamicHeight.m
No more tension about the height calculation. Please review the below implementation.
Updates for iOS7 & Above,iOS 7 below : Dynamically calculate the UILabel height
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
#define iOS7_0 @"7.0"
UILabel+UILabelDynamicHeight.h
#import <UIKit/UIKit.h>
@interface UILabel (UILabelDynamicHeight)
#pragma mark - Calculate the size the Multi line Label
/*====================================================================*/
/* Calculate the size of the Multi line Label */
/*====================================================================*/
/**
* Returns the size of the Label
*
* @param aLabel To be used to calculte the height
*
* @return size of the Label
*/
-(CGSize)sizeOfMultiLineLabel;
@end
UILabel+UILabelDynamicHeight.m
#import "UILabel+UILabelDynamicHeight.h"
@implementation UILabel (UILabelDynamicHeight)
#pragma mark - Calculate the size,bounds,frame of the Multi line Label
/*====================================================================*/
/* Calculate the size,bounds,frame of the Multi line Label */
/*====================================================================*/
/**
* Returns the size of the Label
*
* @param aLabel To be used to calculte the height
*
* @return size of the Label
*/
-(CGSize)sizeOfMultiLineLabel{
//Label text
NSString *aLabelTextString = [self text];
//Label font
UIFont *aLabelFont = [self font];
//Width of the Label
CGFloat aLabelSizeWidth = self.frame.size.width;
if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) {
//version < 7.0
return [aLabelTextString sizeWithFont:aLabelFont
constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
}
else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) {
//version >= 7.0
//Return the calculated size of the Label
return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{
NSFontAttributeName : aLabelFont
}
context:nil].size;
}
return [self bounds].size;
}
@end
The rubocop gem contributors propose in their Ruby Style Guide:
Prefer alias when aliasing methods in lexical class scope as the resolution of self in this context is also lexical, and it communicates clearly to the user that the indirection of your alias will not be altered at runtime or by any subclass unless made explicit.
class Westerner
def first_name
@names.first
end
alias given_name first_name
end
Always use alias_method when aliasing methods of modules, classes, or singleton classes at runtime, as the lexical scope of alias leads to unpredictability in these cases
module Mononymous
def self.included(other)
other.class_eval { alias_method :full_name, :given_name }
end
end
class Sting < Westerner
include Mononymous
end
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
No, I don't think you can append key/value pairs. The only thing closest that I am aware of is using the store
method:
h = {}
h.store("key", "value")
Old question, but Elevation, available with Material Design now provides a shadow to any views.
<TextView
android:id="@+id/myview"
...
android:elevation="2dp"
android:background="@drawable/myrect" />
See the docs at https://developer.android.com/training/material/shadows-clipping.html
It's also possible to use java Foo | tee -a some.log
. it just prints to stdout as well. Like:
user at Computer in ~
$ echo "hi" | tee -a foo.txt
hi
user at Computer in ~
$ echo "hello" | tee -a foo.txt
hello
user at Computer in ~
$ cat foo.txt
hi
hello
a:link
-> It defines the style for unvisited links.
a:hover
-> It defines the style for hovered links.
A link is hovered when the mouse moves over it.
unicode
is meant to handle text. Text is a sequence of code points which may be bigger than a single byte. Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8
, latin-1
...).
Note that unicode
is not encoded! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want.
On the contrary str
in Python 2 is a plain sequence of bytes. It does not represent text!
You can think of unicode
as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str
.
Note: In Python 3, unicode
was renamed to str
and there is a new bytes
type for a plain sequence of bytes.
Some differences that you can see:
>>> len(u'à') # a single code point
1
>>> len('à') # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1')) # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8') # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte
?
Note that using str
you have a lower-level control on the single bytes of a specific encoding representation, while using unicode
you can only control at the code-point level. For example you can do:
>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à?ìòù
What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text. You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.
If you wish to customize your legend, just use the add_legend
method. It takes the same parameters as matplotlib plt.legend
.
import seaborn as sns
sns.set(style="whitegrid")
titanic = sns.load_dataset("titanic")
g = sns.factorplot("class", "survived", "sex",
data=titanic, kind="bar",
size=6, palette="muted",
legend_out=False)
g.despine(left=True)
g.set_ylabels("survival probability")
g.add_legend(bbox_to_anchor=(1.05, 0), loc=2, borderaxespad=0.)
There is an explicit cast on CString to LPCTSTR, so you can do (provided unicode is not specified):
CString str;
// ....
const char* cstr = (LPCTSTR)str;
std::string s = "Sambuca";
QString q = s.c_str();
Warning: This won't work if the std::string
contains \0
s.
you can use setInterval()
in javascript
<script>
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall(){...}
</script>
Usually, I don't care about the order of the calls, only that they happened. In that case, I combine assert_any_call
with an assertion about call_count
.
>>> import mock
>>> m = mock.Mock()
>>> m(1)
<Mock name='mock()' id='37578160'>
>>> m(2)
<Mock name='mock()' id='37578160'>
>>> m(3)
<Mock name='mock()' id='37578160'>
>>> m.assert_any_call(1)
>>> m.assert_any_call(2)
>>> m.assert_any_call(3)
>>> assert 3 == m.call_count
>>> m.assert_any_call(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "[python path]\lib\site-packages\mock.py", line 891, in assert_any_call
'%s call not found' % expected_string
AssertionError: mock(4) call not found
I find doing it this way to be easier to read and understand than a large list of calls passed into a single method.
If you do care about order or you expect multiple identical calls, assert_has_calls
might be more appropriate.
Since I posted this answer, I've rethought my approach to testing in general. I think it's worth mentioning that if your test is getting this complicated, you may be testing inappropriately or have a design problem. Mocks are designed for testing inter-object communication in an object oriented design. If your design is not objected oriented (as in more procedural or functional), the mock may be totally inappropriate. You may also have too much going on inside the method, or you might be testing internal details that are best left unmocked. I developed the strategy mentioned in this method when my code was not very object oriented, and I believe I was also testing internal details that would have been best left unmocked.
Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.
Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :
<beans:bean id="movieFinder" class="com.movies.MovieFinder" />
or if the MovieFinder class has a constructor with a primitive value, then you could something like this,
<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
<beans:constructor-arg value="100" />
</beans:bean>
or if the MovieFinder class has a constructor expecting another class, then you could do something like this,
<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
<beans:constructor-arg ref="otherBeanRef" />
</beans:bean>
...where 'otherBeanRef' is another bean that has a reference to the expected class.
This should work
function updatePostID(val)
{
document.getElementById('PostID').value = val;
//and probably call document.forms[0].submit();
}
Then have a hidden field or other control for the PostID
@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)
Either
Method 2 by step
This error occurs if some unit test cases are failing.
In my application, certain unit tests were not compatible with Java 8 so they were failing. My error was resolved after changing jdk1.8.0_92
to jdk1.7.0_80
.
The build would succeed with mvn clean install -DskipTests
but this will skip the unit tests. So just ensure that you run then separately after the build is complete.
The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.
The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc). ......
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hyphen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
You can check .flv signature. You can download specification here:
http://www.adobe.com/devnet/flv/
See "The FLV header" chapter.
Example, if you have:
$config['base_url'] = 'www.example.com'
set in your config.php then
echo base_url();
This works very well almost at every place.
/* Edit */
This might work for the latest versions of codeigniter (4 and above).
You cannot really find the display resolution from a web page. There is a CSS Media Queries statement for it, but it is poorly implemented in most devices and browsers, if at all. However, you do not need to know the resolution of the display, because changing it causes the (pixel) width of the window to change, which can be detected using the methods others have described:
$(window).resize(function() {
// This will execute whenever the window is resized
$(window).height(); // New height
$(window).width(); // New width
});
You can also use CSS Media Queries in browsers that support them to adapt your page's style to various display widths, but you should really be using em
units and percentages and min-width
and max-width
in your CSS if you want a proper flexible layout. Gmail probably uses a combination of all these.
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
You can create a function and then refer to it in the select statement. The function may look similar to this:
if OBJECT_ID('fn_month_name_to_number', 'IF') is not null
drop function fn_month_name_to_number
go
create function fn_month_name_to_number (@monthname varchar(25))
returns int as
begin
declare @monthno as int;
select @monthno =
case @monthname
when 'January' then 1
when 'February' then 2
when 'March' then 3
when 'April' then 4
when 'May' then 5
when 'June' then 6
when 'July' then 7
when 'August' then 8
when 'September' then 9
when 'October' then 10
when 'November' then 11
when 'December' then 12
end
return @monthno
end
Then you can query it.
select fn_month_name_to_number ('February') as month_no
This query will return 2 as month number. You can pass values from a column as parameters to the function.
select fn_month_name_to_number (*columnname*) as month_no from *tablename*
Have a good day!
This specific issue may arise in localhost also. We cannot rule out this is because network issue or internet connectivity issue. This issue will come even though all the database connection properties are correct.
I have faced the same issue when i have used host name. Instead use ip address. It will get resolved.
The issue of adding tooltips to any HTML-Output (not only FontAwesome) is an entire book on its own. ;-)
The default way would be to use the title-attribute:
<div id="welcomeText" title="So nice to see you!">
<p>Welcome Harriet</p>
</div>
or
<i class="fa fa-cog" title="Do you like my fa-coq icon?"></i>
But since most people (including me) do not like the standard-tooltips, there are MANY tools out there which will "beautify" them and offer all sort of enhancements. My personal favourites are jBox and qtip2.
For anyone who tried everything without luck, this is the only thing that got it working for me. For the multiline labels inside cell, try adding this magic line:
label.preferredMaxLayoutWidth = 200
More info: here
Cheers!
Have a look at this picture: Graphical Projections
The glOrtho
command produces an "Oblique" projection that you see in the bottom row. No matter how far away vertexes are in the z direction, they will not recede into the distance.
I use glOrtho every time I need to do 2D graphics in OpenGL (such as health bars, menus etc) using the following code every time the window is resized:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, windowWidth, windowHeight, 0.0f, 0.0f, 1.0f);
This will remap the OpenGL coordinates into the equivalent pixel values (X going from 0 to windowWidth and Y going from 0 to windowHeight). Note that I've flipped the Y values because OpenGL coordinates start from the bottom left corner of the window. So by flipping, I get a more conventional (0,0) starting at the top left corner of the window rather.
Note that the Z values are clipped from 0 to 1. So be careful when you specify a Z value for your vertex's position, it will be clipped if it falls outside that range. Otherwise if it's inside that range, it will appear to have no effect on the position except for Z tests.
Sometimes your json is not a string. For example if you are getting a json from a url like this:
j = urllib2.urlopen('http://site.com/data.json')
you will need to use json.load, not json.loads:
j_obj = json.load(j)
(it is easy to forget: the 's' is for 'string')
Once I had written a program that handle the short (-h), long (--help) and non-option arguments in batch file. This techniques includes:
non-option arguments followed by a option arguments.
shift operator for those options that have no argument like '--help'.
two time shift operator for those options that require an argument.
loop through a label for processing all command line arguments.
Exit script and stop processing for those options that no need to require further action like '--help'.
Wrote help functions for user guidiness
Here is my code.
set BOARD=
set WORKSPACE=
set CFLAGS=
set LIB_INSTALL=true
set PREFIX=lib
set PROGRAM=install_boards
:initial
set result=false
if "%1" == "-h" set result=true
if "%1" == "--help" set result=true
if "%result%" == "true" (
goto :usage
)
if "%1" == "-b" set result=true
if "%1" == "--board" set result=true
if "%result%" == "true" (
goto :board_list
)
if "%1" == "-n" set result=true
if "%1" == "--no-lib" set result=true
if "%result%" == "true" (
set LIB_INSTALL=false
shift & goto :initial
)
if "%1" == "-c" set result=true
if "%1" == "--cflag" set result=true
if "%result%" == "true" (
set CFLAGS=%2
if not defined CFLAGS (
echo %PROGRAM%: option requires an argument -- 'c'
goto :try_usage
)
shift & shift & goto :initial
)
if "%1" == "-p" set result=true
if "%1" == "--prefix" set result=true
if "%result%" == "true" (
set PREFIX=%2
if not defined PREFIX (
echo %PROGRAM%: option requires an argument -- 'p'
goto :try_usage
)
shift & shift & goto :initial
)
:: handle non-option arguments
set BOARD=%1
set WORKSPACE=%2
goto :eof
:: Help section
:usage
echo Usage: %PROGRAM% [OPTIONS]... BOARD... WORKSPACE
echo Install BOARD to WORKSPACE location.
echo WORKSPACE directory doesn't already exist!
echo.
echo Mandatory arguments to long options are mandatory for short options too.
echo -h, --help display this help and exit
echo -b, --boards inquire about available CS3 boards
echo -c, --cflag=CFLAGS making the CS3 BOARD libraries for CFLAGS
echo -p. --prefix=PREFIX install CS3 BOARD libraries in PREFIX
echo [lib]
echo -n, --no-lib don't install CS3 BOARD libraries by default
goto :eof
:try_usage
echo Try '%PROGRAM% --help' for more information
goto :eof
Not sure how long this has bee available but there is an Rspec configuration for run filtering - so now you can add this to your spec_helper.rb
:
RSpec.configure do |config|
config.filter_run_when_matching :focus
end
And then add a focus tag to the it
, context
or describe
to run only that block:
it 'runs a test', :focus do
...test code
end
RSpec documentation:
I started out with this article
http://en.tekstenuitleg.net/articles/software/database-design-tutorial/intro.html
It's pretty concise compared to reading an entire book and it explains the basics of database design (normalization, types of relationships) very well.
The first thing to do (if not already done) is to split your database into a front end (with all the forms/reports etc) and a back end(with all the data). The second thing is to setup version control on the front end.
The way I have done that in a lot of my databases is to have the users run a small “jumper” database to open the main database. This jumper does the following things
• Checks to see if the user has the database on their C drive
• If they do not then install and run
• If they do then check what version they have
• If the version numbers do not match then copy down the latest version
• Open the database
This whole checking process normally takes under half a second. Using this model you can do all your development on a separate database then when you are ready to “release” you just put the new mde up onto the network share and the next time the user opens the jumper the latest version is copied down.
There are also other things to think about in multiuser database and it might be worth checking for the common mistakes such as binding a form to a whole table etc
The important thing is one of the elements of calculation be a float-double type. Then to get a double result you need to cast this element like shown below:
c = static_cast<double>(a) / b;
or c = a / static_cast(b);
Or you can create it directly::
c = 7.0 / 3;
Note that one of elements of calculation must have the '.0' to indicate a division of a float-double type by an integer. Otherwise, despite the c variable be a double, the result will be zero too (an integer).
My understanding of the question is that the OP is trying to avoid specifying a class-path in his command line. You can do this by putting the class-path in the Manifest file.
In the manifest:
Class-Path: Library.jar
This document gives more details:
http://docs.oracle.com/javase/tutorial/deployment/jar/downman.html
To create a jar using the a manifest file named MANIFEST, you can use the following command:
jar -cmf MANIFEST MyJar.jar <class files>
If you specify relative class-paths (ie, other jars in the same directory), then you can move the jar's around and the batch file mentioned in mdm's answer will still work.
I use something like this to load properties file.
final ResourceBundle bundle = ResourceBundle
.getBundle("properties/errormessages");
for (final Enumeration<String> keys = bundle.getKeys(); keys
.hasMoreElements();) {
final String key = keys.nextElement();
final String value = bundle.getString(key);
prop.put(key, value);
}
For non-anonymous functions
function foo()
{
alert(arguments.callee.name)
}
But in case of an error handler the result would be the name of the error handler function, wouldn't it?
If you happen to use Spring Boot you can make use of the BuildProperties class.
Take the following snippet from our OpenAPI configuration class as an example:
@Configuration
@RequiredArgsConstructor // <- lombok
public class OpenApi {
private final BuildProperties buildProperties; // <- you can also autowire it
@Bean
public OpenAPI yourBeautifulAPI() {
return new OpenAPI().info(new Info()
.title(buildProperties.getName())
.description("The description")
.version(buildProperties.getVersion())
.license(new License().name("Your company")));
}
}
Try to see if the following code helps you:
Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)
If you don't need to use the writer afterwards the shortest and cleanest way to do it would be like that:
new FileWriter("/path/to/your/file.txt").close();
Have you tried using Html.fromHtml(source)?
I think that class is pretty liberal with respect to source quality (it uses TagSoup internally, which was designed with real-life, bad HTML in mind). It doesn't support all HTML tags though, but it does come with a handler you can implement to react on tags it doesn't understand.
As other mentioned JSX
is not a standard Javascript extension. It's better to name your entry point of Application based on .js
and for the rest components, you can use .jsx
.
I have an important reason for why I'm using .JSX
for all component's file names.
Actually, In a large scale project with huge bunch of code, if we set all React's component with .jsx
extension, It'll be easier while navigating to different javascript files across the project(like helpers, middleware, etc.) and you know this is a React Component and not other types of the javascript file.
Could be short as:
LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
{x: a[a.index(x)+1] for x in a if a.index(x) % 2 ==0}
result : {'hello': 'world', '1': '2'}
* First we declare JTextField like this
JTextField testField = new JTextField(10);
* We can get textfield value in String like this on any button click event.
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String getValue = testField.getText()
}
})
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
I've seen that problem when I'm writing to a filesystem which doesn't (properly) handle times -- I think SMB shares or FAT or something.
What is your target filesystem?
Update
This solution would not longer work because browsers are fixing webrtc leak: for more info on that read this other question: RTCIceCandidate no longer returning IP
In addition to afourney's answer this code works in browsers that support WebRTC (Chrome and Firefox). I heard there is a movement going on to implement a feature that makes sites request the IP (like in case of user's geo-location or user-media) though it has yet to be implemented in either of those browsers.
Here is a modified version of the source code, reduced the lines, not making any stun requests since you only want Local IP not the Public IP:
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;//compatibility for Firefox and chrome
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
pc.createDataChannel('');//create a bogus data channel
pc.createOffer(pc.setLocalDescription.bind(pc), noop);// create offer and set local description
pc.onicecandidate = function(ice)
{
if (ice && ice.candidate && ice.candidate.candidate)
{
var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
console.log('my IP: ', myIP);
pc.onicecandidate = noop;
}
};
We are creating a dummy peer connection for the remote peer to contact us. We generally exchange ice candidates with each other and reading the ice candidates we can tell the ip of the user.
You can find a demo at --> Demo
Try this:
$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}, $str);
In case it's UTF-16 based C/C++/Java/Json-style:
$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
}, $str);
Mac OS: You have to install ChromeDriver first:
brew cask install chromedriver
It will be copied to /usr/local/bin/chromedriver. Then you can use it in java code classes.
It is not possible since a UUID is a 16-byte number per definition. But of course, you can generate 8-character long unique strings (see the other answers).
Also be careful with generating longer UUIDs and substring-ing them, since some parts of the ID may contain fixed bytes (e.g. this is the case with MAC, DCE and MD5 UUIDs).
var out = new java.io.PrintWriter(new java.io.File(path), "UTF-8");
text = new java.lang.String( src || "" );
out.print(text);
out.flush();
out.close();
This is possible in HTML5. Example (PHP 5.4):
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
</body>
</html>
Here's what it looks like in Chrome after selecting 2 items in the file dialog:
And here's what it looks like after clicking the "Upload" button.
This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.
Because the script will get executed first.. When the script will get executed, at that time controls are not getting loaded. So after loading controls you write a script.
It will work.
Use a negative lookahead and a negative lookbehind:
> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']
In other words, you always split by \s
(whitespace), and only split by commas and periods if they are not followed (?!\d)
or preceded (?<!\d)
by a digit.
DEMO.
EDIT: As per @verdesmarald comment, you may want to use the following instead:
> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']
This will split "1.2,a,5"
into ["1.2", "a", "5"]
.
DEMO.
If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using:
performSegue(withIdentifier: "mySegueID", sender: nil)
For older versions:
performSegueWithIdentifier("mySegueID", sender: nil)
You could also do:
presentViewController(nextViewController, animated: true, completion: nil)
Or if you are in a Navigation controller:
self.navigationController?.pushViewController(nextViewController, animated: true)
While the above answers are valid, and I agree with readability being important, there are 2 further points to consider:
This makes it particularly concise to use the ternary:
string GetDrink(DayOfWeek day)
=> day == DayOfWeek.Friday
? "Beer" : "Tea";
If you have types T1
and T2
that can both be implicitly converted to T
, then the below does not work:
T GetT() => true ? new T1() : new T2();
(because the compiler tries to determine the type of the ternary expression, and there is no conversion between T1
and T2
.)
On the other hand, the if/else
version below does work:
T GetT()
{
if (true) return new T1();
return new T2();
}
because T1
is converted to T
and so is T2
If you want a certain message, use this:
String phoneNo = "";//The phone number you want to text
String sms= "";//The message you want to text to the phone
Intent smsIntent = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", phoneNo, null));
smsIntent.putExtra("sms_body",sms);
startActivity(smsIntent);
I am using Chosen. Look at: http://harvesthq.github.io/chosen/
It works on Firefox, Chrome, IE and Safari with the same style. But not on Mobile Devices.
I had the same issue. Fixed it by adding a static route on my host to my VM via the VMnet8 adapter:
route ADD VM_addr MASK 255.255.255.255 VMnet8_addr
As previously mentioned, you need a bridged connection.
Be careful though, for those who using pip install --user some_pkg
inside a virtual environment.
$ path/to/python -m venv ~/my_py_venv
$ source ~/my_py_venv/bin/activate
(my_py_venv) $ pip install --user some_pkg
(my_py_venv) $ pip uninstall some_pkg
WARNING: Skipping some_pkg as it is not installed.
(my_py_venv) $ pip list
# Even `pip list` will not properly list the `some_pkg` in this case
In this case, you have to deactivate the current virtual environment, then use the corresponding python
/pip
executable to list or uninstall the user site packages:
(my_py_venv) $ deactivate
$ path/to/python -m pip list
$ path/to/python -m pip uninstall some_pkg
Note that this issue was reported few years ago. And it seems that the current conclusion is: --user
is not valid inside a virtual env's pip
, since a user location doesn't really make sense for a virtual environment.
For installing
gem install gemname -v versionnumber
For uninstall
gem uninstall gemname -v versionnumber
In your script, this part:
document.getElementById('Noite')
must be returning null
and you are also attempting to set the display
property to an invalid value. There are a couple of possible reasons for this first part to be null
.
You are running the script too early before the document has been loaded and thus the Noite
item can't be found.
There is no Noite
item in your HTML.
I should point out that your use of document.write()
in this case code probably signifies a problem. If the document has already loaded, then a new document.write()
will clear the old content and start a new fresh document so no Noite
item would be found.
If your document has not yet been loaded and thus you're doing document.write()
inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noite
item.
The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:
document.getElementById('Noite').style.display='block';
And, make sure that there are no document.write()
statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).
In addition, setting the display
property to "display"
doesn't make sense to me. The valid options for that are "block"
, "inline"
, "none"
, "table"
, etc... I'm not aware of any option named "display"
for that style property. See here for valid options for teh display
property.
You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/. That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.
P.S. I should point out that your lack of braces for your if
statements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.
I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/. Here's a list of the changes I made:
var
declarations to your variables (a good habit to always use).if
statement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.if
statement so it absolutely clear which statements are part of the if/else
and which are not.</dd>
tag you were inserting.style.display = '';
to style.display = 'block';
.The code:
<div id="Night" style="display: none;">
<img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
<img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
document.write("Meia-noite!<br>Já é amanhã!");
} else if (hr <=5 ) {
document.write(" Você não<br> devia<br> estar<br>dormindo?");
} else if (hr <= 11) {
document.write("Bom dia!");
} else if (hr == 12) {
document.write(" Vamos<br> almoçar?");
} else if (hr <= 17) {
document.write("Boa Tarde");
} else if (hr <= 19) {
document.write(" Bom final<br> de tarde!");
} else if (hr == 20) {
document.write(" Boa Noite");
document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
document.write(" Boa Noite");
document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
document.write(" Boa Noite");
} else if (hr == 23) {
document.write("Ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>
Hoisted from the comments
2020 comment: rather than using regex, we now have
URLSearchParams
, which does all of this for us, so no custom code, let alone regex, are necessary anymore.
Browser support is listed here https://caniuse.com/#feat=urlsearchparams
I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually and re.exec()
:
function getUrlParams(url) {
var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
match, params = {},
decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};
if (typeof url == "undefined") url = document.location.href;
while (match = re.exec(url)) {
params[decode(match[1])] = decode(match[2]);
}
return params;
}
var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr");
result
is an object:
{ f: "q" geocode: "" hl: "de" ie: "UTF8" iwloc: "addr" ll: "50.116616,8.680573" q: "Frankfurt am Main" sll: "50.106047,8.679886" source: "s_q" spn: "0.35972,0.833588" sspn: "0.370369,0.833588" z: "11" }
The regex breaks down as follows:
(?: # non-capturing group \?|& # "?" or "&" (?:amp;)? # (allow "&", for wrongly HTML-encoded URLs) ) # end non-capturing group ( # group 1 [^=]+ # any character except "=", "&" or "#"; at least once ) # end group 1 - this will be the parameter's name (?: # non-capturing group =? # an "=", optional ( # group 2 [^]* # any character except "&" or "#"; any number of times ) # end group 2 - this will be the parameter's value ) # end non-capturing group
I'm adding this answer late since this is the answer that pops up most on Google...
You can use PHP to...
$url = "www.google.co.uk";
$host = parse_url($url, PHP_URL_HOST);
// $host == "www.google.co.uk"
to grab the host but not the private domain to which the host refers. (Example www.google.co.uk
is the host, but google.co.uk
is the private domain)
To grab the private domain, you must need know the list of public suffixes to which one can register a private domain. This list happens to be curated by Mozilla at https://publicsuffix.org/
The below code works when an array of public suffixes has been created already. Simply call
$domain = get_private_domain("www.google.co.uk");
with the remaining code...
// find some way to parse the above list of public suffix
// then add them to a PHP array
$suffix = [... all valid public suffix ...];
function get_public_suffix($host) {
$parts = split("\.", $host);
while (count($parts) > 0) {
if (is_public_suffix(join(".", $parts)))
return join(".", $parts);
array_shift($parts);
}
return false;
}
function is_public_suffix($host) {
global $suffix;
return isset($suffix[$host]);
}
function get_private_domain($host) {
$public = get_public_suffix($host);
$public_parts = split("\.", $public);
$all_parts = split("\.", $host);
$private = [];
for ($x = 0; $x < count($public_parts); ++$x)
$private[] = array_pop($all_parts);
if (count($all_parts) > 0)
$private[] = array_pop($all_parts);
return join(".", array_reverse($private));
}
$imgTag = <<< LOB
<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />
<img border="0" src="/images/not_match_image.jpg" alt="Image" width="100" height="100" />
LOB;
preg_match('%<img.*?src=["\'](.*?)["\'].*?/>%i', $imgTag, $matches);
$imgSrc = $matches[1];
NOTE: You should use an HTML Parser like DOMDocument
and NOT a regex.
I found out how to configure requests's logging level, it's done via the standard logging module. I decided to configure it to not log messages unless they are at least warnings:
import logging
logging.getLogger("requests").setLevel(logging.WARNING)
If you wish to apply this setting for the urllib3 library (typically used by requests) too, add the following:
logging.getLogger("urllib3").setLevel(logging.WARNING)
A URL of the form https://github.com/<owner>/<project>/commit/<hash>
will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:
https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685
You can also shorten the hash to any unique prefix, like so:
https://github.com/jerith666/git-graph/commit/35e32b
I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):
git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685
Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.
Let consider that your data are in the file values.txt
and that you want to import them in the database table myTable
then the following query does the job
COPY myTable FROM 'value.txt' (DELIMITER('|'));
https://www.postgresql.org/docs/current/static/sql-copy.html
If one trying to debug the app in real iOS devices connected through XCode, make sure you have selected provisional profile with iOS development certificate
.
If you have selected provisional profile with distribution certificate
then you will not able to use for debugging purpose this launching app locally through XCode will not work.
If you are using anaconda distribution, you can do the following to use python 3.5 on the new environnement "tensorflow":
conda create --name tensorflow python=3.5
activate tensorflow
conda install jupyter
conda install scipy
pip install tensorflow
# or
# pip install tensorflow-gpu
It is important to add python=3.5 at the end of the first line, because it will install Python 3.5.
Source: https://github.com/tensorflow/tensorflow/issues/6999#issuecomment-278459224
npm install -g @angular/cli --registry http://registry.npmjs.org/ worked for me
That is how I prevented direct access from URL to my ini files. Paste the following code in .htaccess
file on root. (no need to create extra folder)
<Files ~ "\.ini$">
Order allow,deny
Deny from all
</Files>
my settings.ini
file is on the root, and without this code is accessible www.mydomain.com/settings.ini
Also you need this, to implement some action to every options of menu.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_help:
Toast.makeText(this, "This is teh option help", Toast.LENGTH_LONG).show();
break;
default:
break;
}
return true;
}
git rm yourfiles/*.class
git commit -a -m "deleted all class files in folder 'yourfiles'"
or
git reset --hard HEAD~1
Warning: The above command will permanently remove the modifications to the .java
files (and any other files) that you wanted to commit.
The hard reset
to HEAD-1
will set your working copy to the state of the commit before your wrong commit.
If this is a query parameter that you want to pass like this:
/toState?referer=current_user
then you need to describe your state like this:
$stateProvider.state('toState', {
url:'toState?referer',
views:{'...'}
});
source: https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
The git command that would be the closest from what you are looking for would by git archive
.
See backing up project which uses git: it will include in an archive all files (including submodules if you are using the git-archive-all
script)
You can then use that archive anywhere, giving you back only files, no .git
directory.
git archive --remote=<repository URL> | tar -t
If you need folders and files just from the first level:
git archive --remote=<repository URL> | tar -t --exclude="*/*"
To list only first-level folders of a remote repo:
git archive --remote=<repository URL> | tar -t --exclude="*/*" | grep "/"
Note: that does not work for GitHub (not supported)
So you would need to clone (shallow to quicken the clone step), and then archive locally:
git clone --depth=1 [email protected]:xxx/yyy.git
cd yyy
git archive --format=tar aTag -o aTag.tar
Another option would be to do a shallow clone (as mentioned below), but locating the .git folder elsewhere.
git --git-dir=/path/to/another/folder.git clone --depth=1 /url/to/repo
The repo folder would include only the file, without .git
.
Note: git --git-dir
is an option of the command git
, not git clone
.
Update with Git 2.14.X/2.15 (Q4 2017): it will make sure to avoid adding empty folders.
"
git archive
", especially when used with pathspec, stored an empty directory in its output, even though Git itself never does so.
This has been fixed.
See commit 4318094 (12 Sep 2017) by René Scharfe (``).
Suggested-by: Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 62b1cb7, 25 Sep 2017)
archive
: don't add empty directories to archivesWhile git doesn't track empty directories,
git archive
can be tricked into putting some into archives.
While that is supported by the object database, it can't be represented in the index and thus it's unlikely to occur in the wild.As empty directories are not supported by git, they should also not be written into archives.
If an empty directory is really needed then it can be tracked and archived by placing an empty.gitignore
file in it.
The only way I was able to do this is via this code (TD tables). I tested in outlook client 2010. I also tested via webmail client and it worked for both.
The only things you have to do is change your_image.jpg (there are two instances of this for the same image make sure you update both for your code) and #your_color.
<td bgcolor="#your_color" background="your_image.jpg">
<!--[if gte mso 9]>
<v:image xmlns:v="urn:schemas-microsoft-com:vml" id="theImage" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:0; left:0; border:0; z-index:1;' src="your_image.jpg"/>
<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="theText" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:-5; left:-10; border:0; z-index:2;'>
<![endif]-->
<p>Text over background image.</p>
<!--[if gte mso 9]>
</v:shape>
<![endif]-->
</td>
I don't understand how other answers don't answer the original question about how to use PHP (not very consistent with the title).
PHP files or PHP code embedded in HTML code start always with the tag <?php
and ends with ?>
.
You can embed PHP code inside HTML like this (you have to save the file using .php
extension to let PHP server recognize and process it, ie: index.php):
<body>
<?php echo "<div>Hello World!</div>" ?>
</body>
or you can use a whole php file, ie: test.php:
<?php
$mycontent = "Hello World!";
echo "<div>$mycontent</div>";
?> // is not mandatory to put this at the end of the file
there's no document.ready
in PHP, the scripts are processed when they are invoked from the browser or from another PHP file.
Here try this out.
.parentdiv {_x000D_
height: 400px;_x000D_
border: 2px solid #cccccc;_x000D_
background: #efefef;_x000D_
position: relative;_x000D_
}_x000D_
.childcontainer {_x000D_
position: absolute;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
}_x000D_
.childdiv {_x000D_
width: 150px;_x000D_
height:150px;_x000D_
background: lightgreen;_x000D_
border-radius: 50%;_x000D_
border: 2px solid green;_x000D_
margin-top: -50%;_x000D_
margin-left: -50%;_x000D_
}
_x000D_
<div class="parentdiv">_x000D_
<div class="childcontainer">_x000D_
<div class="childdiv">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
You can use and test uninitialized variables at least for their 'definedness'. Like this:
var iAmNotDefined;
alert(!iAmNotDefined); //true
//or
alert(!!iAmNotDefined); //false
Furthermore, there are many possibilites: if you're not interested in exact types use the '==' operator (or ![variable] / !![variable]) for comparison (that is what Douglas Crockford calls 'truthy' or 'falsy' I think). In that case assigning true or 1 or '1' to the unitialized variable always returns true when asked. Otherwise [if you need type safe comparison] use '===' for comparison.
var thisMayBeTrue;
thisMayBeTrue = 1;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
thisMayBeTrue = '1';
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, in this case, using == or !! '1' is implicitly
// converted to 1 and 1 is implicitly converted to true)
thisMayBeTrue = true;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> true
thisMayBeTrue = 'true';
alert(thisMayBeTrue == true); //=> false
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, here's no implicit conversion of the string 'true'
// it's also a demonstration of the fact that the
// ! or !! operator tests the 'definedness' of a variable.
PS: you can't test 'definedness' for nonexisting variables though. So:
alert(!!HelloWorld);
gives a reference Error ('HelloWorld is not defined')
(is there a better word for 'definedness'? Pardon my dutch anyway;~)
This is what Visual C# program manager has to say: Why doesn't C# have a 'with' statement?
Many people, including the C# language designers, believe that 'with' often harms readability, and is more of a curse than a blessing. It is clearer to declare a local variable with a meaningful name, and use that variable to perform multiple operations on a single object, than it is to have a block with a sort of implicit context.
In JavaScript this
always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.
in phpmyadmin
note: this will work if you delete last rows not middle rows.
goto your table-> click on operations menu-> goto table options->change AUTO_INCREMENT to that no from where you want to start.
your table autoincrement start from that no.
The proper way to sort strings is:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']
# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']
The previous example of mylist.sort(key=lambda x: x.lower())
will work fine for ASCII-only contexts.
Anyone using ButterKnife. You can use like:
@OnTextChanged(R.id.zip_code)
void onZipCodeTextChanged(CharSequence zipCode, int start, int count, int after) {
}
To your remark in the comments to your question:
"...SavingChanges (for each record)..."
That's the worst thing you can do! Calling SaveChanges()
for each record slows bulk inserts extremely down. I would do a few simple tests which will very likely improve the performance:
SaveChanges()
once after ALL records.SaveChanges()
after for example 100 records.SaveChanges()
after for example 100 records and dispose the context and create a new one.For bulk inserts I am working and experimenting with a pattern like this:
using (TransactionScope scope = new TransactionScope())
{
MyDbContext context = null;
try
{
context = new MyDbContext();
context.Configuration.AutoDetectChangesEnabled = false;
int count = 0;
foreach (var entityToInsert in someCollectionOfEntitiesToInsert)
{
++count;
context = AddToContext(context, entityToInsert, count, 100, true);
}
context.SaveChanges();
}
finally
{
if (context != null)
context.Dispose();
}
scope.Complete();
}
private MyDbContext AddToContext(MyDbContext context,
Entity entity, int count, int commitCount, bool recreateContext)
{
context.Set<Entity>().Add(entity);
if (count % commitCount == 0)
{
context.SaveChanges();
if (recreateContext)
{
context.Dispose();
context = new MyDbContext();
context.Configuration.AutoDetectChangesEnabled = false;
}
}
return context;
}
I have a test program which inserts 560.000 entities (9 scalar properties, no navigation properties) into the DB. With this code it works in less than 3 minutes.
For the performance it is important to call SaveChanges()
after "many" records ("many" around 100 or 1000). It also improves the performance to dispose the context after SaveChanges and create a new one. This clears the context from all entites, SaveChanges
doesn't do that, the entities are still attached to the context in state Unchanged
. It is the growing size of attached entities in the context what slows down the insertion step by step. So, it is helpful to clear it after some time.
Here are a few measurements for my 560000 entities:
The behaviour in the first test above is that the performance is very non-linear and decreases extremely over time. ("Many hours" is an estimation, I never finished this test, I stopped at 50.000 entities after 20 minutes.) This non-linear behaviour is not so significant in all other tests.
Check out http://mywiki.wooledge.org/DotFiles for an excellent resource on the topic aside from man bash
.
Summary:
~/.bash_profile
or ~/.profile
is read and executed. Since everything you run from your login shell inherits the login shell's environment, you should put all your environment variables in there. Like LESS
, PATH
, MANPATH
, LC_*
, ... For an example, see: My .profile
~/.bashrc
, not /.profile
or ~/.bash_profile
, for this exact reason, so in there define everything that only applies to bash. That's functions, aliases, bash-only variables like HISTSIZE (this is not an environment variable, don't export it!), shell options with set
and shopt
, etc. For an example, see: My .bashrc
~/.bashrc
but only ~/.profile
or ~/.bash_profile
, so you should source that one manually from the latter. You'll see me do that in my ~/.profile
too: source ~/.bashrc
.It worked for = I just removed "archetypes" folder from below location
C:\Users\Lenovo.m2\repository\org\apache\maven
But you may change following for experiment - download latest binary zip of Maven, add to you C:\ drive and change following....
Change Proxy
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username></username>
<password></password>
<host>10.23.73.253</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
In Sql Developer, navidate to Tools->preferences->Datababae->advanced->Set Tnsname directory to the directory containing tnsnames.ora
If your server is Ubuntu and Apache version is 2.4
Server version: Apache/2.4.29 (Ubuntu)
Then you export variables in "/etc/apache2/envvars" location.
Just like this below line, you need to add an extra line in "/etc/apache2/envvars" export GOROOT=/usr/local/go
In my case function eval() works very good. Below I generate 10 variables and assign them 10 values.
lhs <- rnorm(10)
rhs <- paste("perf.a", 1:10, "<-", lhs, sep="")
eval(parse(text=rhs))
If you would like to get GMT time only with intiger: var currentTime = new Date(); var currentYear ='2010' var currentMonth = 10; var currentDay ='30' var currentHours ='20' var currentMinutes ='20' var currentSeconds ='00' var currentMilliseconds ='00'
currentTime.setFullYear(currentYear);
currentTime.setMonth((currentMonth-1)); //0is January
currentTime.setDate(currentDay);
currentTime.setHours(currentHours);
currentTime.setMinutes(currentMinutes);
currentTime.setSeconds(currentSeconds);
currentTime.setMilliseconds(currentMilliseconds);
var currentTimezone = currentTime.getTimezoneOffset();
currentTimezone = (currentTimezone/60) * -1;
var gmt ="";
if (currentTimezone !== 0) {
gmt += currentTimezone > 0 ? ' +' : ' ';
gmt += currentTimezone;
}
alert(gmt)
A way to use this in react:
class Timeout extends Component {
constructor(props){
super(props)
this.state = {
timeout: null
}
}
userTimeout(){
const { timeout } = this.state;
clearTimeout(timeout);
this.setState({
timeout: setTimeout(() => {this.callAPI()}, 250)
})
}
}
Helpful if you'd like to only call an API after the user has stopped typing for instance. The userTimeout function could be bound via onKeyUp to an input.
If you'd like to check for a particular module installed globally, on *nix systems use:
npm list -g --depth=0 | grep <module_name>
While Yi Jiang's solution may work, I don't believe abandoning the Google Web Font API is the right answer here. We serve a local jQuery file when it's not properly loaded from the CDN, right?
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/js/jquery-1.9.0.min.js"><\/script>')</script>
So why wouldn't we do the same for fonts, specifically for < IE9?
<link href='http://fonts.googleapis.com/css?family=Cardo:400,400italic,700' rel='stylesheet' type='text/css'>
<!--[if lt IE 9]><link href='/css/fonts.css' rel='stylesheet' type='text/css'><![endif]-->
Here's my process when using custom fonts:
Create a fonts.css
file that calls the newly created, locally hosted font files (only linking to the file if < IE9, as shown above). NOTE: The @font-face Generator creates this file for you.
@font-face {
font-family: 'cardoitalic';
src: url('cardo-italic-webfont.eot');
src: url('cardo-italic-webfont.eot?#iefix') format('embedded-opentype'),
url('cardo-italic-webfont.woff') format('woff'),
url('cardo-italic-webfont.ttf') format('truetype'),
url('cardo-italic-webfont.svg#cardoitalic') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'cardobold';
src: url('cardo-bold-webfont.eot');
src: url('cardo-bold-webfont.eot?#iefix') format('embedded-opentype'),
url('cardo-bold-webfont.woff') format('woff'),
url('cardo-bold-webfont.ttf') format('truetype'),
url('cardo-bold-webfont.svg#cardobold') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'cardoregular';
src: url('cardo-regular-webfont.eot');
src: url('cardo-regular-webfont.eot?#iefix') format('embedded-opentype'),
url('cardo-regular-webfont.woff') format('woff'),
url('cardo-regular-webfont.ttf') format('truetype'),
url('cardo-regular-webfont.svg#cardoregular') format('svg');
font-weight: normal;
font-style: normal;
}
Using IE conditional classes in your main stylesheet to avoide faux weights and styles, your font styles might look like this:
h1{
font-size:3.25em;
font-weight:normal;
font-style:italic;
font-family:'Cardo','cardoitalic',serif;
line-height:1.25em;
}
h2{
font-size:2.75em;
font-weight:700;
font-family:'Cardo','cardobold',serif;
line-height:1.25em;
}
strong
,b{
font-family:'Cardo','cardobold',serif;
font-weight:700,
}
.lt-ie9 h1{
font-style:normal;
}
.lt-ie9 h2{
font-weight:normal;
}
.lt-ie9 strong,
.lt-ie9 b{
font-weight:normal,
}
Sure, it's a little extra work, but haven't we come to expect this from IE? Besides, it becomes second-nature after awhile.
Its a CORS issue, your api cannot be accessed directly from remote or different origin, In order to allow other ip address or other origins from accessing you api, you should add the 'Access-Control-Allow-Origin' on the api's header, you can set its value to '*' if you want it to be accessible to all, or you can set specific domain or ips like 'http://siteA.com' or 'http://192. ip address ';
Include this on your api's header, it may vary depending on how you are displaying json data,
if your using ajax, to retrieve and display data your header would look like this,
$.ajax({
url: '',
headers: { 'Access-Control-Allow-Origin': 'http://The web site allowed to access' },
data: data,
type: 'dataType',
/* etc */
success: function(jsondata){
}
})
As I can see the code
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
is unreachable.
With dplyr 0.7.2
, you can use the very useful case_when
function :
x=read.table(
text="V1 V2 V3 V4
1 1 2 3 5
2 2 4 4 1
3 1 4 1 1
4 4 5 1 3
5 5 5 5 4")
x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
x$V2==4 & x$V3!=1 ~ 2,
TRUE ~ 0)
Expressed with dplyr::mutate
, it gives:
x = x %>% mutate(
V5 = case_when(
V1==1 & V2!=4 ~ 1,
V2==4 & V3!=1 ~ 2,
TRUE ~ 0
)
)
Please note that NA
are not treated specially, as it can be misleading. The function will return NA
only when no condition is matched. If you put a line with TRUE ~ ...
, like I did in my example, the return value will then never be NA
.
Therefore, you have to expressively tell case_when
to put NA
where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_
. Hint: the dplyr::coalesce()
function can be really useful here sometimes!
Moreover, please note that NA
alone will usually not work, you have to put special NA
values : NA_integer_
, NA_character_
or NA_real_
.
var exclude_div = $("#ExcludedDiv");; _x000D_
$(document).click(function(e){_x000D_
if( !exclude_div.is( e.target ) ) // if target div is not the one you want to exclude then add the class hidden_x000D_
$(".myDiv1").addClass("hidden"); _x000D_
_x000D_
});
_x000D_
Dedication to LightStriker:
Sample Code:
class CallBackExample
{
public delegate void MyNumber();
public static void CallMeBack()
{
Console.WriteLine("He/She is calling you. Pick your phone!:)");
Console.Read();
}
public static void MetYourCrush(MyNumber number)
{
int j;
Console.WriteLine("is she/he interested 0/1?:");
var i = Console.ReadLine();
if (int.TryParse(i, out j))
{
var interested = (j == 0) ? false : true;
if (interested)//event
{
//call his/her number
number();
}
else
{
Console.WriteLine("Nothing happened! :(");
Console.Read();
}
}
}
static void Main(string[] args)
{
MyNumber number = Program.CallMeBack;
Console.WriteLine("You have just met your crush and given your number");
MetYourCrush(number);
Console.Read();
Console.Read();
}
}
Code Explanation:
I created the code to implement the funny explanation provided by LightStriker in the above one of the replies. We are passing delegate (number) to a method (MetYourCrush
). If the Interested (event) occurs in the method (MetYourCrush
) then it will call the delegate (number) which was holding the reference of CallMeBack
method. So, the CallMeBack
method will be called. Basically, we are passing delegate to call the callback method.
Please let me know if you have any questions.
The other answers were incomplete for me. I started from @Vladimir Novopashin answer and modified it. Here are the things, that I needed and bug I found:
.prop
instead of [prop]
. For example, formData.append('photos[0][file]', file)
didn't work on google chrome, while
formData.append('photos[0].file', file)
workedThe following code should work on IE11 and evergreen browsers.
function objectToFormData(obj, rootName, ignoreList) {
var formData = new FormData();
function appendFormData(data, root) {
if (!ignore(root)) {
root = root || '';
if (data instanceof File) {
formData.append(root, data);
} else if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
appendFormData(data[i], root + '[' + i + ']');
}
} else if (typeof data === 'object' && data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
if (root === '') {
appendFormData(data[key], key);
} else {
appendFormData(data[key], root + '.' + key);
}
}
}
} else {
if (data !== null && typeof data !== 'undefined') {
formData.append(root, data);
}
}
}
}
function ignore(root){
return Array.isArray(ignoreList)
&& ignoreList.some(function(x) { return x === root; });
}
appendFormData(obj, rootName);
return formData;
}
I had the same problem, It was solved when I checked the below checkbox
Include externals
This probably should be a comment under the cmdow.exe
answer, but here is a simple batch file I wrote to allow for fairly sophisticated and simple control over all windows that you can see in the taskbar.
First step is to run cmdow /t
to display a list of those windows. Look at what the image name is in the column Image
, then command line:
mycmdowscript.cmd imagename
Here are the contents of the batch file:
:: mycmdowscript.cmd
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET IMAGE=%1
SET ACTION=/%2
SET REST=1
SET PARAMS=
:: GET ANY ADDITIONAL PARAMS AND STORE THEM IN A VARIABLE
FOR %%I in (%*) DO (
IF !REST! geq 3 (
SET PARAMS=!PARAMS! %%I
)
SET /A REST+=1
)
FOR /F "USEBACKQ tokens=1,8" %%I IN (`CMDOW /t`) DO (
IF %IMAGE%==%%J (
:: you now have access to the handle in %%I
cmdow %%I %ACTION% !PARAMS!
)
)
ENDLOCAL
@echo on
EXIT /b
example usage
:: will set notepad to 500 500
mycmdowscript.cmd notepad siz 500 500
You could probably rewrite this to allow for multiple actions on a single command, but I haven't tried yet.
For this to work, cmdow.exe must be located in your path. Beware that when you download this, your AV program might yell at you. This tool has (I guess) in the past been used by malware authors to manipulate windows. It is not harmful by itself.
You can also do this with pandas by broadcasting your columns as categories first, e.g. dtype="category"
e.g.
cats = ['client', 'hotel', 'currency', 'ota', 'user_country']
df[cats] = df[cats].astype('category')
and then calling describe
:
df[cats].describe()
This will give you a nice table of value counts and a bit more :):
client hotel currency ota user_country
count 852845 852845 852845 852845 852845
unique 2554 17477 132 14 219
top 2198 13202 USD Hades US
freq 102562 8847 516500 242734 340992
This happens when JDK and JRE have different versions installed on your system. Update the JDK with the matching version of JRE. Also verify that System variable path has bin value from same JDK version.
Frankly the errors are really hard to see, especially if only one character is "underwaved" in a sea of Java code. I used the instructions above to make the background an orangey-red color and things are much more obvious.
Instant.ofEpochMilli( 1_322_018_752_992L ) // Parse count of milliseconds-since-start-of-1970-UTC into an `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Assign a time zone to the `Instant` to produce a `ZonedDateTime` object.
The other answers use outmoded or incorrect classes.
Avoid the old date-time classes such as java.util.Date/.Calendar. They have proven to be poorly designed, confusing, and troublesome.
The java.time framework comes built into Java 8 and later. Much of the functionality is backported to Java 6 & 7 and further adapted to Android. Made by the some of the same folks as had made Joda-Time.
An Instant
is a moment on the timeline in UTC with a resolution of nanoseconds. Its epoch is first moment of 1970 in UTC.
Assuming your input data is a count of milliseconds from 1970-01-01T00:00:00Z (not clear in the Question), then we can easily instantiate an Instant
.
Instant instant = Instant.ofEpochMilli( 1_322_018_752_992L );
instant.toString(): 2011-11-23T03:25:52.992Z
The Z
in that standard ISO 8601 formatted string is short for Zulu
and means UTC.
Apply a time zone using a proper time zone name, to get a ZonedDateTime
.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( zoneId );
See this code run live at IdeOne.com.
Asia/Kolkata
time zone ?I am guessing your are had an India time zone affecting your code. We see here that adjusting into Asia/Kolkata
time zone renders the same time-of-day as you report, 08:55
which is five and a half hours ahead of our UTC value 03:25
.
2011-11-23T08:55:52.992+05:30[Asia/Kolkata]
You can apply the current default time zone of the JVM. Beware that the default can change at any moment during runtime. Any code in any thread of any app within the JVM can change the current default. If important, ask the user for their desired/expected time zone.
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.
OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.
You can invoke onNewIntent always by putting it into onCreate method like
@Override
public void onCreate(Bundle savedState){
super.onCreate(savedState);
onNewIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//code
}
I found a particular edge case where I was using the tini init in an alpine container, but since I was not using the statically linked version, and Alpine uses musl libc rather than GNU LibC library installed by default, it was crashing with the very same error message.
Had I understood this and also taken time to read the documentation properly, I would have found Tini Static, which upon changing to, resolved my problem.
For anyone using Bootstrap and having this problem, they use :active:focus as well as just :active and :focus so you'll need:
element:active:focus {
outline: 0;
}
Hopefully saved someone some time figuring that one out, banged my head for bit wondering why such a simple thing wasn't working.
I think the differences can be put as the following:
In this blog post I write about it in more detail.
Your code work fine, provided the value in Sheet2!D2
exists in Sheet1!A:A
. If it does not then error 1004 is raised.
To handle this case, try
Sub Demo()
Dim MyStringVar1 As Variant
On Error Resume Next
MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
Worksheets("Sheet1").Range("A:C"), 1, False)
On Error GoTo 0
If IsEmpty(MyStringVar1) Then
MsgBox "Value not found!"
End If
Range("E2") = MyStringVar1
End Sub
They're generally stored on the server. Where they're stored is up to you as the developer. You can use the session.save_handler
configuration variable and the session_set_save_handler
to control how sessions get saved on the server. The default save method is to save sessions to files. Where they get saved is controlled by the session.save_path
variable.
I suggest you to see "How do I run a bat file in the background from another bat file?"
Also, good answer (of using start
command) was given in "Parallel execution of shell processes" question page here;
But my recommendation is to use PowerShell. I believe it will perfectly suit your needs.
you can put all route functions in other files(modules) , and link it to the main server file. in the main express file, add a function that will link the module to the server:
function link_routes(app, route_collection){
route_collection['get'].forEach(route => app.get(route.path, route.func));
route_collection['post'].forEach(route => app.post(route.path, route.func));
route_collection['delete'].forEach(route => app.delete(route.path, route.func));
route_collection['put'].forEach(route => app.put(route.path, route.func));
}
and call that function for each route model:
link_routes(app, require('./login.js'))
in the module files(for example - login.js file), define the functions as usual:
const login_screen = (req, res) => {
res.sendFile(`${__dirname}/pages/login.html`);
};
const forgot_password = (req, res) => {
console.log('we will reset the password here')
}
and export it with the request method as a key and the value is an array of objects, each with path and function keys.
module.exports = {
get: [{path:'/',func:login_screen}, {...} ],
post: [{path:'/login:forgotPassword', func:forgot_password}]
};
You might find this article of interest which is available at codeplex.com.
The article presents a new way of expressing queries that span multiple tables in the form of declarative graph shapes.
Moreover, the article contains a thorough performance comparison of this new approach with EF queries. This analysis shows that GBQ quickly outperforms EF queries.
I got the same issue (View in a Fragment could not be reached). The reason turned out to be, that - immediately after (FragmentTransaction).commit() -, the View had not been activated in the UI. There is no guarantee when, after .commit(), the transaction takes place; it's only queued. So I added a (FragmentManager).executePendingTransactions() to force the transaction to be done. After that, referencing the View works as expected !
I would try to avoid inserting empty lists in the first place, but, would generally use:
d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty
If prior to 2.7:
d = dict( (k, v) for k,v in d.iteritems() if v )
or just:
empty_key_vals = list(k for k in k,v in d.iteritems() if v)
for k in empty_key_vals:
del[k]
If you don't want to grant admin permission to dashboard service account, you can create cluster admin service account.
$ kubectl create serviceaccount cluster-admin-dashboard-sa
$ kubectl create clusterrolebinding cluster-admin-dashboard-sa \
--clusterrole=cluster-admin \
--serviceaccount=default:cluster-admin-dashboard-sa
And then, you can use the token of just created cluster admin service account.
$ kubectl get secret | grep cluster-admin-dashboard-sa
cluster-admin-dashboard-sa-token-6xm8l kubernetes.io/service-account-token 3 18m
$ kubectl describe secret cluster-admin-dashboard-sa-token-6xm8l
I quoted it from giantswarm guide - https://docs.giantswarm.io/guides/install-kubernetes-dashboard/
For Angular 9+ You can add headers and params directly without the key-value notion:
const headers = new HttpHeaders().append('header', 'value');
const params = new HttpParams().append('param', 'value');
this.http.get('url', {headers, params});
Just pass your string to following method:
+(BOOL)isEmpty:(NSString *)str
{
if(str.length==0 || [str isKindOfClass:[NSNull class]] || [str isEqualToString:@""]||[str isEqualToString:NULL]||[str isEqualToString:@"(null)"]||str==nil || [str isEqualToString:@"<null>"]){
return YES;
}
return NO;
}
If you google. "Count down for loop python" you get these, which are pretty accurate.
how to loop down in python list (countdown)
Loop backwards using indices in Python?
I recommend doing minor searches before posting. Also "Learn Python The Hard Way" is a good place to start.
if (nfile.eof()) // Prompt data from the Priming read:
nfile >> CODE >> QTY >> PRICE;
else
{
/*used to check that the file is not empty*/
ofile << "empty file!!" << endl;
return 1;
}
You can try replacing this line:
return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
By those:
DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
DatePicker datePicker = dpDialog.getDatePicker();
Calendar calendar = Calendar.getInstance();//get the current day
datePicker.setMaxDate(calendar.getTimeInMillis());//set the current day as the max date
return dpDialog;
Ctrl+A , Ctrl+Shift+U
should do the trick!
Edit: Ctrl+U is the shortcut to be used to convert capital letters to lowercase (reverse scenario)
As others have said, it's macro recording, and you turn it off with q. Here's a nice article about how-to and why it's useful.
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()
resp.read()
is the straight html of the page you want to open, and you can use opener
to view any page using your session cookie.
By using order separately each subset gets order, but not the whole set, which is what you would want uniting two tables.
You should use something like this to have one ordered set:
SELECT TOP (100) PERCENT field1, field2, field3, field4, field5 FROM
(SELECT table1.field1, table1.field2, table1.field3, table1.field4, table1.field5 FROM table1
UNION ALL
SELECT table2.field1, table2.field2, table2.field3, table2.field4, table2.field5 FROM table2)
AS unitedTables ORDER BY field5 DESC
I found this example
https://github.com/square/retrofit/issues/1557
Here we set custom url client connection client before before we build API rest service implementation.
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import retrofit.Endpoint
import retrofit.RestAdapter
import retrofit.client.Request
import retrofit.client.UrlConnectionClient
import retrofit.converter.GsonConverter
class ClientBuilder {
public static <T> T buildClient(final Class<T> client, final String serviceUrl) {
Endpoint mCustomRetrofitEndpoint = new CustomRetrofitEndpoint()
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(mCustomRetrofitEndpoint)
.setConverter(new GsonConverter(gson))
.setClient(new MyUrlConnectionClient())
RestAdapter restAdapter = builder.build()
return restAdapter.create(client)
}
}
public final class MyUrlConnectionClient extends UrlConnectionClient {
@Override
protected HttpURLConnection openConnection(Request request) {
HttpURLConnection connection = super.openConnection(request);
connection.setConnectTimeout(15 * 1000);
connection.setReadTimeout(30 * 1000);
return connection;
}
}
just override the method:
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
*targetContentOffset = scrollView.contentOffset; // set acceleration to 0.0
float pageWidth = (float)self.articlesCollectionView.bounds.size.width;
int minSpace = 10;
int cellToSwipe = (scrollView.contentOffset.x)/(pageWidth + minSpace) + 0.5; // cell width + min spacing for lines
if (cellToSwipe < 0) {
cellToSwipe = 0;
} else if (cellToSwipe >= self.articles.count) {
cellToSwipe = self.articles.count - 1;
}
[self.articlesCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:cellToSwipe inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}
As far as I know, there are three different ways.
Use \n
in your print:
print("first line\nSecond line")
Use sep="\n"
in print:
print("first line", "second line", sep="\n")
Use triple quotes and a multiline string:
print("""
Line1
Line2
""")
I think an option for your purposes is git log --online --decorate
. This lets you know the checked commit, and the top commits for each branch that you have in your story line. By doing this, you have a nice view on the structure of your repo and the commits associated to a specific branch. I think reading this might help.
I deployed Facebook Android SDK to Sonatype repository.
You can include this library as Gradle dependency:
repositories {
maven {
url 'https://oss.sonatype.org/content/groups/public'
}
}
dependencies {
compile 'com.shamanland:facebook-android-sdk:3.15.0-SNAPSHOT'
}
Original post here.
The simplest way you can do is:
#include <stdlib.h>
system("Color F3");
Where "F" is the code for the background color and 3 is the code for the text color.
Mess around with it to see other color combinations:
system("Color 1A");
std::cout << "Hello, what is your name?" << std::endl;
system("Color 3B");
std::cout << "Hello, what is your name?" << std::endl;
system("Color 4c");
std::cout << "Hello, what is your name?" << std::endl;
Note: I only tested on Windows. Works. As pointed out, this is not cross-platform, it will not work on Linux systems.
&
is always evaluated in a string context, while +
may not concatenate if one of the operands is no string:
"1" + "2" => "12"
"1" + 2 => 3
1 + "2" => 3
"a" + 2 => type mismatch
This is simply a subtle source of potential bugs and therefore should be avoided. &
always means "string concatenation", even if its arguments are non-strings:
"1" & "2" => "12"
"1" & 2 => "12"
1 & "2" => "12"
1 & 2 => "12"
"a" & 2 => "a2"
Yes scaling horizontally means adding more machines, but it also implies that the machines are equal in the cluster. MySQL can scale horizontally in terms of Reading data, through the use of replicas, but once it reaches capacity of the server mem/disk, you have to begin sharding data across servers. This becomes increasingly more complex. Often keeping data consistent across replicas is a problem as replication rates are often too slow to keep up with data change rates.
Couchbase is also a fantastic NoSQL Horizontal Scaling database, used in many commercial high availability applications and games and arguably the highest performer in the category. It partitions data automatically across cluster, adding nodes is simple, and you can use commodity hardware, cheaper vm instances (using Large instead of High Mem, High Disk machines at AWS for instance). It is built off the Membase (Memcached) but adds persistence. Also, in the case of Couchbase, every node can do reads and writes, and are equals in the cluster, with only failover replication (not full dataset replication across all servers like in mySQL).
Performance-wise, you can see an excellent Cisco benchmark: http://blog.couchbase.com/understanding-performance-benchmark-published-cisco-and-solarflare-using-couchbase-server
Here is a great blog post about Couchbase Architecture: http://horicky.blogspot.com/2012/07/couchbase-architecture.html
for ImageView or others views who layout-gravity or gravity does not exist use :
android:layout_centerInParent="true"
in the child
(I had a relative layout with an ImageView as a child).
Set CSS display property to none.
document.getElementById("test").style.display = "none";
Also, you do not need javascript:
for the onclick
attribute.
<input type="image" src="../images/btnFind.png" id="find" name="find"
onclick="hide();" />
Finally, make sure you do not have multiple elements with the same ID.
If your form goes nowhere, Phil suggested that you should prevent submission of the form. Simply return false
in the onsubmit handler.
<form method="post" id="test" onsubmit="return false;">
If you want the form to post, but hide the div on subsequent page load, you will have to use server-side code to hide the element:
<script type="text/javascript">
function hide() {
document.getElementById("test").style.display = "none";
}
window.onload = function() {
// if form was submitted, PHP will print the below,
// which runs function hide() on page load
<?= ($_POST['ampid'] != '') ? 'hide();' : '' ?>
}
</script>
The various primitive wrappers, e.g., Integer
are immutable so there's really not a more concise way to do what you're asking unless you can do it with something like AtomicLong. I can give that a go in a minute and update. BTW, Hashtable is a part of the Collections Framework.
Use bootstraps align-items
and justify-content
. See example below:
<div class="well" style="align-items:center;justify-content:center;">
<img src="img_source" height="50px" width="50px"/>
</div>
well there are really enough examples for this, but anyway, here you go
using System;
using System.Security.Cryptography;
namespace RsaCryptoExample
{
static class Program
{
static void Main()
{
//lets take a new CSP with a new 2048 bit rsa key pair
var csp = new RSACryptoServiceProvider(2048);
//how to get the private key
var privKey = csp.ExportParameters(true);
//and the public key ...
var pubKey = csp.ExportParameters(false);
//converting the public key into a string representation
string pubKeyString;
{
//we need some buffer
var sw = new System.IO.StringWriter();
//we need a serializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs.Serialize(sw, pubKey);
//get the string from the stream
pubKeyString = sw.ToString();
}
//converting it back
{
//get a stream from the string
var sr = new System.IO.StringReader(pubKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
pubKey = (RSAParameters)xs.Deserialize(sr);
}
//conversion for the private key is no black magic either ... omitted
//we have a public key ... let's get a new csp and load that key
csp = new RSACryptoServiceProvider();
csp.ImportParameters(pubKey);
//we need some data to encrypt
var plainTextData = "foobar";
//for encryption, always handle bytes...
var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData);
//apply pkcs#1.5 padding and encrypt our data
var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);
//we might want a string representation of our cypher text... base64 will do
var cypherText = Convert.ToBase64String(bytesCypherText);
/*
* some transmission / storage / retrieval
*
* and we want to decrypt our cypherText
*/
//first, get our bytes back from the base64 string ...
bytesCypherText = Convert.FromBase64String(cypherText);
//we want to decrypt, therefore we need a csp and load our private key
csp = new RSACryptoServiceProvider();
csp.ImportParameters(privKey);
//decrypt and strip pkcs#1.5 padding
bytesPlainTextData = csp.Decrypt(bytesCypherText, false);
//get our original plainText back...
plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData);
}
}
}
as a side note: the calls to Encrypt() and Decrypt() have a bool parameter that switches between OAEP and PKCS#1.5 padding ... you might want to choose OAEP if it's available in your situation
Are you using the userdir mod?
In that case the thing is that PHP5 seems to be disabling running scripts from that location by default and you have to comment out the following lines:
<IfModule mod_userdir.c>
<Directory /home/*/public_html>
php_admin_flag engine Off
</Directory>
</IfModule>
in /etc/apache2/mods-enabled/php5.conf
(on a ubuntu system)
For SQL Server 2016 and later, here is a really simple and relatively efficient expression to generate cryptographically random strings of a given byte length:
--Generates 36 bytes (48 characters) of base64 encoded random data
select r from OpenJson((select Crypt_Gen_Random(36) r for json path))
with (r varchar(max))
Note that the byte length is not the same as the encoded size; use the following from this article to convert:
Bytes = 3 * (LengthInCharacters / 4) - Padding
If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY()
would be a better approach. I would not advice to use @@IDENTITY
, as this can return any ID.
CREATE PROC [dbo].[sp_Test] (
@myID int output,
@myFirstName nvarchar(50),
@myLastName nvarchar(50),
@myAddress nvarchar(50),
@myPort int
) AS
BEGIN
INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
VALUES (@myFirstName, @myLastName, @myAddress, @myPort);
SET @myID = SCOPE_IDENTITY();
END
GO
Before asking questions of this kind, please check MSDN documentation.
When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To determine the remainder of 7 / 3, use the remainder operator (%).
int a = 5;
int b = 3;
int div = a / b; //quotient is 1
int mod = a % b; //remainder is 2
While this is very likely to be lost at the bottom of so many answers, the top solutions here were not working for me.
As far as I could tell neither would any of the other answers have helped.
Situation:
In an HTML5 page I had a menu that was a nav element inside a header (not THE header but a header in another element).
I wanted the navigation to stick to the top once a user scrolled to it, but previous to this the header was absolute positioned (so I could have it overlay something else slightly).
The solutions above never triggered a change because .offsetTop was not going to change as this was an absolute positioned element. Additionally the .scrollTop property was simply the top of the top most element... that is to say 0 and always would be 0.
Any tests I performed utilizing these two (and same with getBoundingClientRect results) would not tell me if the top of the navigation bar ever scrolled to the top of the viewable page (again, as reported in console, they simply stayed the same numbers while scrolling occurred).
Solution
The solution for me was utilizing
window.visualViewport.pageTop
The value of the pageTop property reflects the viewable section of the screen, therefore allowing me to track where an element is in reference to the boundaries of the viewable area.
Probably unnecessary to say, anytime I am dealing with scrolling I expect to use this solution to programatically respond to movement of elements being scrolled.
Hope it helps someone else.
IMPORTANT NOTE: This appears to work in Chrome and Opera currently & definitely not in Firefox (6-2018)... until Firefox supports visualViewport I recommend NOT using this method, (and I hope they do soon... it makes a lot more sense than the rest).
UPDATE:
Just a note regarding this solution.
While I still find what I discovered to be very valuable for situations in which "...programmatically respond to movement of elements being scrolled." is applicable. The better solution for the problem that I had was to use CSS to set position: sticky on the element. Using sticky you can have an element stay at the top without using javascript (NOTE: there are times this will not work as effectively as changing the element to fixed but for most uses the sticky approach will likely be superior)
UPDATE01:
So I realized that for a different page I had a requirement where I needed to detect the position of an element in a mildly complex scrolling setup (parallax plus elements that scroll past as part of a message).
I realized in that scenario that the following provided the value I utilized to determine when to do something:
let bodyElement = document.getElementsByTagName('body')[0];
let elementToTrack = bodyElement.querySelector('.trackme');
trackedObjPos = elementToTrack.getBoundingClientRect().top;
if(trackedObjPos > 264)
{
bodyElement.style.cssText = '';
}
Hope this answer is more widely useful now.
You mentioned that you're interested in the equality of the contents of the list (and didn't mention order). So containsExactlyInAnyOrder
from AssertJ is a good fit. It comes packaged with spring-boot-starter-test
, for example.
From the AssertJ docs ListAssert#containsExactlyInAnyOrder:
Verifies that the actual group contains exactly the given values and nothing else, in any order. Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya, vilya);
// assertion will pass
assertThat(elvesRings).containsExactlyInAnyOrder(vilya, vilya, nenya, narya);
// assertion will fail as vilya is contained twice in elvesRings.
assertThat(elvesRings).containsExactlyInAnyOrder(nenya, vilya, narya);
It's my reload. Because of some browser very weird. location.reload
can't reload.
methods:{
reload: function(){
this.isRouterAlive = false
setTimeout(()=>{
this.isRouterAlive = true
},0)
}
}
<router-view v-if="isRouterAlive"/>
This does it in text.
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>_x000D_
_x000D_
<script type="text/javascript">_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
timeleft--;_x000D_
document.getElementById("countdowntimer").textContent = timeleft;_x000D_
if(timeleft <= 0)_x000D_
clearInterval(downloadTimer);_x000D_
},1000);_x000D_
</script>
_x000D_
The main differences are:
1) OFFLINE index rebuild is faster than ONLINE rebuild.
2) Extra disk space required during SQL Server online index rebuilds.
3) SQL Server locks acquired with SQL Server online index rebuilds.
I stumbled over the same question and I've found a solution.
First make sure you upgrade to LESS 1.6 at least.
You can use npm
for that case.
Now you can use the following mixin:
.if (@condition, @property, @value) when (@condition = true){
@{property}: @value;
}
Since LESS 1.6 you are able to pass PropertyNames to Mixins as well. So for example you could just use:
.myHeadline {
.if(@include-lineHeight, line-height, '35px');
}
If @include-lineheight resolves to true LESS will print the line-height: 35px
and it will skip the mixin if @include-lineheight is not true.