I had difficulty with the answers above, potentially because I set the checkStyle warnings to be errors. What did work was SuppressionFilter: http://checkstyle.sourceforge.net/config_filters.html#SuppressionFilter
The drawback of this is that the line range is stored in a separate suppresssions.xml file, so an unfamiliar developer may not immediately make the connection.
Just use the command go run *.go
to execute all the go files in your package!
Here's a nice 2013 update using FastMember from NuGet:
IEnumerable<SomeType> data = ...
DataTable table = new DataTable();
using(var reader = ObjectReader.Create(data)) {
table.Load(reader);
}
This uses FastMember's meta-programming API for maximum performance. If you want to restrict it to particular members (or enforce the order), then you can do that too:
IEnumerable<SomeType> data = ...
DataTable table = new DataTable();
using(var reader = ObjectReader.Create(data, "Id", "Name", "Description")) {
table.Load(reader);
}
Editor's Dis/claimer: FastMember is a Marc Gravell project. It's gold and full-on flies!
Yes, this is pretty much the exact opposite of this one; reflection would suffice - or if you need quicker, HyperDescriptor
in 2.0, or maybe Expression
in 3.5. Actually, HyperDescriptor
should be more than adequate.
For example:
// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for(int i = 0 ; i < props.Count ; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
Now with one line you can make this many many times faster than reflection (by enabling HyperDescriptor
for the object-type T
).
Edit re performance query; here's a test rig with results:
Vanilla 27179
Hyper 6997
I suspect that the bottleneck has shifted from member-access to DataTable
performance... I doubt you'll improve much on that...
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
public class MyData
{
public int A { get; set; }
public string B { get; set; }
public DateTime C { get; set; }
public decimal D { get; set; }
public string E { get; set; }
public int F { get; set; }
}
static class Program
{
static void RunTest(List<MyData> data, string caption)
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
GC.WaitForFullGCComplete();
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < 500; i++)
{
data.ToDataTable();
}
watch.Stop();
Console.WriteLine(caption + "\t" + watch.ElapsedMilliseconds);
}
static void Main()
{
List<MyData> foos = new List<MyData>();
for (int i = 0 ; i < 5000 ; i++ ){
foos.Add(new MyData
{ // just gibberish...
A = i,
B = i.ToString(),
C = DateTime.Now.AddSeconds(i),
D = i,
E = "hello",
F = i * 2
});
}
RunTest(foos, "Vanilla");
Hyper.ComponentModel.HyperTypeDescriptionProvider.Add(
typeof(MyData));
RunTest(foos, "Hyper");
Console.ReadLine(); // return to exit
}
}
Here is a simple example I wrote to convert and convert back using the 2 convert methods, I also checked it with a fixed string
declare @VB1 VARBINARY(500),@VB2 VARBINARY(500),@VB3 VARBINARY(500)
declare @S1 VARCHAR(500)
SET @VB1=HASHBYTES('SHA1','Test')
SET @S1=CONVERT(varchar(500),@VB1,2)
SET @VB2=CONVERT(varbinary(500),@S1,2)
SET @VB3=CONVERT(varbinary(500),'640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA',2)
SELECT @VB1,@S1,@VB2,@VB3
IF @VB1=@VB2 PRINT 'They Match(2)'
IF @VB1=@VB3 PRINT 'They Match(3)'
PRINT str(Len(@VB1))
PRINT str(Len(@S1))
PRINT str(Len(@VB2))
SET @VB1=HASHBYTES('SHA1','Test')
SET @S1=CONVERT(varchar(500),@VB1,1)
SET @VB2=CONVERT(varbinary(500),@S1,1)
SELECT @VB1,@S1,@VB2
IF @VB1=@VB2 PRINT 'They Match(1)'
PRINT str(Len(@VB1))
PRINT str(Len(@S1))
PRINT str(Len(@VB2))
and the output
||| 0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA
(1 row(s) affected)
They Match(2)
They Match(3)
20
40
20
|| 0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA
(1 row(s) affected)
They Match(1)
20
42
20
.equals()
compares the data in a class (assuming the function is implemented).
==
compares pointer locations (location of the object in memory).
==
returns true if both objects (NOT TALKING ABOUT PRIMITIVES) point to the SAME object instance.
.equals()
returns true if the two objects contain the same data equals()
Versus ==
in Java
That may help you.
If you want a deep copy without override while retaining the same obj
reference
obj = _.assign(obj, _.merge(obj, [source]))
HTML Formatting Elements:
HTML also defines special elements for defining text with a special meaning. HTML uses elements like <b> and <i> for formatting output, like bold or italic text.
HTML Bold and Strong Formatting:
The HTML <b> element defines bold text, without any extra importance.
<b>This text is bold</b>
The HTML <strong> element defines strong text, with added semantic "strong" importance.
<strong>This text is strong</strong>
HTML Italic and Emphasized Formatting:
The HTML <i> element defines italic text, without any extra importance.
<i>This text is italic</i>
The HTML <em> element defines emphasized text, with added semantic importance.
<em>This text is emphasized</em>
Kotlin 2020: Very simple method
After dialog.show()
use:
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(requireContext(), R.color.yourColor))
Your key selectors are incorrect. They should take an object of the type of the table in question and return the key to use in the join. I think you mean this:
var query = database.Posts.Join(database.Post_Metas,
post => post.ID,
meta => meta.Post_ID,
(post, meta) => new { Post = post, Meta = meta });
You can apply the where clause afterwards, not as part of the key selector.
Here is a nifty solution with a filter:
app.filter('status', function() {
var statusDict = {
0: "No payment",
1: "Late",
2: "Late",
3: "Some payment made",
4: "Some payment made",
5: "Some payment made",
6: "Late and further taken out"
};
return function(status) {
return statusDict[status] || 'Error';
};
});
Markup:
<div ng-repeat="details in myDataSet">
<p>{{ details.Name }}</p>
<p>{{ details.DOB }}</p>
<p>{{ details.Payment[0].Status | status }}</p>
<p>{{ details.Gender}}</p>
</div>
In Ubuntu for install imap use
sudo apt-get install php-imap
Ubuntu 14.04 and above use
sudo apt-get install php5-imap
And imap by default not enabled by PHP so use this command to enable imap extension
sudo php5enmod imap
Then restart your Apache
sudo service apache2 restart
From: http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40
Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster since it doesn't set a return value if you really want to get down to the nitty gritty.
Expression. print()
behaves like a function in that you can do:
$ret = print "Hello World"
; And $ret
will be 1
. That means that print
can be used as part of a more complex expression where echo cannot. An
example from the PHP Manual:
$b ? print "true" : print "false";
print is also part of the precedence table which it needs to be if it
is to be used within a complex expression. It is just about at the bottom
of the precedence list though. Only ,
AND
OR
XOR
are lower.
echo expression [, expression[,
expression] ... ]
But echo ( expression, expression )
is not valid.
This would be valid: echo ("howdy"),("partner")
; the same as: echo
"howdy","partner"
; (Putting the brackets in that simple example
serves
no purpose since there is no operator precedence issue with a single
term like that.)So, echo without parentheses can take multiple parameters, which get concatenated:
echo "and a ", 1, 2, 3; // comma-separated without parentheses
echo ("and a 123"); // just one parameter with parentheses
print()
can only take one parameter:
print ("and a 123");
print "and a 123";
Just telling my resolution: in my case, the libraries and projects weren't being added automatically to the classpath (i don't know why), even clicking at the "add to build path" option. So I went on run -> run configurations -> classpath and added everything I needed through there.
A little late here, but I've found this to be a common problem worth a custom directive to handle. Here's how that might look:
.directive('toggleOnHover', function(){
return {
restrict: 'A',
link: link
};
function link(scope, elem, attrs){
elem.on('mouseenter', applyToggleExp);
elem.on('mouseleave', applyToggleExp);
function applyToggleExp(){
scope.$apply(attrs.toggleOnHover);
}
}
});
You can use it like this:
<li toggle-on-hover="editableProp = !editableProp">edit</li>
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
I had a similar issue, I was using the ViewBag and Element name as same. (Typing mistake)
One more way is to extend the application (as my application was to inherit and customize the parent). It invokes the parent and its commandlinerunner automatically.
@SpringBootApplication
public class ChildApplication extends ParentApplication{
public static void main(String[] args) {
SpringApplication.run(ChildApplication.class, args);
}
}
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
For prevent form from submittion you only need to do this.
<form onsubmit="event.preventDefault()">
.....
</form>
By using above code this will prevent your form submittion.
when do you call timerReset()? Perhaps you get that error when trying to call it after setTimeout() has already done its thing?
wrap it in
if (window.myTimeout) {
clearTimeout(myTimeout);
myTimeout = setTimeout("timerDone()", 1000 * 1440);
}
edit: Actually, upon further reflection, since you did mention jQuery (and yet don't have any actual jQuery code here... I wonder if you have this nested within some jQuery (like inside a $(document).ready(..
and this is a matter of variable scope. If so, try this:
window.message="Logged in";
window.myTimeout = setTimeout("timerDone()",1000 * 1440);
function timerDone()
{
window.message="Logged out";
}
function timerReset()
{
clearTimeout(window.myTimeout);
window.myTimeout = setTimeout("timerDone()", 1000 * 1440);
}
For php 5.3+
you can use the SplFileInfo()
class
$spl = new SplFileInfo($filename);
print_r($spl->getExtension()); //gives extension
Also since you are checking extension for file uploads, I highly recommend using the mime type instead..
For php 5.3+
use the finfo
class
$finfo = new finfo(FILEINFO_MIME);
print_r($finfo->buffer(file_get_contents($file name));
Put the environment variables into the global /etc/environment
file:
...
export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun
...
Execute "source /etc/environment" in every shell where you want the variables to be updated:
$ source /etc/environment
Check that it works:
$ echo $JAVA_HOME
$ /usr/lib/jvm/java-1.5.0-sun
Great, no logout needed.
If you want to set JAVA_HOME environment variable in only the terminal, set it in ~/.bashrc file.
val() is more like a shortcut for attr('value'). For your usage use text() or html() instead
I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even
SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;
Here is the code with line 156, it has try and catch above it
/// <summary>
/// Execute a SQL Query statement, using the default SQL connection for the application
/// </summary>
/// <param name="query">SQL query to execute</param>
/// <returns>DataTable of results</returns>
public static DataTable Query(string query)
{
DataTable results = new DataTable();
string configConnectionString = "ApplicationServices";
System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
System.Configuration.ConnectionStringSettings connString;
if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];
if (connString != null)
{
try
{
using (SqlConnection conn = new SqlConnection(connString.ToString()))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
dataAdapter.Fill(results);
return results;
}
catch (Exception ex)
{
throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
}
}
else
{
throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
}
}
else
{
throw new SqlException(string.Format("No connection strings found in Web.config file."));
}
}
What solves my problem: I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...
The above answer is good, but if you need a version that can operate along different axes, here's a working implementation.
def entropy(A, axis=None):
"""Computes the Shannon entropy of the elements of A. Assumes A is
an array-like of nonnegative ints whose max value is approximately
the number of unique values present.
>>> a = [0, 1]
>>> entropy(a)
1.0
>>> A = np.c_[a, a]
>>> entropy(A)
1.0
>>> A # doctest: +NORMALIZE_WHITESPACE
array([[0, 0], [1, 1]])
>>> entropy(A, axis=0) # doctest: +NORMALIZE_WHITESPACE
array([ 1., 1.])
>>> entropy(A, axis=1) # doctest: +NORMALIZE_WHITESPACE
array([[ 0.], [ 0.]])
>>> entropy([0, 0, 0])
0.0
>>> entropy([])
0.0
>>> entropy([5])
0.0
"""
if A is None or len(A) < 2:
return 0.
A = np.asarray(A)
if axis is None:
A = A.flatten()
counts = np.bincount(A) # needs small, non-negative ints
counts = counts[counts > 0]
if len(counts) == 1:
return 0. # avoid returning -0.0 to prevent weird doctests
probs = counts / float(A.size)
return -np.sum(probs * np.log2(probs))
elif axis == 0:
entropies = map(lambda col: entropy(col), A.T)
return np.array(entropies)
elif axis == 1:
entropies = map(lambda row: entropy(row), A)
return np.array(entropies).reshape((-1, 1))
else:
raise ValueError("unsupported axis: {}".format(axis))
Using jQuery you can do exactly the same thing, for example:
$("a").click();
Which will "click" all anchors on the page.
From the documentation:
Returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.
So you have done everything right, but there is no phone number stored.
If you get null
, you could display something to get the user to input the phone number on his/her own.
I believe this will do the trick:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
After some googling, I came across ng2-search-filter
. In will take your object and apply the search term against all object properties looking for a match.
No worries, Agreed with the above answers:
But for Private project, please follow the steps for Gitlab:
You will be asked to type your project name
This action can lead to data loss. To prevent accidental actions we ask you to confirm your intention. Please type 'sample_project' to proceed or close this modal to cancel.
Now your project is deleted successfully.
The right shift logical operator (>>> N
) shifts bits to the right by N positions, discarding the sign bit and padding the N left-most bits with 0's. For example:
-1 (in 32-bit): 11111111111111111111111111111111
after a >>> 1
operation becomes:
2147483647: 01111111111111111111111111111111
The right shift arithmetic operator (>> N
) also shifts bits to the right by N positions, but preserves the sign bit and pads the N left-most bits with 1's. For example:
-2 (in 32-bit): 11111111111111111111111111111110
after a >> 1
operation becomes:
-1: 11111111111111111111111111111111
Call the parent method with the parent scope resolution operator.
Parent::method()
class Primate {
public:
void whatAmI(){
cout << "I am of Primate order";
}
};
class Human : public Primate{
public:
void whatAmI(){
cout << "I am of Human species";
}
void whatIsMyOrder(){
Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
}
};
Exec the query in TOAD or SQL DEVELOPER
---select /*csv*/ username, user_id, created from all_users;
Save in .SQL format in "C" drive
--- x.sql
execute command
---- set serveroutput on
spool y.csv
@c:\x.sql
spool off;
The height is a 100% unsure, try putting display: block; or display: inline-block;
Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.
Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.
The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
template: function(element, attrs) {
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
return htmlText;
}
compile: function(element, attrs)
{
//do whatever else is necessary
}
}
})
Solve problem with two method parse common
public <T> T jsonToObject(String json, Class<T> type) {
T target = null;
try {
target = objectMapper.readValue(json, type);
} catch (Jsenter code hereonProcessingException e) {
e.printStackTrace();
}
return target;
}
public <T> T jsonToObject(String json, TypeReference<T> type) {
T target = null;
try {
target = objectMapper.readValue(json, type);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return target;
}
This is a version of Ben James's answer, above:
>>> import datetime
>>> x = datetime.date.today()
>>> print x
2013-01-11
>>>
>>>
>>> print "Today's date is %s ..." % x
Today's date is 2013-01-11 ...
>>>
>>> print "Today's date is %r ..." % x
Today's date is datetime.date(2013, 1, 11) ...
>>>
When I ran this, it helped me see the usefulness of %r.
The Sean's solution didn't work for me initially (Android 4.2.2). I had to add a dummy activity to the same Android project and run the activity manually on the device at least once. Then the Sean's solution started to work and the BroadcastReceiver was notified after subsequent reboots.
Instead of checking, just perform the action (web request, mail, ftp, etc.) and be prepared for the request to fail, which you have to do anyway, even if your check was successful.
Consider the following:
1 - check, and it is OK
2 - start to perform action
3 - network goes down
4 - action fails
5 - lot of good your check did
If the network is down your action will fail just as rapidly as a ping, etc.
1 - start to perform action
2 - if the net is down(or goes down) the action will fail
try to change this solved my issue, you may other graphics options, and change to a lower resolution model
You can do something like this (add access modifiers as required):
Map<String,Map<String,String>> complexMap=new HashMap<String,Map<String,String>>();
You can insert data like this:
Map<String,String> componentMap = new HashMap<String,String>();
componentMap.put("foo","bar");
componentMap.put("secondFoo","secondBar");
complexMap.put("superFoo",componentMap);
The Generated Data Structure would be:
{superFoo={secondFoo=secondBar, foo=bar}}
This way each value for the key should have a unique identifier. Also gives O(1) for fetches,if keys are known.
Start each row with \"-\" to create bullet list.
It is easier to use UseWaitCursor at the Form or Window level. A typical use case can look like below:
private void button1_Click(object sender, EventArgs e)
{
try
{
this.Enabled = false;//optional, better target a panel or specific controls
this.UseWaitCursor = true;//from the Form/Window instance
Application.DoEvents();//messages pumped to update controls
//execute a lengthy blocking operation here,
//bla bla ....
}
finally
{
this.Enabled = true;//optional
this.UseWaitCursor = false;
}
}
For a better UI experience you should use Asynchrony from a different thread.
You are giving colour to the background and then expecting it to be transparent?
Remove background-color: #D8F0DA
,
If you want #D8F0DA to be the colour of text, use color: #D8F0DA
You can also try ghex2 GNOME utilities. This give you the automated hex-to-ASCII on the side, as well as the various character/integer decodes at the bottom.
(source: googlepages.com)
Try like this
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= '2013-12-04'
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
Value 127 is returned by /bin/sh
when the given command is not found within your PATH
system variable and it is not a built-in shell command. In other words, the system doesn't understand your command, because it doesn't know where to find the binary you're trying to call.
There are many answers recommend to use: Array.prototype.push(a, b)
. It's nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.
See What is the most efficient way to concatenate N arrays? for more details.
I answered a virtually identical question just the other day: Save CSV files into mysql database
MySQL has a feature LOAD DATA INFILE
, which allows it to import a CSV file directly in a single SQL query, without needing it to be processed in a loop via your PHP program at all.
Simple example:
<?php
$query = <<<eof
LOAD DATA INFILE '$fileName'
INTO TABLE tableName
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(field1,field2,field3,etc)
eof;
$db->query($query);
?>
It's as simple as that.
No loops, no fuss. And much much quicker than parsing it in PHP.
MySQL manual page here: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Hope that helps
You can also look at the Date.getTime() API. That gives a long to which you can add your increment. Then create a new Date.
List<Date> dates = new ArrayList<Date>();
long interval = 1000 * 60 * 60; // 1 hour in millis
long endtime = ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
and maybe apache commons has something like this in DateUtils, or perhaps they have a CalendarUtils too :)
EDIT
including the start and enddate may not be possible if your interval is not perfect :)
Why not just take the base-10 log of the absolute value of the number, round it down, and add one? This works for positive and negative numbers that aren't 0, and avoids having to use any string conversion functions.
The log10
, abs
, and floor
functions are provided by math.h
. For example:
int nDigits = floor(log10(abs(the_integer))) + 1;
You should wrap this in a clause ensuring that the_integer != 0
, since log10(0)
returns -HUGE_VAL
according to man 3 log
.
Additionally, you may want to add one to the final result if the input is negative, if you're interested in the length of the number including its negative sign.
int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;
N.B. The floating-point nature of the calculations involved in this method may cause it to be slower than a more direct approach. See the comments for Kangkan's answer for some discussion of efficiency.
You are not initializing your String[]
. You either need to initialize it using the exact array size, as suggested by @Tr?nSiLong, or use a List<String>
and then convert to a String[]
(in case you do not know the length):
String[] title = {
"Abundance",
"Anxiety",
"Bruxism",
"Discipline",
"Drug Addiction"
};
String urlbase = "http://www.somewhere.com/data/";
String imgSel = "/logo.png";
List<String> mStrings = new ArrayList<String>();
for(int i=0;i<title.length;i++) {
mStrings.add(urlbase + title[i].toLowerCase() + imgSel);
System.out.println(mStrings[i]);
}
String[] strings = new String[mStrings.size()];
strings = mStrings.toArray(strings);//now strings is the resulting array
For me, this simply works:
error: function(xhr, status, error) {
alert(xhr.responseText);
}
According to the select_list Oracle select documentation the AS is optional.
As a personal note I think it is easier to read with the AS
I got this error after using $.getJSON() from JQuery. I just changed to post:
data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
.done(function (response) {
if (response instanceof Object)
var json = response;
else
var json = $.parseJSON(response);
// console.log(response);
// console.log(json);
jsonToDom(json);
if (json.reload != undefined && json.reload)
location.reload();
$("body").delay(1000).css("cursor", "default");
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
alert("Fehler!");
});
In case of SSL connections this may be caused by issue in older versions of nginx server that segfault during curl and Safari requests. This bug was fixed around version 1.10 of nginx but there is still a lot of older versions of nginx on the internet.
For nginx admins: adding ssl_session_cache shared:SSL:1m;
to http
block should solve the problem.
I'm aware that OP was asking for non-SSL case but since this is the top page in goole for "empty reply from server" issue, I'm leaving the SSL answer here as I was one of many that was banging my head against the wall with this issue.
I use it all the time in my coding.
The -ansi
flag is equivalent to -std=c89
. As noted, it turns off some extensions of GCC. Adding -pedantic
turns off more extensions and generates more warnings. For example, if you have a string literal longer than 509 characters, then -pedantic
warns about that because it exceeds the minimum limit required by the C89 standard. That is, every C89 compiler must accept strings of length 509; they are permitted to accept longer, but if you are being pedantic, it is not portable to use longer strings, even though a compiler is permitted to accept longer strings and, without the pedantic warnings, GCC will accept them too.
Optimising @Don approach to use only One Query
SELECT * from (
SELECT
@rownum:=@rownum+1 row,
CASE a.id WHEN 'CurrentArticleID' THEN @currentrow:=@rownum ELSE NULL END as 'current_row',
a.*
FROM articles a,
(SELECT @currentrow:=0) c,
(SELECT @rownum:=0) r
ORDER BY `date`, id DESC
) as article_with_row
where row > @currentrow - 2
limit 3
change CurrentArticleID with current article ID like
SELECT * from (
SELECT
@rownum:=@rownum+1 row,
CASE a.id WHEN '100' THEN @currentrow:=@rownum ELSE NULL END as 'current_row',
a.*
FROM articles a,
(SELECT @currentrow:=0) c,
(SELECT @rownum:=0) r
ORDER BY `date`, id DESC
) as article_with_row
where row > @currentrow - 2
limit 3
It's pretty pointless to return a const
value from a function.
It's difficult to get it to have any effect on your code:
const int foo() {
return 3;
}
int main() {
int x = foo(); // copies happily
x = 4;
}
and:
const int foo() {
return 3;
}
int main() {
foo() = 4; // not valid anyway for built-in types
}
// error: lvalue required as left operand of assignment
Though you can notice if the return type is a user-defined type:
struct T {};
const T foo() {
return T();
}
int main() {
foo() = T();
}
// error: passing ‘const T’ as ‘this’ argument of ‘T& T::operator=(const T&)’ discards qualifiers
it's questionable whether this is of any benefit to anyone.
Returning a reference is different, but unless Object
is some template parameter, you're not doing that.
This will help you.
import java.nio.ByteBuffer;
import java.util.Arrays;
public class MyClass
{
public static void main(String args[]) {
byte [] hbhbytes = ByteBuffer.allocate(4).putInt(16666666).array();
System.out.println(Arrays.toString(hbhbytes));
}
}
You can think of internal conversion of that as a multiple statements;
i++;
you can think it as,
i;
i = i+1;
++i;
you can think it as,
i = i+i;
i;
Here is the code to set up a MediaPlayer
to play off of the SD card:
String PATH_TO_FILE = "/sdcard/music.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();
mediaPlayer.start()
You can see the full example here. Let me know if you have any problems.
please try following to generate
function addRow()
{
var e1 = document.createElement("input");
e1.type = "text";
e1.name = "name1";
var cont = document.getElementById("content")
cont.appendChild(e1);
}
Although it does not seem to be the case for your situation, sometimes a connection refused error can also indicate that there is an ip address conflict on your network. You can search for possible ip conflicts by running:
arp-scan -I eth0 -l | grep <ipaddress>
and
arping <ipaddress>
This AskUbuntu question has some more information also.
As pointed out, you cannot set arbitrary inline styles for hover, but you can change the style of the hover cursor in CSS using the following in the appropriate tag:
style="cursor: pointer;"
Build solution only builds those projects which have changed in the solution, and does not effect assemblies that have not changed,
ReBuild first cleans, all the assemblies from the solution and then builds entire solution regardless of changes done.
Clean, simply cleans the solution.
Check out the ColumnComparator. It is basically the same solution as proposed by Costi, but it also supports sorting on columns in a List and has a few more sort properties.
Switch to Branch2
git checkout Branch2
Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:
git rebase Branch1
Which would leave you with the desired result in Branch2:
a -- b -- c <-- Master
\
d -- e <-- Branch1
\
d -- e -- f' -- g' <-- Branch2
You can delete Branch1.
EDIT: While this is currently accepted answer, readers might find this other answer by user John Hart more adapted to their needs. It uses an option which, according to user Ken, was introduced in version 7.21.3 (which was released in December 2010, i.e. after this initial answer).
In your edited question, you're using the URL as the host name, whereas it needs to be the host name only.
Try:
curl -H 'Host: project1.loc' http://127.0.0.1/something
where project1.loc
is just the host name and 127.0.0.1
is the target IP address.
(If you're using curl from a library and not on the command line, make sure you don't put http://
in the Host
header.)
If you use it in a database, this is a good way:
Set the ip field in database to varchar(250), and then use this:
$theip = $_SERVER["REMOTE_ADDR"];
if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$theip .= '('.$_SERVER["HTTP_X_FORWARDED_FOR"].')';
}
if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
$theip .= '('.$_SERVER["HTTP_CLIENT_IP"].')';
}
$realip = substr($theip, 0, 250);
Then you just check $realip against the database ip field
I was able to solve this problem by executing this statement
sudo dpkg-reconfigure mysql-server-5.5
Which will change the root password.
There is a handy HAProxy wrapper.
docker run -it -p LOCALPORT:PROXYPORT --rm --link TARGET_CONTAINER:EZNAME -e "BACKEND_HOST=EZNAME" -e "BACKEND_PORT=PROXYPORT" demandbase/docker-tcp-proxy
This creates an HAProxy to the target container. easy peasy.
This did the trick for me:
var express = require('express'),
app = express();
app.use('/', express.static(__dirname + '/'));
app.listen(8080);
select t.name as TriggerName,m.definition,is_disabled
from sys.all_sql_modules m
inner join
sys.triggers t
on m.object_id = t.object_id
inner join sys.objects o
on o.object_id = t.parent_id
Where o.name = 'YourTableName'
This will give you all triggers on a Specified Table
Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not.
class Explicit() {
Explicit() {
super();
}
}
class Implicit {
Implicit() {
}
}
nflog is better
sudo apt-get -y install ulogd2
ICMP Block rule example:
iptables=/sbin/iptables
# Drop ICMP (PING)
$iptables -t mangle -A PREROUTING -p icmp -j NFLOG --nflog-prefix 'ICMP Block'
$iptables -t mangle -A PREROUTING -p icmp -j DROP
And you can search prefix "ICMP Block" in log:
/var/log/ulog/syslogemu.log
In C# 5.0, this problem is fixed and you can close over loop variables and get the results you expect.
The language specification says:
8.8.4 The foreach statement
(...)
A foreach statement of the form
foreach (V v in x) embedded-statement
is then expanded to:
{ E e = ((C)(x)).GetEnumerator(); try { while (e.MoveNext()) { V v = (V)(T)e.Current; embedded-statement } } finally { … // Dispose e } }
(...)
The placement of
v
inside the while loop is important for how it is captured by any anonymous function occurring in the embedded-statement. For example:int[] values = { 7, 9, 13 }; Action f = null; foreach (var value in values) { if (f == null) f = () => Console.WriteLine("First value: " + value); } f();
If
v
was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value,13
, which is what the invocation off
would print. Instead, because each iteration has its own variablev
, the one captured byf
in the first iteration will continue to hold the value7
, which is what will be printed. (Note: earlier versions of C# declaredv
outside of the while loop.)
Use this:
lWebView.setWebViewClient(new WebViewClient());
Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
import android.net.Uri;
Uri uri = Uri.parse("http://example.com/foo/bar/42?param=true");
String token = uri.getLastPathSegment();
Try this
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.custom_actionbar, menu);
menu.setGroupVisible(...);
}
There are different ways to do that.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],
'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })
def getMonth(s): return s.split("-")[1] def getDay(s): return s.split("-")[0] def getYear(s): return s.split("-")[2] def getYearMonth(s): return s.split("-")[1]+"-"+s.split("-")[2]
year
, month
, day
and 'yearMonth
'. In your case, you need one of both. You can group using two columns 'year','month'
or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x)) df['month']= df['Date'].apply(lambda x: getMonth(x)) df['day']= df['Date'].apply(lambda x: getDay(x)) df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
3 20-Jan-14 25 15 14 Jan 20 Jan-14
4 21-Feb-14 60 80 14 Feb 21 Feb-14
In this case, we are grouping by two columns:
for key,g in df.groupby(['year','month']): print key,g
Output:
('13', 'Jun') Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
('13', 'Aug') Date abc xyz year month day YearMonth
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
('14', 'Jan') Date abc xyz year month day YearMonth
3 20-Jan-14 25 15 14 Jan 20 Jan-14
('14', 'Feb') Date abc xyz year month day YearMonth
In this case, we are grouping by one column:
for key,g in df.groupby(['YearMonth']): print key,g
Output:
Jun-13 Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
Aug-13 Date abc xyz year month day YearMonth
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
Jan-14 Date abc xyz year month day YearMonth
3 20-Jan-14 25 15 14 Jan 20 Jan-14
Feb-14 Date abc xyz year month day YearMonth
4 21-Feb-14 60 80 14 Feb 21 Feb-14
get_group
print df.groupby(['YearMonth']).get_group('Jun-13')
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
get_group
. This hack would help to filter values and get the grouped values.This also would give the same result.
print df[df['YearMonth']=='Jun-13']
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
You can select list of abc
or xyz
values during Jun-13
print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values
Output:
[100 -20] #abc values
[200 50] #xyz values
You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.
for x in set(df.YearMonth):
print df[df['YearMonth']==x].abc.values
print df[df['YearMonth']==x].xyz.values
I recommend also to check this answer as well.
You can also Right Click on the table, choose modify, then go to the attribute, right click on it, and choose drop primary key.
I know this is a pretty old question, but I dealt with this recently. Let me know what you think of this solution.
I created a utility that lets me strongly type arguments and let them be optional. You basically wrap your function in a proxy. If you skip an argument, it's undefined. It may get quirky if you have multiple optional arguments with the same type right next to each other. (There are options to pass functions instead of types to do custom argument checks, as well as specifying default values for each parameter.)
This is what the implementation looks like:
function displayOverlay(/*message, timeout, callback*/) {
return arrangeArgs(arguments, String, Number, Function,
function(message, timeout, callback) {
/* ... your code ... */
});
};
For clarity, here is what is going on:
function displayOverlay(/*message, timeout, callback*/) {
//arrangeArgs is the proxy
return arrangeArgs(
//first pass in the original arguments
arguments,
//then pass in the type for each argument
String, Number, Function,
//lastly, pass in your function and the proxy will do the rest!
function(message, timeout, callback) {
//debug output of each argument to verify it's working
console.log("message", message, "timeout", timeout, "callback", callback);
/* ... your code ... */
}
);
};
You can view the arrangeArgs proxy code in my GitHub repository here:
https://github.com/joelvh/Sysmo.js/blob/master/sysmo.js
Here is the utility function with some comments copied from the repository:
/*
****** Overview ******
*
* Strongly type a function's arguments to allow for any arguments to be optional.
*
* Other resources:
* http://ejohn.org/blog/javascript-method-overloading/
*
****** Example implementation ******
*
* //all args are optional... will display overlay with default settings
* var displayOverlay = function() {
* return Sysmo.optionalArgs(arguments,
* String, [Number, false, 0], Function,
* function(message, timeout, callback) {
* var overlay = new Overlay(message);
* overlay.timeout = timeout;
* overlay.display({onDisplayed: callback});
* });
* }
*
****** Example function call ******
*
* //the window.alert() function is the callback, message and timeout are not defined.
* displayOverlay(alert);
*
* //displays the overlay after 500 miliseconds, then alerts... message is not defined.
* displayOverlay(500, alert);
*
****** Setup ******
*
* arguments = the original arguments to the function defined in your javascript API.
* config = describe the argument type
* - Class - specify the type (e.g. String, Number, Function, Array)
* - [Class/function, boolean, default] - pass an array where the first value is a class or a function...
* The "boolean" indicates if the first value should be treated as a function.
* The "default" is an optional default value to use instead of undefined.
*
*/
arrangeArgs: function (/* arguments, config1 [, config2] , callback */) {
//config format: [String, false, ''], [Number, false, 0], [Function, false, function(){}]
//config doesn't need a default value.
//config can also be classes instead of an array if not required and no default value.
var configs = Sysmo.makeArray(arguments),
values = Sysmo.makeArray(configs.shift()),
callback = configs.pop(),
args = [],
done = function() {
//add the proper number of arguments before adding remaining values
if (!args.length) {
args = Array(configs.length);
}
//fire callback with args and remaining values concatenated
return callback.apply(null, args.concat(values));
};
//if there are not values to process, just fire callback
if (!values.length) {
return done();
}
//loop through configs to create more easily readable objects
for (var i = 0; i < configs.length; i++) {
var config = configs[i];
//make sure there's a value
if (values.length) {
//type or validator function
var fn = config[0] || config,
//if config[1] is true, use fn as validator,
//otherwise create a validator from a closure to preserve fn for later use
validate = (config[1]) ? fn : function(value) {
return value.constructor === fn;
};
//see if arg value matches config
if (validate(values[0])) {
args.push(values.shift());
continue;
}
}
//add a default value if there is no value in the original args
//or if the type didn't match
args.push(config[2]);
}
return done();
}
Intellij IDEA 15: File->Project Structure...->Project Settings->Libraries
The Following Android Classes uses Design Patterns
1) View Holder uses Singleton Design Pattern
2) Intent uses Factory Design Pattern
3) Adapter uses Adapter Design Pattern
4) Broadcast Receiver uses Observer Design Pattern
5) View uses Composite Design Pattern
6) Media FrameWork uses Façade Design Pattern
A convenient way would be boost's string algorithms library.
#include <boost/algorithm/string/classification.hpp> // Include boost::for is_any_of
#include <boost/algorithm/string/split.hpp> // Include for boost::split
// ...
std::vector<std::string> words;
std::string s;
boost::split(words, s, boost::is_any_of(", "), boost::token_compress_on);
Just treat the ES6 class name the same as you would have treated the constructor name in the ES5 way. They are one and the same.
The ES6 syntax is just syntactic sugar and creates exactly the same underlying prototype, constructor function and objects.
So, in your ES6 example with:
// animal.js
class Animal {
...
}
var a = new Animal();
module.exports = {Animal: Animal};
You can just treat Animal
like the constructor of your object (the same as you would have done in ES5). You can export the constructor. You can call the constructor with new Animal()
. Everything is the same for using it. Only the declaration syntax is different. There's even still an Animal.prototype
that has all your methods on it. The ES6 way really does create the same coding result, just with fancier/nicer syntax.
On the import side, this would then be used like this:
const Animal = require('./animal.js').Animal;
let a = new Animal();
This scheme exports the Animal constructor as the .Animal
property which allows you to export more than one thing from that module.
If you don't need to export more than one thing, you can do this:
// animal.js
class Animal {
...
}
module.exports = Animal;
And, then import it with:
const Animal = require('./animal.js');
let a = new Animal();
This issue only happens in Android emulators. I also faced this issue in an emulator but when I checked in a device then it worked fine.
So please check in a device. It may be run in device.
My solution, to only hide the navigation bar, is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final View decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener (new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
});
}
@Override
protected void onResume() {
super.onResume();
final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
final View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(uiOptions);
}
Just change your port,might be your current port is in use by iis or some other server.
Your IDs are #1
, and cycle
just wants a number passed to it. You need to remove the #
before calling cycle
.
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('#', ''));
return false;
});
Also, IDs shouldn't contain the #
character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1
.
<a href="#" id="pager_1" class="pagerlink" >link</a>
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('pager_', ''));
return false;
});
If you're using the public API, the best way to do it is using if
statements.
If the video is public or unlisted, you set the thumbnail using the URL method. If the video is private you use the API to get the thumbnail.
<?php
if($video_status == 'unlisted'){
$video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
$video_status = '<i class="fa fa-lock"></i> Unlisted';
}
elseif($video_status == 'public'){
$video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
$video_status = '<i class="fa fa-eye"></i> Public';
}
elseif($video_status == 'private'){
$video_thumbnail = $playlistItem['snippet']['thumbnails']['maxres']['url'];
$video_status = '<i class="fa fa-lock"></i> Private';
}
You need to look for the Increase Font Size
and Decrease Font Size
options on the Keymap menu, you can see the options on my screenshot. You will find the Keymap menu under Preferences > Keymap
.
Assigning on those will have the expected effect for font zoom.
To report differences between dirA and dirB, while also updating/syncing.
rsync -auv <dirA> <dirB>
Consider IPv4 address as "ip".
if re.match(r'^((\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$', ip):
print "Valid IP"
else:
print "Invalid IP"
Possibly not cross browser but I managed get this: http://jsfiddle.net/QexkH/
basically it requires a fixed height header and footer. and it absolute positions the table.
table {
width: 50%;
height: 50%;
border-spacing: 0;
position:absolute;
}
td {
border: 1px solid black;
}
#content {
position:absolute;
width:100%;
left:0px;
top:20px;
bottom:20px;
overflow: hidden;
}
If updating cURL doesn't fix it, updating NSS should do the trick.
You see the behavior when your target element contains child elements:
Each time your mouse enters or leaves a child element, mouseover
is triggered, but not mouseenter
.
$('#my_div').bind("mouseover mouseenter", function(e) {_x000D_
var el = $("#" + e.type);_x000D_
var n = +el.text();_x000D_
el.text(++n);_x000D_
});
_x000D_
#my_div {_x000D_
padding: 0 20px 20px 0;_x000D_
background-color: #eee;_x000D_
margin-bottom: 10px;_x000D_
width: 90px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#my_div>div {_x000D_
float: left;_x000D_
margin: 20px 0 0 20px;_x000D_
height: 25px;_x000D_
width: 25px;_x000D_
background-color: #aaa;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
_x000D_
<div>MouseEnter: <span id="mouseenter">0</span></div>_x000D_
<div>MouseOver: <span id="mouseover">0</span></div>_x000D_
_x000D_
<div id="my_div">_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
</div>
_x000D_
I would like to add that if the object that is created is static and not coming through http something like that can be done:
public fetchModel(uuid: string = undefined): Observable<string> {
if(!uuid) { //static data
return Observable.of(new TestModel()).map(o => JSON.stringify(o));
}
else {
return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
.map(res => res.text());
}
}
Edit: For Angular 7.x.x mapping needs to be done using pipe() as described here (https://stackoverflow.com/a/54085359/986160):
import {of, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
[...]
public fetchModel(uuid: string = undefined): Observable<string> {
if(!uuid) { //static data
return of(new TestModel());
}
else {
return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
.pipe(map((res:any) => res)) //already contains json
}
}
from answer to my question about observers and static data: https://stackoverflow.com/a/35219772/986160
If you try set a value in datetime-local
date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));
//output : 2010-12-30T23:21
In Kotlin, you can do this.
val editText1 = findViewById(R.id.editText)
val intNum = editText1.text.toString().toInt()
I just had this issue. So there are a few approaches. The first is that new browsers support the
var formData = new FormData();
Follow this link to a blog with info about how support is limited to modern browsers but otherwise it totally solves this issue.
Otherwise you can post the form to an iframe using the target attribute. When you post the form be sure to set the target to an iframe with its display property set to none. The target is the name of the iframe. (Just so you know.)
I hope this helps
I have a minor improvement on Ross Drew's answer.
For a small array, a simple loop is faster than the System.arraycopy approach, because of the overhead associated with setting up System.arraycopy. Therefore, it's better to fill the first few bytes of the array using a simple loop, and only move to System.arraycopy when the filled array has a certain size.
The optimal size of the initial loop will be JVM specific and system specific of course.
private static final int SMALL = 16;
public static void arrayFill(byte[] array, byte value) {
int len = array.length;
int lenB = len < SMALL ? len : SMALL;
for (int i = 0; i < lenB; i++) {
array[i] = value;
}
for (int i = SMALL; i < len; i += i) {
System.arraycopy(array, 0, array, i, len < i + i ? len - i : i);
}
}
To set headers in an Axios POST request, pass the third object to the axios.post() call.
const token = '..your token..'
axios.post(url, {
//...data
}, {
headers: {
'Authorization': `Basic ${token}`
}
})
To set headers in an Axios GET request, pass a second object to the axios.get() call.
const token = '..your token..'
axios.get(url, {
headers: {
'Authorization': `Basic ${token}`
}
})
Cheers!! Read Simple Write Simple
In my case, issue was occured even after all these configurations have done (@Pekka has mentioned changes in httpd.conf & .htaccess files). It was resolved only after I add
<Directory "project/path">
Order allow,deny
Allow from all
AllowOverride All
</Directory>
to virtual host configuration in vhost file
Edit on 29/09/2017 (For Apache 2.4 <) Refer this answer
<VirtualHost dropbox.local:80>
DocumentRoot "E:/Documenten/Dropbox/Dropbox/dummy-htdocs"
ServerName dropbox.local
ErrorLog "logs/dropbox.local-error.log"
CustomLog "logs/dropbox.local-access.log" combined
<Directory "E:/Documenten/Dropbox/Dropbox/dummy-htdocs">
# AllowOverride All # Deprecated
# Order Allow,Deny # Deprecated
# Allow from all # Deprecated
# --New way of doing it
Require all granted
</Directory>
It's just as simple as command+s or File
> Save Screen Shot
in iOS Simulator. It will appear on your desktop by default.
This is a very old thread but I found it while searching for a simple solution to display retina (high res) screen capture on standard resolution display.
So there is an HTML only solution for modern browsers :
<img srcset="image.jpg 100w" sizes="50px" src="image.jpg"/>
This is telling the browser that the image is twice the dimension of it intended display size. The value are proportional and do not need to reflect the actual size of the image. One can use 2w 1px as well to achieve the same effect. The src attribute is only used by legacy browsers.
The nice effect of it is that it display the same size on retina or standard display, shrinking on the latter.
To get your radio button to list horizontally , just add
RepeatDirection="Horizontal"
to your .aspx file where the asp:radiobuttonlist is being declared.
Looks like /e
option is what you need, it'll skip same files/directories.
robocopy c:\data c:\backup /e
If you run the command twice, you'll see the second round is much faster since it skips a lot of things.
From: http://nginx.org/r/large_client_header_buffers
Syntax:
large_client_header_buffers
number
size
;
Default:large_client_header_buffers 4 8k;
Context: http, serverSets the maximum
number
andsize
of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.
so you need to change the size parameter at the end of that line to something bigger for your needs.
Imageio is a Python library that provides an easy interface to read and write a wide range of image data, including animated images, video, volumetric data, and scientific formats. It is cross-platform, runs on Python 2.7 and 3.4+, and is easy to install.
This is example for grayscale image:
import numpy as np
import imageio
# data is numpy array with grayscale value for each pixel.
data = np.array([70,80,82,72,58,58,60,63,54,58,60,48,89,115,121,119])
# 16 pixels can be converted into square of 4x4 or 2x8 or 8x2
data = data.reshape((4, 4)).astype('uint8')
# save image
imageio.imwrite('pic.jpg', data)
You can try using this code,
private WebDriver driver;
System.setProperty("webdriver.firefox.marionette","Your path to driver/geckodriver.exe");
driver = new FirefoxDriver();
I upgraded to selenium 3.0.0 and Firefox version is 49.0.1
You can download geckodriver.exe from https://github.com/mozilla/geckodriver/releases
Make sure you download zip file only, geckodriver-v0.11.1-win64.zip file or win32 one as per your system and extract it in a folder.
Put the path for that folder in the "Your path to driver" quotes.Don't forget to put geckodriver.exe in the path.
If you're looking for the current and the latest versions of all your installed packages, you can also use:
npm outdated
I am not sure what you really want here. If you want to see the .NET framework source code, you may try Netmassdownloader. It's free.
If you want to see any assembly's code (not just .NET), you can use ReSharper. Although it's not free.
I did not see any reference to Raphael.js. So I thought I'd include it here. Raphael.js is backwards compatible all the way back to IE5 and a very early Firefox as well as all of the rest of the browsers. It uses SVG when it can and VML when it can not. What you do with it is to draw onto a canvas. Some browsers will even let you select the text that is generated. Raphael.js can be found here:
It can be as simple as creating your paper drawing area, specifying the font, font-weight, size, etc... and then telling it to put your string of text onto the paper. I am not sure if it gets around the licensing issues or not but it is drawing the text so I'm fairly certain it does circumvent the licensing issues. But check with your lawyer to be sure. :-)
First of All Theory
Big O = Upper Limit O(n)
Theta = Order Function - theta(n)
Omega = Q-Notation(Lower Limit) Q(n)
In many Blogs & Books How this Statement is emphasised is Like
"This is Big O(n^3)" etc.
and people often Confuse like weather
O(n) == theta(n) == Q(n)
But What Worth keeping in mind is They Are Just Mathematical Function With Names O, Theta & Omega
so they have same General Formula of Polynomial,
Let,
f(n) = 2n4 + 100n2 + 10n + 50 then,
g(n) = n4, So g(n) is Function which Take function as Input and returns Variable with Biggerst Power,
Same f(n) & g(n) for Below all explainations
Big O(n4) = 3n4, Because 3n4 > 2n4
3n4 is value of Big O(n4) Just like f(x) = 3x
n4 is playing a role of x here so,
Replacing n4 with x'so, Big O(x') = 2x', Now we both are happy General Concept is
So 0 = f(n) = O(x')
O(x') = cg(n) = 3n4
Putting Value,
0 = 2n4 + 100n2 + 10n + 50 = 3n4
3n4 is our Upper Bound
Theta(n4) = cg(n) = 2n4 Because 2n4 = Our Example f(n)
2n4 is Value of Theta(n4)
so, 0 = cg(n) = f(n)
0 = 2n4 = 2n4 + 100n2 + 10n + 50
2n4 is our Lower Bound
This is Calculated to find out that weather lower Bound is similar to Upper bound,
Case 1). Upper Bound is Similar to Lower Bound
if Upper Bound is Similar to Lower Bound, The Average Case is Similar
Example, 2n4 = f(x) = 2n4,
Then Omega(n) = 2n4
Case 2). if Upper Bound is not Similar to Lower Bound
in this case, Omega(n) is Not fixed but Omega(n) is the set of functions with the same order of growth as g(n).
Example 2n4 = f(x) = 3n4, This is Our Default Case,
Then, Omega(n) = c'n4, is a set of functions with 2 = c' = 3
Hope This Explained!!
If you're using Devise, please note that
For Rails 5,
protect_from_forgery
is no longer prepended to thebefore_action
chain, so if you have setauthenticate_user
beforeprotect_from_forgery
, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or useprotect_from_forgery prepend: true
.
You can get path by this code
Dim CurDir as string = My.Application.Info.DirectoryPath
Do simply like below....
HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put(yourKey+"message","message");
yourHash.put(yourKey+"timestamp",timestamp);
yourHash.put(yourKey+"count ",count);
yourHash.put(yourKey+"version ",version);
typecast the value while getting back. For ex:
int count = Integer.parseInt(yourHash.get(yourKey+"count"));
//or
int count = Integer.valueOf(yourHash.get(yourKey+"count"));
//or
int count = (Integer)yourHash.get(yourKey+"count"); //or (int)
you have to import this files into the <head></head>
of your html.
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
Basically, you have three options:
EXPOSE
nor -p
EXPOSE
EXPOSE
and -p
1) If you specify neither EXPOSE
nor -p
, the service in the container will only be accessible from inside the container itself.
2) If you EXPOSE
a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.
3) If you EXPOSE
and -p
a port, the service in the container is accessible from anywhere, even outside Docker.
The reason why both are separated is IMHO because:
The documentation explicitly states:
The
EXPOSE
instruction exposes ports for use within links.
It also points you to how to link containers, which basically is the inter-container communication I talked about.
PS: If you do -p
, but do not EXPOSE
, Docker does an implicit EXPOSE
. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p
includes EXPOSE
. That's why I didn't list it above as a fourth case.
In C++, you can access any address, but it doesn't mean you should. The address you are accessing is no longer valid. It works because nothing else scrambled the memory after foo returned, but it could crash under many circumstances. Try analyzing your program with Valgrind, or even just compiling it optimized, and see...
Another possible solution is to completely reset the settings. This is what fixed it for me:
Tools->Import and Export settings->Reset all settings.
The optimiser will judge if the use of your index will make your query run faster, and if it is, it will use the index.
Depending on your RDBMS you can force the use of an index, although it is not recommended unless you know what you are doing.
In general you should index columns that you use in table join's and where statements
If logical test is against a single column then you could use something like
USE AdventureWorks2012;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
More information - https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017
armhf
stands for "arm hard float", and is the name given to a debian port for arm processors (armv7+) that have hardware floating point support.
On the beaglebone black, for example:
:~$ dpkg --print-architecture
armhf
Although other commands (such as uname -a
or arch
) will just show armv7l
:~$ cat /proc/cpuinfo
processor : 0
model name : ARMv7 Processor rev 2 (v7l)
BogoMIPS : 995.32
Features : half thumb fastmult vfp edsp thumbee neon vfpv3 tls
...
The vfpv3
listed under Features
is what refers to the floating point support.
Incidentally, armhf
, if your processor supports it, basically supersedes Raspbian, which if I understand correctly was mainly a rebuild of armhf
with work arounds to deal with the lack of floating point support on the original raspberry pi's. Nowdays, of course, there's a whole ecosystem build up around Raspbian, so they're probably not going to abandon it. However, this is partly why the beaglebone runs straight debian, and that's ok even if you're used to Raspbian, unless you want some of the special included non-free software such as Mathematica.
Bind & protected-mode both are the essential steps. But if ufw is enabled then you will have to make redis port allow in ufw.
ufw status
if Status: active
then allow redis-port ufw allow 6379
vi /etc/redis/redis.conf
bind 127.0.0.1
to bind 0.0.0.0
protected-mode yes
to protected-mode no
In terms of what you are doing with jQuery, my understanding is that you can chain functions like you have and the inner ones have access to variables from the outer ones. So is your ShowDialog(x) function contains these other functions, you can re-use the x variable within them and it will be taken as a reference to the parameter from the outer function.
I agree with mausch, you should really look at using POST for these actions, which will add a <form>
tag around each element, but make the chances of an automated script or tool triggering the Cancel event much less likely. The Change action can remain as is because it (presumably just opens an edit form).
You could try Mobilenium (https://github.com/rafpyprog/Mobilenium), a python package that binds BrowserMob Proxy and Selenium.
An usage example:
>>> from mobilenium import mobidriver
>>>
>>> browsermob_path = 'path/to/browsermob-proxy'
>>> mob = mobidriver.Firefox(browsermob_binary=browsermob_path)
>>> mob.get('http://python-requests.org')
301
>>> mob.response['redirectURL']
'http://docs.python-requests.org'
>>> mob.headers['Content-Type']
'application/json; charset=utf8'
>>> mob.title
'Requests: HTTP for Humans \u2014 Requests 2.13.0 documentation'
>>> mob.find_elements_by_tag_name('strong')[1].text
'Behold, the power of Requests'
Download the package and unpack it. In Terminal, go to the package's directory and type
python setup.py install
I would put the secondSet in a HashMap before the comparison. This way you will reduce the second list's search time to n(1). Like this:
HashMap<Integer,Record> hm = new HashMap<Integer,Record>(secondSet.size());
int i = 0;
for(Record secondRecord : secondSet){
hm.put(i,secondRecord);
i++;
}
for(Record firstRecord : firstSet){
for(int i=0; i<secondSet.size(); i++){
//use hm for comparison
}
}
sendStickyBroadcast()
performs a sendBroadcast(Intent)
known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter)
. In all other ways, this behaves the same as sendBroadcast(Intent)
. One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED
. When you call registerReceiver()
for that action -- even with a null BroadcastReceiver
-- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
An alternative approach is to use numpy.resize()
as in:
In [37]: shp = (50,100,25)
In [38]: arr = np.random.random_sample(shp)
In [45]: resized_arr = np.resize(arr, (np.prod(shp[:2]), shp[-1]))
In [46]: resized_arr.shape
Out[46]: (5000, 25)
# sanity check with other solutions
In [47]: resized = np.reshape(arr, (-1, shp[-1]))
In [48]: np.allclose(resized_arr, resized)
Out[48]: True
This feature is included as part of jquery ui http://docs.jquery.com/UI/Effects/Slide if you want to extend it with your own names you can use this.
jQuery.fn.extend({
slideRightShow: function() {
return this.each(function() {
$(this).show('slide', {direction: 'right'}, 1000);
});
},
slideLeftHide: function() {
return this.each(function() {
$(this).hide('slide', {direction: 'left'}, 1000);
});
},
slideRightHide: function() {
return this.each(function() {
$(this).hide('slide', {direction: 'right'}, 1000);
});
},
slideLeftShow: function() {
return this.each(function() {
$(this).show('slide', {direction: 'left'}, 1000);
});
}
});
you will need the following references
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://jquery-ui.googlecode.com/svn/tags/latest/ui/jquery.effects.core.js"></script>
<script src="http://jquery-ui.googlecode.com/svn/tags/latest/ui/jquery.effects.slide.js"></script>
Here are the docs about the "new" format syntax. An example would be:
"({:d} goals, ${:d})".format(self.goals, self.penalties)
If both goals
and penalties
are integers (i.e. their default format is ok), it could be shortened to:
"({} goals, ${})".format(self.goals, self.penalties)
And since the parameters are fields of self
, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):
"({0.goals} goals, ${0.penalties})".format(self)
Explaining:
{}
means just the next positional argument, with default format;{0}
means the argument with index 0
, with default format;{:d}
is the next positional argument, with decimal integer format;{0:d}
is the argument with index 0
, with decimal integer format.There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:
"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)
"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)
"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'
"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'
"games: {:>3}".format(player1.games) # 'games: 123'
"games: {:>3}".format(player2.games) # 'games: 4'
"games: {:0>3}".format(player2.games) # 'games: 004'
Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).
Here's what worked for me to download the latest version of an artifact called "component.jar" with Maven 3.1.1 in the end (other suggestions did not, mostly due to maven version changes I believe)
This actually downloads the file and copies it into the local working directory
From bash:
mvn dependency:get \
-DrepoUrl=http://.../ \
-Dartifact=com.foo.something:component:LATEST:jar \
-Dtransitive=false \
-Ddest=component.jar \
I had a similar problem but with a twist - the solutions listed above worked when the resultset was from one query but in my situation, I had multiple individual select queries for which I needed results to be exported to Excel. Below is just an example to illustrate although I could do a name in
clause...
select a,b from Table_A where name = 'x'
select a,b from Table_A where name = 'y'
select a,b from Table_A where name = 'z'
The wizard was letting me export the result from one query to excel but not all results from different queries in this case.
When I researched, I found that we could disable the results to grid and enable results to Text. So, press Ctrl + T, then execute all the statements. This should show the results as a text file in the output window. You can manipulate the text into a tab delimited format for you to import into Excel.
You could also press Ctrl + Shift + F to export the results to a file - it exports as a .rpt file that can be opened using a text editor and manipulated for excel import.
Hope this helps any others having a similar issue.
With v25.3.x of the Android Emulator & x86 Google API Emulator system images API Level 19 (Android 4.4 - Kitkat) and higher, you can simply copy and paste from your desktop with your mouse or keyboard.
This feature was announced with Android Studio 2.3
There's no need to use lambdas and/or give radix
parameter to parseInt
, just use parseFloat
or Number
instead.
Reasons:
It's working:
var src = "1,2,5,4,3";
var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
var obj = {1: ..., 3: ..., 4: ..., 7: ...};
var keys= Object.keys(obj); // ["1", "3", "4", "7"]
var ids = keys.map(parseFloat); // [1, 3, 4, 7]
var arr = ["1", 5, "7", 11];
var ints= arr.map(parseFloat); // [1, 5, 7, 11]
ints[1] === "5" // false
ints[1] === 5 // true
ints[2] === "7" // false
ints[2] === 7 // true
It's shorter.
It's a tiny bit quickier and takes advantage of cache, when parseInt
-approach - doesn't:
// execution time measure function
// keep it simple, yeah?
> var f = (function (arr, c, n, m) {
var i,t,m,s=n();
for(i=0;i++<c;)t=arr.map(m);
return n()-s
}).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
> f(Number) // first launch, just warming-up cache
> 3971 // nice =)
> f(Number)
> 3964 // still the same
> f(function(e){return+e})
> 5132 // yup, just little bit slower
> f(function(e){return+e})
> 5112 // second run... and ok.
> f(parseFloat)
> 3727 // little bit quicker than .map(Number)
> f(parseFloat)
> 3737 // all ok
> f(function(e){return parseInt(e,10)})
> 21852 // awww, how adorable...
> f(function(e){return parseInt(e)})
> 22928 // maybe, without '10'?.. nope.
> f(function(e){return parseInt(e)})
> 22769 // second run... and nothing changes.
> f(Number)
> 3873 // and again
> f(parseFloat)
> 3583 // and again
> f(function(e){return+e})
> 4967 // and again
> f(function(e){return parseInt(e,10)})
> 21649 // dammit 'parseInt'! >_<
Notice: In Firefox parseInt
works about 4 times faster, but still slower than others. In total: +e
< Number
< parseFloat
< parseInt
I had the same problem. I ran my Docker image, and it created a container with a specific CONTAINER_ID. I wanted to work with the same container:
First run your Docker image:
docker run -it -p 8888:8888 -p 6006:6006 -v ~/:/host waleedka/modern-deep-learning
Then list all the containers you have made:
sudo docker ps -a
And select the container you want to work with (mine is 167ddd6d7f15):
sudo docker start -ai 167ddd6d7f15
On particular table
<table style="border-collapse: separate; border-spacing: 10px;" >_x000D_
<tr>_x000D_
<td>Hi</td>_x000D_
<td>Hello</td>_x000D_
<tr/>_x000D_
<tr>_x000D_
<td>Hola</td>_x000D_
<td>Oi!</td>_x000D_
<tr/>_x000D_
</table>
_x000D_
Get-Content grabs data and dumps it into an array, line by line. Assuming there aren't other special requirements than you listed, you could just save your content into a variable?
$file = Get-Content c:\file\whatever.txt
Running just $file
will return the full contents. Then you can just do $file.Count
(because arrays already have a count method built in) to get the total # of lines.
Hope this helps! I'm not a scripting wiz, but this seemed easier to me than a lot of the stuff above.
Try below one:
svn copy http://svn.example.com/repos/calc/trunk@rev-no
http://svn.example.com/repos/calc/branches/my-calc-branch
-m "Creating a private branch of /calc/trunk." --parents
No slash "\" between the svn URLs.
The top answers by Paul H and J. Li do not work for all types of seaborn figures. For the FacetGrid
type (for instance sns.lmplot()
), use the size
and aspect
parameter.
Size
changes both the height and width, maintaining the aspect ratio.
Aspect
only changes the width, keeping the height constant.
You can always get your desired size by playing with these two parameters.
I tried several jquery based custom select with images, but none worked in responsive layouts. Finally i came across Bootstrap-Select. After some modifications i was able to produce this code.
A monad is a data type that encapsulates a value, and to which, essentially, two operations can be applied:
return x
creates a value of the monad type that encapsulates x
m >>= f
(read it as "the bind operator") applies the function f
to the value in the monad m
That's what a monad is. There are a few more technicalities, but basically those two operations define a monad. The real question is, "What a monad does?", and that depends on the monad — lists are monads, Maybes are monads, IO operations are monads. All that it means when we say those things are monads is that they have the monad interface of return
and >>=
.
I think you should edit the anchor tag on bootstrap.css. Otherwise give customized style to the anchor tag with !important
(to override the default style on bootstrap.css).
Example code
.nav {_x000D_
background-color: #000 !important;_x000D_
}_x000D_
_x000D_
.nav>li>a {_x000D_
background-color: #666 !important;_x000D_
color: #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div role="tabpanel">_x000D_
_x000D_
<!-- Nav tabs -->_x000D_
<ul class="nav nav-tabs" role="tablist">_x000D_
<li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>_x000D_
<li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>_x000D_
<li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>_x000D_
<li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>_x000D_
</ul>_x000D_
_x000D_
<!-- Tab panes -->_x000D_
<div class="tab-content">_x000D_
<div role="tabpanel" class="tab-pane active" id="home">...</div>_x000D_
<div role="tabpanel" class="tab-pane" id="profile">tab1</div>_x000D_
<div role="tabpanel" class="tab-pane" id="messages">tab2</div>_x000D_
<div role="tabpanel" class="tab-pane" id="settings">tab3</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Fiddle: http://jsfiddle.net/zjjpocv6/2/
You can do it like this, too:
<?php
if(isset($_POST['select1'])){
$select1 = $_POST['select1'];
switch ($select1) {
case 'value1':
echo 'this is value1<br/>';
break;
case 'value2':
echo 'value2<br/>';
break;
default:
# code...
break;
}
}
?>
<form action="" method="post">
<select name="select1">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
@Amaynut Thanks
SELECT *
FROM eventList
WHERE date BETWEEN UNIX_TIMESTAMP('2017-08-01') AND UNIX_TIMESTAMP('2017/08/01');
above mention, code works and my problem solved.
The problem is that skew
isn't being subsetted in colour=factor(skew)
, so it's the wrong length. Since subset(skew, product == 'p1')
is the same as subset(skew, product == 'p3')
, in this case it doesn't matter which subset is used. So you can solve your problem with:
p1 <- ggplot(df, aes(x=subset(price, product=='p1'),
y=subset(price, product=='p3'),
colour=factor(subset(skew, product == 'p1')))) +
geom_point(size=2, shape=19)
Note that most R users would write this as the more concise:
p1 <- ggplot(df, aes(x=price[product=='p1'],
y=price[product=='p3'],
colour=factor(skew[product == 'p1']))) +
geom_point(size=2, shape=19)
There is a bug in robocopy in interpreting the source name. If you include a back slash at the end of the path to describe a folder it keeps including the string for the source into the rest of the line. ie
robocopy "C:\back up\" %destination% /e Nothing here will go to the destination string
robocopy "C:\back up" %destination% /e but this works
I may be wrong but I think both should work!
It's true that some databases recognize the OUTER keyword. Some do not. Where it is recognized, it is usually an optional keyword. Almost always, FULL JOIN and FULL OUTER JOIN do exactly the same thing. (I can't think of an example where they do not. Can anyone else think of one?)
This may leave you wondering, "Why would it even be a keyword if it has no meaning?" The answer boils down to programming style.
In the old days, programmers strived to make their code as compact as possible. Every character meant longer processing time. We used 1, 2, and 3 letter variables. We used 2 digit years. We eliminated all unnecessary white space. Some people still program that way. It's not about processing time anymore. It's more about fast coding.
Modern programmers are learning to use more descriptive variables and put more remarks and documentation into their code. Using extra words like OUTER make sure that other people who read the code will have an easier time understanding it. There will be less ambiguity. This style is much more readable and kinder to the people in the future who will have to maintain that code.
One possibility you can try is to create 3 axes stacked one on top of the other with the 'Color'
properties of the top two set to 'none'
so that all the plots are visible. You would have to adjust the axes width, position, and x-axis limits so that the 3 y axes are side-by-side instead of on top of one another. You would also want to remove the x-axis tick marks and labels from 2 of the axes since they will lie on top of one another.
Here's a general implementation that computes the proper positions for the axes and offsets for the x-axis limits to keep the plots lined up properly:
%# Some sample data:
x = 0:20;
N = numel(x);
y1 = rand(1,N);
y2 = 5.*rand(1,N)+5;
y3 = 50.*rand(1,N)-50;
%# Some initial computations:
axesPosition = [110 40 200 200]; %# Axes position, in pixels
yWidth = 30; %# y axes spacing, in pixels
xLimit = [min(x) max(x)]; %# Range of x values
xOffset = -yWidth*diff(xLimit)/axesPosition(3);
%# Create the figure and axes:
figure('Units','pixels','Position',[200 200 330 260]);
h1 = axes('Units','pixels','Position',axesPosition,...
'Color','w','XColor','k','YColor','r',...
'XLim',xLimit,'YLim',[0 1],'NextPlot','add');
h2 = axes('Units','pixels','Position',axesPosition+yWidth.*[-1 0 1 0],...
'Color','none','XColor','k','YColor','m',...
'XLim',xLimit+[xOffset 0],'YLim',[0 10],...
'XTick',[],'XTickLabel',[],'NextPlot','add');
h3 = axes('Units','pixels','Position',axesPosition+yWidth.*[-2 0 2 0],...
'Color','none','XColor','k','YColor','b',...
'XLim',xLimit+[2*xOffset 0],'YLim',[-50 50],...
'XTick',[],'XTickLabel',[],'NextPlot','add');
xlabel(h1,'time');
ylabel(h3,'values');
%# Plot the data:
plot(h1,x,y1,'r');
plot(h2,x,y2,'m');
plot(h3,x,y3,'b');
and here's the resulting figure:
It is txtName.BackColor = System.Drawing.Color.Red;
one can also use txtName.BackColor = Color.Aqua;
which is the same as txtName.BackColor = System.Color.Aqua;
Only Problem with System.color is that it does not contain a definition for some basic colors especially white, which is important cause usually textboxes are white;
I was able to solve the issue by granting complete s3 access to Lambda from policies. Make a new role for Lambda and attach the policy with complete S3 Access to it.
Hope this will help.
try this:
textarea {
border-style: none;
border-color: Transparent;
overflow: auto;
outline: none;
}
jsbin: http://jsbin.com/orozon/2/
$('#el').prop('disabled', function(i, v) { return !v; });
The .prop()
method accepts two arguments:
So in this case, I used a function that supplied me the index (i) and the current value (v), then I returned the opposite of the current value, so the property state is reversed.
Re: textFile.getch()
, did you make that up, or do you have a reference that says it should work? If it's the latter, get rid of it. If it's the former, don't do that. Get a good reference.
char ch;
textFile.unsetf(ios_base::skipws);
textFile >> ch;
An elegant method would be to use the ~=
compatible release operator according to PEP 440. In your case this would amount to:
package~=0.5.0
As an example, if the following versions exist, it would choose 0.5.9
:
0.5.0
0.5.9
0.6.0
For clarification, each pair is equivalent:
~= 0.5.0
>= 0.5.0, == 0.5.*
~= 0.5
>= 0.5, == 0.*
Here is small utility class that converts JSON to DataFrame and back: Hope you find this helpful.
# -*- coding: utf-8 -*-
from pandas.io.json import json_normalize
class DFConverter:
#Converts the input JSON to a DataFrame
def convertToDF(self,dfJSON):
return(json_normalize(dfJSON))
#Converts the input DataFrame to JSON
def convertToJSON(self, df):
resultJSON = df.to_json(orient='records')
return(resultJSON)
SELECT *
FROM ...
WHERE EXISTS(SELECT 1
FROM sys.columns c
WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
AND c.name = 'ModifiedByUser'
)
The easiest way that I found to recover a lost commit (that only exists on github and not locally) is to create a new branch that includes this commit.
git pull
the new branch down to localThis specifies the default collation for the database. Every text field that you create in tables in the database will use that collation, unless you specify a different one.
A database always has a default collation. If you don't specify any, the default collation of the SQL Server instance is used.
The name of the collation that you use shows that it uses the Latin1 code page 1, is case insensitive (CI) and accent sensitive (AS). This collation is used in the USA, so it will contain sorting rules that are used in the USA.
The collation decides how text values are compared for equality and likeness, and how they are compared when sorting. The code page is used when storing non-unicode data, e.g. varchar fields.
Try This:
mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one','ten']
newList=[mydict[k] for k in mykeys if k in mydict]
print newList
[3, 1]
It is good practice to make sure the callback is an actual function before attempting to execute it:
if (callback && typeof(callback) === "function") {
callback();
}
I have also tried that error , I got it right by just adding /hello/any name because it is path that there must be an hello/name
example : instead of just putting http://localhost/app_dev.php
put it like this way http://localhost/name_of_your_project/web/app_dev.php/hello/ai
it will display Hello Ai . I hope I answer your question.
@Stephen Paul continuation...
ngOnDestroy
(ed) when the modal is exited.Why?
In some cases you might not want to modal to retain its status after having been closed, but rather restored to the initial state.
Original modal issue
Passing the content straightforward into the view actually generates initializes it even before the modal gets it. The modal doesn't have a way to kill such content even if using a *ngIf
wrapper.
Solution
ng-template
. ng-template
doesn't render until ordered to do so.
my-component.module.ts
...
imports: [
...
ModalModule
]
my-component.ts
<button (click)="reuseModal.open()">Open</button>
<app-modal #reuseModal>
<ng-template #header></ng-template>
<ng-template #body>
<app-my-body-component>
<!-- This component will be created only when modal is visible and will be destroyed when it's not. -->
</app-my-body-content>
<ng-template #footer></ng-template>
</app-modal>
modal.component.ts
export class ModalComponent ... {
@ContentChild('header') header: TemplateRef<any>;
@ContentChild('body') body: TemplateRef<any>;
@ContentChild('footer') footer: TemplateRef<any>;
...
}
modal.component.html
<div ... *ngIf="visible">
...
<div class="modal-body">
ng-container *ngTemplateOutlet="body"></ng-container>
</div>
References
I have to say that it wouldn't have been possible without the excellent official and community documentation around the net. It might help some of you too to understand better how ng-template
, *ngTemplateOutlet
and @ContentChild
work.
https://angular.io/api/common/NgTemplateOutlet
https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/
https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
modal.component.html
<div
(click)="onContainerClicked($event)"
class="modal fade"
tabindex="-1"
[ngClass]="{'in': visibleAnimate}"
[ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}"
*ngIf="visible">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<ng-container *ngTemplateOutlet="header"></ng-container>
<button class="close" data-dismiss="modal" type="button" aria-label="Close" (click)="close()">×</button>
</div>
<div class="modal-body">
<ng-container *ngTemplateOutlet="body"></ng-container>
</div>
<div class="modal-footer">
<ng-container *ngTemplateOutlet="footer"></ng-container>
</div>
</div>
</div>
</div>
modal.component.ts
/**
* @Stephen Paul https://stackoverflow.com/a/40144809/2013580
* @zurfyx https://stackoverflow.com/a/46949848/2013580
*/
import { Component, OnDestroy, ContentChild, TemplateRef } from '@angular/core';
@Component({
selector: 'app-modal',
templateUrl: 'modal.component.html',
styleUrls: ['modal.component.scss'],
})
export class ModalComponent implements OnDestroy {
@ContentChild('header') header: TemplateRef<any>;
@ContentChild('body') body: TemplateRef<any>;
@ContentChild('footer') footer: TemplateRef<any>;
public visible = false;
public visibleAnimate = false;
ngOnDestroy() {
// Prevent modal from not executing its closing actions if the user navigated away (for example,
// through a link).
this.close();
}
open(): void {
document.body.style.overflow = 'hidden';
this.visible = true;
setTimeout(() => this.visibleAnimate = true, 200);
}
close(): void {
document.body.style.overflow = 'auto';
this.visibleAnimate = false;
setTimeout(() => this.visible = false, 100);
}
onContainerClicked(event: MouseEvent): void {
if ((<HTMLElement>event.target).classList.contains('modal')) {
this.close();
}
}
}
modal.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ModalComponent } from './modal.component';
@NgModule({
imports: [
CommonModule,
],
exports: [ModalComponent],
declarations: [ModalComponent],
providers: [],
})
export class ModalModule { }
The port is probably being used by another application, try listing and see if it's your application:
lsof -i:8080
You can kill the process of this port:
lsof -ti:8080 | xargs kill
this can be achieved with the css calc()
operator
@media screen and (min-width: 480px) {
body {
background-color: lightgreen;
zoom:calc(100% / 480);
}
}
You can use belw code for show and hide bootstrap model.
$('#my-model').on('shown.bs.modal', function (e) {
// do something here...
})
and if you want to hide model then you can use below code.
$('#my-model').on('hidden.bs.modal', function() {
// do something here...
});
I hope this answer is useful for your project.
Plain and simple:
If Jenkins sees the build step (which is a script too) exits with non-zero code, the build is marked with a red ball (= failed).
Why exactly that happens depends on your build script.
I wrote something similar from another point-of-view but maybe it will help to read it anyway: Why does Jenkins think my build succeeded?
Here you will find a better solution OLTP vs. OLAP
OLTP (On-line Transaction Processing) is involved in the operation of a particular system. OLTP is characterized by a large number of short on-line transactions (INSERT, UPDATE, DELETE). The main emphasis for OLTP systems is put on very fast query processing, maintaining data integrity in multi-access environments and an effectiveness measured by number of transactions per second. In OLTP database there is detailed and current data, and schema used to store transactional databases is the entity model (usually 3NF). It involves Queries accessing individual record like Update your Email in Company database.
OLAP (On-line Analytical Processing) deals with Historical Data or Archival Data. OLAP is characterized by relatively low volume of transactions. Queries are often very complex and involve aggregations. For OLAP systems a response time is an effectiveness measure. OLAP applications are widely used by Data Mining techniques. In OLAP database there is aggregated, historical data, stored in multi-dimensional schemas (usually star schema). Sometime query need to access large amount of data in Management records like what was the profit of your company in last year.
You can use this method:
boolean isAlive()
It returns true if the thread is still alive and false if the Thread is dead. This is not static. You need a reference to the object of the Thread class.
One more tip: If you're checking it's status to make the main thread wait while the new thread is still running, you may use join() method. It is more handy.
I can use pointers, but I am a bit afraid of using them.
If you need a dynamic array, you can't escape pointers. Why are you afraid though? They won't bite (as long as you're careful, that is). There's no built-in dynamic array in C, you'll just have to write one yourself. In C++, you can use the built-in std::vector
class. C# and just about every other high-level language also have some similar class that manages dynamic arrays for you.
If you do plan to write your own, here's something to get you started: most dynamic array implementations work by starting off with an array of some (small) default size, then whenever you run out of space when adding a new element, double the size of the array. As you can see in the example below, it's not very difficult at all: (I've omitted safety checks for brevity)
typedef struct {
int *array;
size_t used;
size_t size;
} Array;
void initArray(Array *a, size_t initialSize) {
a->array = malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}
void insertArray(Array *a, int element) {
// a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
// Therefore a->used can go up to a->size
if (a->used == a->size) {
a->size *= 2;
a->array = realloc(a->array, a->size * sizeof(int));
}
a->array[a->used++] = element;
}
void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
Using it is just as simple:
Array a;
int i;
initArray(&a, 5); // initially 5 elements
for (i = 0; i < 100; i++)
insertArray(&a, i); // automatically resizes as necessary
printf("%d\n", a.array[9]); // print 10th element
printf("%d\n", a.used); // print number of elements
freeArray(&a);
I would do something like:
filename = "mynumbers.txt"
mynumbers = []
with open(filename) as f:
for line in f:
mynumbers.append([int(n) for n in line.strip().split(',')])
for pair in mynumbers:
try:
x,y = pair[0],pair[1]
# Do Something with x and y
except IndexError:
print "A line in the file doesn't have enough entries."
The with open is recommended in http://docs.python.org/tutorial/inputoutput.html since it makes sure files are closed correctly even if an exception is raised during the processing.
function check(selId) {
var sel = document.getElementById(selId);
var dropDown_sel = sel.options[sel.selectedIndex].text;
if (dropDown_sel != "none") {
state=1;
//state is a Global variable initially it is set to 0
}
}
function checkstatevalue() {
if (state==1) {
return 1;
}
return false;
}
and html is for example
<form name="droptest" onSubmit="return checkstatevalue()">
<select id='Sel1' onchange='check("Sel1");'>
<option value='junaid'>Junaid</option>
<option value='none'>none</option>
<option value='ali'>Ali</option>
</select>
</form>
Now when submitting a form first check what is the value of state if it is 0 it means that no item has been selected.
I'd use a 'where not exists' -- exactly as you suggest in your title:
SELECT `voter`.`ID`, `voter`.`Last_Name`, `voter`.`First_Name`,
`voter`.`Middle_Name`, `voter`.`Age`, `voter`.`Sex`,
`voter`.`Party`, `voter`.`Demo`, `voter`.`PV`,
`household`.`Address`, `household`.`City`, `household`.`Zip`
FROM (`voter`)
JOIN `household` ON `voter`.`House_ID`=`household`.`id`
WHERE `CT` = '5'
AND `Precnum` = 'CTY3'
AND `Last_Name` LIKE '%Cumbee%'
AND `First_Name` LIKE '%John%'
AND NOT EXISTS (
SELECT * FROM `elimination`
WHERE `elimination`.`voter_id` = `voter`.`ID`
)
ORDER BY `Last_Name` ASC
LIMIT 30
That may be marginally faster than doing a left join (of course, depending on your indexes, cardinality of your tables, etc), and is almost certainly much faster than using IN.
The way I would do it is to leave the __ init__.py files empty, and do:
import lib.mod1.mod11
lib.mod1.mod11.mod12()
or
from lib.mod1.mod11 import mod12
mod12()
You may find that the mod1 dir is unnecessary, just have mod12.py in lib.
array.split(' ').slice(-1)[0]
The best one ever and my favorite.
This issue will also occur while using some packages like webpack-hot-middleware
and open multiple pages at the same time. webpack-hot-middleware
will create a connection for each page for listening to the changes of code then to refresh the page. Each browser has a max-connections-per-server
limitation which is 6 for Chrome, so if you have already opened more than 6 pages in Chrome, the new request will be hung there until you close some pages.
Lets try this code:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.tintColor = UIColor.whiteColor() // Back buttons and such
navigationBarAppearace.barTintColor = UIColor.purpleColor() // Bar's background color
navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()] // Title's text color
self.window?.backgroundColor = UIColor.whiteColor()
return true
}
Probably the simplest way to do it is to create a delegate and then BeginInvoke
, followed by a wait at some time in the future, and an EndInvoke
.
public bool Foo(){
Thread.Sleep(100000); // Do work
return true;
}
public SomeMethod()
{
var fooCaller = new Func<bool>(Foo);
// Call the method asynchronously
var asyncResult = fooCaller.BeginInvoke(null, null);
// Potentially do other work while the asynchronous method is executing.
// Finally, wait for result
asyncResult.AsyncWaitHandle.WaitOne();
bool fooResult = fooCaller.EndInvoke(asyncResult);
Console.WriteLine("Foo returned {0}", fooResult);
}
In bootstrap 4 use:
<ul class="nav navbar-nav ml-auto">
This will push the navbar to the right. Use mr-auto to push it to the left, this is the default behaviour.
See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")
You can easily convert miliseconds into seconds, minutes and hours.
val millis = **milliSecondsYouWantToConvert**
val seconds = (millis / 1000) % 60
val minutes = ((millis / 1000) / 60) % 60
val hours = ((millis / 1000) / 60) / 60
println("--------------------------------------------------------------------")
println(String.format("%02dh : %02dm : %02ds remaining", hours, minutes, seconds))
println("--------------------------------------------------------------------")
**RESULT :**
--------------------------------------------------------------------
01h : 23m : 37s remaining
--------------------------------------------------------------------
Since you're using jQuery, stop binding event handlers in your HTML, and start writing unobtrusive JavaScript.
$(document).ready(function ()
{
function myfunction(me)
{
$(me).fancybox({
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true // remove the trailing comma!!
}).click();
// fire the click event after initializing fancybox on this element
// this should open the fancybox
}
// use .one() so that the handler is executed at most once per element
$('a[href=#modalMine]').one('click', function ()
{
myfunction(this);
return false;
});
});
However, I don't particularly see a reason for setting up the fancybox on click. You could just do this instead:
$(document).ready(function ()
{
function myfunction()
{
// note the use of "this" rather than a function argument
$(this).fancybox({
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true
});
}
$('a[href=#modalMine]').each(myfunction);
});
I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.
String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);
Hope this helps :)
You need to make use of Label Callback. A common example to round data values, the following example rounds the data to two decimal places.
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += Math.round(tooltipItem.yLabel * 100) / 100;
return label;
}
}
}
}
});
Now let me write the scenario where I used the label callback functionality.
Let's start with logging the arguments of Label Callback function, you will see structure similar to this here datasets, array comprises of different lines you want to plot in the chart. In my case it's 4, that's why length of datasets array is 4.
In my case, I had to perform some calculations on each dataset and have to identify the correct line, every-time I hover upon a line in a chart.
To differentiate different lines and manipulate the data of hovered tooltip based on the data of other lines I had to write this logic.
callbacks: {
label: function (tooltipItem, data) {
console.log('data', data);
console.log('tooltipItem', tooltipItem);
let updatedToolTip: number;
if (tooltipItem.datasetIndex == 0) {
updatedToolTip = tooltipItem.yLabel;
}
if (tooltipItem.datasetIndex == 1) {
updatedToolTip = tooltipItem.yLabel - data.datasets[0].data[tooltipItem.index];
}
if (tooltipItem.datasetIndex == 2) {
updatedToolTip = tooltipItem.yLabel - data.datasets[1].data[tooltipItem.index];
}
if (tooltipItem.datasetIndex == 3) {
updatedToolTip = tooltipItem.yLabel - data.datasets[2].data[tooltipItem.index]
}
return updatedToolTip;
}
}
Above mentioned scenario will come handy, when you have to plot different lines in line-chart and manipulate tooltip of the hovered point of a line, based on the data of other point belonging to different line in the chart at the same index.
Download the ZIP file from this URL and extract it to get the Jar. Add the Jar to your build path. To check the available classes in this Jar use this URL.
To Add this Jar to your build path Right click the Project > Build Path > Configure build path> Select Libraries tab > Click Add External Libraries > Select the Jar file Download
I hope this will solve your problem
One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader
module. If you have used create-react-app
to scaffold your project, the module is already included, you just need to import your json:
import Profile from './components/profile';
This answer explains more.
Actually, with strings, you can do something like this:
oldStr = 'Hello World!'
newStr = ''
for i in oldStr:
if 'a' < i < 'z':
newStr += chr(ord(i)-32)
else:
newStr += i
print(newStr)
'HELLO WORLD!'
Basically, I'm "adding"+"strings" together into a new string :).
Edit: note that this answer is 3+ years old. For newer versions of apache, please see the answer by sp00n. Leaving this answer for users of older versions of apache.
For debugging mod_rewrite issues, you'll want to use RewriteLogLevel and RewriteLog:
RewriteLogLevel 3
RewriteLog "/usr/local/var/apache/logs/rewrite.log"