I purpose to you a very simple method who use String.contains
:
public static boolean containWhitespace(String value) {
return value.contains(" ");
}
A little usage example:
public static void main(String[] args) {
System.out.println(containWhitespace("i love potatoes"));
System.out.println(containWhitespace("butihatewhitespaces"));
}
Output:
true
false
I'd try something like:
#!/usr/bin/python
from __future__ import print_function
import shlex
from subprocess import Popen, PIPE
def shlep(cmd):
'''shlex split and popen
'''
parsed_cmd = shlex.split(cmd)
## if parsed_cmd[0] not in approved_commands:
## raise ValueError, "Bad User! No output for you!"
proc = Popen(parsed_command, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
return (proc.returncode, out, err)
... In other words let shlex.split() do most of the work. I would NOT attempt to parse the shell's command line, find pipe operators and set up your own pipeline. If you're going to do that then you'll basically have to write a complete shell syntax parser and you'll end up doing an awful lot of plumbing.
Of course this raises the question, why not just use Popen with the shell=True (keyword) option? This will let you pass a string (no splitting nor parsing) to the shell and still gather up the results to handle as you wish. My example here won't process any pipelines, backticks, file descriptor redirection, etc that might be in the command, they'll all appear as literal arguments to the command. Thus it is still safer then running with shell=True ... I've given a silly example of checking the command against some sort of "approved command" dictionary or set --- through it would make more sense to normalize that into an absolute path unless you intend to require that the arguments be normalized prior to passing the command string to this function.
Chrome Developer Tools has an Audits tab which can show unused CSS selectors.
Run an audit, then, under Web Page Performance see Remove unused CSS rules
Problem
I was running into the same error message while calling a third party API from my ASP.NET Core MVC project.
Could not establish secure channel for SSL/TLS with authority '{base_url_of_WS}'.
Solution
It turned out that the third party API's server required TLS 1.2. To resolve this issue, I added the following line of code to my controller's constructor:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
How about std::remove()
instead:
#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());
This combination is also known as the erase-remove idiom.
return RedirectToAction("ActionName", "ControllerName");
If you only need to execute only one command all by itself and no wait needed, you should try "cmd /c", this works for me!
cmd /c start iexplore "http://your/url.html"
cmd /c means executing a command and then exit.
You can learn the functions of your switches by typing in your command prompt
anycmd /?
In Java latest versions you get -13%64 = -13
. The answer will always have sign of numerator.
It is not necessary to use System.Drawing
to find the image format in a URI. System.Drawing
is not available for .NET Core
unless you download the System.Drawing.Common NuGet package and therefore I don't see any good cross-platform answers to this question.
Also, my example does not use System.Net.WebClient
since Microsoft explicitly discourage the use of System.Net.WebClient
.
We don't recommend that you use the
WebClient
class for new development. Instead, use the System.Net.Http.HttpClient class.
*Without old System.Net.WebClient
and System.Drawing
.
This method will asynchronously download an image (or any file as long as the URI has a file extension) using the System.Net.Http.HttpClient
and then write it to a file, using the same file extension as the image had in the URI.
First part of getting the file extension is removing all the unnecessary parts from the URI.
We use Uri.GetLeftPart() with UriPartial.Path to get everything from the Scheme
up to the Path
.
In other words, https://www.example.com/image.png?query&with.dots
becomes https://www.example.com/image.png
.
After that, we use Path.GetExtension() to get only the extension (in my previous example, .png
).
var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
var fileExtension = Path.GetExtension(uriWithoutQuery);
From here it should be straight forward. Download the image with HttpClient.GetByteArrayAsync, create the path, ensure the directory exists and then write the bytes to the path with File.WriteAllBytesAsync() (or File.WriteAllBytes
if you are on .NET Framework)
private async Task DownloadImageAsync(string directoryPath, string fileName, Uri uri)
{
using var httpClient = new HttpClient();
// Get the file extension
var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
var fileExtension = Path.GetExtension(uriWithoutQuery);
// Create file path and ensure directory exists
var path = Path.Combine(directoryPath, $"{fileName}{fileExtension}");
Directory.CreateDirectory(directoryPath);
// Download the image and write to the file
var imageBytes = await _httpClient.GetByteArrayAsync(uri);
await File.WriteAllBytesAsync(path, imageBytes);
}
Note that you need the following using directives.
using System;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http;
var folder = "images";
var fileName = "test";
var url = "https://cdn.discordapp.com/attachments/458291463663386646/592779619212460054/Screenshot_20190624-201411.jpg?query&with.dots";
await DownloadImageAsync(folder, fileName, new Uri(url));
HttpClient
for every method call. It is supposed to be reused throughout the application. I wrote a short example of an ImageDownloader
(50 lines) with more documentation that correctly reuses the HttpClient
and properly disposes of it that you can find here.dump this into a more specific collection of just the ids you don't want
var notTheseBarIds = filterBars.Select(fb => fb.BarId);
then try this:
fooSelect = (from f in fooBunch
where !notTheseBarIds.Contains(f.BarId)
select f).ToList();
or this:
fooSelect = fooBunch.Where(f => !notTheseBarIds.Contains(f.BarId)).ToList();
Seems that only index.js get loaded when you require("./routes") . I used the following code in index.js to load the rest of the routes:
var fs = require('fs')
, path = require('path');
fs.readdirSync(__dirname).forEach(function(file){
var route_fname = __dirname + '/' + file;
var route_name = path.basename(route_fname, '.js');
if(route_name !== 'index' && route_name[0] !== "."){
exports[route_name] = require(route_fname)[route_name];
}
});
The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/
Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)
See this question for additional information.
input[type="text"], textarea {
background-color : #d1d1d1;
}
Hope that helps :)
Edit: working example, http://jsfiddle.net/C5WxK/
this code will give you latest post first, i think this answer is helpful.
mInstaList=(RecyclerView)findViewById(R.id.insta_list);
mInstaList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mInstaList.setLayoutManager(layoutManager);
layoutManager.setStackFromEnd(true);
layoutManager.setReverseLayout(true);
I had the same problem. I was using Docker Toolbox on Windows Home.
Instead of localhost
I had to use http://192.168.99.100:8080/
.
You can get the correct IP address using the command:
docker-machine ip
The above command returned 192.168.99.100
for me.
I find std::getline()
is often the simplest. The optional delimiter parameter means it's not just for reading "lines":
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> strings;
istringstream f("denmark;sweden;india;us");
string s;
while (getline(f, s, ';')) {
cout << s << endl;
strings.push_back(s);
}
}
Try "sudo mysql -u root -p" please.
public class CountWords
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ' && str1.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " + wordCount));
}
}
This gives the correct result because if space comes twice or more then it can't increase wordcount. Enjoy.
You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)
$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property
Or just this, xpath is case sensitive. Both have the same output:
$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml
Name Type #text
---- ---- -----
DisplayName System.String SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName System.String SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
You need to use smtp as backend in settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
If you use backend as console, you will receive output in console
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
And also below settings in addition
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'
If you are using gmail for this, setup 2-step verification and Application specific password and copy and paste that password in above EMAIL_HOST_PASSWORD value.
just close the eclipse and avd emulator and restart it. It works fine
=counta(range)
counta
: "Returns a count of the number of values in a dataset"
Note: CountA
considers ""
to be a value. Only cells that are blank (press delete in a cell to blank it) are not counted.
Google support: https://support.google.com/docs/answer/3093991
countblank
: "Returns the number of empty cells in a given range"
Note: CountBlank
considers both blank cells (press delete to blank a cell) and cells that have a formula that returns ""
to be empty cells.
Google Support: https://support.google.com/docs/answer/3093403
If you have a range that includes formulae that result in ""
, then you can modify your formula from
=counta(range)
to:
=Counta(range) - Countblank(range)
EDIT: the function is countblank
, not countblanks
, the latter will give an error.
if you know the file name, but don't know the file extention you can use this function:
public function showImage($name)
{
$types = [
'gif'=> 'image/gif',
'png'=> 'image/png',
'jpeg'=> 'image/jpeg',
'jpg'=> 'image/jpeg',
];
$root_path = '/var/www/my_app'; //use your framework to get this properly ..
foreach($types as $type=>$meta){
if(file_exists($root_path .'/uploads/'.$name .'.'. $type)){
header('Content-type: ' . $meta);
readfile($root_path .'/uploads/'.$name .'.'. $type);
return;
}
}
}
Note: the correct content-type for JPG files is image/jpeg
.
Here you can find how to set path to JDK for Glassfish: http://www.devdaily.com/blog/post/java/fixing-glassfish-jdk-path-problem-solved
Check
glassfish\config\asenv.bat
where java path is configured
REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16
You should use NMAP:
nmap -T5 -sP 192.168.0.0-255
[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]
tempData.push( data[index] );
I agree with the correct answer above, but.... your still not giving the index value for the data that you want to add to tempData. Without the [index] value the whole array will be added.
Aside from readability and performance, one aspect commonly overlooked is consistency. There are many ways to implement a for (or while) loop over iterators, from:
for (C::iterator iter = c.begin(); iter != c.end(); iter++) {
do_something(*iter);
}
to:
C::iterator iter = c.begin();
C::iterator end = c.end();
while (iter != end) {
do_something(*iter);
++iter;
}
with many examples in between at varying levels of efficiency and bug potential.
Using for_each, however, enforces consistency by abstracting away the loop:
for_each(c.begin(), c.end(), do_something);
The only thing you have to worry about now is: do you implement the loop body as function, a functor, or a lambda using Boost or C++0x features? Personally, I'd rather worry about that than how to implement or read a random for/while loop.
Working with just one class:
select {
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 5px;
height: 34px;
background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
-webkit-appearance: none;
background-position-x: 244px;
}
You should be looking for the second tr that has the td that equals ' Color Digest ', then you need to look at either the following sibling of the first td in the tr, or the second td.
Try the following:
//tr[td='Color Digest'][2]/td/following-sibling::td[1]
or
//tr[td='Color Digest'][2]/td[2]
http://www.xpathtester.com/saved/76bb0bca-1896-43b7-8312-54f924a98a89
As pointed by @EmJiHash PercentRelativeLayout is deprecated in API level 26.0.0
Below quoting google comment:
This class was deprecated in API level 26.0.0. consider using ConstraintLayout and associated layouts instead. The following shows how to replicate the functionality of percentage layouts with a ConstraintLayout
Google introduced new API called android.support.percent
Then you can just specify percentage to take by view
Add compile dependency like
implementation 'com.android.support:percent:22.2.0
in that, PercentRelativeLayout is what we can do a percentage wise layout
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
app:layout_marginTopPercent="25%"
app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentRelativeLayout>
shape()
consists of array having two arguments rows and columns.
if you search shape[0]
then it will gave you the number of rows.
shape[1]
will gave you number of columns.
Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
@model MvcVariousApplication.Models.RechargeMobileViewModel
@{
ViewBag.Title = "Contact";
}
@Html.LabelFor(model=> model.CustomerFullName)
@Html.TextBoxFor(model => model.CustomerFullName)
@Html.LabelFor(model => model.MobileNumber)
@Html.TextBoxFor(model => model.MobileNumber)
@Html.LabelFor(model => model.TelecomSubscriber)
@Html.TextBoxFor(model => model.TelecomSubscriber)
@Html.LabelFor(model => model.TotalAmount)
@Html.TextBoxFor(model => model.TotalAmount)
@Html.LabelFor(model => model.Month)
@Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")
I can think of 2 ways to achieve this:
IFNULL():
The IFNULL() function returns a specified value if the expression is NULL.If the expression is NOT NULL, this function returns the expression.
Syntax:
IFNULL(expression, alt_value)
Example of IFNULL() with your query:
SELECT AVG( price )
FROM(
SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
WHERE listing_Type = 'AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
AND IFNULL( price, 0 ) > ( SELECT AVG( IFNULL( price, 0 ) )* 0.50
FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
FROM web_price_scan
WHERE listing_Type='AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
) g
WHERE cume_dist < 0.50
)
AND IFNULL( price, 0 ) < ( SELECT AVG( IFNULL( price, 0 ) ) *2
FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
FROM web_price_scan
WHERE listing_Type='AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
) d
WHERE cume_dist < 0.50)
)s
HAVING COUNT(*) > 5
COALESCE()
The COALESCE() function returns the first non-null value in a list.
Syntax:
COALESCE(val1, val2, ...., val_n)
Example of COALESCE() with your query:
SELECT AVG( price )
FROM(
SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
WHERE listing_Type = 'AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
FROM web_price_scan
WHERE listing_Type='AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
) g
WHERE cume_dist < 0.50
)
AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
FROM web_price_scan
WHERE listing_Type='AARM'
AND u_kbalikepartnumbers_id = 1000307
AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
) d
WHERE cume_dist < 0.50)
)s
HAVING COUNT(*) > 5
C11 standard draft
The C11 N1570 standard draft says:
7.24.2.1 "The memcpy function":
2 The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.
7.24.2.2 "The memmove function":
2 The memmove function copies n characters from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n characters from the object pointed to by s2 are first copied into a temporary array of n characters that does not overlap the objects pointed to by s1 and s2, and then the n characters from the temporary array are copied into the object pointed to by s1
Therefore, any overlap on memcpy
leads to undefined behavior, and anything can happen: bad, nothing or even good. Good is rare though :-)
memmove
however clearly says that everything happens as if an intermediate buffer is used, so clearly overlaps are OK.
C++ std::copy
is more forgiving however, and allows overlaps: Does std::copy handle overlapping ranges?
Following points really helped me a lot. There might be other points too, but these are very crucial:
I store my data this way:
accountsTable ->
key1 -> account1
key2 -> account2
in order to get object data:
accountsDb = mDatabase.child("accountsTable");
accountsDb.child("some key").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
try{
Account account = snapshot.getChildren().iterator().next()
.getValue(Account.class);
} catch (Throwable e) {
MyLogger.error(this, "onCreate eror", e);
}
}
@Override public void onCancelled(DatabaseError error) { }
});
I have encountered this one too and this is my solution.
If you are encountering an invalid json object exception when parsing data, even though you know that your json string is correct, stringify the data you received in your ajax code before parsing it to JSON:
$.post(CONTEXT+"servlet/capture",{
yesTransactionId : yesTransactionId,
productOfferId : productOfferId
},
function(data){
try{
var trimData = $.trim(JSON.stringify(data));
var obj = $.parseJSON(trimData);
if(obj.success == 'true'){
//some codes ...
Actually, a decent shortcut method for getting the colors to cycle is to use hold all;
in place of hold on;
. Each successive plot
will rotate (automatically for you) through MATLAB's default colormap.
From the MATLAB site on hold
:
hold all
holds the plot and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and LineStyleOrder property values to the beginning of the list. Plotting commands continue cycling through the predefined colors and linestyles from where the last plot stopped in the list.
I've been using Chilkat's native SFTP library ( http://www.chilkatsoft.com/ssh-sftp-component.asp ) for a couple of months now and it's working great. Been using it in a nightly job to download large files and do private key authentication. Only problem that I had was getting the 64bit version to work on windows server 2008, I needed to install vcredist_x64.exe ( http://www.microsoft.com/download/en/details.aspx?id=14632 ) on my server.
I had a similar problem and for me it boiled down to adding the following HTTP headers at the response of the receiving end:
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *
You may prefer not to use the *
at the end, but only the domainname of the host sending the data. Like *.example.com
But this is only feasible when you have access to the configuration of the server.
The -maxdepth
option should be before the -name
option, like below.,
find . -maxdepth 1 -name "string" -print
Only way known for me is to looping through all array:
var index=-1;
for(var i=0;i<Data.length;i++)
if(Data[i].name==="John"){index=i;break;}
or case insensitive:
var index=-1;
for(var i=0;i<Data.length;i++)
if(Data[i].name.toLowerCase()==="john"){index=i;break;}
On result variable index contain index of object or -1 if not found.
Creating a table and copying the data in a single command:
create table T_NEW as
select * from T;
* This will not copy PKs, FKs, Triggers, etc.
Converter:
public class NullableToVisibilityConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Collapsed : Visibility.Visible;
}
}
Binding:
Visibility="{Binding PropertyToBind, Converter={StaticResource nullableToVisibilityConverter}}"
public String convertImageToBase64(String filePath) {
byte[] fileContent = new byte[0];
String base64encoded = null;
try {
fileContent = FileUtils.readFileToByteArray(new File(filePath));
} catch (IOException e) {
log.error("Error reading file: {}", filePath);
}
try {
base64encoded = Base64.getEncoder().encodeToString(fileContent);
} catch (Exception e) {
log.error("Error encoding the image to base64", e);
}
return base64encoded;
}
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
You can just compare the boolean array. For example
X = [True, False, True]
then
Y = X == False
would give you
Y = [False, True, False]
You can just do "TYPE1".
I think, the statement
everyone hates it except me
makes any further discussion waste: when you keep using Git, they will blame you if anything goes wrong.
Apart from this, for me Git has two advantages over a centralized VCS that I appreciate most (as partly described by Rob Sobers):
But as I said: I think that you're fighting a lost battle: when everyone hates Git, don't use Git. It could help you more to know why they hate Git instead of trying them to convince them.
If they simply don't want it 'cause it's new to them and are not willing to learn something new: are you sure that you will do successful development with that staff?
Does really every single person hate Git or are they influenced by some opinion leaders? Find the leaders and ask them what's the problem. Convince them and you'll convince the rest of the team.
If you cannot convince the leaders: forget about using Git, take the TFS. Will make your life easier.
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
HTML5 ARIA attribute is what you're looking for. It can be used in your code even without bootstrap.
Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications (especially those developed with Ajax and JavaScript) more accessible to people with disabilities.
To be precise for your question, here is what your attributes are called as ARIA attribute states and model
aria-labelledby
: Identifies the element (or elements) that labels the current element.
aria-hidden (state)
: Indicates that the element and all of its descendants are not visible or perceivable to any user as implemented by the author.
I would use cron to run a script every minute, and make that script run your script four times with a 15-second sleep between runs.
(That assumes your script is quick to run - you could adjust the sleep times if not.)
That way, you get all the benefits of cron
as well as your 15 second run period.
Edit: See also @bmb's comment below.
A string is a list of characters (i.e. code points). The number of bytes taken to represent the string depends entirely on which encoding you use to turn it into bytes.
That said, you can turn the string into a byte array and then look at its size as follows:
// The input string for this test
final String string = "Hello World";
// Check length, in characters
System.out.println(string.length()); // prints "11"
// Check encoded sizes
final byte[] utf8Bytes = string.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "11"
final byte[] utf16Bytes= string.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "24"
final byte[] utf32Bytes = string.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "44"
final byte[] isoBytes = string.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "11"
final byte[] winBytes = string.getBytes("CP1252");
System.out.println(winBytes.length); // prints "11"
So you see, even a simple "ASCII" string can have different number of bytes in its representation, depending which encoding is used. Use whichever character set you're interested in for your case, as the argument to getBytes()
. And don't fall into the trap of assuming that UTF-8 represents every character as a single byte, as that's not true either:
final String interesting = "\uF93D\uF936\uF949\uF942"; // Chinese ideograms
// Check length, in characters
System.out.println(interesting.length()); // prints "4"
// Check encoded sizes
final byte[] utf8Bytes = interesting.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "12"
final byte[] utf16Bytes= interesting.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "10"
final byte[] utf32Bytes = interesting.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "16"
final byte[] isoBytes = interesting.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "4" (probably encoded "????")
final byte[] winBytes = interesting.getBytes("CP1252");
System.out.println(winBytes.length); // prints "4" (probably encoded "????")
(Note that if you don't provide a character set argument, the platform's default character set is used. This might be useful in some contexts, but in general you should avoid depending on defaults, and always use an explicit character set when encoding/decoding is required.)
I would guess that you either haven't edited the right php.ini
or you haven't restarted PHP and/or the webserver.
Create a phpinfo.php
page in your docroot with the contents <?php phpinfo();
to make sure you are changing the correct php.ini
. In addition to the location of the php.ini
file the webserver is using, it will also state the maximum script memory allowed.
Next, I would add some stack traces to your page so you can see the chain of events that led to this. The following function will catch fatal errors and provide more information about what happened.
register_shutdown_function(function()
{
if($error = error_get_last())
{
// Should actually log this instead of printing out...
var_dump($error);
var_dump(debug_backtrace());
}
});
Personally, Nginx + PHP-FPM is what I have used for years since I left slow ol' Apache.
Another way is to tell the marshaller to always use a certain prefix
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
@Override
public String getPreferredPrefix(String arg0, String arg1, boolean arg2) {
return "ns1";
}
});'
If the file is only numerical values separated by tabs, try using the csv library: http://docs.python.org/library/csv.html (you can set the delimiter to '\t')
If you have a textual file in which every line represents a row in a matrix and has integers separated by spaces\tabs, wrapped by a 'arrayname = [...]' syntax, you should do something like:
import re
f = open("your-filename", 'rb')
result_matrix = []
for line in f.readlines():
match = re.match(r'\s*\w+\s+\=\s+\[(.*?)\]\s*', line)
if match is None:
pass # line syntax is wrong - ignore the line
values_as_strings = match.group(1).split()
result_matrix.append(map(int, values_as_strings))
import datetime
# convert string into date time format.
str_date = '2016-10-06 15:14:54.322989'
d_date = datetime.datetime.strptime(str_date , '%Y-%m-%d %H:%M:%S.%f')
print(d_date)
print(type(d_date)) # check d_date type.
# convert date time to regular format.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
# some other date formats.
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)
<<<<<< OUTPUT >>>>>>>
2016-10-06 15:14:54.322989
<class 'datetime.datetime'>
06 October 2016 03:14:54 PM
2016-10-06 03:14:54 PM
2016-10-06 15:14:54
I think this should work:
#include <time.h>
clock_t start = clock(), diff;
ProcessIntenseFunction();
diff = clock() - start;
int msec = diff * 1000 / CLOCKS_PER_SEC;
printf("Time taken %d seconds %d milliseconds", msec/1000, msec%1000);
As written, your function accepts only two ranges as arguments.
To allow for a variable number of ranges to be used in the function, you need to declare a ParamArray variant array in your argument list. Then, you can process each of the ranges in the array in turn.
For example,
Function myAdd(Arg1 As Range, ParamArray Args2() As Variant) As Double
Dim elem As Variant
Dim i As Long
For Each elem In Arg1
myAdd = myAdd + elem.Value
Next elem
For i = LBound(Args2) To UBound(Args2)
For Each elem In Args2(i)
myAdd = myAdd + elem.Value
Next elem
Next i
End Function
This function could then be used in the worksheet to add multiple ranges.
For your function, there is the question of which of the ranges (or cells) that can passed to the function are 'Sessions' and which are 'Customers'.
The easiest case to deal with would be if you decided that the first range is Sessions and any subsequent ranges are Customers.
Function calculateIt(Sessions As Range, ParamArray Customers() As Variant) As Double
'This function accepts a single Sessions range and one or more Customers
'ranges
Dim i As Long
Dim sessElem As Variant
Dim custElem As Variant
For Each sessElem In Sessions
'do something with sessElem.Value, the value of each
'cell in the single range Sessions
Debug.Print "sessElem: " & sessElem.Value
Next sessElem
'loop through each of the one or more ranges in Customers()
For i = LBound(Customers) To UBound(Customers)
'loop through the cells in the range Customers(i)
For Each custElem In Customers(i)
'do something with custElem.Value, the value of
'each cell in the range Customers(i)
Debug.Print "custElem: " & custElem.Value
Next custElem
Next i
End Function
If you want to include any number of Sessions ranges and any number of Customers range, then you will have to include an argument that will tell the function so that it can separate the Sessions ranges from the Customers range.
This argument could be set up as the first, numeric, argument to the function that would identify how many of the following arguments are Sessions ranges, with the remaining arguments implicitly being Customers ranges. The function's signature would then be:
Function calculateIt(numOfSessionRanges, ParamAray Args() As Variant)
Or it could be a "guard" argument that separates the Sessions ranges from the Customers ranges. Then, your code would have to test each argument to see if it was the guard. The function would look like:
Function calculateIt(ParamArray Args() As Variant)
Perhaps with a call something like:
calculateIt(sessRange1,sessRange2,...,"|",custRange1,custRange2,...)
The program logic might then be along the lines of:
Function calculateIt(ParamArray Args() As Variant) As Double
...
'loop through Args
IsSessionArg = True
For i = lbound(Args) to UBound(Args)
'only need to check for the type of the argument
If TypeName(Args(i)) = "String" Then
IsSessionArg = False
ElseIf IsSessionArg Then
'process Args(i) as Session range
Else
'process Args(i) as Customer range
End if
Next i
calculateIt = <somevalue>
End Function
Check the namespace from where we are importing
import { MatDialogModule } from **"@angular/material/dialog";**
import { MatCardModule } from **"@angular/material/card";**
import { MatButtonModule } from **"@angular/material/button";**
Additionally, this will only work if Value is of type bool. Normally this is used with predicates. Any predicate would be generally used find whether there is any element satisfying a given condition. Here you're just doing a map from your element i to a bool property. It will search for an "i" whose Value property is true. Once done, the method will return true.
For SQL Server
select *
from YourTable
where DateCol between getdate() and dateadd(d, 90, getdate())
"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:
Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.
This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.
Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.
This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:
Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false
I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.
In case anyone landed here in search of "how to specify types of multiple return values?", use Tuple[type_value1, ..., type_valueN]
from typing import Tuple
def f() -> Tuple[dict, str]:
a = {1: 2}
b = "hello"
return a, b
If you're just after console logging here's what I'd do:
export default class App extends Component {
componentDidMount() {
console.log('I was triggered during componentDidMount')
}
render() {
console.log('I was triggered during render')
return (
<div> I am the App component </div>
)
}
}
Shouldn't be any need for those packages just to do console logging.
Try Winhttrack
...offline browser utility.
It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.
WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...
I would put an absolutely positioned, z-index: 100;
span (or spans) with the background: url("myImageWithRoundedCorners.jpg");
set on it inside the #mainWrapperDivWithBGImage
.
For me it worked:
df['id'].convert_dtypes()
see the documentation here:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.convert_dtypes.html
If you pass the -v
flag to the ansible-playbook command, then ansible will show the output on your terminal.
For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.
The command select username from all_users;
requires less privileges
Actually I think that more general approach to loop through dictionary is to use iteritems():
# get tuples of term, courses
for term, term_courses in courses.iteritems():
# get tuples of course number, info
for course, info in term_courses.iteritems():
# loop through info
for k, v in info.iteritems():
print k, v
output:
assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian
Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():
for term_courses in courses.itervalues():
for info in term_courses.itervalues():
for k, v in info.iteritems():
print k, v
Swift 3
you want call some closure in swift code then you want to change in storyboard ya any type off change belong to view your application will crash
but you want to use dispatch method your application will not crash
async method
DispatchQueue.main.async
{
//Write code here
}
sync method
DispatchQueue.main.sync
{
//Write code here
}
What is “export default” in JavaScript?
In default export the naming of import is completely independent and we can use any name we like.
I will illustrate this line with a simple example.
Let’s say we have three modules and an index.html file:
export function hello() {
console.log("Modul: Saying hello!");
}
export let variable = 123;
export function hello2() {
console.log("Module2: Saying hello for the second time!");
}
export let variable2 = 456;
modul3.js
export default function hello3() {
console.log("Module3: Saying hello for the third time!");
}
<script type="module">
import * as mod from './modul.js';
import {hello2, variable2} from './modul2.js';
import blabla from './modul3.js'; // ! Here is the important stuff - we name the variable for the module as we like
mod.hello();
console.log("Module: " + mod.variable);
hello2();
console.log("Module2: " + variable2);
blabla();
</script>
The output is:
modul.js:2:10 -> Modul: Saying hello!
index.html:7:9 -> Module: 123
modul2.js:2:10 -> Module2: Saying hello for the second time!
index.html:10:9 -> Module2: 456
modul3.js:2:10 -> Module3: Saying hello for the third time!
So the longer explanation is:
'export default' is used if you want to export a single thing for a module.
So the thing that is important is "import blabla from './modul3.js'" - we could say instead:
"import pamelanderson from './modul3.js" and then pamelanderson();
. This will work just fine when we use 'export default' and basically this is it - it allows us to name it whatever we like when it is default.
P.S.: If you want to test the example - create the files first, and then allow CORS in the browser -> if you are using Firefox type in the URL of the browser: about:config -> Search for "privacy.file_unique_origin" -> change it to "false" -> open index.html -> press F12 to open the console and see the output -> Enjoy and don't forget to return the CORS settings to default.
P.S.2: Sorry for the silly variable naming
More information is in link2medium and link2mdn.
You need to add an action
into your form like:
<form name='form1' method='post' action='<?php echo($_SERVER['PHP_SELF']);'>
<!-- All your input for the form here -->
</form>
Then put your snippet at the top of the document en send the mail. What echo($_SERVER['PHP_SELF']);
does is that it sends your information to the top of your script so you could use it.
You can download the ISO from https://beta.visualstudio.com/downloads/ (even if it has "beta" in the URL you'll have the latest stable version. Currently update 3)
If you are using Oracle (or configure the application to the SQL Server) then Oracle SQL Developer does this for you. choose 'unload' for a table and follow the options through (untick DDL if you don't want all the table create stuff).
DateTime? d=null;
DateTime d2;
bool success = DateTime.TryParse("some date text", out d2);
if (success) d=d2;
(There might be more elegant solutions, but why don't you simply do something as above?)
string ImagePath = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
string a = "";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
if (receiveStream.CanRead)
{ a = "OK"; }
}
catch { }
You can use define window.myvar = {}
.
When you want to use it, you can use like window.myvar = 1
For Apache server, you should check mod_expires for setting Expires and Cache-Control headers.
Alternatively, you can use Header directive to add Cache-Control on your own:
Header set Cache-Control "max-age=290304000, public"
Gradle is a build system running on Android Studio.
In other languages for example:
We can set the response headers in Python Flask application using Flask application context using flask.g
This way of setting response headers in Flask application context using flask.g
is thread safe and can be used to set custom & dynamic attributes from any file of application, this is especially helpful if we are setting custom/dynamic response headers from any helper class, that can also be accessed from any other file ( say like middleware, etc), this flask.g
is global & valid for that request thread only.
Say if i want to read the response header from another api/http call that is being called from this app, and then extract any & set it as response headers for this app.
Sample Code: file: helper.py
import flask
from flask import request, g
from multidict import CIMultiDict
from asyncio import TimeoutError as HttpTimeout
from aiohttp import ClientSession
def _extract_response_header(response)
"""
extracts response headers from response object
and stores that required response header in flask.g app context
"""
headers = CIMultiDict(response.headers)
if 'my_response_header' not in g:
g.my_response_header= {}
g.my_response_header['x-custom-header'] = headers['x-custom-header']
async def call_post_api(post_body):
"""
sample method to make post api call using aiohttp clientsession
"""
try:
async with ClientSession() as session:
async with session.post(uri, headers=_headers, json=post_body) as response:
responseResult = await response.read()
_extract_headers(response, responseResult)
response_text = await response.text()
except (HttpTimeout, ConnectionError) as ex:
raise HttpTimeout(exception_message)
file: middleware.py
import flask
from flask import request, g
class SimpleMiddleWare(object):
"""
Simple WSGI middleware
"""
def __init__(self, app):
self.app = app
self._header_name = "any_request_header"
def __call__(self, environ, start_response):
"""
middleware to capture request header from incoming http request
"""
request_id_header = environ.get(self._header_name)
environ[self._header_name] = request_id_header
def new_start_response(status, response_headers, exc_info=None):
"""
set custom response headers
"""
# set the request header as response header
response_headers.append((self._header_name, request_id_header))
# this is trying to access flask.g values set in helper class & set that as response header
values = g.get(my_response_header, {})
if values.get('x-custom-header'):
response_headers.append(('x-custom-header', values.get('x-custom-header')))
return start_response(status, response_headers, exc_info)
return self.app(environ, new_start_response)
Calling the middleware from main class
file : main.py
from flask import Flask
import asyncio
from gevent.pywsgi import WSGIServer
from middleware import SimpleMiddleWare
app = Flask(__name__)
app.wsgi_app = SimpleMiddleWare(app.wsgi_app)
I found this link while looking for something slightly different, how to start appending array objects to an empty numpy array, but tried all the solutions on this page to no avail.
Then I found this question and answer: How to add a new row to an empty numpy array
The gist here:
The way to "start" the array that you want is:
arr = np.empty((0,3), int)
Then you can use concatenate to add rows like so:
arr = np.concatenate( ( arr, [[x, y, z]] ) , axis=0)
See also https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html
Add a column to your existing data to get rid of the hour:minute:second time stamp on each row:
=DATE(YEAR(A1), MONTH(A1), DAY(A1))
Extend this down the length of your data. Even easier: quit collecting the hh:mm:ss data if you don't need it. Assuming your date/time was in column A, and your value was in column B, you'd put the above formula in column C, and auto-extend it for all your data.
Now, in another column (let's say E), create a series of dates corresponding to each day of the specific month you're interested in. Just type the first date, (for example, 10/7/2016 in E1), and auto-extend. Then, in the cell next to the first date, F1, enter:
=SUMIF(C:C, E1, B:B )
autoextend the formula to cover every date in the month, and you're done. Begin at 1/1/2016, and auto-extend for the whole year if you like.
By default Vagrant uses a generated private key to login, you can try this:
ssh -l ubuntu -p 2222 -i .vagrant/machines/default/virtualbox/private_key 127.0.0.1
Here is an example of how to use ProcessBuilder
to execute your remote application. Since you do not care about input/output and/or errors, you can do as follows:
List<String> args = new ArrayList<String>();
args.add ("script.bat"); // command name
args.add ("-option"); // optional args added as separate list items
ProcessBuilder pb = new ProcessBuilder (args);
Process p = pb.start();
p.waitFor();
the waitFor()
method will wait until the process had ended before continuing. This method returns the error code of the process but, since you don't care about it, I didn't put it in the example.
brute force (and only tested on an Oracle system, but I think this is pretty standard):
select distinct usr_id from users where user_id in (
select user_id from (
Select user_id, Count(User_Id) As Cc
From users
GROUP BY user_id
) Where Cc =3
)
and ancestry in ('England', 'France', 'Germany')
;
edit: I like @HuckIt's answer even better.
Just FYI, Geocoder is asynchronous so the accepted answer while logical doesn't really work in this instance. I would prefer to have an outside object that acts as your updater.
var updater = {};
function geoCodeCity(goocoord) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': goocoord
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
updater.currentLocation = results[1].formatted_address;
} else {
if (status == "ERROR") {
console.log(status);
}
}
});
};
Given this example url:
http://www.example.com/some-dir/yourpage.php?q=bogus&n=10
$_SERVER['REQUEST_URI']
will give you:
/some-dir/yourpage.php?q=bogus&n=10
Whereas $_GET['q']
will give you:
bogus
In other words, $_SERVER['REQUEST_URI']
will hold the full request path including the querystring. And $_GET['q']
will give you the value of parameter q
in the querystring.
Sorry, I wasn't sure which SQL platform you're talking about:
In MySQL:
$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");
in MSSQL
$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");
The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.
Edit
I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.
So, for MySQL there's the CHAR_LENGTH()
. The following example highlights the difference between LENGTH()
an CHAR_LENGTH()
:
CREATE TABLE words (
word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;
INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');
SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;
+--------+-----------+----------------+
| word | num_bytes | num_characters |
+--------+-----------+----------------+
| ?? | 6 | 2 |
| happy | 5 | 5 |
| hayir | 6 | 5 |
+--------+-----------+----------------+
Be careful if you're dealing with multi-byte characters.
LENGTH()
returns the length of the string measured in bytes.
CHAR_LENGTH()
returns the length of the string measured in characters.
This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:
select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1
As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC
in UTF-8) even though it's only one character.
I suggest you use CSS instead, seems like you're going to repeat those lines later on. But to answer your question:
<html>
<head>
<style type="text/css">
td.randname {
padding-left: 5px;
padding-bottom:3px;
font-size:35px;
}
</style>
</head>
<body>
<table>
<tr>
<td class="randname"> <b>Datum:</b><br/>
November 2010 </td></tr>
</table>
</body>
</html>
An another way is simply :
if($test){
echo "Yes 1";
}
if(!is_null($test)){
echo "Yes 2";
}
$test = "hello";
if($test){
echo "Yes 3";
}
Will return :
"Yes 3"
The best way is to use isset(), otherwise you can have an error like "undefined $test".
You can do it like this :
if( isset($test) && ($test!==null) )
You'll not have any error because the first condition isn't accepted.
You can assign the class name like text-center, left or right. The text will align accordingly to these class name. You don't need to make extra class name separately. These classes are built in BootStrap 3 and bootstrap 4.
<p class="text-left">Left aligned text.</p>
<p class="text-center">Center aligned text.</p>
<p class="text-right">Right aligned text.</p>
<p class="text-justify">Justified text.</p>
<p class="text-nowrap">No wrap text.</p>
<p class="text-xs-left">Left aligned text on all viewport sizes.</p>
<p class="text-xs-center">Center aligned text on all viewport sizes.</p>
<p class="text-xs-right">Right aligned text on all viewport sizes.</p>
<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
<p class="text-md-left">Left aligned text on viewports sized MD (medium) or wider.</p>
<p class="text-lg-left">Left aligned text on viewports sized LG (large) or wider.</p>
<p class="text-xl-left">Left aligned text on viewports sized XL (extra-large) or wider.</p>
This is implemented in Nexus since Version 3.9.0.
You want this - enter N and then take N number of elements.I am considering your input case is just like this
5
2 3 6 6 5
have this in this way in python 3.x (for python 2.x use raw_input()
instead if input()
)
n = int(input())
arr = input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
n = int(raw_input())
arr = raw_input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
using
memset(members, 0, 255);
in general
memset(members, 0, sizeof members);
if the array is in scope, or
memset(members, 0, nMembers * (sizeof members[0]) );
if you only have the pointer value, and nMembers is the number of elements in the array.
EDIT Of course, now the requirement has changed from the generic task of clearing an array to purely resetting a string, memset
is overkill and just zeroing the first element suffices (as noted in other answers).
EDIT In order to use memset, you have to include string.h.
There are three issues here that need to be fixed:
First is that you are expecting synchronous behavior while using stdout asynchronously. All of the calls in your run_cmd
function are asynchronous, so it will spawn the child process and return immediately regardless of whether some, all, or none of the data has been read off of stdout. As such, when you run
console.log(foo.stdout);
you get whatever happens to be stored in foo.stdout at the moment, and there's no guarantee what that will be because your child process might still be running.
Second is that stdout is a readable stream, so 1) the data event can be called multiple times, and 2) the callback is given a buffer, not a string. Easy to remedy; just change
foo = new run_cmd(
'netstat.exe', ['-an'], function (me, data){me.stdout=data;}
);
into
foo = new run_cmd(
'netstat.exe', ['-an'], function (me, buffer){me.stdout+=buffer.toString();}
);
so that we convert our buffer into a string and append that string to our stdout variable.
Third is that you can only know you've received all output when you get the 'end' event, which means we need another listener and callback:
function run_cmd(cmd, args, cb, end) {
// ...
child.stdout.on('end', end);
}
So, your final result is this:
function run_cmd(cmd, args, cb, end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
child.stdout.on('data', function (buffer) { cb(me, buffer) });
child.stdout.on('end', end);
}
// Run C:\Windows\System32\netstat.exe -an
var foo = new run_cmd(
'netstat.exe', ['-an'],
function (me, buffer) { me.stdout += buffer.toString() },
function () { console.log(foo.stdout) }
);
addendum;tested those 3 methods considering performance.
The result, at least in my testing environment:
Curl wins
This test is done under the consideration that only the headers (noBody) is needed. Test yourself:
$url = "http://de.wikipedia.org/wiki/Pinocchio";
$start_time = microtime(TRUE);
$headers = get_headers($url);
echo $headers[0]."<br>";
$end_time = microtime(TRUE);
echo $end_time - $start_time."<br>";
$start_time = microtime(TRUE);
$response = file_get_contents($url);
echo $http_response_header[0]."<br>";
$end_time = microtime(TRUE);
echo $end_time - $start_time."<br>";
$start_time = microtime(TRUE);
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_NOBODY, 1); // and *only* get the header
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
// if($httpCode == 404) {
// /* Handle 404 here. */
// }
echo $httpCode."<br>";
curl_close($handle);
$end_time = microtime(TRUE);
echo $end_time - $start_time."<br>";
I had a similar situation and solved it like this:
WebElement webElement = driver.findElement(By.xpath(""));
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);
100vh works for me, but at first I had used javascript (actually jQuery, but you can adapt it), to tackle a similar problw.
HTML
<body>
<div id="wrapper">
<div id="header">header</div>
<div id="content">content</div>
</div>
</body>
js/jQuery
var innerWindowHeight = $(window).height();
var headerHeight = $("#header").height();
var contentHeight = innerWindowHeight - headerHeight;
$(".content").height(contentHeight + "px");
Alternately, you can just use 111px if you don't want to calculate headerHeight.
Also, you may want to put this in a window resize event, to rerun the script if the window height increases for example.
You can actually change the grey box around the dropdown arrow in IE:
select::-ms-expand {
width:12px;
border:none;
background:#fff;
}
Here is a small code snippet that does the job:
double a = 34.51234;
NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(a));
I've several plugins (including Unicode Character Highlighter), but the only one which found the character that was hiding from me today was Highlighter.
You can test to see if it's working by pasting in the text from the readme.
For reference, the character causing me trouble was ?
.
For a sanity check, tap your right arrow key over a range of text containing an invisible character, and you'll need to right-arrow twice to move past the character.
I'm also using the following custom regex string (which I don't fully grok):
{
// there's an extra range in use [^\\x00-\\x7F]
// also, don't highlight spaces at the end of the line (my settings take care of that)
"highlighter_regex": "(\t+ +)|( +\t+)|[^\\x00-\\x7F]|[\u2026\u2018\u2019\u201c\u201d\u2013\u2014]"
}
Please make use of the code below to display images inline:
<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>
My first contribution to the site. Also, according to the tests that I have done, this code runs faster than all the other methods mentioned here before this date, of course it is minimal if there are few values, but the time increases exponentially when adding too many.
var result = permutations([1,2,3,4]);
var output = window.document.getElementById('output');
output.innerHTML = JSON.stringify(result);
function permutations(arr) {
var finalArr = [];
function iterator(arrayTaken, tree) {
var temp;
for (var i = 0; i < tree; i++) {
temp = arrayTaken.slice();
temp.splice(tree - 1 - i, 0, temp.splice(tree - 1, 1)[0]);
if (tree >= arr.length) {
finalArr.push(temp);
} else {
iterator(temp, tree + 1);
}
}
}
iterator(arr, 1);
return finalArr;
};
_x000D_
<div id="output"></div>
_x000D_
This worked for me:
export _JAVA_OPTIONS="-Xmx1g"
It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:
java -XshowSettings:vm
and it will tell you:
Picked up _JAVA_OPTIONS: -Xmx1g
You can also simply use props to access history object: this.props.history.push('new_url')
With abstract classes you can have some kind of skeleton for other classes to extend.
You can't instantiate them but you can put some common implementation which you can use in the classes that extend them.
The way I do it is to do a Topological Sort, counting the number of vertices visited. If that number is less than the total number of vertices in the DAG, you have a cycle.
A major practical difference is its use:
in security scenario
where we always needed a new session, we should use request.getSession(true)
.
request.getSession(false): will return null if no session found.
The problem may lie in you don't have enabled openssl extention in your php.ini file
go to your php.ini file end remove ;
in line where extension=openssl
is
Of course in question code there is a part of code responsible for checking whether extension is loaded or not but maybe some uncautious forget about it
you can done this way also.
if (dateFormat(first, "yyyy-mm-dd") > dateFormat(second, "yyyy-mm-dd")) {
console.log("done");
}
OR
if (dateFormat(first, "mm-dd-yyyy") > dateFormat(second, "mm-dd-yyyy")) {
console.log("done");
}
i use following plugin for dateFormat()
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
};
// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}
// Passing date through Date applies Date.parse, if necessary
date = date ? new Date(date) : new Date;
if (isNaN(date)) throw SyntaxError("invalid date");
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
flags = {
d: d,
dd: pad(d),
ddd: dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
};
Additional Solution: use Restul api wrapper libraries written in Java
/ python
/ Ruby
- An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.
For documentation and links: Remote Access API
Please look at http://www.tldp.org/LDP/abs/html/parameter-substitution.html for examples
${parameter-default}, ${parameter:-default}
If parameter not set, use default. After the call, parameter is still not set.
Both forms are almost equivalent. The extra :
makes a difference only when parameter has been declared, but is null.
unset EGGS
echo 1 ${EGGS-spam} # 1 spam
echo 2 ${EGGS:-spam} # 2 spam
EGGS=
echo 3 ${EGGS-spam} # 3
echo 4 ${EGGS:-spam} # 4 spam
EGGS=cheese
echo 5 ${EGGS-spam} # 5 cheese
echo 6 ${EGGS:-spam} # 6 cheese
${parameter=default}, ${parameter:=default}
If parameter not set, set parameter value to default.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null
# sets variable without needing to reassign
# colons suppress attempting to run the string
unset EGGS
: ${EGGS=spam}
echo 1 $EGGS # 1 spam
unset EGGS
: ${EGGS:=spam}
echo 2 $EGGS # 2 spam
EGGS=
: ${EGGS=spam}
echo 3 $EGGS # 3 (set, but blank -> leaves alone)
EGGS=
: ${EGGS:=spam}
echo 4 $EGGS # 4 spam
EGGS=cheese
: ${EGGS:=spam}
echo 5 $EGGS # 5 cheese
EGGS=cheese
: ${EGGS=spam}
echo 6 $EGGS # 6 cheese
${parameter+alt_value}, ${parameter:+alt_value}
If parameter set, use alt_value, else use null string. After the call, parameter value not changed.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null
unset EGGS
echo 1 ${EGGS+spam} # 1
echo 2 ${EGGS:+spam} # 2
EGGS=
echo 3 ${EGGS+spam} # 3 spam
echo 4 ${EGGS:+spam} # 4
EGGS=cheese
echo 5 ${EGGS+spam} # 5 spam
echo 6 ${EGGS:+spam} # 6 spam
yes you can. Android kitkat boosts of this functionality here
The %d
and %s
string formatting "commands" are used to format strings. The %d
is for numbers, and %s
is for strings.
For an example:
print("%s" % "hi")
and
print("%d" % 34.6)
To pass multiple arguments:
print("%s %s %s%d" % ("hi", "there", "user", 123456))
will return hi there user123456
Have you tried setting the painted border false?
JButton button = new JButton();
button.setBackground(Color.red);
button.setOpaque(true);
button.setBorderPainted(false);
It works on my mac :)
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
More information can be found at Google Maps API - LatLng
You can use system() or %x[] depending what kind of result you need.
system() returning true if the command was found and ran successfully, false otherwise.
>> s = system 'uptime'
10:56 up 3 days, 23:10, 2 users, load averages: 0.17 0.17 0.14
=> true
>> s.class
=> TrueClass
>> $?.class
=> Process::Status
%x[..] on the other hand saves the results of the command as a string:
>> result = %x[uptime]
=> "13:16 up 4 days, 1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> p result
"13:16 up 4 days, 1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> result.class
=> String
Th blog post by Jay Fields explains in detail the differences between using system, exec and %x[..] .
<font size=1>- font size 1</font><br>
<span style="font-size:0.63em">- font size: 0.63em</span><br>
<font size=2>- font size 2</font><br>
<span style="font-size: 0.82em">- font size: 0.82em</span><br>
<font size=3>- font size 3</font><br>
<span style="font-size: 1.0em">- font size: 1.0em</span><br>
<font size=4>- font size 4</font><br>
<span style="font-size: 1.13em">- font size: 1.13em</span><br>
<font size=5>- font size 5</font><br>
<span style="font-size: 1.5em">- font size: 1.5em</span><br>
<font size=6>- font size 6</font><br>
<span style="font-size: 2em">- font size: 2em</span><br>
<font size=7>- font size 7</font><br>
<span style="font-size: 3em">- font size: 3em</span><br>
Instant.now()
The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Instant
An Instant
represents a moment on the timeline in UTC with a resolution of up to nanoseconds.
Instant instant = Instant.now();
The toString
method generates a String object with text representing the date-time value using one of the standard ISO 8601 formats.
String output = instant.toString();
2016-06-27T19:15:25.864Z
The Instant
class is a basic building-block class in java.time. This should be your go-to class when handling date-time as generally the best practice is to track, store, and exchange date-time values in UTC.
OffsetDateTime
But Instant
has limitations such as no formatting options for generating strings in alternate formats. For more flexibility, convert from Instant
to OffsetDateTime
. Specify an offset-from-UTC. In java.time that means a ZoneOffset
object. Here we want to stick with UTC (+00) so we can use the convenient constant ZoneOffset.UTC
.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
2016-06-27T19:15:25.864Z
Or skip the Instant
class.
OffsetDateTime.now( ZoneOffset.UTC )
Now with an OffsetDateTime
object in hand, you can use DateTimeFormatter
to create String objects with text in alternate formats. Search Stack Overflow for many examples of using DateTimeFormatter
.
ZonedDateTime
When you want to display wall-clock time for some particular time zone, apply a ZoneId
to get a ZonedDateTime
.
In this example we apply Montréal time zone. In the summer, under Daylight Saving Time (DST) nonsense, the zone has an offset of -04:00
. So note how the time-of-day is four hours earlier in the output, 15
instead of 19
hours. Instant
and the ZonedDateTime
both represent the very same simultaneous moment, just viewed through two different lenses.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
2016-06-27T15:15:25.864-04:00[America/Montreal]
While you should avoid the old date-time classes, if you must you can convert using new methods added to the old classes. Here we use java.util.Date.from( Instant )
and java.util.Date::toInstant
.
java.util.Date utilDate = java.util.Date.from( instant );
And going the other direction.
Instant instant= utilDate.toInstant();
Similarly, look for new methods added to GregorianCalendar
(subclass of Calendar
) to convert to and from java.time.ZonedDateTime
.
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
I can see this post was viewed over 46,000 times. I would bet many of the 46,000 viewers are asking this question simply because they just want the file name... and these answers can be a rabbit hole if you cannot make your substring verbatim using the at sign.
If you simply want to get the file name, then there is a simple answer which should be mentioned here. Even if it's not the precise answer to the question.
result = Path.GetFileName(fileName);
see https://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx
Most modern Linux distributions use NetworkManager for this. You could use D-BUS to listen for the events.
If you want a command-line tool to check the status, you can also use mii-tool
, given that you have Ethernet in mind.
I've got this error and I finally solved it with the command below.
restorecon -r /var/www/html
The issue is caused when you mv something from one place to another. It preserves the selinux context of the original when you move it, so if you untar something in /home or /tmp it gets given an selinux context that matches its location. Now you mv that to /var/www/html and it takes the context saying it belongs in /tmp or /home with it and httpd is not allowed by policy to access those files.
If you cp the files instead of mv them, the selinux context gets assigned according to the location you're copying to, not where it's coming from. Running restorecon puts the context back to its default and fixes it too.
The problem with Javascript's MIME type is that there hasn't been a standard for years. Now we've got application/javascript as an official MIME type.
But actually, the MIME type doesn't matter at all, as the browser can determine the type itself. That's why the HTML5 specs state that the type="text/javascript"
is no longer required.
Example code (without exception-handling):
XMLGregorianCalendar xgc =
DatatypeFactory // Data-type converter.
.newInstance() // Instantiate a converter object.
.newXMLGregorianCalendar( // Converter going from `GregorianCalendar` to `XMLGregorianCalendar`.
GregorianCalendar.from( // Convert from modern `ZonedDateTime` class to legacy `GregorianCalendar` class.
LocalDate // Modern class for representing a date-only, without time-of-day and without time zone.
.parse( "2014-01-07" ) // Parsing strings in standard ISO 8601 format is handled by default, with no need for custom formatting pattern.
.atStartOfDay( ZoneOffset.UTC ) // Determine the first moment of the day as seen in UTC. Returns a `ZonedDateTime` object.
) // Returns a `GregorianCalendar` object.
) // Returns a `XMLGregorianCalendar` object.
;
XMLGregorianCalendar
classAvoid the terrible legacy date-time classes whenever possible, such as XMLGregorianCalendar
, GregorianCalendar
, Calendar
, and Date
. Use only modern java.time classes.
When presented with a string such as "2014-01-07"
, parse as a LocalDate
.
LocalDate.parse( "2014-01-07" )
To get a date with time-of-day, assuming you want the first moment of the day, specify a time zone. Let java.time determine the first moment of the day, as it is not always 00:00:00.0 in some zones on some dates.
LocalDate.parse( "2014-01-07" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
This returns a ZonedDateTime
object.
ZonedDateTime zdt =
LocalDate
.parse( "2014-01-07" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
;
zdt.toString() = 2014-01-07T00:00-05:00[America/Montreal]
But apparently, you want the start-of-day as seen in UTC (an offset of zero hours-minutes-seconds). So we specify ZoneOffset.UTC
constant as our ZoneId
argument.
ZonedDateTime zdt =
LocalDate
.parse( "2014-01-07" )
.atStartOfDay( ZoneOffset.UTC )
;
zdt.toString() = 2014-01-07T00:00Z
The Z
on the end means UTC (an offset of zero), and is pronounced “Zulu”.
If you must work with legacy classes, convert to GregorianCalendar
, a subclass of Calendar
.
GregorianCalendar gc = GregorianCalendar.from( zdt ) ;
gc.toString() = java.util.GregorianCalendar[time=1389052800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=0,WEEK_OF_YEAR=2,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]
Apparently, you really need an object of the legacy class XMLGregorianCalendar
. If the calling code cannot be updated to use java.time, convert.
XMLGregorianCalendar xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc )
;
Actually, that code requires a try-catch.
try
{
XMLGregorianCalendar xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
xgc = 2014-01-07T00:00:00.000Z
Putting that all together, with appropriate exception-handling.
// Given an input string such as "2014-01-07", return a `XMLGregorianCalendar` object
// representing first moment of the day on that date as seen in UTC.
static public XMLGregorianCalendar getXMLGregorianCalendar ( String input )
{
Objects.requireNonNull( input );
if( input.isBlank() ) { throw new IllegalArgumentException( "Received empty/blank input string for date argument. Message # 11818896-7412-49ba-8f8f-9b3053690c5d." ) ; }
XMLGregorianCalendar xgc = null;
ZonedDateTime zdt = null;
try
{
zdt =
LocalDate
.parse( input )
.atStartOfDay( ZoneOffset.UTC );
}
catch ( DateTimeParseException e )
{
throw new IllegalArgumentException( "Faulty input string for date does not comply with standard ISO 8601 format. Message # 568db0ef-d6bf-41c9-8228-cc3516558e68." );
}
GregorianCalendar gc = GregorianCalendar.from( zdt );
try
{
xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
Objects.requireNonNull( xgc );
return xgc ;
}
Usage.
String input = "2014-01-07";
XMLGregorianCalendar xgc = App.getXMLGregorianCalendar( input );
Dump to console.
System.out.println( "xgc = " + xgc );
xgc = 2014-01-07T00:00:00.000Z
Do not conflate a date-time value with its textual representation. We parse strings to get a date-time object, and we ask the date-time object to generate a string to represent its value. The date-time object has no ‘format’, only strings have a format.
So shift your thinking into two separate modes: model and presentation. Determine the date-value you have in mind, applying appropriate time zone, as the model. When you need to display that value, generate a string in a particular format as expected by the user.
The Question and other Answers all use old troublesome date-time classes now supplanted by the java.time classes.
Your input string "2014-01-07"
is in standard ISO 8601 format.
The T
in the middle separates date portion from time portion.
The Z
on the end is short for Zulu and means UTC.
Fortunately, the java.time classes use the ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2014-01-07" ) ;
ld.toString(): 2014-01-07
ZonedDateTime
If you want to see the first moment of that day, specify a ZoneId
time zone to get a moment on the timeline, a ZonedDateTime
. The time zone is crucial because the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Never assume the day begins at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day may begin at another time-of-day such as 01:00:00. Let java.time determine the first moment.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
zdt.toString(): 2014-01-07T00:00:00Z
For your desired format, generate a string using the predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME
and then replace the T
in the middle with a SPACE.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " ) ;
2014-01-07 00:00:00
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.
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.
You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:
Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
cout << "Numarul complex este: " << firstComplexNumber << endl;
// ^^^^^^^^^^^^^^^^^^ No need to dereference now
// ...
Complex::distanta(firstComplexNumber, secondComplexNumber);
Some people have asked: how can the singleton return a null pointer? I'm answering that question. (I cannot answer in a comment because I need to post code.)
It may return null in between two events: (1) the class is loaded, and (2) the object of this class is created. Here's an example:
class X {
static X xinstance;
static Y yinstance = Y.yinstance;
X() {xinstance=this;}
}
class Y {
static X xinstance = X.xinstance;
static Y yinstance;
Y() {yinstance=this;}
}
public class A {
public static void main(String[] p) {
X x = new X();
Y y = new Y();
System.out.println("x:"+X.xinstance+" y:"+Y.yinstance);
System.out.println("x:"+Y.xinstance+" y:"+X.yinstance);
}
}
Let's run the code:
$ javac A.java
$ java A
x:X@a63599 y:Y@9036e
x:null y:null
The second line shows that Y.xinstance and X.yinstance are null; they are null because the variables X.xinstance ans Y.yinstance were read when they were null.
Can this be fixed? Yes,
class X {
static Y y = Y.getInstance();
static X theinstance;
static X getInstance() {if(theinstance==null) {theinstance = new X();} return theinstance;}
}
class Y {
static X x = X.getInstance();
static Y theinstance;
static Y getInstance() {if(theinstance==null) {theinstance = new Y();} return theinstance;}
}
public class A {
public static void main(String[] p) {
System.out.println("x:"+X.getInstance()+" y:"+Y.getInstance());
System.out.println("x:"+Y.x+" y:"+X.y);
}
}
and this code shows no anomaly:
$ javac A.java
$ java A
x:X@1c059f6 y:Y@152506e
x:X@1c059f6 y:Y@152506e
BUT this is not an option for the Android Application
object: the programmer does not control the time when it is created.
Once again: the difference between the first example and the second one is that the second example creates an instance if the static pointer is null. But a programmer cannot create the Android application object before the system decides to do it.
UPDATE
One more puzzling example where initialized static fields happen to be null
.
Main.java:
enum MyEnum {
FIRST,SECOND;
private static String prefix="<", suffix=">";
String myName;
MyEnum() {
myName = makeMyName();
}
String makeMyName() {
return prefix + name() + suffix;
}
String getMyName() {
return myName;
}
}
public class Main {
public static void main(String args[]) {
System.out.println("first: "+MyEnum.FIRST+" second: "+MyEnum.SECOND);
System.out.println("first: "+MyEnum.FIRST.makeMyName()+" second: "+MyEnum.SECOND.makeMyName());
System.out.println("first: "+MyEnum.FIRST.getMyName()+" second: "+MyEnum.SECOND.getMyName());
}
}
And you get:
$ javac Main.java
$ java Main
first: FIRST second: SECOND
first: <FIRST> second: <SECOND>
first: nullFIRSTnull second: nullSECONDnull
Note that you cannot move the static variable declaration one line upper, the code will not compile.
brew switch to python3 by default, so if you want to still set python2 as default bin python, running:
brew unlink python && brew link python2 --force
In my experience over the past few months, I've realized that the best way to achieve this is:
class App extends React.Component{
constructor(){
super();
this.state = {
serverResponse: ''
}
}
componentDidMount(){
this.getData();
}
async getData(){
const res = await axios.get('url-to-get-the-data');
const { data } = await res;
this.setState({serverResponse: data})
}
render(){
return(
<div>
{this.state.serverResponse}
</div>
);
}
}
If you are trying to make post request on events such as click, then call getData()
function on the event and replace the content of it like so:
async getData(username, password){
const res = await axios.post('url-to-post-the-data', {
username,
password
});
...
}
Furthermore, if you are making any request when the component is about to load then simply replace async getData()
with async componentDidMount()
and change the render function like so:
render(){
return (
<div>{this.state.serverResponse}</div>
)
}
Alternatively, if generating your markup server-side, you can just fetch and inject. For example, in JSTL you could do this:
<script type="text/javascript">
<c:import url="https://raw.github.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js" />
</script>
They don't allow hotlinking for a reason, so probably bad form if you want to be a good citizen. I'd suggest you cache that javascript and only actually re-fetch periodically as you see fit.
As of Bootstrap 4, you can use the spacing utilities.
Add for instance px-2
in the classes of the nav-item
to increase the padding.
If you use XCode
5 you should do it in a different way.
UIViewController
in UIStoryboard
Identity Inspector
on the right top paneUse Storyboard ID
checkboxStoryboard ID
fieldThen write your code.
// Override point for customization after application launch.
if (<your implementation>) {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"
bundle: nil];
YourViewController *yourController = (YourViewController *)[mainStoryboard
instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
self.window.rootViewController = yourController;
}
return YES;
The trailing quote "
in line 4 is adding a quote "
to the string. It should be removed.
The syntax for line 4 ends with %
The code starts file search from root colon, If I want to start search from a specific directory, to avoid going to that directory every time, where I should put one. I did it like
Sub GetFilePath()
FileSelected = "G:\Audits\A2010"
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
FileSelected = .SelectedItems(1)
End With
ActiveSheet.Range("C14") = FileSelected
End Sub
But it could not start reach from "G:\Audits\A2010"
If you're using WinJS you can change the src
through the Utilities
functions.
WinJS.Utilities.id("pic1").setAttribute("src", searchPic.src);
The Navigation Drawer pattern is officially described in the Android documentation!
Check out the following links:
Roman Nurik (an Android design engineer at Google) has confirmed that the recommended behavior is to not move the Action Bar when opening the drawer (like the YouTube app). See this Google+ post.
I answered this question a while ago, but I'm back to re-emphasize that Prixing has the best fly-out menu out there... by far. It's absolutely beautiful, perfectly smooth, and it puts Facebook, Google+, and YouTube to shame. EverNote is pretty good too... but still not as perfect as Prixing. Check out this series of posts on how the flyout menu was implemented (from none other than the head developer at Prixing himself!).
Adam Powell and Richard Fulcher talk about this at 49:47 - 52:50 in the Google I/O talk titled "Navigation in Android".
To summarize their answer, as of the date of this posting the slide out navigation menu is not officially part of the Android application design standard. As you have probably discovered, there's currently no native support for this feature, but there was talk about making this an addition to an upcoming revision of the support package.
With regards to the YouTube and G+ apps, it does seem odd that they behave differently. My best guess is that the reason the YouTube app fixes the position of the action bar is,
One of the most important navigational options for users using the YouTube app is search, which is performed in the SearchView
in the action bar. It would make sense to make the action bar static in this regard, since it would allow the user to always have the option to search for new videos.
The G+ app uses a ViewPager
to display its content, so making the pull out menu specific to the layout content (i.e. everything under the action bar) wouldn't make much sense. Swiping is supposed to provide a means of navigating between pages, not a means of global navigation. This might be why they decided to do it differently in the G+ app than they did in the YouTube app.
On another note, check out the Google Play app for another version of the "pull out menu" (when you are at the left most page, swipe left and a pull out, "half-page" menu will appear).
You're right in that this isn't very consistent behavior, but it doesn't seem like there is a 100% consensus within the Android team on how this behavior should be implemented yet. I wouldn't be surprised if in the future the apps are updated so that the navigation in both apps are identical (they seemed very keen on making navigation consistent across all Google-made apps in the talk).
One-liner: re.match(r"pattern", string) # No need to compile
import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
... print('Yes')
...
Yes
You can evalute it as bool
if needed
>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True
1) Open code in Xcode
2) Continue with : ionic cordova build ios
This is clearly a problem that a lot of programmers have and to which Google has yet to provide a satisfactory, supported solution.
There are a lot of crossed intentions and misunderstandings floating around posts on this topic, so please read this whole answer before responding.
Below I include a more "refined" and well-commented version of the hack from other answers on this page, also incorporating ideas from these very closely related questions:
Change background color of android menu
How to change the background color of the options menu?
Android: customize application's menu (e.g background color)
http://www.macadamian.com/blog/post/android_-_theming_the_unthemable/
Android MenuItem Toggle Button
Is it possible to make the Android options menu background non-translucent?
http://www.codeproject.com/KB/android/AndroidMenusMyWay.aspx
Setting the menu background to be opaque
I tested this hack on 2.1 (simulator), 2.2 (2 real devices), and 2.3 (2 real devices). I don't have any 3.X tablets to test on yet but will post any needed changes here when/if I do. Given that 3.X tablets use Action Bars instead of Options Menus, as explained here:
http://developer.android.com/guide/topics/ui/menus.html#options-menu
this hack will almost certainly do nothing (no harm and no good) on 3.X tablets.
STATEMENT OF THE PROBLEM (read this before trigger-replying with a negative comment):
The Options menu has vastly different styles on different devices. Pure black with white text on some, pure white with black text on some. I and many other developers wish to control the background color of the Options menu cells as well as the color of the Options menu text.
Certain app developers only need to set the cell background color (not the text color), and they can do this in a cleaner manner using the android:panelFullBackground style described in another answer. However, there is currently no way to control the Options menu text color with styles, and so one can only use this method to change the background to another color that won't make the text "disappear."
We would love to do this with a documented, future-proof solution, but one is simply not available as of Android <= 2.3. So we have to use a solution that works in current versions and is designed to minimize the chances of crashing/breaking in future versions. We want a solution that fails gracefully back to the default behavior if it has to fail.
There are many legitimate reasons why one may need to control the look of Options menus (typically to match a visual style for the rest of the app) so I won't dwell on that.
There is a Google Android bug posted about this: please add your support by starring this bug (note Google discourages "me too" comments: just a star is enough):
http://code.google.com/p/android/issues/detail?id=4441
SUMMARY OF SOLUTIONS SO FAR:
Several posters have suggested a hack involving LayoutInflater.Factory. The suggested hack worked for Android <= 2.2 and failed for Android 2.3 because the hack made an undocumented assumption: that one could call LayoutInflater.getView() directly without currently being inside a call to LayoutInflater.inflate() on the same LayoutInflater instance. New code in Android 2.3 broke this assumption and led to a NullPointerException.
My slightly refined hack below does not rely on this assumption.
Furthermore, the hacks also rely on using an internal, undocumented class name "com.android.internal.view.menu.IconMenuItemView" as a string (not as a Java type). I do not see any way to avoid this and still accomplish the stated goal. However, it is possible to do the hack in a careful way that will fall back if "com.android.internal.view.menu.IconMenuItemView" does not appear on the current system.
Again, understand that this is a hack and by no means am I claiming this will work on all platforms. But we developers are not living in a fantasy academic world where everything has to be by the book: we have a problem to solve and we have to solve it as best we can. For example, it seems unlikely that "com.android.internal.view.menu.IconMenuItemView" will exist on 3.X tablets since they use Action Bars instead of Options Menus.
Finally, some developers have solved this problem by totally suppressing the Android Options Menu and writing their own menu class (see some of the links above). I haven't tried this, but if you have time to write your own View and figure out how to replace Android's view (I'm sure the devil's in the details here) then it might be a nice solution that doesn't require any undocumented hacks.
HACK:
Here is the code.
To use this code, call addOptionsMenuHackerInflaterFactory() ONCE from your activity onCreate() or your activity onCreateOptionsMenu(). It sets a default factory that will affect subsequent creation of any Options Menu. It does not affect Options Menus that have already been created (the previous hacks used a function name of setMenuBackground(), which is very misleading since the function doesn't set any menu properties before it returns).
@SuppressWarnings("rawtypes")
static Class IconMenuItemView_class = null;
@SuppressWarnings("rawtypes")
static Constructor IconMenuItemView_constructor = null;
// standard signature of constructor expected by inflater of all View classes
@SuppressWarnings("rawtypes")
private static final Class[] standard_inflater_constructor_signature =
new Class[] { Context.class, AttributeSet.class };
protected void addOptionsMenuHackerInflaterFactory()
{
final LayoutInflater infl = getLayoutInflater();
infl.setFactory(new Factory()
{
public View onCreateView(final String name,
final Context context,
final AttributeSet attrs)
{
if (!name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView"))
return null; // use normal inflater
View view = null;
// "com.android.internal.view.menu.IconMenuItemView"
// - is the name of an internal Java class
// - that exists in Android <= 3.2 and possibly beyond
// - that may or may not exist in other Android revs
// - is the class whose instance we want to modify to set background etc.
// - is the class we want to instantiate with the standard constructor:
// IconMenuItemView(context, attrs)
// - this is what the LayoutInflater does if we return null
// - unfortunately we cannot just call:
// infl.createView(name, null, attrs);
// here because on Android 3.2 (and possibly later):
// 1. createView() can only be called inside inflate(),
// because inflate() sets the context parameter ultimately
// passed to the IconMenuItemView constructor's first arg,
// storing it in a LayoutInflater instance variable.
// 2. we are inside inflate(),
// 3. BUT from a different instance of LayoutInflater (not infl)
// 4. there is no way to get access to the actual instance being used
// - so we must do what createView() would have done for us
//
if (IconMenuItemView_class == null)
{
try
{
IconMenuItemView_class = getClassLoader().loadClass(name);
}
catch (ClassNotFoundException e)
{
// this OS does not have IconMenuItemView - fail gracefully
return null; // hack failed: use normal inflater
}
}
if (IconMenuItemView_class == null)
return null; // hack failed: use normal inflater
if (IconMenuItemView_constructor == null)
{
try
{
IconMenuItemView_constructor =
IconMenuItemView_class.getConstructor(standard_inflater_constructor_signature);
}
catch (SecurityException e)
{
return null; // hack failed: use normal inflater
}
catch (NoSuchMethodException e)
{
return null; // hack failed: use normal inflater
}
}
if (IconMenuItemView_constructor == null)
return null; // hack failed: use normal inflater
try
{
Object[] args = new Object[] { context, attrs };
view = (View)(IconMenuItemView_constructor.newInstance(args));
}
catch (IllegalArgumentException e)
{
return null; // hack failed: use normal inflater
}
catch (InstantiationException e)
{
return null; // hack failed: use normal inflater
}
catch (IllegalAccessException e)
{
return null; // hack failed: use normal inflater
}
catch (InvocationTargetException e)
{
return null; // hack failed: use normal inflater
}
if (null == view) // in theory handled above, but be safe...
return null; // hack failed: use normal inflater
// apply our own View settings after we get back to runloop
// - android will overwrite almost any setting we make now
final View v = view;
new Handler().post(new Runnable()
{
public void run()
{
v.setBackgroundColor(Color.BLACK);
try
{
// in Android <= 3.2, IconMenuItemView implemented with TextView
// guard against possible future change in implementation
TextView tv = (TextView)v;
tv.setTextColor(Color.WHITE);
}
catch (ClassCastException e)
{
// hack failed: do not set TextView attributes
}
}
});
return view;
}
});
}
Thanks for reading and enjoy!
The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.
To use the yaml module is extremely simple:
import yaml
config = yaml.safe_load(open("path/to/config.yml"))
Many of the Python directory functions are in the os.path
module.
import os
os.path.isdir(d)
Answering my own question.
curl -X GET --basic --user username:password \
https://www.example.com/mobile/resource
curl -X DELETE --basic --user username:password \
https://www.example.com/mobile/resource
curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
-d 'param2_name=param2_value' https://www.example.com/mobile/resource
POSTing a file and additional parameter
curl -X POST -F 'param_name=@/filepath/filename' \
-F 'extra_param_name=extra_param_value' --basic --user username:password \
https://www.example.com/mobile/resource
Instead of doing this:
compile "com.android.support:support-v4:18.0.+"
Do this:
compile 'com.android.support:support-v4:18.0.+'
Worked for me
Postman is the best application to test your APIs !
You can import or export your routes and let him remember all your body requests ! :)
EDIT : This comment is 5 yea's old and deprecated :D
Here's the new Postman App : https://www.postman.com/
You can sets the body's background colour using document.body.style.backgroundColor = "red";
so this can be put into a function that's called when the user clicks.
The next part can be done by using document.getElementByID("divID").style.backgroundColor = "red";
window.setTimeout("yourFunction()",10000);
which calls yourFunction in 10 seconds to change the colour back.
You can use the scales package just for this operation (without loading it with require or library)
scales::percent(m)
My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):
Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".
Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"
Not sure why both were needed. I used this to remove a dependency on glut32.dll.
Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.
Let's consider f(n) > 0
and g(n) > 0
for all n
. It's ok to consider this, because the fastest real algorithm has at least one operation and completes its execution after the start. This will simplify the calculus, because we can use the value (f(n)
) instead of the absolute value (|f(n)|
).
f(n) = O(g(n))
General:
f(n)
0 = lim -------- < 8
n?8 g(n)
For g(n) = n
:
f(n)
0 = lim -------- < 8
n?8 n
Examples:
Expression Value of the limit
------------------------------------------------
n = O(n) 1
1/2*n = O(n) 1/2
2*n = O(n) 2
n+log(n) = O(n) 1
n = O(n*log(n)) 0
n = O(n²) 0
n = O(nn) 0
Counterexamples:
Expression Value of the limit
-------------------------------------------------
n ? O(log(n)) 8
1/2*n ? O(sqrt(n)) 8
2*n ? O(1) 8
n+log(n) ? O(log(n)) 8
f(n) = T(g(n))
General:
f(n)
0 < lim -------- < 8
n?8 g(n)
For g(n) = n
:
f(n)
0 < lim -------- < 8
n?8 n
Examples:
Expression Value of the limit
------------------------------------------------
n = T(n) 1
1/2*n = T(n) 1/2
2*n = T(n) 2
n+log(n) = T(n) 1
Counterexamples:
Expression Value of the limit
-------------------------------------------------
n ? T(log(n)) 8
1/2*n ? T(sqrt(n)) 8
2*n ? T(1) 8
n+log(n) ? T(log(n)) 8
n ? T(n*log(n)) 0
n ? T(n²) 0
n ? T(nn) 0
// Force HTTPS for security
if($_SERVER["HTTPS"] != "on") {
$pageURL = "Location: https://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
header($pageURL);
}
in android 3.1.1 we cant find sync project in tools
so C:\Users\AndroidStudioProjects\projectname\.idea\libraries
remove the files from libraries and sync again
I tried the most popular answers on this page but ran into an issue: the node_modules
directory in my Docker instance would get cached in the the named or unnamed mount point, and later would overwrite the node_modules
directory that was built as part of the Docker build process. Thus, new modules I added to package.json
would not show up in the Docker instance.
Fortunately I found this excellent page which explains what was going on and gives at least 3 ways to work around it: https://burnedikt.com/dockerized-node-development-and-mounting-node-volumes/
I'd also consider using a plain old <rect>
which provides the rx
and ry
attributes
MDN SVG docs <- note the second drawn rect element
Add a View:
Add a controller and action method to call the view:
public ActionResult Index()
{
var users = DataContext.GetUsers();
return View(users);
}
ConvertValue( System.Object o ), then you can branch out by o.GetType() result and up-cast o to the types to work with the value.
You would usually use map for that kind of thing.
buttonsListArr = initialArr.map(buttonInfo => (
<Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button>
);
(key is a necessary prop whenever you do mapping in React. The key needs to be a unique identifier for the generated component)
As a side, I would use an object instead of an array. I find it looks nicer:
initialArr = [
{
id: 1,
color: "blue",
text: "text1"
},
{
id: 2,
color: "red",
text: "text2"
},
];
buttonsListArr = initialArr.map(buttonInfo => (
<Button ... key={buttonInfo.id}>{buttonInfo.text}</Button>
);
Based on the new Android Support Library (and this update), now you should call:
ContextCompat.getColor(context, R.color.name.color);
According to the documentation:
public int getColor (int id)
This method was deprecated in API level 23. Use getColor(int, Theme) instead
It is the same solution for getResources().getColorStateList(id)
:
You have to change it like this:
ContextCompat.getColorStateList(getContext(),id);
EDIT 2019
Regarding ThemeOverlay
use the context of the closest view:
val color = ContextCompat.getColor(
closestView.context,
R.color.name.color
)
So this way you get the right color based on your ThemeOverlay.
Specially needed when in same activity you use different themes, like dark/light theme. If you would like to understand more about Themes and Styles this talk is suggested: Developing Themes with Style
Another simple way I found for using in LAN is
ssh [username@ip] uname -n
If you need to login command line will be
sshpass -p "[password]" ssh [username@ip] uname -n
In Android Studio there is a built-in tool to adjust the color and alpha/opacity value:
Explanation with example:
https://devdeeds.com/how-to-add-custom-color-to-views-in-xml-android-studio-ide/
if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:
select
psat.schemaname,
psat.relname,
pa.attname,
psat.relid
from
pg_catalog.pg_stat_all_tables psat,
pg_catalog.pg_attribute pa
where
psat.relid = pa.attrelid
change schema name:
ALTER SCHEMA "XXXXX" RENAME TO xxxxx;
change table names:
ALTER TABLE xxxxx."AAAAA" RENAME TO aaaaa;
change column names:
ALTER TABLE xxxxx.aaaaa RENAME COLUMN "CCCCC" TO ccccc;
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
I found one way to supply credentials for a https connection on the command line. You just need to specify the complete URL to git pull and include the credentials there:
git pull https://username:[email protected]/my/repository
You do not need to have the repository cloned with the credentials before, this means your credentials don't end up in .git/config
. (But make sure your shell doesn't betray you and stores the command line in a history file.)
I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.
Two ways of solving it:
Get the path you want using native python functions, e.g.:
test = os.getcwd() # In case the path in question is your current directory
print(repr(test))
This makes it platform independent and it now works with .encode
. If this is an option for you, it's the more elegant solution.
If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:
test = 'C:\\Windows\\Users\\alexb\\'
print(repr(test))
public static Method[] getAccessibleMethods(Class clazz) {
List<Method> result = new ArrayList<Method>();
while (clazz != null) {
for (Method method : clazz.getDeclaredMethods()) {
int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
result.add(method);
}
}
clazz = clazz.getSuperclass();
}
return result.toArray(new Method[result.size()]);
}
Use the following:
echo (text here) >> (name here).txt
Ex. echo my name is jeff >> test.txt
test.txt
my name is jeff
You can use it in a script too.
Good afternoon, you could always use a little LINQ to get the selected list items and then do what you want with the results:
var selected = CBLGold.Items.Cast<ListItem>().Where(x => x.Selected);
// work with selected...
There are online tools that simplify this process of sharing, for example https://abbashare.com or https://diawi.com Create an ipa file from xcode with adhoc or inhouse profile, and upload this file on these site. I prefer abbashare because save file on your dropbox and you can delete it whenever you want
Very simple solution and test for JavaScript!
ToBase64 = function (u8) {
return btoa(String.fromCharCode.apply(null, u8));
}
FromBase64 = function (str) {
return atob(str).split('').map(function (c) { return c.charCodeAt(0); });
}
var u8 = new Uint8Array(256);
for (var i = 0; i < 256; i++)
u8[i] = i;
var b64 = ToBase64(u8);
console.debug(b64);
console.debug(FromBase64(b64));
I know this is an old post, but I've been looking for a while and didn't find anything.
I've implemented the JavaScript Flash Detection Library.
It works very well and it is documented for quick use. It literally took me 2 minutes. Here is the code I wrote in the header:
<script src="Scripts/flash_detect.js"></script>
<script type="text/javascript">
if (!FlashDetect.installed) {
alert("Flash is required to enjoy this site.");
} else {
alert("Flash is installed on your Web browser.");
}
</script>
Header Row cells sometimes will not work. This will just return the column Index. It will help in a lot of different ways. I know this is not the answer he is requesting. But this will help for a lot people.
public static int GetColumnIndexByHeaderText(GridView gridView, string columnName)
{
for (int i = 0; i < gridView.Columns.Count ; i++)
{
if (gridView.Columns[i].HeaderText.ToUpper() == columnName.ToUpper() )
{
return i;
}
}
return -1;
}
[UPDATED privacy keys list to iOS 13 - see below]
There is a list of all Cocoa Keys
that you can specify in your Info.plist
file:
(Xcode: Target -> Info -> Custom iOS Target Properties)
iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).
Privacy keys with example description:
Alternatively, you can open Info.plist
as source code:
And add privacy keys like this:
<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>
List of all privacy keys: [UPDATED to iOS 13]
NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription
In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.
I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo
to ${PRODUCT_NAME} need access to the camera to update your avatar
even though the app context was obvious (user tapped on the avatar).
It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.
You can login to mysql and type
mysql> SHOW INNODB STATUS\G
You will have all the output and you should have a better idea of what the error is.
also, you can fetch all data and count in the blade file. for example:
your code in the controller
$posts = Post::all();
return view('post', compact('posts'));
your code in the blade file.
{{ $posts->count() }}
finally, you can see the total of your posts.
to make it in short-hand version by using jQuery
The select all checkbox
<input type="checkbox" id="chkSelectAll">
The children checkbox
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
jQuery
$("#chkSelectAll").on('click', function(){
this.checked ? $(".chkDel").prop("checked",true) : $(".chkDel").prop("checked",false);
})
Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event()
and data pointers to a framework function watch_events()
(for example). When an event happens, your function is called with your data and some event-specific data.
Callbacks are also used in GUI programming. The GTK+ tutorial has a nice section on the theory of signals and callbacks.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.writeqrcode_main, container, false);
// Inflate the layout for this fragment
txt_name = (TextView) view.findViewById(R.id.name);
txt_usranme = (TextView) view.findViewById(R.id.surname);
txt_number = (TextView) view.findViewById(R.id.number);
txt_province = (TextView) view.findViewById(R.id.province);
txt_write = (EditText) view.findViewById(R.id.editText_write);
txt_show1 = (Button) view.findViewById(R.id.buttonShow1);
txt_show1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("Onclick","Onclick");
txt_show1.setVisibility(View.INVISIBLE);
txt_name.setVisibility(View.VISIBLE);
txt_usranme.setVisibility(View.VISIBLE);
txt_number.setVisibility(View.VISIBLE);
txt_province.setVisibility(View.VISIBLE);
}
});
return view;
}
You OK !!!!
i have been working on Apachi Axis1.1 and Axis2.0 and JAX-WS but i would suggest you must JAX-WS because it allow you make wsdl in any format , i was making operation as GetInquiry() in Apache Axis2 it did not allow me to Start Operation name in Upper Case , so i find it not good , so i would suggest you must use JAX-WS
Steps to perform the task:
First, download and install the compiler.
Then, type the C/C++ program and save it.
Then, open the command line and change directory to the particular one where the source file is stored, using cd
like so:
cd C:\Documents and Settings\...
Then, to compile, type in the command prompt:
gcc sourcefile_name.c -o outputfile.exe
Finally, to run the code, type:
outputfile.exe
From your command line, we can see your jupyter server is running normally.The reason you can't access your remote jupyter server is that your remote centos6.5 server's firewall rules block the incoming request from your local browser,i.e. block your tcp:8045 port.
sudo ufw allow 80 # enable http server
sudo ufw allow 443 # enable https server
sudo ufw allow 8045 # enable your tcp:8045 port
then try to access your jupyter again.
Maybe you also need to uncomment and edit that place in your jupyter_notebook_config.py
file:
c.NotebookApp.allow_remote_access = True
and even shut down your VPN if you have one.
Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.
The problem appears to be that you are reinitializing the list to an empty list in each iteration:
while choice != 0:
...
a = []
a.append(s)
Try moving the initialization above the loop so that it is executed only once.
a = []
while choice != 0:
...
a.append(s)
In two way ssl the client asks for servers digital certificate and server ask for the same from the client. It is more secured as it is both ways, although its bit slow. Generally we dont follow it as the server doesnt care about the identity of the client, but a client needs to make sure about the integrity of server it is connecting to.
This is a one line solution.
It will run taskkill only if the process is really running otherwise it will just info that it is not running.
tasklist | find /i "notepad.exe" && taskkill /im notepad.exe /F || echo process "notepad.exe" not running.
This is the output in case the process was running:
notepad.exe 1960 Console 0 112,260 K
SUCCESS: The process "notepad.exe" with PID 1960 has been terminated.
This is the output in case not running:
process "notepad.exe" not running.
Okay, found this one myself. You can use Ctrl+Alt+F9 to accomplish this.
The problem is in the line,
int([x[age1]])
What you want is
x = int(age1)
You also need to convert the int to a string for the output...
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."
The complete script looks like,
name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
x = 0
x = int(age1)
twentyone = 21 - x
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."
I wrote my own FactoryBean which instantiates an ObjectMapper (simplified version):
public class ObjectMapperFactoryBean implements FactoryBean<ObjectMapper>{
@Override
public ObjectMapper getObject() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
return mapper;
}
@Override
public Class<?> getObjectType() {
return ObjectMapper.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
And the usage in the spring configuration:
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
Here's a little function that will do "NATO encoding" for you:
CREATE FUNCTION dbo.NATOEncode (
@String varchar(max)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN (
WITH L1 (N) AS (SELECT 1 UNION ALL SELECT 1),
L2 (N) AS (SELECT 1 FROM L1, L1 B),
L3 (N) AS (SELECT 1 FROM L2, L2 B),
L4 (N) AS (SELECT 1 FROM L3, L3 B),
L5 (N) AS (SELECT 1 FROM L4, L4 C),
L6 (N) AS (SELECT 1 FROM L5, L5 C),
Nums (Num) AS (SELECT Row_Number() OVER (ORDER BY (SELECT 1)) FROM L6)
SELECT
NATOString = Substring((
SELECT
Convert(varchar(max), ' ' + D.Word)
FROM
Nums N
INNER JOIN (VALUES
('A', 'Alpha'),
('B', 'Beta'),
('C', 'Charlie'),
('D', 'Delta'),
('E', 'Echo'),
('F', 'Foxtrot'),
('G', 'Golf'),
('H', 'Hotel'),
('I', 'India'),
('J', 'Juliet'),
('K', 'Kilo'),
('L', 'Lima'),
('M', 'Mike'),
('N', 'November'),
('O', 'Oscar'),
('P', 'Papa'),
('Q', 'Quebec'),
('R', 'Romeo'),
('S', 'Sierra'),
('T', 'Tango'),
('U', 'Uniform'),
('V', 'Victor'),
('W', 'Whiskey'),
('X', 'X-Ray'),
('Y', 'Yankee'),
('Z', 'Zulu'),
('0', 'Zero'),
('1', 'One'),
('2', 'Two'),
('3', 'Three'),
('4', 'Four'),
('5', 'Five'),
('6', 'Six'),
('7', 'Seven'),
('8', 'Eight'),
('9', 'Niner')
) D (Digit, Word)
ON Substring(@String, N.Num, 1) = D.Digit
WHERE
N.Num <= Len(@String)
FOR XML PATH(''), TYPE
).value('.[1]', 'varchar(max)'), 2, 2147483647)
);
This function will work on even very long strings, and performs pretty well (I ran it against a 100,000-character string and it returned in 589 ms). Here's an example of how to use it:
SELECT NATOString FROM dbo.NATOEncode('LD-23DSP-1430');
-- Output: Lima Delta Two Three Delta Sierra Papa One Four Three Zero
I intentionally made it a table-valued function so it could be inlined into a query if you run it against many rows at once, just use CROSS APPLY
or wrap the above example in parentheses to use it as a value in the SELECT
clause (you can put a column name in the function parameter position).
window.fbAsyncInit = function () {_x000D_
FB.init({_x000D_
appId: 'Your-appId',_x000D_
cookie: false, // enable cookies to allow the server to access _x000D_
// the session_x000D_
xfbml: true, // parse social plugins on this page_x000D_
version: 'v2.0' // use version 2.0_x000D_
});_x000D_
};_x000D_
_x000D_
// Load the SDK asynchronously_x000D_
(function (d, s, id) {_x000D_
var js, fjs = d.getElementsByTagName(s)[0];_x000D_
if (d.getElementById(id)) return;_x000D_
js = d.createElement(s); js.id = id;_x000D_
js.src = "//connect.facebook.net/en_US/sdk.js";_x000D_
fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));_x000D_
_x000D_
_x000D_
function fb_login() {_x000D_
FB.login(function (response) {_x000D_
_x000D_
if (response.authResponse) {_x000D_
console.log('Welcome! Fetching your information.... ');_x000D_
//console.log(response); // dump complete info_x000D_
access_token = response.authResponse.accessToken; //get access token_x000D_
user_id = response.authResponse.userID; //get FB UID_x000D_
_x000D_
FB.api('/me', function (response) {_x000D_
var email = response.email;_x000D_
var name = response.name;_x000D_
window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;_x000D_
// used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true); _x000D_
});_x000D_
_x000D_
} else {_x000D_
//user hit cancel button_x000D_
console.log('User cancelled login or did not fully authorize.');_x000D_
_x000D_
}_x000D_
}, {_x000D_
scope: 'email'_x000D_
});_x000D_
}
_x000D_
<!-- custom image -->_x000D_
<a href="#" onclick="fb_login();"><img src="/Public/assets/images/facebook/facebook_connect_button.png" /></a>_x000D_
_x000D_
<!-- Facebook button -->_x000D_
<fb:login-button scope="public_profile,email" onlogin="fb_login();">_x000D_
</fb:login-button>
_x000D_
C#
using System.Text.RegularExpressions;
...
Regex.Match(
input: "Check This String",
pattern: "Regex Pattern",
options: RegexOptions.IgnoreCase)
specifically: options: RegexOptions.IgnoreCase
Find the current path of your global node package installation by following command.
npm list -g --depth=0
Change this path to correct path by following command.
npm set prefix C:\Users\username(Number)\AppData\Roaming\npm\node_modules
It worked for me. Read my previous answer for better understanding.
Code that calls COM object dlls (for example, to read proprietary data files), may work fine in a user interface but hang mysteriously from a service. The reason is that as of .Net 2.0 user interfaces assume STA (thread-safe) while services assume MTA ((before that, services assumed STA). Having to create an STA thread for every COM call in a service can add significant overhead.
If you really want to create a foreign key to a non-primary key, it MUST be a column that has a unique constraint on it.
From Books Online:
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
So in your case if you make AnotherID
unique, it will be allowed. If you can't apply a unique constraint you're out of luck, but this really does make sense if you think about it.
Although, as has been mentioned, if you have a perfectly good primary key as a candidate key, why not use that?
There's a width="400"
on the table, remove it and it will work...
Performing CRUD operations using Dapper is an easy task. I have mentioned the below examples that should help you in CRUD operations.
Code for CRUD:
Method #1: This method is used when you are inserting values from different entities.
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string insertQuery = @"INSERT INTO [dbo].[Customer]([FirstName], [LastName], [State], [City], [IsActive], [CreatedOn]) VALUES (@FirstName, @LastName, @State, @City, @IsActive, @CreatedOn)";
var result = db.Execute(insertQuery, new
{
customerModel.FirstName,
customerModel.LastName,
StateModel.State,
CityModel.City,
isActive,
CreatedOn = DateTime.Now
});
}
Method #2: This method is used when your entity properties have the same names as the SQL columns. So, Dapper being an ORM maps entity properties with the matching SQL columns.
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string insertQuery = @"INSERT INTO [dbo].[Customer]([FirstName], [LastName], [State], [City], [IsActive], [CreatedOn]) VALUES (@FirstName, @LastName, @State, @City, @IsActive, @CreatedOn)";
var result = db.Execute(insertQuery, customerViewModel);
}
Code for CRUD:
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string selectQuery = @"SELECT * FROM [dbo].[Customer] WHERE FirstName = @FirstName";
var result = db.Query(selectQuery, new
{
customerModel.FirstName
});
}
Code for CRUD:
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string updateQuery = @"UPDATE [dbo].[Customer] SET IsActive = @IsActive WHERE FirstName = @FirstName AND LastName = @LastName";
var result = db.Execute(updateQuery, new
{
isActive,
customerModel.FirstName,
customerModel.LastName
});
}
Code for CRUD:
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string deleteQuery = @"DELETE FROM [dbo].[Customer] WHERE FirstName = @FirstName AND LastName = @LastName";
var result = db.Execute(deleteQuery, new
{
customerModel.FirstName,
customerModel.LastName
});
}
In case you had to deal with a lot of subfolders contatining subfolders and other recursive stuff. Small improvment of @Mike L'Angelo:
$mypath = "path_to_folder"
$myacl = Get-Acl $mypath
$myaclentry = "username","FullControl","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force | Set-Acl -AclObject $myacl -Verbose
Verbosity is optional in the last line