Try using System.getProperty("line.separator")
to get a new line.
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
A lot of vim's features (like autoindent
and cindent
) are turned off by default. To really see what vim can do for you, you need a decent ~/.vimrc
.
A good starter one is in $VIMRUNTIME/vimrc_example.vim
. If you want to try it out, use
:source $VIMRUNTIME/vimrc_example.vim
when in vim.
I'd actually suggest just copying the contents to your ~/.vimrc
as it's well commented, and a good place to start learning how to use vim. You can do this by
:e $VIMRUNTIME/vimrc_example.vim
:w! ~/.vimrc
This will overwrite your current ~/.vimrc
, but if all you have in there is the indent settings Davr suggested, I wouldn't sweat it, as the example vimrc will take care of that for you as well. For a complete walkthrough of the example, and what it does for you, see :help vimrc-intro
.
This is here:
<button onClick="window.location='page_name.php';" value="click here" />
filter_input(INPUT_POST, 'var_name')
instead of $_POST['var_name']
filter_input_array(INPUT_POST)
instead of $_POST
Thanks to @fortesl and this answer
I'm using VS 2019 and it doesn't easily tell you the C# version you are using. I'm working with .Net Core 3.0, and VS 2019 using C# 8 in that environment. But "csc -langversion:?" makes this clear:
D:\>csc -langversion:?
Supported language versions:
default
1
2
3
4
5
6
7.0
7.1
7.2
7.3
8.0 (default)
latestmajor
preview
latest
Not sure what csc -version is identifying:
D:\>csc --version
Microsoft (R) Visual C# Compiler version 3.4.0-beta1-19462-14 (2f21c63b)
Copyright (C) Microsoft Corporation. All rights reserved.
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
Update: This got fixed in C# 7.0 with pattern matching
switch (MyObj)
case Type1 t1:
case Type2 t2:
case Type3 t3:
Old answer:
It is a hole in C#'s game, no silver bullet yet.
You should google on the 'visitor pattern' but it might be a little heavy for you but still something you should know about.
Here's another take on the matter using Linq: http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx
Otherwise something along these lines could help
// nasty..
switch(MyObj.GetType.ToString()){
case "Type1": etc
}
// clumsy...
if myObj is Type1 then
if myObj is Type2 then
etc.
The Java JNI requires OS libraries of the same "bittiness" as the JVM. If you attempt to build something that depends, for example, on IESHIMS.DLL (lives in %ProgramFiles%\Internet Explorer) you need to take the 32bit version when your JVM is 32bit, the 64bit version when your JVM is 64bit. Likewise for other platforms.
Apart from that, you should be all set. The generated Java bytecode s/b the same.
Note that you should use 64bit Java compiler for larger projects because it can address more memory.
you should convert test type >>>> test.tostring();
change the last line to this :
Label1.Text = "Du har nu lånat filmen:" + test.tostring();
B is not statistically significant. The data is not capable of drawing inferences from it. C does influence B probabilities
df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
avg_c=df['C'].mean()
sumC=df['C'].apply(lambda x: x if x<avg_c else 0).sum()
countC=df['C'].apply(lambda x: 1 if x<avg_c else None).count()
avg_c2=sumC/countC
df['C']=df['C'].apply(lambda x: avg_c2 if x >avg_c else x)
print(df)
model_ols = smf.ols("A ~ B+C",data=df).fit()
print(model_ols.summary())
df[['B','C']].plot()
plt.show()
df2=pd.DataFrame()
df2['B']=np.linspace(10,50,10)
df2['C']=30
df3=pd.DataFrame()
df3['B']=np.linspace(10,50,10)
df3['C']=100
predB=model_ols.predict(df2)
predC=model_ols.predict(df3)
plt.plot(df2['B'],predB,label='predict B C=30')
plt.plot(df3['B'],predC,label='predict B C=100')
plt.legend()
plt.show()
print("A change in the probability of C affects the probability of B")
intercept=model_ols.params.loc['Intercept']
B_slope=model_ols.params.loc['B']
C_slope=model_ols.params.loc['C']
#Intercept 11.874252
#B 0.760859
#C -0.060257
print("Intercept {}\n B slope{}\n C slope{}\n".format(intercept,B_slope,C_slope))
#lower_conf,upper_conf=np.exp(model_ols.conf_int())
#print(lower_conf,upper_conf)
#print((1-(lower_conf/upper_conf))*100)
model_cov=model_ols.cov_params()
std_errorB = np.sqrt(model_cov.loc['B', 'B'])
std_errorC = np.sqrt(model_cov.loc['C', 'C'])
print('SE: ', round(std_errorB, 4),round(std_errorC, 4))
#check for statistically significant
print("B z value {} C z value {}".format((B_slope/std_errorB),(C_slope/std_errorC)))
print("B feature is more statistically significant than C")
Output:
A change in the probability of C affects the probability of B
Intercept 11.874251554067563
B slope0.7608594144571961
C slope-0.060256845997223814
Standard Error: 0.4519 0.0793
B z value 1.683510336937001 C z value -0.7601036314930376
B feature is more statistically significant than C
z>2 is statistically significant
I had this same issue.
The solution for me was found in the Microsoft KB Article 2452723:
Basically, edit your scheduled task and take the Quotes out of the Start In field:
To get the relevant error message:
1) Convert 2147942667 to hex: 8007010B
2) Take last 4 digits (010B) and convert to decimal: 267
3) Run: net helpmsg 267
4) Result: "The directory name is invalid."
curl -H "Jenkins-Crumb: <your_crumb_data>" -u "<username>:<password>" "http://<your_jenkins_url>?buildWithParameters?token=<your_remote_api_name>?<parameterA>=<val_parameter_A>&<parameterB>=<val_parameterB>"
You can change following parameters as you want:
<your_crumb_data>
<username>
<password>
<your_jenkins_url>
<your_remote_api_name>
<parameterA>
<parameterB>
<val_parameter_A>
<val_parameter_B>
Note: Placing double quotes may be critical. Pay attention, please.
From what I know I don't believe that Chart.JS has any functionality to help for drawing text on a pie chart. But that doesn't mean you can't do it yourself in native JavaScript. I will give you an example on how to do that, below is the code for drawing text for each segment in the pie chart:
function drawSegmentValues()
{
for(var i=0; i<myPieChart.segments.length; i++)
{
// Default properties for text (size is scaled)
ctx.fillStyle="white";
var textSize = canvas.width/10;
ctx.font= textSize+"px Verdana";
// Get needed variables
var value = myPieChart.segments[i].value;
var startAngle = myPieChart.segments[i].startAngle;
var endAngle = myPieChart.segments[i].endAngle;
var middleAngle = startAngle + ((endAngle - startAngle)/2);
// Compute text location
var posX = (radius/2) * Math.cos(middleAngle) + midX;
var posY = (radius/2) * Math.sin(middleAngle) + midY;
// Text offside to middle of text
var w_offset = ctx.measureText(value).width/2;
var h_offset = textSize/4;
ctx.fillText(value, posX - w_offset, posY + h_offset);
}
}
A Pie Chart has an array of segments stored in PieChart.segments
, we can look at the startAngle
and endAngle
of these segments to determine the angle in between where the text would be middleAngle
. Then we would move in that direction by Radius/2
to be in the middle point of the chart in radians.
In the example above some other clean-up operations are done, due to the position of text drawn in fillText()
being the top right corner, we need to get some offset values to correct for that. And finally textSize
is determined based on the size of the chart itself, the larger the chart the larger the text.
With some slight modification you can change the discrete number values for a dataset into the percentile numbers in a graph. To do this get the total value
of the items in your dataset, call this totalValue
. Then on each segment you can find the percent by doing:
Math.round(myPieChart.segments[i].value/totalValue*100)+'%';
The section here myPieChart.segments[i].value/totalValue
is what calculates the percent that the segment takes up in the chart. For example if the current segment had a value of 50
and the totalValue was 200
. Then the percent that the segment took up would be: 50/200 => 0.25
. The rest is to make this look nice. 0.25*100 => 25
, then we add a %
at the end. For whole number percent tiles I rounded to the nearest integer, although can can lead to problems with accuracy. If we need more accuracy you can use .toFixed(n)
to save decimal places. For example we could do this to save a single decimal place when needed:
var value = myPieChart.segments[i].value/totalValue*100;
if(Math.round(value) !== value)
value = (myPieChart.segments[i].value/totalValue*100).toFixed(1);
value = value + '%';
Multiple statements are to be separated by a new line:
If SkyIsBlue Then
StartEngines
Pollute
ElseIf SkyIsRed Then
StopAttack
Vent
ElseIf SkyIsYellow Then
If Sunset Then
Sleep
ElseIf Sunrise or IsMorning Then
Smoke
GetCoffee
Else
Error
End If
Else
Joke
Laugh
End If
Actually they are the same. LEFT OUTER JOIN
is same as LEFT JOIN
and RIGHT OUTER JOIN
is same as RIGHT JOIN
. It is more informative way to compare from INNER Join
.
See this Wikipedia article for details.
Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.
So it should just look like this: onclick="CapacityChart()"
then it all should work :)
The glow effect is most-likely controlled by box-shadow. In addition to adding what Pavel said, you can add the box-shadow property for the different browser engines.
textarea {
border: none;
overflow: auto;
outline: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
resize: none; /*remove the resize handle on the bottom right*/
}
You may also try adding !important to prioritize this CSS.
An xmlns
is a unique identifier within the document - it doesn't have to be a URI to the schema:
XML namespaces provide a simple method for qualifying element and attribute names used in Extensible Markup Language documents by associating them with namespaces identified by URI references.
xsi:schemaLocation
is supposed to give a hint as to the actual schema location:
can be used in a document to provide hints as to the physical location of schema documents which may be used for assessment.
create a class with the following CSS and add it to your tags with onclick events:
cursor:pointer;
yes you can, look for std::reference_wrapper
, that mimics a reference but is assignable and also can be "reseated"
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
Never use .onclick()
, or similar attributes from a userscript! (It's also poor practice in a regular web page).
The reason is that userscripts operate in a sandbox ("isolated world"), and onclick
operates in the target-page scope and cannot see any functions your script creates.
Always use addEventListener()
Doc (or an equivalent library function, like jQuery .on()).
So instead of code like:
something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'
You would use:
something.outerHTML += '<input id="btnsave" ...>'
document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);
For the loop, you can't pass data to an event listener like that See the doc. Plus every time you change innerHTML
like that, you destroy the previous event listeners!
Without refactoring your code much, you can pass data with data attributes. So use code like this:
for (i = 0; i < EmoteURLLines.length; i++) {
if (checkIMG (EmoteURLLines[i])) {
localStorage.setItem ("nameEmotes", JSON.stringify (EmoteNameLines));
localStorage.setItem ("urlEmotes", JSON.stringify (EmoteURLLines));
localStorage.setItem ("usageEmotes", JSON.stringify (EmoteUsageLines));
if (i == 0) {
console.log (resetSlot ());
}
emoteTab[2].innerHTML += '<span style="cursor:pointer;" id="'
+ EmoteNameLines[i]
+ '" data-usage="' + EmoteUsageLines[i] + '">'
+ '<img src="' + EmoteURLLines[i] + '" /></span>'
;
} else {
alert ("The maximum emote (" + EmoteNameLines[i] + ") size is (36x36)");
}
}
//-- Only add events when innerHTML overwrites are done.
var targetSpans = emoteTab[2].querySelectorAll ("span[data-usage]");
for (var J in targetSpans) {
targetSpans[J].addEventListener ("click", appendEmote, false);
}
Where appendEmote is like:
function appendEmote (zEvent) {
//-- this and the parameter are special in event handlers. see the linked doc.
var emoteUsage = this.getAttribute ("data-usage");
shoutdata.value += emoteUsage;
}
.outerHTML
or .innerHTML
, you trash any event handlers on the affected nodes. If you use this method beware of that fact.The inconvenience of typing 10 < x && x < 20
is minimal compared to the increase in language complexity if one would allow 10 < x < 20
, so the designers of the Java language decided against supporting it.
If you are making a console window program, you can use system("pause");
Here is the sample on what worked for me. I think that put method is needed in entity class to map sql columns to java class attributes.
//simpleExample
Query query = em.createNativeQuery(
"SELECT u.name,s.something FROM user u, someTable s WHERE s.user_id = u.id",
NameSomething.class);
List list = (List<NameSomething.class>) query.getResultList();
Entity class:
@Entity
public class NameSomething {
@Id
private String name;
private String something;
// getters/setters
/**
* Generic put method to map JPA native Query to this object.
*
* @param column
* @param value
*/
public void put(Object column, Object value) {
if (((String) column).equals("name")) {
setName(String) value);
} else if (((String) column).equals("something")) {
setSomething((String) value);
}
}
}
Some examples of middleware: CORBA, Remote Method Invocation (RMI),...
The examples mentioned above are all pieces of software allowing you to take care of communication between different processes (either running on the same machine or distributed over e.g. the internet).
Using
.getActivity()
solves this issue:
For eg.
Intent i= new Intent(MainActivity.this.getActivity(), Next.class);
startActivity(i);
Hope this helps.
Cheers.
Here are two quickie approaches I know of:
In base
AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1
Not in base
library(qdap)
NAer(airquality)
PS P.S. Does my command above create a new dataframe called AQ1?
Look at AQ1 and see
I think the JavaScriptSerializer does not create a dynamic object.
So you should define the class first:
class MyObj {
public int arg1 {get;set;}
public int arg2 {get;set;}
}
And deserialize that instead of object
:
serializer.Deserialize<MyObj>(str);
Not testet, please try.
I know this is very Old post. Since we don't have any thing sun.misc in maven we can easily use
StringUtils.newStringUtf8(Base64.encodeBase64(encVal)); From org.apache.commons.codec.binary.Base64
suzanshakya, I'm actually modifying your code, I think this will simplify the code, but make sure before running the code the file must be in the same directory of the console otherwise you'll get error.
lookup="The_String_You're_Searching"
file_name = open("file.txt")
for num, line in enumerate(file_name,1):
if lookup in line:
print(num)
Easiest way of doing is: (In Linux/Ububuntu e.t.c)
Go to tomcat bin directory:
cd /opt/tomcat8.5/bin
create new file under bin directory "setenv.sh" and save below mention entries in it.
export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx2048m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"
and issue command:
./catalina.sh run
In your catalina log file you can see entry like this:
INFO [main] VersionLoggerListener.log Command line argument: -Xms512m
INFO [main] VersionLoggerListener.log Command line argument: -Xmx2048m
INFO [main] VersionLoggerListener.log Command line argument: -XX:MaxPermSize=256m
Which confirms that above changes took place.
Also, the value of "Xms512m" and "-Xmx2048m" can be modified accordingly in the setenv.sh file.
Startup of tomcat could be done in two steps as well. cd /opt/tomcat8.5/bin
Step #1
run ./setenv.sh
Step #2
./startup.sh
If you're using systemd edit:
/usr/lib/systemd/system/tomcat8.service
and set
Environment=CATALINA_OPTS="-Xms512M -Xmx2048M -XX:MaxPermSize=256m"
Standard SQL syntax is
DROP TABLE table_name;
IF EXISTS
is not standard; different platforms might support it with different syntax, or not support it at all. In PostgreSQL, the syntax is
DROP TABLE IF EXISTS table_name;
The first one will throw an error if the table doesn't exist, or if other database objects depend on it. Most often, the other database objects will be foreign key references, but there may be others, too. (Views, for example.) The second will not throw an error if the table doesn't exist, but it will still throw an error if other database objects depend on it.
To drop a table, and all the other objects that depend on it, use one of these.
DROP TABLE table_name CASCADE;
DROP TABLE IF EXISTS table_name CASCADE;
Use CASCADE with great care.
I would recommend that you use display: inline;
. float
is screwed up in IE. Here is an example of how I would approach it:
<ul class="side-by-side">
<li>item 1<li>
<li>item 2<li>
<li>item 3<li>
</ul>
and here's the css:
.side-by-side {
width: 100%;
border: 1px solid black;
}
.side-by-side li {
display: inline;
}
Also, if you use floats the ul
will not wrap around the li
's and will instead have a hight of 0 in this example:
.side-by-side li {
float: left;
}
The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:
>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'
You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!
You can use this method.
public static File getRobotCacheFile(Context context) throws IOException {
File cacheFile = new File(context.getCacheDir(), "robot.png");
try {
InputStream inputStream = context.getAssets().open("robot.png");
try {
FileOutputStream outputStream = new FileOutputStream(cacheFile);
try {
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
throw new IOException("Could not open robot png", e);
}
return cacheFile;
}
You should never use InputStream.available() in such cases. It returns only bytes that are buffered. Method with .available() will never work with bigger files and will not work on some devices at all.
In Kotlin (;D):
@Throws(IOException::class)
fun getRobotCacheFile(context: Context): File = File(context.cacheDir, "robot.png")
.also {
it.outputStream().use { cache -> context.assets.open("robot.png").use { it.copyTo(cache) } }
}
If it worked the way you expected it to (resulting in "abc9"
), what would "9" + 9
deliver? 18
or "99"
?
To remove this ambiguity, you are required to make explicit what you want to convert in this case:
"abc" + str(9)
int processed = 0;
foreach(ListViewItem lvi in listView.Items)
{
//do stuff
if (++processed == 50) break;
}
or use LINQ
foreach( ListViewItem lvi in listView.Items.Cast<ListViewItem>().Take(50))
{
//do stuff
}
or just use a regular for loop (as suggested by @sgriffinusa and @Eric J.)
for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
ListViewItem lvi = listView.Items[i];
}
I do like this and its working fine.
constructor() {
super();
this.state ={
status:true
}
}
render() {
return(
{ this.state.status === true ?
<TouchableHighlight onPress={()=>this.hideView()}>
<View style={styles.optionView}>
<Text>Ok Fine :)</Text>
</View>
</TouchableHighlight>
:
<Text>Ok Fine.</Text>
}
);
}
hideView(){
this.setState({
home:!this.state.status
});
}
If the function defined is in a file x.py
:
def greet():
print('Hello! How are you?')
In the file where you are importing the function, write this:
from x import greet
This is useful if you do not wish to import all the functions in a file.
DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
if (dr["Column_Name"] == DBNull.Value)
{
//Do something
}
else
{
//Do something
}
}
I came up with this CSS only method of rotating the screen using media queries. The queries are based on screen sizes that I found here. 480px seemed to be a good as no/few devices had more than 480px width or less than 480px height.
@media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) {
html{
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-transform-origin: left top;
-moz-transform-origin: left top;
-ms-transform-origin: left top;
-o-transform-origin: left top;
transform-origin: left top;
width: 320px; /*this is the iPhone screen width.*/
position: absolute;
top: 100%;
left: 0
}
}
In my opinion this is a design flaw of pytz library. It should be more reliable to specify a timezone using the offset, e.g.
pytz.construct("UTC-07:00")
which gives you Canada/Pacific timezone.
By what you wrote, you are missing a critical piece of understanding: the difference between a class and an object. __init__
doesn't initialize a class, it initializes an instance of a class or an object. Each dog has colour, but dogs as a class don't. Each dog has four or fewer feet, but the class of dogs doesn't. The class is a concept of an object. When you see Fido and Spot, you recognise their similarity, their doghood. That's the class.
When you say
class Dog:
def __init__(self, legs, colour):
self.legs = legs
self.colour = colour
fido = Dog(4, "brown")
spot = Dog(3, "mostly yellow")
You're saying, Fido is a brown dog with 4 legs while Spot is a bit of a cripple and is mostly yellow. The __init__
function is called a constructor, or initializer, and is automatically called when you create a new instance of a class. Within that function, the newly created object is assigned to the parameter self
. The notation self.legs
is an attribute called legs
of the object in the variable self
. Attributes are kind of like variables, but they describe the state of an object, or particular actions (functions) available to the object.
However, notice that you don't set colour
for the doghood itself - it's an abstract concept. There are attributes that make sense on classes. For instance, population_size
is one such - it doesn't make sense to count the Fido because Fido is always one. It does make sense to count dogs. Let us say there're 200 million dogs in the world. It's the property of the Dog class. Fido has nothing to do with the number 200 million, nor does Spot. It's called a "class attribute", as opposed to "instance attributes" that are colour
or legs
above.
Now, to something less canine and more programming-related. As I write below, class to add things is not sensible - what is it a class of? Classes in Python make up of collections of different data, that behave similarly. Class of dogs consists of Fido and Spot and 199999999998 other animals similar to them, all of them peeing on lampposts. What does the class for adding things consist of? By what data inherent to them do they differ? And what actions do they share?
However, numbers... those are more interesting subjects. Say, Integers. There's a lot of them, a lot more than dogs. I know that Python already has integers, but let's play dumb and "implement" them again (by cheating and using Python's integers).
So, Integers are a class. They have some data (value), and some behaviours ("add me to this other number"). Let's show this:
class MyInteger:
def __init__(self, newvalue)
# imagine self as an index card.
# under the heading of "value", we will write
# the contents of the variable newvalue.
self.value = newvalue
def add(self, other):
# when an integer wants to add itself to another integer,
# we'll take their values and add them together,
# then make a new integer with the result value.
return MyInteger(self.value + other.value)
three = MyInteger(3)
# three now contains an object of class MyInteger
# three.value is now 3
five = MyInteger(5)
# five now contains an object of class MyInteger
# five.value is now 5
eight = three.add(five)
# here, we invoked the three's behaviour of adding another integer
# now, eight.value is three.value + five.value = 3 + 5 = 8
print eight.value
# ==> 8
This is a bit fragile (we're assuming other
will be a MyInteger), but we'll ignore now. In real code, we wouldn't; we'd test it to make sure, and maybe even coerce it ("you're not an integer? by golly, you have 10 nanoseconds to become one! 9... 8....")
We could even define fractions. Fractions also know how to add themselves.
class MyFraction:
def __init__(self, newnumerator, newdenominator)
self.numerator = newnumerator
self.denominator = newdenominator
# because every fraction is described by these two things
def add(self, other):
newdenominator = self.denominator * other.denominator
newnumerator = self.numerator * other.denominator + self.denominator * other.numerator
return MyFraction(newnumerator, newdenominator)
There's even more fractions than integers (not really, but computers don't know that). Let's make two:
half = MyFraction(1, 2)
third = MyFraction(1, 3)
five_sixths = half.add(third)
print five_sixths.numerator
# ==> 5
print five_sixths.denominator
# ==> 6
You're not actually declaring anything here. Attributes are like a new kind of variable. Normal variables only have one value. Let us say you write colour = "grey"
. You can't have another variable named colour
that is "fuchsia"
- not in the same place in the code.
Arrays solve that to a degree. If you say colour = ["grey", "fuchsia"]
, you have stacked two colours into the variable, but you distinguish them by their position (0, or 1, in this case).
Attributes are variables that are bound to an object. Like with arrays, we can have plenty colour
variables, on different dogs. So, fido.colour
is one variable, but spot.colour
is another. The first one is bound to the object within the variable fido
; the second, spot
. Now, when you call Dog(4, "brown")
, or three.add(five)
, there will always be an invisible parameter, which will be assigned to the dangling extra one at the front of the parameter list. It is conventionally called self
, and will get the value of the object in front of the dot. Thus, within the Dog's __init__
(constructor), self
will be whatever the new Dog will turn out to be; within MyInteger
's add
, self
will be bound to the object in the variable three
. Thus, three.value
will be the same variable outside the add
, as self.value
within the add
.
If I say the_mangy_one = fido
, I will start referring to the object known as fido
with yet another name. From now on, fido.colour
is exactly the same variable as the_mangy_one.colour
.
So, the things inside the __init__
. You can think of them as noting things into the Dog's birth certificate. colour
by itself is a random variable, could contain anything. fido.colour
or self.colour
is like a form field on the Dog's identity sheet; and __init__
is the clerk filling it out for the first time.
Any clearer?
EDIT: Expanding on the comment below:
You mean a list of objects, don't you?
First of all, fido
is actually not an object. It is a variable, which is currently containing an object, just like when you say x = 5
, x
is a variable currently containing the number five. If you later change your mind, you can do fido = Cat(4, "pleasing")
(as long as you've created a class Cat
), and fido
would from then on "contain" a cat object. If you do fido = x
, it will then contain the number five, and not an animal object at all.
A class by itself doesn't know its instances unless you specifically write code to keep track of them. For instance:
class Cat:
census = [] #define census array
def __init__(self, legs, colour):
self.colour = colour
self.legs = legs
Cat.census.append(self)
Here, census
is a class-level attribute of Cat
class.
fluffy = Cat(4, "white")
spark = Cat(4, "fiery")
Cat.census
# ==> [<__main__.Cat instance at 0x108982cb0>, <__main__.Cat instance at 0x108982e18>]
# or something like that
Note that you won't get [fluffy, sparky]
. Those are just variable names. If you want cats themselves to have names, you have to make a separate attribute for the name, and then override the __str__
method to return this name. This method's (i.e. class-bound function, just like add
or __init__
) purpose is to describe how to convert the object to a string, like when you print it out.
try to use use include_once
or require_once
instead of include
or require
I realize this is an older post, but thought this might be helpful to anyone wondering the same question:
While the previous answers are no doubt valid, there is a more simple reason for the distinction between textarea and input.
As mentioned previously, HTML is used to describe and give as much semantic structure to web content as possible, including input forms. A textarea may be used for input, however a textarea can also be marked as read only via the readonly attribute. The existence of such an attribute would not make any sense for an input type, and thus the distinction.
An evolved version of ossek solution
Custom filter is more appropriate, then you can use it anywhere in the project
js file
var myApp = angular.module('myApp',[]);
myApp.filter('utcdate', ['$filter','$locale', function($filter, $locale){
return function (input, format) {
if (!angular.isDefined(format)) {
format = $locale['DATETIME_FORMATS']['medium'];
}
var date = new Date(input);
var d = new Date()
var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return $filter('date')(_utc, format)
};
}]);
in template
<p>This will convert UTC time to local time<p>
<span>{{dateTimeInUTC | utcdate :'MMM d, y h:mm:ss a'}}</span>
You need to remove the brackets
ALTER TABLE Countries
ADD
HasPhotoInReadyStorage bit,
HasPhotoInWorkStorage bit,
HasPhotoInMaterialStorage bit,
HasText bit;
If you are pushing a view controller from page view controller page, you cannot update the navigation controller's back button title. To solve this create a delegate back to your parent view controller (you may also be able to traverse the view controller hierarchy back up to the parent).
Furthermore, Back buttons have a character limit. If you exceed that character limit, the system will default to "Back". It will not truncate for you. For example:
backItem.title = "Birthdays/Anniversaries" // Get's converted to "Back".
backItem.title = "Birthdays/Anniversa…" // Fits and shows as is.
Have a look here.
Following files have FTL extension:
There is an article here that describes your problem
http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/
<fb:visible-to-connection>
Fans will see this content.
<fb:else>
Non-fans will see this content.
</fb:else>
</fb:visible-to-connection>
let dateObj = new Date();
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
For reference you can see the below details
new Date().getDate() // Return the day as a number (1-31)
new Date().getDay() // Return the weekday as a number (0-6)
new Date().getFullYear() // Return the four digit year (yyyy)
new Date().getHours() // Return the hour (0-23)
new Date().getMilliseconds() // Return the milliseconds (0-999)
new Date().getMinutes() // Return the minutes (0-59)
new Date().getMonth() // Return the month (0-11)
new Date().getSeconds() // Return the seconds (0-59)
new Date().getTime() // Return the time (milliseconds since January 1, 1970)
let dateObj = new Date();_x000D_
_x000D_
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());_x000D_
_x000D_
console.log(myDate)
_x000D_
// Return the minutes (0-59) new Date().getMonth() // Return the month (0-11) new Date().getSeconds() // Return the seconds (0-59) new Date().getTime() // Return the time (milliseconds since January 1, 1970)
Changing this project setting solve the issue for me.
The error means there are some methods of the class that aren't implemented. You cannot instantiate such a class, so there isn't anything you can do, other than implement all of the methods of the class.
On the other hand, a common pattern is to instantiate a concrete class and assign it to a pointer of an abstrate base class:
class Abstract { /* stuff */ 4};
class Derived : virtual public Abstract { /* implement Abstract's methods */ };
Abstract* pAbs = new Derived; // OK
Just an aside, to avoid memory management issues with the above line, you could consider using a smart pointer, such as an `std::unique_ptr:
std::unique_ptr<Abstract> pAbs(new Derived);
You should use a ImageButton and specify the image in android:src
, and set android:scaletype
to fitXY
Drawable drawable = getResources().getDrawable(R.drawable.s_vit);
drawable.setBounds(0, 0, (int)(drawable.getIntrinsicWidth()*0.5),
(int)(drawable.getIntrinsicHeight()*0.5));
ScaleDrawable sd = new ScaleDrawable(drawable, 0, scaleWidth, scaleHeight);
Button btn = findViewbyId(R.id.yourbtnID);
btn.setCompoundDrawables(sd.getDrawable(), null, null, null); //set drawableLeft for example
Funny enough, a same problem I just met, and I get this work in following way:
combining with linux command ln
, we can make thing a lot simper:
1. cd Proj/Client
2. ln -s ../Common ./
3. cd Proj/Server
4. ln -s ../Common ./
And, now if you want to import some_stuff
from file: Proj/Common/Common.py
into your file: Proj/Client/Client.py
, just like this:
# in Proj/Client/Client.py
from Common.Common import some_stuff
And, the same applies to Proj/Server
, Also works for setup.py
process,
a same question discussed here, hope it helps !
When you deploy a Java EE web application (using frameworks or not),its structure must follow some requirements/specifications. These specifications come from :
- The servlet container (e.g Tomcat)
- Java Servlet API
- Your application domain
Java Servlet API requirements
Java Servlet API states that your root application directory must have the following structure :
ApplicationName
|
|--META-INF
|--WEB-INF
|_web.xml <-- Here is the configuration file of your web app(where you define servlets, filters, listeners...)
|_classes <--Here goes all the classes of your webapp, following the package structure you defined. Only
|_lib <--Here goes all the libraries (jars) your application need
These requirements are defined by Java Servlet API.
3. Your application domain
Now that you've followed the requirements of the Servlet container(or application server) and the Java Servlet API requirements, you can organize the other parts of your webapp based upon what you need.
- You can put your resources (JSP files, plain text files, script files) in your application root directory. But then, people can access them directly from their browser, instead of their requests being processed by some logic provided by your application. So, to prevent your resources being directly accessed like that, you can put them in the WEB-INF directory, whose contents is only accessible by the server.
-If you use some frameworks, they often use configuration files. Most of these frameworks (struts, spring, hibernate) require you to put their configuration files in the classpath (the "classes" directory).
Had a similar problem in one of my .Net Standard dlls.
I used Microsoft.XmlSerializer.Generator nuget, which pre-generating XmlSerializer on .Net Core and .Net Standard.
Add target="_blank"
to the <form>
tag.
You can use this way...
grep -P '^\s$' file
-P
is used for Perl regular expressions (an extension to POSIX grep
).\s
match the white space characters; if followed by *
, it matches an empty line also.^
matches the beginning of the line. $
matches the end of the line. Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:
Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):
=$A1<>$B1
Then press OK and that should do it.
use document.activeElement.blur();
example at http://jsfiddle.net/vGGdV/5/ that shows the currently focused element as well.
Keep a note though that calling blur()
on the body element in IE will make the IE lose focus
Here's a correct table of percentages to hex values. E.g. for 50% white you'd use #80FFFFFF.
(source)
Another option could be:
var initial = function() {
console.log( 'initial function!' );
}
var iWantToExecuteThisOneToo = function () {
console.log( 'the other function that i wanted to execute!' );
}
function extendFunction( oldOne, newOne ) {
return (function() {
oldOne();
newOne();
})();
}
var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );
Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery
You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/
All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter
<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">
and run js function
app_handle_listing_horisontal_scroll($('#table-listing'))
In order to build an AJAX webservice, you need TWO files :
So, first you call your webservice using this JQuery syntax, in the JavaScript file :
$.ajax({
url : 'mywebservice.php',
type : 'POST',
data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
dataType : 'json',
success: function (data) {
alert("The file is "+data.fichierZIP);
},
error: function(data) {
//console.log(data);
var responseText=JSON.parse(data.responseText);
alert("Error(s) while building the ZIP file:\n"+responseText.messages);
}
});
Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:
<?php
//...
//I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
//$errors is a string that may contain an error message while preparing the ZIP file
//In the end, I check if there has been an error, and if so, I return an error object
//...
if ($errors==''){
//if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['ZIPFILENAME'] = basename($filename);
print json_encode($result);
} else {
//if there is an error, you should return a special header, followed by another JSON object
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['messages'] = $errors;
//feel free to add other information like $result['errorcode']
die(json_encode($result));
}
?>
Add More detail from @Martin answer
// linked your button here
@IBAction func mobileTFChanged(sender: AnyObject) {
checkMaxLength(sender as! UITextField, maxLength: 10)
}
// linked your button here
@IBAction func citizenTFChanged(sender: AnyObject) {
checkMaxLength(sender as! UITextField, maxLength: 13)
}
func checkMaxLength(textField: UITextField!, maxLength: Int) {
// swift 1.0
//if (count(textField.text!) > maxLength) {
// textField.deleteBackward()
//}
// swift 2.0
if (textField.text!.characters.count > maxLength) {
textField.deleteBackward()
}
}
Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.
Is this what you're looking for?
#include <chrono>
#include <iostream>
int main()
{
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::milliseconds ms;
typedef std::chrono::duration<float> fsec;
auto t0 = Time::now();
auto t1 = Time::now();
fsec fs = t1 - t0;
ms d = std::chrono::duration_cast<ms>(fs);
std::cout << fs.count() << "s\n";
std::cout << d.count() << "ms\n";
}
which for me prints out:
6.5e-08s
0ms
A simple example could be,
import tensorflow as tf
import numpy as np
a=tf.random_normal([2,3],0.0,1.0,dtype=tf.float32) #sampling from a std normal
print(type(a))
#<class 'tensorflow.python.framework.ops.Tensor'>
tf.InteractiveSession() # run an interactive session in Tf.
n now if we want this tensor a to be converted into a numpy array
a_np=a.eval()
print(type(a_np))
#<class 'numpy.ndarray'>
As simple as that!
Look at the jQuery unload function. It handles all the things.
https://api.jquery.com/unload/
The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.
$(window).unload(
function(event) {
alert("navigating");
}
);
This is a simple example for adding the background image in a JFrame:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
JButton b1;
JLabel l1;
public BackgroundImageJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
One way
-----------------
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
*/
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
add(l1);
add(b1);
// Just for refresh :) Not optional!
setSize(399,399);
setSize(400,400);
}
public static void main(String args[])
{
new BackgroundImageJFrame();
}
}
function compareIsEqualArray(array $array1,array $array):bool
{
return (array_diff($array1,$array2)==[] && array_diff($array2,$array1)==[]);
}
An auto-updated column is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. An auto-updated column remains unchanged if all other columns are set to their current values.
To explain it let's imagine you have only one row:
-------------------------------
| price | updated_at |
-------------------------------
| 2 | 2018-02-26 16:16:17 |
-------------------------------
Now, if you run the following update column:
update my_table
set price = 2
it will not change the value of updated_at, since price value wasn't actually changed (it was already 2).
But if you have another row with price value other than 2, then the updated_at value of that row (with price <> 3) will be updated to CURRENT_TIMESTAMP.
This seems to work:
$("#theSelect").change(function(){
var value = $("#theSelect option:selected").val();
var theDiv = $(".is" + value);
theDiv.slideDown().removeClass("hidden");
//Add this...
$("#theSelect option:selected").attr('disabled', 'disabled');
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
//...and this.
$("#theSelect option:disabled").removeAttr('disabled');
});
To do structural modification on the source of the stream, as Pshemo mentioned in his answer, one solution is to create a new instance of a Collection
like ArrayList
with the items inside your primary list; iterate over the new list, and do the operations on the primary list.
new ArrayList<>(users).stream().forEach(u -> users.remove(u));
Take IISReset as a suite of commands that helps you manage IIS start / stop etc.
Which means you need to specify option (/switch
) what you want to do to carry any operation.
Default behavior OR default switch is /restart
with iisreset
so you do not need to run command twice with /start
and /stop
.
Hope this clarifies your question. For reference the output of iisreset /?
is:
IISRESET.EXE (c) Microsoft Corp. 1998-2005 Usage: iisreset [computername] /RESTART Stop and then restart all Internet services. /START Start all Internet services. /STOP Stop all Internet services. /REBOOT Reboot the computer. /REBOOTONERROR Reboot the computer if an error occurs when starting, stopping, or restarting Internet services. /NOFORCE Do not forcefully terminate Internet services if attempting to stop them gracefully fails. /TIMEOUT:val Specify the timeout value ( in seconds ) to wait for a successful stop of Internet services. On expiration of this timeout the computer can be rebooted if the /REBOOTONERROR parameter is specified. The default value is 20s for restart, 60s for stop, and 0s for reboot. /STATUS Display the status of all Internet services. /ENABLE Enable restarting of Internet Services on the local system. /DISABLE Disable restarting of Internet Services on the local system.
Officially, the SQL languages does not support a JOIN or FROM clause in an UPDATE statement unless it is in a subquery. Thus, the Hoyle ANSI approach would be something like
Update addresses
Set cid = (
Select c.id
From customers As c
where c.id = a.id
)
Where Exists (
Select 1
From customers As C1
Where C1.id = addresses.id
)
However many DBMSs such Postgres support the use of a FROM clause in an UPDATE statement. In many cases, you are required to include the updating table and alias it in the FROM clause however I'm not sure about Postgres:
Update addresses
Set cid = c.id
From addresses As a
Join customers As c
On c.id = a.id
I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive
This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.
If you are willing to use an external library, I can't recommend bstrlib
enough. It takes a little extra setup, but is easier to use in the long run.
For example, split the string below, one first creates a bstring
with the bfromcstr()
call. (A bstring
is a wrapper around a char buffer).
Next, split the string on commas, saving the result in a struct bstrList
, which has fields qty
and an array entry
, which is an array of bstring
s.
bstrlib
has many other functions to operate on bstring
s
Easy as pie...
#include "bstrlib.h"
#include <stdio.h>
int main() {
int i;
char *tmp = "Hello,World,sak";
bstring bstr = bfromcstr(tmp);
struct bstrList *blist = bsplit(bstr, ',');
printf("num %d\n", blist->qty);
for(i=0;i<blist->qty;i++) {
printf("%d: %s\n", i, bstr2cstr(blist->entry[i], '_'));
}
}
DELETE FROM tablename a
WHERE a.ROWID > ANY (SELECT b.ROWID
FROM tablename b
WHERE a.fieldname = b.fieldname
AND a.fieldname2 = b.fieldname2)
When I installed OS X Yosemite,I got problem with Mysql. I tried lot of methods but none worked. I actually found a quite easy way. Try this out.
sudo su
sudo /usr/local/mysql/support-files/mysql.server stop
sudo mysqld_safe --skip-grant-tables
mysql -u root
UPDATE mysql.user SET Password=PASSWORD('new_password') WHERE User='root';
FLUSH PRIVILEGES;
That's what echo
does:
echo "Some text here." > myfile.txt
In case of 2 different components (not nested components, parent\child\grandchild ) I suggest you this:
MissionService:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MissionService {
// Observable string sources
private missionAnnouncedSource = new Subject<string>();
private missionConfirmedSource = new Subject<string>();
// Observable string streams
missionAnnounced$ = this.missionAnnouncedSource.asObservable();
missionConfirmed$ = this.missionConfirmedSource.asObservable();
// Service message commands
announceMission(mission: string) {
this.missionAnnouncedSource.next(mission);
}
confirmMission(astronaut: string) {
this.missionConfirmedSource.next(astronaut);
}
}
AstronautComponent:
import { Component, Input, OnDestroy } from '@angular/core';
import { MissionService } from './mission.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'my-astronaut',
template: `
<p>
{{astronaut}}: <strong>{{mission}}</strong>
<button
(click)="confirm()"
[disabled]="!announced || confirmed">
Confirm
</button>
</p>
`
})
export class AstronautComponent implements OnDestroy {
@Input() astronaut: string;
mission = '<no mission announced>';
confirmed = false;
announced = false;
subscription: Subscription;
constructor(private missionService: MissionService) {
this.subscription = missionService.missionAnnounced$.subscribe(
mission => {
this.mission = mission;
this.announced = true;
this.confirmed = false;
});
}
confirm() {
this.confirmed = true;
this.missionService.confirmMission(this.astronaut);
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}
}
With angular 4 you can fix this issue by updating app.module.ts file as follows:
Add import statement at the top as below:
import {APP_BASE_HREF} from '@angular/common';
And add below line inside @NgModule
providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
In the simplest terms, if your query returns column_name and it holds a string:
while (rdr.Read())
{
string yourString = rdr.getString("column_name")
}
Doesn't SELECT LEN(column_name)
work?
This worked for me.
$ echo 54657374696e672031203220330 | xxd -r -p
Testing 1 2 3$
-r
tells it to convert hex to ascii as opposed to its normal mode of doing the opposite
-p
tells it to use a plain format.
Check if you are using session_write_close(); anywhere, I was using this right after another session and then trying to write to the session again and it wasn't working.. so just comment that sh*t out
Given a radius length r and an angle t in radians and a circle's center (h,k), you can calculate the coordinates of a point on the circumference as follows (this is pseudo-code, you'll have to adapt it to your language):
float x = r*cos(t) + h;
float y = r*sin(t) + k;
Today I was looking for this very solution and I tried PDFtoPrinter which I had an issue with (the PDFs I tried printing suggested they used incorrect paper size which hung the print job and nothing else printed until resolved). In my effort to find an alternative, I remembered GhostScript and utilities associated with it. I found GSView and it's associated program GSPrint (reference https://www.ghostscript.com/). Both these require GhostScript (https://www.ghostscript.com/) but when all the components are installed, GSPrint worked flawlessly and I was able to create a scheduled task that printed PDFs automatically overnight.
For multiple interval types use a nested construction as in:
UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)
For updating a given date in the column date
to 1 year + 1 day
Give headercss position fixed.
.headercss {
width: 100%;
height: 320px;
background-color: #000000;
position: fixed;
top:0
}
Then give the content container a 320px padding-top, so it doesn't get behind the header.
You can set tabIndex="-1"
. It will make browser to skip this button when you TAB through focusable controls.
Other "fixes" suggested here, only remove focus outline, but still leaves buttons tabable. However, from usability point of view, you already removed glow, so your user won't know what is currently focused button, any way.
On other hand, making button non-tabable have accessibility implications.
I'm using it to remove focus outline from X button in bootstrap modal
, which have duplicate "Close" button at the bottom any way, so my solution have no impact on accessibility.
An ugly solution that works like a charm for me:
$("#mydialog").dialog(
open: function(){
$('div.ui-widget-overlay').hide();
$("div.ui-dialog").not(':first').remove();
}
});
<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
Left aligned text on viewports sized MD (medium) or wider.
Left aligned text on viewports sized LG (large) or wider.
Left aligned text on viewports sized XL (extra-large) or wider.
Try this:
// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg),
Base64.NO_WRAP);
try {
$result=DB::table('users')->whereExists(function ($Query){
$Query->where('id','<','14162756');
$Query->whereBetween('password',[14162756,48384486]);
$Query->whereIn('id',[3,8,12]);
});
}catch (\Exception $error){
Log::error($error);
DB::rollBack(1);
return redirect()->route('bye');
}
trap 'kill $(jobs -p)' EXIT
I would make only minor changes to Johannes' answer and use jobs -pr to limit the kill to running processes and add a few more signals to the list:
trap 'kill $(jobs -pr)' SIGINT SIGTERM EXIT
You can use the following nginx configuration example:
upstream adminhost {
server adminhostname:8080;
}
server {
listen 80;
location ~ ^/admin/(.*)$ {
proxy_pass http://adminhost/$1$is_args$args;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
Latest Android Studio 1.4.
Click File->Project Structure->SDK Location->JDK Location.
You could also set individual module JDK Version compatibility by going to the Module (below the SDK Location), and edit the Source Compatibility accordingly. (note, this only applies to Android Module).
patrick dw's answer is right on.
For kicks and giggles I thought I would post a simple way to return an array of all the IDs.
var arrayOfIds = $.map($(".myClassName"), function(n, i){
return n.id;
});
alert(arrayOfIds);
For my console program the answers with tkinter above did not quite work for me because the .destroy() always gave an error,:
can't invoke "event" command: application has been destroyed while executing...
or when using .withdraw() the console window did not get the focus back.
To solve this you also have to call .update() before the .destroy(). Example:
# Python 3
import tkinter
r = tkinter.Tk()
text = r.clipboard_get()
r.withdraw()
r.update()
r.destroy()
The r.withdraw() prevents the frame from showing for a milisecond, and then it will be destroyed giving the focus back to the console.
Here's what worked for me:
var clicked = {}
$("[contenteditable='true']").each(function(){
var id = $(this).attr("id");
$(this).bind('focus', function() {
// store the original value of element first time it gets focus
if(!(id in clicked)){
clicked[id] = $(this).html()
}
});
});
// then once the user clicks on save
$("#save").click(function(){
for(var id in clicked){
var original = clicked[id];
var current = $("#"+id).html();
// check if value changed
if(original != current) save(id,current);
}
});
For anyone trying to get this working using the Sysdeo Eclipse Tomcat plugin, try the following steps (I used Sysdeo Tomcat Plugin 3.3.0, Eclipse Kepler, and Tomcat 7.0.53 to construct these steps):
-Djava.util.logging.config.file="{TOMCAT_HOME}\conf\logging.properties"
, where {TOMCAT_HOME}
is the path to your Tomcat directory (example: C:\Tomcat\apache-tomcat-7.0.53\conf\logging.properties). Click OK.-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
. Click OK.{TOMCAT_HOME}\conf\logging.properties
file as specified in the question above.{TOMCAT_HOME}\logs\catalina.yyyy-mm-dd.log
.You can use the HTMLParser module.
The code would probably look something like this:
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, print it.
if name == "href":
print name, "=", value
parser = MyHTMLParser()
parser.feed(your_html_string)
Note: The HTMLParser module has been renamed to html.parser in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.
To get or set an attribute of an HTML element, you can use the element.attr()
function in jQuery.
To get the href attribute, use the following code:
var a_href = $('selector').attr('href');
To set the href attribute, use the following code:
$('selector').attr('href','http://example.com');
In both cases, please use the appropriate selector. If you have set the class for the anchor element, use '.class-name'
and if you have set the id for the anchor element, use '#element-id'
.
You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.
Change const
to static readonly
and initialise it like this
static readonly MyStruct[] MyArray = new[] {
new MyStruct { label = "a", id = 1 },
new MyStruct { label = "b", id = 5 },
new MyStruct { label = "q", id = 29 }
};
from __future__ import print_function
import csv
import MySQLdb
print("Enter File To Be Export")
conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="database")
cursor = conn.cursor()
#sql = 'CREATE DATABASE test1'
sql ='''DROP TABLE IF EXISTS `test1`; CREATE TABLE test1 (policyID int, statecode varchar(255), county varchar(255))'''
cursor.execute(sql)
with open('C:/Users/Desktop/Code/python/sample.csv') as csvfile:
reader = csv.DictReader(csvfile, delimiter = ',')
for row in reader:
print(row['policyID'], row['statecode'], row['county'])
# insert
conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="database")
sql_statement = "INSERT INTO test1(policyID ,statecode,county) VALUES (%s,%s,%s)"
cur = conn.cursor()
cur.executemany(sql_statement,[(row['policyID'], row['statecode'], row['county'])])
conn.escape_string(sql_statement)
conn.commit()
window.location
adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.
window.location.replace
replaces the current history item so you can't go back to it.
See window.location
:
assign(url)
: Load the document at the provided URL.
replace(url)
:Replace the current document with the one at the provided URL. The difference from theassign()
method is that after usingreplace()
the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
Oh and generally speaking:
window.location.href = url;
is favoured over:
window.location = url;
In PostgreSQL, the default limit is 63 characters. Because index names must be unique it's nice to have a little convention. I use (I tweaked the example to explain more complex constructions):
def change
add_index :studies, [:professor_id, :user_id], name: :idx_study_professor_user
end
The normal index would have been:
:index_studies_on_professor_id_and_user_id
The logic would be:
index
becomes idx
_id
Which usually does the job.
You can check elasticsearch cluster health by using (CURL) and Cluster API provieded by elasticsearch:
$ curl -XGET 'localhost:9200/_cluster/health?pretty'
This will give you the status and other related data you need.
{
"cluster_name" : "xxxxxxxx",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 2,
"number_of_data_nodes" : 2,
"active_primary_shards" : 15,
"active_shards" : 12,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0
}
Response.Write("<scrip" + "t>test(" + x + "," + y + ");</script>");
breaking up the script keyword because VStudio / asp.net compiler doesn't like it
If you develop for Android KitKat or newer, you could also use a switch statement (see: Android coding with switch (String)). e.g.
switch(yourString)
{
case "john":
//do something for john
case "mary":
//do something for mary
}
You can change youralias.conf
file like this code:
Alias /Quiz/ "h:/MyServer/Quiz/"
<Directory "h:/MyServer/Quiz/">
Options Indexes FollowSymLinks
AllowOverride all
<IfDefine APACHE24>
Require local
</IfDefine>
<IfDefine !APACHE24>
Order Deny,Allow
Deny from all
Allow from localhost ::1 127.0.0.1
</IfDefine>
</Directory>
A little late to this party - but this also works well:
CREATE VIEW [ABC].[View_SomeDataUniqueKey]
AS
SELECT
CAST(CONCAT(CAST([ID] AS VARCHAR(4)),
CAST(ROW_NUMBER() OVER(ORDER BY [ID] ASC) as VARCHAR(4))
) AS int) AS [UniqueId]
,[ID]
FROM SOME_TABLE JOIN SOME_OTHER_TABLE
GO
In my case the join resulted in [ID] - the primary key being repeated up to 5 times (associated different unique data) The nice trick with this is that the original ID can be determined from each UniqueID effectively [ID]+RowNumber() = 11, 12, 13, 14, 21, 22, 23, 24 etc. If you add RowNumber() and [ID] back into the view - you can easily determine your original key from the data. But - this is not something that should be committed to a table because I am fairly sure that the RowNumber() of a view will never be reliably the same as the underlying data alters, even with the OVER(ORDER BY [ID] ASC) to try and help it.
Example output ( Select UniqueId, ID, ROWNR, Name from [REF].[View_Systems] ) :
UniqueId ID ROWNR Name
11 1 1 Amazon A
12 1 2 Amazon B
13 1 3 Amazon C
14 1 4 Amazon D
15 1 5 Amazon E
Table1:
[ID] [Name]
1 Amazon
Table2:
[ID] [Version]
1 A
1 B
1 C
1 D
1 E
CREATE VIEW [REF].[View_Systems]
AS
SELECT
CAST(CONCAT(CAST(TABA.[ID] AS VARCHAR(4)),
CAST(ROW_NUMBER() OVER(ORDER BY TABA.[ID] ASC) as VARCHAR(4))
) AS int) AS [UniqueId]
,TABA.[ID]
,ROW_NUMBER() OVER(ORDER BY TABA.[ID] ASC) AS ROWNR
,TABA.[Name]
FROM [Ref].[Table1] TABA LEFT JOIN [Ref].[Table2] TABB ON TABA.[ID] = TABB.[ID]
GO
Yes, the most efficient way (as already pointed out by Jonathan Leffler) is to use sed with print & quit:
set -o pipefail # cf. help set
time -p ls -l | sed -n -e '2{p;q;}' # only print the second line & quit (on Mac OS X)
echo "$?: ${PIPESTATUS[*]}" # cf. man bash | less -p 'PIPESTATUS'
Another alternative is the following, although not the cleanest as it assumes the image to be the only element in a container, such as in this case:
<header class="siteHeader">
<img src="img" class="siteLogo" />
</header>
You can then use the container as a mask with the desired size, and surround the image with a negative margin to move it into the right position:
.siteHeader{
width: 50px;
height: 50px;
overflow: hidden;
}
.siteHeader .siteLogo{
margin: -100px;
}
Demo can be seen in this JSFiddle.
Only seems to work in IE>9, and probably all significant versions of all other browsers.
Are you talking about automated unit/integration tests or manual tests?
For the former, my rule of thumb (based on measurements) is 40-50% added to development time i.e. if developing a use case takes 10 days (before an QA and serious bugfixing happens), writing good tests takes another 4 to 5 days - though this should best happen before and during development, not afterwards.
If you are hiring graduates with Java "experience" a simple question like Write some code that will cause a NullPointerException to be thrown can distinguish which candidates have used Java recently, and didn't just stop when they finished their unit/course.
If it helps, I am using the following to get a gravatar image:
<img
:src="`https://www.gravatar.com/avatar/${this.gravatarHash(email)}?s=${size}&d=${this.defaultAvatar(email)}`"
class="rounded-circle"
:width="size"
/>
The performance of @atk's implementation for sorted arrays of primitives can be improved by using .pop rather than .shift.
function intersect(array1, array2) {
var result = [];
// Don't destroy the original arrays
var a = array1.slice(0);
var b = array2.slice(0);
var aLast = a.length - 1;
var bLast = b.length - 1;
while (aLast >= 0 && bLast >= 0) {
if (a[aLast] > b[bLast] ) {
a.pop();
aLast--;
} else if (a[aLast] < b[bLast] ){
b.pop();
bLast--;
} else /* they're equal */ {
result.push(a.pop());
b.pop();
aLast--;
bLast--;
}
}
return result;
}
I created a benchmark using jsPerf: http://bit.ly/P9FrZK. It's about three times faster to use .pop.
Create a model which contains your list and other things you need for the view.
For example:
public class MyModel
{
public List<string> _MyList { get; set; }
}
From the action method put your desired list to the Model, _MyList
property, like:
public ActionResult ArticleList(MyModel model)
{
model._MyList = new List<string>{"item1","item2","item3"};
return PartialView(@"~/Views/Home/MyView.cshtml", model);
}
In your view access the model as follows
@model MyModel
foreach (var item in Model)
{
<div>@item</div>
}
I think it will help for start.
Interface Builder uses them to determine what members and messages can be 'wired' up to the interface controls you are using in your window/view.
IBOutlet and IBAction are purely there as markers that Interface Builder looks for when it parses your code at design time, they don't have any affect on the code generated by the compiler.
I prefer @Ista solution, cause needs no extra package and is simple.
A modification of the data.table
solution also solve my problem, and is more general.
My data.frame is
> str(df)
'data.frame': 579 obs. of 11 variables:
$ trees : num 2000 5000 1000 2000 1000 1000 2000 5000 5000 1000 ...
$ interDepth: num 2 3 5 2 3 4 4 2 3 5 ...
$ minObs : num 6 4 1 4 10 6 10 10 6 6 ...
$ shrinkage : num 0.01 0.001 0.01 0.005 0.01 0.01 0.001 0.005 0.005 0.001 ...
$ G1 : num 0 2 2 2 2 2 8 8 8 8 ...
$ G2 : logi FALSE FALSE FALSE FALSE FALSE FALSE ...
$ qx : num 0.44 0.43 0.419 0.439 0.43 ...
$ efet : num 43.1 40.6 39.9 39.2 38.6 ...
$ prec : num 0.606 0.593 0.587 0.582 0.574 0.578 0.576 0.579 0.588 0.585 ...
$ sens : num 0.575 0.57 0.573 0.575 0.587 0.574 0.576 0.566 0.542 0.545 ...
$ acu : num 0.631 0.645 0.647 0.648 0.655 0.647 0.619 0.611 0.591 0.594 ...
The data.table
solution needs order
on i
to do the job:
> require(data.table)
> dt1 <- data.table(df)
> dt2 = dt1[order(-efet, G1, G2), head(.SD, 3), by = .(G1, G2)]
> dt2
G1 G2 trees interDepth minObs shrinkage qx efet prec sens acu
1: 0 FALSE 2000 2 6 0.010 0.4395953 43.066 0.606 0.575 0.631
2: 0 FALSE 2000 5 1 0.005 0.4294718 37.554 0.583 0.548 0.607
3: 0 FALSE 5000 2 6 0.005 0.4395753 36.981 0.575 0.559 0.616
4: 2 FALSE 5000 3 4 0.001 0.4296346 40.624 0.593 0.570 0.645
5: 2 FALSE 1000 5 1 0.010 0.4186802 39.915 0.587 0.573 0.647
6: 2 FALSE 2000 2 4 0.005 0.4390503 39.164 0.582 0.575 0.648
7: 8 FALSE 2000 4 10 0.001 0.4511349 38.240 0.576 0.576 0.619
8: 8 FALSE 5000 2 10 0.005 0.4469665 38.064 0.579 0.566 0.611
9: 8 FALSE 5000 3 6 0.005 0.4426952 37.888 0.588 0.542 0.591
10: 2 TRUE 5000 3 4 0.001 0.3812878 21.057 0.510 0.479 0.615
11: 2 TRUE 2000 3 10 0.005 0.3790536 20.127 0.507 0.470 0.608
12: 2 TRUE 1000 5 4 0.001 0.3690911 18.981 0.500 0.475 0.611
13: 8 TRUE 5000 6 10 0.010 0.2865042 16.870 0.497 0.435 0.635
14: 0 TRUE 2000 6 4 0.010 0.3192862 9.779 0.460 0.433 0.621
By some reason, it does not order the way pointed (probably because ordering by the groups). So, another ordering is done.
> dt2[order(G1, G2)]
G1 G2 trees interDepth minObs shrinkage qx efet prec sens acu
1: 0 FALSE 2000 2 6 0.010 0.4395953 43.066 0.606 0.575 0.631
2: 0 FALSE 2000 5 1 0.005 0.4294718 37.554 0.583 0.548 0.607
3: 0 FALSE 5000 2 6 0.005 0.4395753 36.981 0.575 0.559 0.616
4: 0 TRUE 2000 6 4 0.010 0.3192862 9.779 0.460 0.433 0.621
5: 2 FALSE 5000 3 4 0.001 0.4296346 40.624 0.593 0.570 0.645
6: 2 FALSE 1000 5 1 0.010 0.4186802 39.915 0.587 0.573 0.647
7: 2 FALSE 2000 2 4 0.005 0.4390503 39.164 0.582 0.575 0.648
8: 2 TRUE 5000 3 4 0.001 0.3812878 21.057 0.510 0.479 0.615
9: 2 TRUE 2000 3 10 0.005 0.3790536 20.127 0.507 0.470 0.608
10: 2 TRUE 1000 5 4 0.001 0.3690911 18.981 0.500 0.475 0.611
11: 8 FALSE 2000 4 10 0.001 0.4511349 38.240 0.576 0.576 0.619
12: 8 FALSE 5000 2 10 0.005 0.4469665 38.064 0.579 0.566 0.611
13: 8 FALSE 5000 3 6 0.005 0.4426952 37.888 0.588 0.542 0.591
14: 8 TRUE 5000 6 10 0.010 0.2865042 16.870 0.497 0.435 0.635
global static variables are initialized at compile-time unlike automatic
We can change the item by value, here is the trick:
radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2
If you can use CSS and are willing to use the deprecated align
attribute, a styled fieldset/legend will work:
<style type="text/css">
fieldset {
border-width: 1px 0 0 0;
}
</style>
<fieldset>
<legend align="center">First Section</legend>
Section 1 Stuff
</fieldset>
<fieldset>
<legend align="center">Second Section</legend>
Section 2 Stuff
</fieldset>
The intended purpose of a fieldset is to logically group form fields. As willoler pointed out, a text-align: center
style for will not work for legend
elements. align="center"
is deprecated HTML but it should center the text properly in all browsers.
\n
is an escape sequence, denoted by the backslash. A normal forward slash, such as /n
will not do the job. In your code you are using /n
instead of \n
.
I think you will need to edit the doxys file and set GENERATE_UML (something like that) to true. And you need to have dot/graphviz installed.
To set focus, delay the requestFocus() using a Handler.
private Handler mHandler= new Handler();
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout mainVw = (LinearLayout) findViewById(R.id.main_layout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
EditText edit = new EditText(this);
edit.setLayoutParams(params);
mainVw.addView(edit);
TextView titleTv = new TextView(this);
titleTv.setText("test");
titleTv.setLayoutParams(params);
mainVw.addView(titleTv);
mHandler.post(
new Runnable()
{
public void run()
{
titleTv.requestFocus();
}
}
);
}
}
I see two problems:
DOUBLE(10) precision definitions need a total number of digits, as well as a total number of digits after the decimal:
DOUBLE(10,8) would make be ten total digits, with 8 allowed after the decimal.
Also, you'll need to specify your id column as a key :
CREATE TABLE transactions(
id int NOT NULL AUTO_INCREMENT,
location varchar(50) NOT NULL,
description varchar(50) NOT NULL,
category varchar(50) NOT NULL,
amount double(10,9) NOT NULL,
type varchar(6) NOT NULL,
notes varchar(512),
receipt int(10),
PRIMARY KEY(id) );
git reset --hard
This command will completely remove all the local changes from your local repository. This is the best way to avoid conflicts during pull command, only if you don't want to keep your local changes at all.
If you want to pull the new changes from remote and want to ignore the local changes during this pull then,
git stash
It will stash all the local changes, now you can pull the remote changes,
git pull
Now, you can bring back your local changes by,
git stash pop
This type of problem can happen when you delete/move files around - in essence making changes to your directory structure. Subversion only checks for changes made in files already added to subversion, not changes made to the directory structure. Instead of using your OS's copy etc commands rather use svn copy etc. Please see http://svnbook.red-bean.com/en/1.7/svn.tour.cycle.html
Further, upon committing changes svn first stores a "summary" of changes in a todo list. Upon performing the svn operations in this todo list it locks the file to prevent other changes while these svn actions are performed. If the svn action is interrupted midway, say by a crash, the file will remain locked until svn could complete the actions in the todo list. This can be "reactivated" by using the svn cleanup command. Please see http://svnbook.red-bean.com/en/1.7/svn.tour.cleanup.html
This question needed a more up-to-date answer, with sources. This is what actually works (though you don't have to take my word for it):
// Storing this jQuery object outside of the event callback
// prevents jQuery from having to search the DOM for it again
// every time an event is fired.
var $myButton = $("#buttonID")
// input :: for all modern browsers [1]
// selectionchange :: for IE9 [2]
// propertychange :: for <IE9 [3]
$('#textareaID').on('input selectionchange propertychange', function() {
// This is the correct way to enable/disabled a button in jQuery [4]
$myButton.prop('disabled', this.value.length === 0)
}
1: https://developer.mozilla.org/en-US/docs/Web/Events/input#Browser_compatibility
2: oninput in IE9 doesn't fire when we hit BACKSPACE / DEL / do CUT
3: https://msdn.microsoft.com/en-us/library/ms536956(v=vs.85).aspx
4: http://api.jquery.com/prop/#prop-propertyName-function
BUT, for a more global solution that you can use throughout your project, I recommend using the textchange jQuery plugin to gain a new, cross-browser compatible textchange
event. It was developed by the same person who implemented the equivalent onChange
event for Facebook's ReactJS, which they use for nearly their entire website. And I think it's safe to say, if it's a robust enough solution for Facebook, it's probably robust enough for you. :-)
UPDATE: If you happen to need features like drag and drop support in Internet Explorer, you may instead want to check out pandell
's more recently updated fork of jquery-splendid-textchange
.
You can not specify the password from the command line but you can do either using ssh keys or using sshpass
as suggested by John C. or using a expect
script.
To use sshpass, you need to install it first. Then
sshpass -f <(printf '%s\n' your_password) ssh user@hostname
instead of using sshpass -p your_password
. As mentioned by Charles Duffy
in the comments, it is safer to supply the password from a file or from a variable instead of from command line.
BTW, a little explanation for the <(command)
syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe
UPDATE: As of 2018, this seems to work now. Tested in Chrome, Firefox, IE and Edge
UPDATE: Yes I changed the background-color, not the image, stop voting me down, showing that you can change style here is still a useful contribution.
<!DOCTYPE html>
<html>
<body>
<style>
select#newlocale option[value="volvo"] { background-color: powderblue; }
select#newlocale option[value="opel"] { background-color: red; }
select#newlocale option[value="audi"] { background-color: green; }
</style>
<select id="newlocale">
<option value="volvo"><div >Volvo</div></option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
It was much easier (on my Mac) to do this in Ruby. Here are 2 examples:
# for your fgh example. renames all files from "fgh..." to "jkl..."
files = Dir['fgh*']
files.each do |f|
f2 = f.gsub('fgh', 'jkl')
system("mv #{f} #{f2}")
end
# renames all files in directory from "021roman.rb" to "021_roman.rb"
files = Dir['*rb'].select {|f| f =~ /^[0-9]{3}[a-zA-Z]+/}
files.each do |f|
f1 = f.clone
f2 = f.insert(3, '_')
system("mv #{f1} #{f2}")
end
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
To be able to detect unused imports, code or variables, make sure you have this options in tsconfig.json file
"compilerOptions": {
"noUnusedLocals": true,
"noUnusedParameters": true
}
have the typescript compiler installed, ifnot install it with:
npm install -g typescript
and the tslint extension installed in Vcode, this worked for me, but after enabling I notice an increase amount of CPU usage, specially on big projects.
I would also recomend using typescript hero extension for organizing your imports.
I have achieved that programatically with this code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
//set image for button
button.setImage(UIImage(named: "fb.png"), forState: UIControlState.Normal)
//add function for button
button.addTarget(self, action: "fbButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
//set frame
button.frame = CGRectMake(0, 0, 53, 31)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
//This method will call when you press button.
func fbButtonPressed() {
println("Share to fb")
}
}
And result will be:
Same way you can set button for left side too this way:
self.navigationItem.leftBarButtonItem = barButton
And result will be:
And if you want same transaction as navigation controller have when you go back with default back button then you can achieve that with custom back button with this code:
func backButtonPressed(sender:UIButton) {
navigationController?.popViewControllerAnimated(true)
}
For swift 3.0:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button = UIButton.init(type: .custom)
//set image for button
button.setImage(UIImage(named: "fb.png"), for: UIControlState.normal)
//add function for button
button.addTarget(self, action: #selector(ViewController.fbButtonPressed), for: UIControlEvents.touchUpInside)
//set frame
button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
//This method will call when you press button.
func fbButtonPressed() {
print("Share to fb")
}
}
For swift 4.0:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button = UIButton(type: .custom)
//set image for button
button.setImage(UIImage(named: "fb.png"), for: .normal)
//add function for button
button.addTarget(self, action: #selector(fbButtonPressed), for: .touchUpInside)
//set frame
button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
//This method will call when you press button.
@objc func fbButtonPressed() {
print("Share to fb")
}
}
Adding an object to header we use the examples used here,yet i will complete
ObjectFactory objectFactory = new ObjectFactory();
CabeceraCR cabeceraCR =objectFactory.createCabeceraCR();
cabeceraCR.setUsuario("xxxxx");
cabeceraCR.setClave("xxxxx");
With object factory we create the object asked to pass on the header. The to add to the header
WSBindingProvider bp = (WSBindingProvider)wsXXXXXXSoap;
bp.setOutboundHeaders(
// Sets a simple string value as a header
Headers.create(jaxbContext,objectFactory.createCabeceraCR(cabeceraCR))
);
We used the WSBindingProvider to add the header. The object will have some error if used directly so we use the method
objectFactory.createCabeceraCR(cabeceraCR)
This method will create a JAXBElement like this on the object Factory
@XmlElementDecl(namespace = "http://www.creditreport.ec/", name = "CabeceraCR")
public JAXBElement<CabeceraCR> createCabeceraCR(CabeceraCR value) {
return new JAXBElement<CabeceraCR>(_CabeceraCR_QNAME, CabeceraCR.class, null, value);
}
And the jaxbContext we obtained like this:
jaxbContext = (JAXBRIContext) JAXBContext.newInstance(CabeceraCR.class.getPackage().getName());
This will add the object to the header.
Use SpecialCells to delete only the rows that are visible after autofiltering:
ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:
ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
In my case home on nfs was 777, needed to be 750. That fixed the issue.
Since you are using SQL, would recommend against using adhoc ('writing statements in strings'), especially given that you are loading an image.
ADO.NET can do all of the hard work of mapping, escaping etc for you.
Either create a Stored Procedure, or use SqlParameter to do the binding.
As the other posters say, use VARBINARY(MAX) as your storage type - IMAGE is being depracated.
Note: The last line is mandatory.
If we didn't specify Access-Control-Expose-Headers, we will not get File Name in UI.
FileInfo file = new FileInfo(FILEPATH);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = file.Name
};
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
var bs []byte
value, _ := strconv.ParseInt(string(bs), 10, 64)
To create elements with equal width using Flex
, you should set to your's child (flex elements):
flex-basis: 25%;
flex-grow: 0;
It will give to all elements in row 25% width. They will not grow and go one by one.
Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for/path/to/repo.git
andfoo
forhost.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
For covering my case -> I've got a range start & end date, and dates list that can be as partly in provided range, as fully (overlapping).
Solution covered with tests:
/**
* Check has any of quote work days in provided range.
*
* @param startDate inclusively
* @param endDate inclusively
*
* @return true if any in provided range inclusively
*/
public boolean hasAnyWorkdaysInRange(LocalDate startDate, LocalDate endDate) {
if (CollectionUtils.isEmpty(workdays)) {
return false;
}
LocalDate firstWorkDay = getFirstWorkDay().getDate();
LocalDate lastWorkDay = getLastWorkDay().getDate();
return (firstWorkDay.isBefore(endDate) || firstWorkDay.equals(endDate))
&& (lastWorkDay.isAfter(startDate) || lastWorkDay.equals(startDate));
}
Hi you can use URLSearchParams, you can read more about it here.
import:
import {URLSearchParams} from "@angular/http";
and function:
getParam(){
let params = new URLSearchParams(window.location.search);
let someParam = params.get('someParam');
return someParam;
}
Notice: It's not supported by all platforms and seems to be in "EXPERIMENTAL" state by angular docs
For some reason, the above solutions were not working for me. I went with the following:
$('#container').on('mousedown', function(e) {
$(this).data('p0', { x: e.pageX, y: e.pageY });
}).on('mouseup', function(e) {
var p0 = $(this).data('p0'),
p1 = { x: e.pageX, y: e.pageY },
d = Math.sqrt(Math.pow(p1.x - p0.x, 2) + Math.pow(p1.y - p0.y, 2));
if (d < 4) {
alert('clicked');
}
})
You can tweak the distance limit to whatever you please, or even take it all the way to zero.
if in multiple class you want to change additional operation in perticular class that show in below example
$('.like').click(function(){
var like= $(this).text();
$(this).text(+like + +1);
});
&
is always evaluated in a string context, while +
may not concatenate if one of the operands is no string:
"1" + "2" => "12"
"1" + 2 => 3
1 + "2" => 3
"a" + 2 => type mismatch
This is simply a subtle source of potential bugs and therefore should be avoided. &
always means "string concatenation", even if its arguments are non-strings:
"1" & "2" => "12"
"1" & 2 => "12"
1 & "2" => "12"
1 & 2 => "12"
"a" & 2 => "a2"
Below code is used in my application to send email with an attachment here the attachments is an image .You can send any type of file only thing is to keep in mind is that you had to specify the correct 'mimeType'
add this to your .h file
#import <MessageUI/MFMailComposeViewController.h>
Add MessageUI.framework to your project file
NSArray *paths = SSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"myGreenCard.png"];
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"Green card application"];
[controller setMessageBody:@"Hi , <br/> This is my new latest designed green card." isHTML:YES];
[controller addAttachmentData:[NSData dataWithContentsOfFile:getImagePath] mimeType:@"png" fileName:@"My Green Card"];
if (controller)
[self presentModalViewController:controller animated:YES];
[controller release];
Delegate method is as shown below
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
In JAVA, values like:
Is assumed as double and not float.
You can also perform a cast in order to solve the problem:
float b = (float) 3.5
;
Another solution:
float b = 3.5f
;
got it resolved:
uninstall the entire android studio
rm -Rf /Applications/Android\ Studio.app
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/com.google.android.*
rm -Rf ~/Library/Preferences/com.android.*
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Caches/AndroidStudio*
rm -Rf ~/.AndroidStudio*
rm -Rf ~/.gradle
rm -Rf ~/.android
rm -Rf ~/Library/Android*
rm -Rf /usr/local/var/lib/android-sdk/
rm -Rf /Users/<username>/.tooling/gradle
Remove your project and clone it again and then goto Gradle Scripts
and open gradle-wrapper.properties
and change the below url which ever version you need
distributionUrl=https\://services.gradle.org/distributions/gradle-4.2-all.zip
think works
Criteria criteria = getSession().createCriteria(clazz);
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"),
Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"),
Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));
Please use the attributes from the System.Web.Http namespace on your WebAPI actions:
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public string Auth(string username, string password)
{...}
The reason why it doesn't work is because you were using the attributes that are from the MVC namespace System.Web.Mvc
. The classes in the System.Web.Http
namespace are for WebAPI.
Easy quick solution which worked for me. 1. Go to the root folder. Copy the default.aspx file. 2. Delete the original file. 3. Rename the copied file to default.aspx.
Its all set to experiment again. Not sure how sharepoint referencing these webparts in that page. But works :)
Some of the above answers will give you a black bar on top if you set your screen bound 20px, other will keep reduce your webview screen if you use webview.frame.size.height -20px; Try this one then, it works on any ios and no need to change css, put in inside
- (void)webViewDidFinishLoad:(UIWebView*)theWebView {
//is it IOS7 and up
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
//get the device screen size
CGRect screenBounds = [[UIScreen mainScreen] bounds];
//reduce the height by 20px
int x= screenBounds.size.height -20;
//set the webview top pos 20px so it is under the status bar and reduce the size by 20px
[theWebView setFrame:CGRectMake(0, 20, theWebView.frame.size.width, x )];
}
Combining the two answers:
First create sql to make all index unusable:
alter session set skip_unusable_indexes = true;
select 'alter index ' || u.index_name || ' unusable;' from user_indexes u;
Do import...
select 'alter index ' || u.index_name || ' rebuild online;' from user_indexes u;
strtol()
is your friend here. The third parameter is the numerical base that you are converting.
Example:
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main(int argc, char **argv)
{
long int num = 0;
long int num2 =0;
char * str. = "f00d";
char * str2 = "0xf00d";
num = strtol( str, 0, 16); //converts hexadecimal string to long.
num2 = strtol( str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal.
printf( "%ld\n", num);
printf( "%ld\n", num);
}
Go File -> New Project.
Select Web under Visual C#.
Select ASP.NET Web Application
select mvc
when solution is created, you will find resources getting added in solution in status bar of vs 2013.
Check property of Dll file --> system.web.mvc, it shows latest version (5.2.2.0)
but depending on your OS runtime version will be decided.
Use BOOST_BINARY (Yes, you can use it in C).
#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);
This macro is expanded to an octal literal during preprocessing.
I use the csc.exe compiler called from a .vbs script.
In your xyz.cs script, add the following lines after the directives (my example is for the Renci SSH):
using System;
using Renci;//FOR THE SSH
using System.Net;//FOR THE ADDRESS TRANSLATION
using System.Reflection;//FOR THE Assembly
//+ref>"C:\Program Files (x86)\Microsoft\ILMerge\Renci.SshNet.dll"
//+res>"C:\Program Files (x86)\Microsoft\ILMerge\Renci.SshNet.dll"
//+ico>"C:\Program Files (x86)\Microsoft CAPICOM 2.1.0.2 SDK\Samples\c_sharp\xmldsig\resources\Traffic.ico"
The ref, res and ico tags will be picked up by the .vbs script below to form the csc command.
Then add the assembly resolver caller in the Main:
public static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
.
...and add the resolver itself somewhere in the class:
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { String resourceName = new AssemblyName(args.Name).Name + ".dll"; using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { Byte[] assemblyData = new Byte[stream.Length]; stream.Read(assemblyData, 0, assemblyData.Length); return Assembly.Load(assemblyData); } }
I name the vbs script to match the .cs filename (e.g. ssh.vbs looks for ssh.cs); this makes running the script numerous times a lot easier, but if you aren't an idiot like me then a generic script could pick up the target .cs file from a drag-and-drop:
Dim name_,oShell,fso Set oShell = CreateObject("Shell.Application") Set fso = CreateObject("Scripting.fileSystemObject") 'TAKE THE VBS SCRIPT NAME AS THE TARGET FILE NAME '################################################ name_ = Split(wscript.ScriptName, ".")(0) 'GET THE EXTERNAL DLL's AND ICON NAMES FROM THE .CS FILE '####################################################### Const OPEN_FILE_FOR_READING = 1 Set objInputFile = fso.OpenTextFile(name_ & ".cs", 1) 'READ EVERYTHING INTO AN ARRAY '############################# inputData = Split(objInputFile.ReadAll, vbNewline) For each strData In inputData if left(strData,7)="//+ref>" then csc_references = csc_references & " /reference:" & trim(replace(strData,"//+ref>","")) & " " end if if left(strData,7)="//+res>" then csc_resources = csc_resources & " /resource:" & trim(replace(strData,"//+res>","")) & " " end if if left(strData,7)="//+ico>" then csc_icon = " /win32icon:" & trim(replace(strData,"//+ico>","")) & " " end if Next objInputFile.Close 'COMPILE THE FILE '################ oShell.ShellExecute "c:\windows\microsoft.net\framework\v3.5\csc.exe", "/warn:1 /target:exe " & csc_references & csc_resources & csc_icon & " " & name_ & ".cs", "", "runas", 2 WScript.Quit(0)
The accepted answer does not work in Jupyter (at least when using some libraries).
The Javascript solutions here only hide warnings that are already showing but not warnings that would be shown in the future.
To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings.
%%javascript
(function(on) {
const e=$( "<a>Setup failed</a>" );
const ns="js_jupyter_suppress_warnings";
var cssrules=$("#"+ns);
if(!cssrules.length) cssrules = $("<style id='"+ns+"' type='text/css'>div.output_stderr { } </style>").appendTo("head");
e.click(function() {
var s='Showing';
cssrules.empty()
if(on) {
s='Hiding';
cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
}
e.text(s+' warnings (click to toggle)');
on=!on;
}).click();
$(element).append(e);
})(true);
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
The object spread operator (...) doesn't work in browsers, because it isn't part of any ES specification yet, just a proposal. The only option is to compile it with Babel (or something similar).
As you can see, it's just syntactic sugar over Object.assign({}).
As far as I can see, these are the important differences.
...
for objects isn't standardized...
protects you from accidentally mutating the object...
will polyfill Object.assign in browsers without it...
needs less code to express the same ideaTo handle Android Volley Timeout you need to use RetryPolicy
RetryPolicy
is an interface where you need to implement your logic of how you want to retry a particular request when a timeout happens.
It deals with these three parameters
For ex. If RetryPolicy is created with these values
Timeout - 3000 ms, Num of Retry Attempts - 2, Back Off Multiplier - 2.0
Retry Attempt 1:
Retry Attempt 2:
So at the end of Retry Attempt 2 if still Socket Timeout happens Volley would throw a TimeoutError
in your UI Error response handler.
//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions.
//Volley does retry for you if you have specified the policy.
jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
There are two problems in your code:
visibility
and not visiblity
..style
property.It's easy to fix. Simple replace this:
document.getElementById("remember").visiblity
with this:
document.getElementById("remember").style.visibility
Considering the String
you're asking about is
C:\Hello\AnotherFolder\The File Name.PDF
we need to extract everything after the last separator, ie. \
. That is what we are interested in.
You can do
String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);
This will retrieve the index of the last \
in your String
and extract everything that comes after it into fileName
.
If you have a String
with a different separator, adjust the lastIndexOf
to use that separator. (There's even an overload that accepts an entire String
as a separator.)
I've omitted it in the example above, but if you're unsure where the String
comes from or what it might contain, you'll want to validate that the lastIndexOf
returns a non-negative value because the Javadoc states it'll return
-1 if there is no such occurrence
using System.Security.Cryptography;
public static byte[] GetHash(string inputString)
{
using (HashAlgorithm algorithm = SHA256.Create())
return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}
public static string GetHashString(string inputString)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in GetHash(inputString))
sb.Append(b.ToString("X2"));
return sb.ToString();
}
Additional Notes
$abc=array("a"=>1,"b"=>2,"c"=>4,"e"=>7,"d"=>5);
/*program to find max value*/
$lagest = array();
$i=0;
foreach($abc as $key=>$a) {
if($i==0) $b=$a;
if($b<$a) {
$b=$a;
$k=$key;
}
$i++;
}
$lagest[$k]=$b;
print_r($lagest);
my_styles.xml
and save it in res/values
.Add the following code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="ListFont" parent="@android:style/Widget.ListView">
<item name="android:textColor">#FF0000</item>
<item name="android:typeface">sans</item>
</style>
</resources>
Add your style to your Activity
definition in your AndroidManifest.xml
as an android:theme
attribute, and assign as value the name of the style you created. For example:
<activity android:name="your.activityClass" android:theme="@style/ListFont">
Given a unix timestamp (seconds since epoch) of 1494500000
, do:
find . -type f -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d @1494500000)"
To grep those files for "foo":
find . -type f -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d @1494500000)" -exec grep -H 'foo' '{}' \;
You will have to use Array.find
or Array.filter
or Array.forEach
.
Since you value is array and you need position of element, you will have to iterate over it.
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var index = -1;
var val = "allInterests"
var filteredObj = data.find(function(item, i){
if(item.name === val){
index = i;
return i;
}
});
console.log(index, filteredObj);
_x000D_
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var val = "allInterests"
var index = data.findIndex(function(item, i){
return item.name === val
});
console.log(index);
_x000D_
Default Array.indexOf()
will match searchValue to current element and not its properties. You can refer Array.indexOf - polyfill on MDN
Sometimes the columns will have commas within themselves, such as:
"Some item", "Another Item", "Also, One more item"
In these cases, splitting on "," will break some columns. Maybe an easier way, but I just made my own method (as a bonus, handles spaces after commas and returns an IList):
private IList<string> GetColumns(string columns)
{
IList<string> list = new List<string>();
if (!string.IsNullOrWhiteSpace(columns))
{
if (columns[0] != '\"')
{
// treat as just one item
list.Add(columns);
}
else
{
bool gettingItemName = true;
bool justChanged = false;
string itemName = string.Empty;
for (int index = 1; index < columns.Length; index++)
{
justChanged = false;
if (subIndustries[index] == '\"')
{
gettingItemName = !gettingItemName;
justChanged = true;
}
if ((gettingItemName == false) &&
(justChanged == true))
{
list.Add(itemName);
itemName = string.Empty;
justChanged = false;
}
if ((gettingItemName == true) && (justChanged == false))
{
itemName += columns[index];
}
}
}
}
return list;
}
Check out the MSDN article Asynchronous Programming with Async and Await if you can afford to play with new stuff. It was added to .NET 4.5.
Example code snippet from the link (which is itself from this MSDN sample code project):
// Three things to note in the signature:
// - The method has an async modifier.
// - The return type is Task or Task<T>. (See "Return Types" section.)
// Here, it is Task<int> because the return statement returns an integer.
// - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}
Quoting:
If
AccessTheWebAsync
doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.
string urlContents = await client.GetStringAsync();
More details are in the link.
To follow up on Robert's answer, this is even later, but you can use a static helper class to make the runtime check once only per type:
public bool Foo<T>() where T : class
{
FooHelper<T>.Foo();
}
private static class FooHelper<TInterface> where TInterface : class
{
static FooHelper()
{
if (!typeof(TInterface).IsInterface)
throw // ... some exception
}
public static void Foo() { /*...*/ }
}
I also note that your "should work" solution does not, in fact, work. Consider:
public bool Foo<T>() where T : IBase;
public interface IBase { }
public interface IActual : IBase { string S { get; } }
public class Actual : IActual { public string S { get; set; } }
Now there's nothing stopping you from calling Foo thus:
Foo<Actual>();
The Actual
class, after all, satisfies the IBase
constraint.
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
Coding in C#, java, C, C++ and objective C at the same time, I've adopted a very simple and clear naming convention to simplify my life.
First of all, it relies on the power of modern IDEs (such as eclipse, Xcode...), with the possibility to get fast information by hovering or ctrl click... Accepting that, I suppressed the use of any prefix, suffix and other markers that are simply given by the IDE.
Then, the convention:
And that's it.
It gives
class MyClass {
enum TheEnumeration {
FIRST_ELEMENT,
SECOND_ELEMENT,
}
int class_variable;
int MyMethod(int first_param, int second_parameter) {
int local_variable;
TheEnumeration local_enum;
for(int myindex=0, myindex<class_variable, myindex++) {
localEnum = FIRST_ELEMENT;
}
}
}
the most simple solution for removing the brackets is,
1.convert the arraylist into string with .toString() method.
2.use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).
3.Hurraaah..the result string is your string with removed brackets.
hope this is useful...:-)
UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;
I describe two ways to do this, one based on data.table and the other based on reshape2 package . The data.table way already has an answer, but I have tried to make it cleaner and more detailed.
The data is like this:
d <- structure(list(Name = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L,
3L, 3L), .Label = c("Aira", "Ben", "Cat"), class = "factor"),
Month = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Rate1 = c(12L,
18L, 19L, 53L, 22L, 19L, 22L, 67L, 45L), Rate2 = c(23L, 73L,
45L, 19L, 87L, 45L, 87L, 43L, 32L)), .Names = c("Name", "Month",
"Rate1", "Rate2"), class = "data.frame", row.names = c(NA, -9L
))
head(d)
Name Month Rate1 Rate2
1 Aira 1 12 23
2 Aira 2 18 73
3 Aira 3 19 45
4 Ben 1 53 19
5 Ben 2 22 87
6 Ben 3 19 45
library("reshape2")
mym <- melt(d, id = c("Name"))
res <- dcast(mym, Name ~ variable, mean)
res
#Name Month Rate1 Rate2
#1 Aira 2 16.33333 47.00000
#2 Ben 2 31.33333 50.33333
#3 Cat 2 44.66667 54.00000
Using data.table:
# At first, I convert the data.frame to data.table and then I group it
setDT(d)
d[, .(Rate1 = mean(Rate1), Rate2 = mean(Rate2)), by = .(Name)]
# Name Rate1 Rate2
#1: Aira 16.33333 47.00000
#2: Ben 31.33333 50.33333
#3: Cat 44.66667 54.00000
There is another way of doing it by avoiding to write many argument for j in data.table using a .SD
d[, lapply(.SD, mean), by = .(Name)]
# Name Month Rate1 Rate2
#1: Aira 2 16.33333 47.00000
#2: Ben 2 31.33333 50.33333
#3: Cat 2 44.66667 54.00000
if we only want to have Rate1 and Rate2 then we can use the .SDcols as follows:
d[, lapply(.SD, mean), by = .(Name), .SDcols = 3:4]
# Name Rate1 Rate2
#1: Aira 16.33333 47.00000
#2: Ben 31.33333 50.33333
#3: Cat 44.66667 54.00000
Yes you can.
You just need to understand what they are for, the class
is more general and can be used several times, the id
(is like your id's) you can use it only once.
This excellent tutorial helped me with that:
The Difference Between ID and Class
Though it's not an exact answer to your question I'm sure it will help you a lot!
Good luck!
EDIT: Reading your question, I just want to clarify that:
<div class="x" id="y">
--
</div>
And that if you want to "use them" in CSS for styling purposes you should do as David Says: #x.y { }
Just as a addition. You can find the Catalina Paths in
->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS
In the VM Arguments the Paths are listed and changeable
Try Catch exists via workaround in VBScript:
Class CFunc1
Private Sub Class_Initialize
WScript.Echo "Starting"
Dim i : i = 65535 ^ 65535
MsgBox "Should not see this"
End Sub
Private Sub CatchErr
If Err.Number = 0 Then Exit Sub
Select Case Err.Number
Case 6 WScript.Echo "Overflow handled!"
Case Else WScript.Echo "Unhandled error " & Err.Number & " occurred."
End Select
Err.Clear
End Sub
Private Sub Class_Terminate
CatchErr
WScript.Echo "Exiting"
End Sub
End Class
Dim Func1 : Set Func1 = New CFunc1 : Set Func1 = Nothing
if you have null value then in doing mathematical operation you will get this error to resolve it use df[~df['x'].isnull()]df[['x']].astype(int)
if you want your dataset to be unchangeable.
https://github.com/mattt/TTTAttributedLabel
That's definitely what you need. You can also apply attributes for your label, like underline, and apply different colors to it. Just check the instructions for clickable urls.
Mainly, you do something like the following:
NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring
Solution:
Cause of the problem: Android emulator hasn't loaded all its libraries which handle the installing of a new application and due to that you run into java.io.IOException: EOF
That was causing me the problem.
From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.
Here's what your code would look like if changed as suggested:
beforecreate: function(node,targetNode,type,to) {
jQuery.ajax({
url: url,
success: function(result) {
if(result.isOk == false)
alert(result.message);
},
async: false
});
}
this is because $.ajax is the only request type that you can set the asynchronousity for
Nodejs supports async/await from version 7.6.
Release post: https://v8project.blogspot.com.br/2016/10/v8-release-55.html
I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
The same approach should work for other attribute types.
(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)
I have published an article on working with AngularJS+SVG that talks about this and related issues. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS