Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
I eventually used:
weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)
It worked just fine, except that I got the following message.
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated. Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.
print("the furnace is now " + str(temperature) + "degrees!")
cast it to str
Swift 5
Cant fetch data from your api.
Easiest way to parse json is Use Decodable
protocol. Or Codable
(Encodable & Decodable
).
For ex:
let json = """
{
"dueDate": {
"year": 2021,
"month": 2,
"day": 17
}
}
"""
struct WrapperModel: Codable {
var dueDate: DueDate
}
struct DueDate: Codable {
var year: Int
var month: Int
var day: Int
}
let jsonData = Data(json.utf8)
let decoder = JSONDecoder()
do {
let model = try decoder.decode(WrapperModel.self, from: jsonData)
print(model)
} catch {
print(error.localizedDescription)
}
According to this post, you should enable it in XCode.
As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &
. That also requires using parentheses so that &
wouldn't take precedence.
It would go something like this:
mask = ((50 < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...
In order to avoid that, you can build series for lower and upper limits:
low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)
Now you can slice it as follows:
mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out:
dyastolic blood pressure heart rate pulse oximetry respiratory rate \
17 136 62 97 15
69 110 85 96 18
72 105 85 97 16
161 126 57 99 16
286 127 84 99 12
435 92 67 96 13
499 110 66 97 15
systolic blood pressure temperature
17 141 37
69 155 38
72 154 36
161 153 36
286 156 37
435 155 36
499 149 36
And for assignment you can use np.where:
df['class'] = np.where(mask, 'excellent', 'critical')
Those who got still error like me:
Convert model.fit_generator() to model.fit()
<Scatter
data={data}
// style={{ width: "50%", height: "50%" }}
options={{
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: "Probability",
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Hours",
},
},
],
},
}}
/>
As Aaron states, you can use .index(value)
, but because that will throw an exception if value
is not present, you should handle that case, even if you're sure it will never happen. A couple options are by checking its presence first, such as:
if value in my_list:
value_index = my_list.index(value)
or by catching the exception as in:
try:
value_index = my_list.index(value)
except:
value_index = -1
You can never go wrong with proper error handling.
You need to understand the difference between classes and objects. From the Java tutorial:
An object is a software bundle of related state and behavior
A class is a blueprint or prototype from which objects are created
You've defined the prototypes but done nothing with them. To use an object, you need to create it. In Java, we use the new
keyword.
new Date();
You will need to assign the object to a variable of the same type as the class the object was created from.
Date d = new Date();
Once you have a reference to the object you can interact with it
d.date("01", "12", "14");
The exception to this is static methods that belong to the class and are referenced through it
public class MyDate{
public static date(){ ... }
}
...
MyDate.date();
In case you aren't aware, Java already has a class for representing dates, you probably don't want to create your own.
According to Apple-doc
Weak references are always of an optional type, and automatically become nil when the instance they reference is deallocated.
If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference
Example -
// if my response can nil use [weak self]
resource.request().onComplete { [weak self] response in
guard let strongSelf = self else {
return
}
let model = strongSelf.updateModel(response)
strongSelf.updateUI(model)
}
// Only use [unowned self] unowned if guarantees that response never nil
resource.request().onComplete { [unowned self] response in
let model = self.updateModel(response)
self.updateUI(model)
}
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
A .tex file should be a LaTeX source file.
If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.
Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.
Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.
You can also check out this question and answer for how to do it: How to compile a LaTeX document?
Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.
Watch out for possible unintended literals in your argument
for example you can have a space within your argument, rendering it to a string / literal:
float(' 0.33')
After making sure the unintended space did not make it into the argument, I was left with:
float(0.33)
Like this it works like a charm.
Take away is: Pay Attention for unintended literals (e.g. spaces that you didn't see) within your input.
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
The DictWriter()
class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer()
and pass in a simple row for the header:
import csv
with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.writer(outcsv)
writer.writerow(["Date", "temperature 1", "Temperature 2"])
with open('t1.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows(row + [0.0] for row in reader)
with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)
The alternative would be to generate dictionaries when copying across your data:
import csv
with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
writer.writeheader()
with open('t1.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)
with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)
Get the content of the JSON file using file_get_contents()
:
$str = file_get_contents('http://example.com/example.json/');
Now decode the JSON using json_decode()
:
$json = json_decode($str, true); // decode the JSON into an associative array
You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:
echo '<pre>' . print_r($json, true) . '</pre>';
This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true
in order to let print_r()
know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
Or loop through the array however you wish:
foreach ($json['daily']['data'] as $field => $value) {
// Use $field and $value here
}
In xaml
<TextBlock Text="{Binding CelsiusTemp}" />
In ViewModel
, this way setting the value also works:
public string CelsiusTemp
{
get { return string.Format("{0}°C", _CelsiusTemp); }
set
{
value = value.Replace("°C", "");
_CelsiusTemp = value;
}
}
write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.
Other answers seem a bit complex, you can just add a parameter 'label' in scatter function and that will be the legend for your plot.
import matplotlib.pyplot as plt
from numpy.random import random
colors = ['b', 'c', 'y', 'm', 'r']
lo = plt.scatter(random(10), random(10), marker='x', color=colors[0],label='Low Outlier')
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0],label='LoLo')
l = plt.scatter(random(10), random(10), marker='o', color=colors[1],label='Lo')
a = plt.scatter(random(10), random(10), marker='o', color=colors[2],label='Average')
h = plt.scatter(random(10), random(10), marker='o', color=colors[3],label='Hi')
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4],label='HiHi')
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4],label='High Outlier')
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
fancybox=True, shadow=True, ncol=4)
plt.show()
This is your output:
When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.
Data in XML format are rarely organized in a way that would allow the xmlToDataFrame
function to work. You're better off extracting everything in lists and then binding the lists together in a data frame:
require(XML)
data <- xmlParse("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")
xml_data <- xmlToList(data)
In the case of your example data, getting location and start time is fairly straightforward:
location <- as.list(xml_data[["data"]][["location"]][["point"]])
start_time <- unlist(xml_data[["data"]][["time-layout"]][
names(xml_data[["data"]][["time-layout"]]) == "start-valid-time"])
Temperature data is a bit more complicated. First you need to get to the node that contains the temperature lists. Then you need extract both the lists, look within each one, and pick the one that has "hourly" as one of its values. Then you need to select only that list but only keep the values that have the "value" label:
temps <- xml_data[["data"]][["parameters"]]
temps <- temps[names(temps) == "temperature"]
temps <- temps[sapply(temps, function(x) any(unlist(x) == "hourly"))]
temps <- unlist(temps[[1]][sapply(temps, names) == "value"])
out <- data.frame(
as.list(location),
"start_valid_time" = start_time,
"hourly_temperature" = temps)
head(out)
latitude longitude start_valid_time hourly_temperature
1 29.81 -82.42 2013-06-19T16:00:00-04:00 91
2 29.81 -82.42 2013-06-19T17:00:00-04:00 90
3 29.81 -82.42 2013-06-19T18:00:00-04:00 89
4 29.81 -82.42 2013-06-19T19:00:00-04:00 85
5 29.81 -82.42 2013-06-19T20:00:00-04:00 83
6 29.81 -82.42 2013-06-19T21:00:00-04:00 80
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
If you check out the help of the unittest module it tells you about several combinations that allow you to run test case classes from a module and test methods from a test case class.
python3 -m unittest -h
[...]
Examples:
python3 -m unittest test_module - run tests from test_module
python3 -m unittest module.TestClass - run tests from module.TestClass
python3 -m unittest module.Class.test_method - run specified test method
```lang-none
It does not require you to define a `unittest.main()` as the default behaviour of your module.
This should work:
for /F "tokens=*" %i in ('temperature') do prismcom.exe usb %i
If running in a batch file, you need to use %%i
instead of just %i
(in both places).
Suggest the following simplification: capture return value from Workbooks.Add
instead of subscripting Windows()
afterward, as follows:
Set wkb = Workbooks.Add
wkb.SaveAs ...
wkb.Activate ' instead of Windows(expression).Activate
General Philosophy Advice:
Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.
Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.
Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection
During and within macros do not rely on these built-in names, instead capture return values, e.g.
Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate
Also, try to use qualified expressions, e.g.
wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"
or
Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"
Use qualified expressions, e.g.
newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar"
These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.
Also please note that you'll likely find that you don't need to .Activate
nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate
could simply be eliminated instead of even being replaced by wkb.Activate
.
(Also note: I think the .Select statements you show are not contributing and can be omitted.)
(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)
It seems that in VBA macro code for an ActiveX checkbox control you use
If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)
and for a Form checkbox control you use
If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)
I don't know if this is good enough but I made a static ThreadHelperClass class and implemented it as following .Now I can easily set text property of various controls without much coding .
public static class ThreadHelperClass
{
delegate void SetTextCallback(Form f, Control ctrl, string text);
/// <summary>
/// Set text property of various controls
/// </summary>
/// <param name="form">The calling form</param>
/// <param name="ctrl"></param>
/// <param name="text"></param>
public static void SetText(Form form, Control ctrl, string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (ctrl.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
form.Invoke(d, new object[] { form, ctrl, text });
}
else
{
ctrl.Text = text;
}
}
}
Using the code:
private void btnTestThread_Click(object sender, EventArgs e)
{
Thread demoThread =
new Thread(new ThreadStart(this.ThreadProcSafe));
demoThread.Start();
}
// This method is executed on the worker thread and makes
// a thread-safe call on the TextBox control.
private void ThreadProcSafe()
{
ThreadHelperClass.SetText(this, textBox1, "This text was set safely.");
ThreadHelperClass.SetText(this, textBox2, "another text was set safely.");
}
I think from the author's point of view, the main reason is to reduce the overhead for string concatenation.I just read the logger's documentation, you could find following words:
/**
* <p>This form avoids superfluous string concatenation when the logger
* is disabled for the DEBUG level. However, this variant incurs the hidden
* (and relatively small) cost of creating an <code>Object[]</code> before
invoking the method,
* even if this logger is disabled for DEBUG. The variants taking
* {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
* arguments exist solely in order to avoid this hidden cost.</p>
*/
*
* @param format the format string
* @param arguments a list of 3 or more arguments
*/
public void debug(String format, Object... arguments);
The recommended approach in this case is to sort the data in the database, adding an ORDER BY
at the end of the query that fetches the results, something like this:
SELECT temperature FROM temperatures ORDER BY temperature ASC; -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order
If for some reason that is not an option, you can change the sorting order like this in Python:
templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int) # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]
As has been pointed in the comments, the int
key (or float
if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string
, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.
Use this function:
function searchThroughArray($search,array $lists){
try{
foreach ($lists as $key => $value) {
if(is_array($value)){
array_walk_recursive($value, function($v, $k) use($search ,$key,$value,&$val){
if(strpos($v, $search) !== false ) $val[$key]=$value;
});
}else{
if(strpos($value, $search) !== false ) $val[$key]=$value;
}
}
return $val;
}catch (Exception $e) {
return false;
}
}
and call function.
print_r(searchThroughArray('breville-one-touch-tea-maker-BTM800XL',$products));
406 Not Acceptable
The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.
So, your request accept header is application/json and your controller is not able to return that. This happens when the correct HTTPMessageConverter can not be found to satisfy the @ResponseBody annotated return value. HTTPMessageConverter are automatically registered when you use the <mvc:annotation-driven>
, given certain 3-d party libraries in the classpath.
Either you don't have the correct Jackson library in your classpath, or you haven't used the
<mvc:annotation-driven>
directive.
I successfully replicated your scenario and it worked fine using these two libraries and no headers="Accept=*/*"
directive.
You can easily get what you want by adding the line in ax:
ax.plot([], [], '-r', label = 'temp')
or
ax.plot(np.nan, '-r', label = 'temp')
This would plot nothing but add a label to legend of ax.
I think this is a much easier way. It's not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.
The whole code is as below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()
#---------- look at below -----------
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2.plot(time, temp, '-r') # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp') # Make an agent in ax
ax.legend(loc=0)
#---------------done-----------------
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
The plot is as below:
Update: add a better version:
ax.plot(np.nan, '-r', label = 'temp')
This will do nothing while plot(0, 0)
may change the axis range.
One extra example for scatter
ax.scatter([], [], s=100, label = 'temp') # Make an agent in ax
ax2.scatter(time, temp, s=10) # The true scatter in ax2
ax.legend(loc=1, framealpha=1)
If you just have included a layout file at the beginning of onCreate()
inside setContentView
and want to get this layout to add new elements programmatically try this:
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);
then you can create a new Button
for example and just add it:
Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
Why do I need the descriptor class?
It gives you extra control over how attributes work. If you're used to getters and setters in Java, for example, then it's Python's way of doing that. One advantage is that it looks to users just like an attribute (there's no change in syntax). So you can start with an ordinary attribute and then, when you need to do something fancy, switch to a descriptor.
An attribute is just a mutable value. A descriptor lets you execute arbitrary code when reading or setting (or deleting) a value. So you could imagine using it to map an attribute to a field in a database, for example – a kind of ORM.
Another use might be refusing to accept a new value by throwing an exception in __set__
– effectively making the "attribute" read only.
What is
instance
andowner
here? (in__get__
). What is the purpose of these parameters?
This is pretty subtle (and the reason I am writing a new answer here - I found this question while wondering the same thing and didn't find the existing answer that great).
A descriptor is defined on a class, but is typically called from an instance. When it's called from an instance both instance
and owner
are set (and you can work out owner
from instance
so it seems kinda pointless). But when called from a class, only owner
is set – which is why it's there.
This is only needed for __get__
because it's the only one that can be called on a class. If you set the class value you set the descriptor itself. Similarly for deletion. Which is why the owner
isn't needed there.
How would I call/use this example?
Well, here's a cool trick using similar classes:
class Celsius:
def __get__(self, instance, owner):
return 5 * (instance.fahrenheit - 32) / 9
def __set__(self, instance, value):
instance.fahrenheit = 32 + 9 * value / 5
class Temperature:
celsius = Celsius()
def __init__(self, initial_f):
self.fahrenheit = initial_f
t = Temperature(212)
print(t.celsius)
t.celsius = 0
print(t.fahrenheit)
(I'm using Python 3; for python 2 you need to make sure those divisions are / 5.0
and / 9.0
). That gives:
100.0
32.0
Now there are other, arguably better ways to achieve the same effect in python (e.g. if celsius were a property, which is the same basic mechanism but places all the source inside the Temperature class), but that shows what can be done...
Sometimes it may be required to execute the update atomically that is using one update request to the database without reading it first.
Also get
-set attribute
-save
may cause problems if such updates may be done concurrently or if you need to set the new value based on the old field value.
In such cases query expressions together with update
may by useful:
TemperatureData.objects.filter(id=1).update(value=F('value') + 1)
Use this link http://ip-api.com/json ,this will provide all the information as json. From this json you can get the country easily. This site works using your current IP,it automatically detects the IP and sendback details.
Docs http://ip-api.com/docs/api:json Hope it helps.
Example json
{
"status": "success",
"country": "United States",
"countryCode": "US",
"region": "CA",
"regionName": "California",
"city": "San Francisco",
"zip": "94105",
"lat": "37.7898",
"lon": "-122.3942",
"timezone": "America/Los_Angeles",
"isp": "Wikimedia Foundation",
"org": "Wikimedia Foundation",
"as": "AS14907 Wikimedia US network",
"query": "208.80.152.201"
}
note : As this is a 3rd party solution, only use if others didn't work.
It is the simplest one I could come up with, so wanted to share here,
#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type float
float cel, fah;
//Input the Temperature in given unit save them in ‘cel’
cout<<”Enter the Temperature in Celsius”<<endl;
cin>>cel;
//convert and save it in ‘fah’
fah=1.8*cel+32.0;
//show the output ‘fah’
cout<<”Temperature in Fahrenheit is “<<fah;
//get character
getch();
}
Source: Celsius to Fahrenheit
If you don't want to use any java predefined libraries then below is the
simplest way
public class Test {
public static void main(String[] args) {
double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4,
8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2,
3.5, 3, 1.1, 6.5, 5.1, -1.2, -5.1, 2, 5.2, 2.1};
double maxx = decMax[0];
for (int i = 0; i < decMax.length; i++) {
if (maxx < decMax[i]) {
maxx = decMax[i];
}
}
System.out.println(maxx);
}
}
I'm pretty sure it's manufacturer dependent, since they will be accessed through an I/O port. If you have a specific board you're trying to work with, try looking through the manuals and/or contacting the manufacturer.
If you want to do this for a lot of different boards, I'd recommend contacting someone at something like SiSoftware or be prepared to read a LOT of motherboard manuals.
As another note, not all boards have temperature monitors.
You also might run into problems getting privileged access from the kernel.
Try this (but once clicked, it is not reversible):
HTML:
<a id="test"><img src="normal-image.png"/></a>
CSS:
a#test {
border: 0;
}
a#test:visited img, a#test:active img {
background-image: url(clicked-image.png);
}
zvolkov's answer is the perfect one to find out if there is such a customer. If you need to use the customer afterwards, you can do:
Customer customer = list.FirstOrDefault(cus => cus.FirstName == "John");
if (customer != null)
{
// Use customer
}
I know this isn't what you were asking, but I thought I'd pre-empt a follow-on question :) (Of course, this only finds the first such customer... to find all of them, just use a normal where
clause.)
Explanation from the Preshing on Programming blog:
It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:
with open('output.txt', 'w') as f: f.write('Hi there!')
The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.
The answer to this one is actually wrong.
Auto filling in the value (auto_now/auto_now_add isn't the same as default). The default value will actually be what the user sees if its a brand new object. What I typically do is:
date = models.DateTimeField(default=datetime.now, editable=False,)
Make sure, if your trying to represent this in an Admin page, that you list it as 'read_only' and reference the field name
read_only = 'date'
Again, I do this since my default value isn't typically editable, and Admin pages ignore non-editables unless specified otherwise. There is certainly a difference however between setting a default value and implementing the auto_add which is key here. Test it out!
For what it's worth - I had a similar issue, assuming it's related to a Chrome update.
I had to add font-src, and then specify the url because I was using a CDN
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; font-src 'self' data: fonts.gstatic.com;">
I like this method,use sind(x)
or cosd(x)
import math
def sind(x):
return math.sin(math.radians(x))
def cosd(x):
return math.cos(math.radians(x))
You can simply use this:
if ($("#one")){
alert('yes');
}
if ($("#two")){
alert('yes');
}
if ($("#three")){
alert('yes');
}
if ($("#four")){
alert('no');
}
Sorry, my mistake, it does not work.
This is a one line solution.
It will run taskkill only if the process is really running otherwise it will just info that it is not running.
tasklist | find /i "notepad.exe" && taskkill /im notepad.exe /F || echo process "notepad.exe" not running.
This is the output in case the process was running:
notepad.exe 1960 Console 0 112,260 K
SUCCESS: The process "notepad.exe" with PID 1960 has been terminated.
This is the output in case not running:
process "notepad.exe" not running.
SELECT sum(isnull(TotalHoursM,0))
+ isnull(TotalHoursT,0)
+ isnull(TotalHoursW,0)
+ isnull(TotalHoursTH,0)
+ isnull(TotalHoursF,0))
AS TOTAL FROM LeaveRequest
I took a slightly different approach than others
static float NextFloat(Random random)
{
double val = random.NextDouble(); // range 0.0 to 1.0
val -= 0.5; // expected range now -0.5 to +0.5
val *= 2; // expected range now -1.0 to +1.0
return float.MaxValue * (float)val;
}
The comments explain what I'm doing. Get the next double, convert that number to a value between -1 and 1 and then multiply that with float.MaxValue
.
You can set the border color in IE however there are some issues.
Argh... I could have sworn you could do this... just tested and realized I wasn't correct. The notes below still apply though.
in IE8 (Beta1 -> RC1) changing the border color or the background color/image causes a de-theming of the control in WindowsXP (the drop arrow and box look like Windows 95)
you still can't style the options within the select control very well because IE doesn't support it. (see bug #291)
The difference between respectively || and OR and && and AND is operator precedence :
$bool = FALSE || TRUE;
($bool = (FALSE || TRUE))
$bool
is TRUE
$bool = FALSE OR TRUE;
(($bool = FALSE) OR TRUE)
$bool
is FALSE
$bool = TRUE && FALSE;
($bool = (TRUE && FALSE))
$bool
is FALSE
$bool = TRUE AND FALSE;
(($bool = TRUE) AND FALSE)
$bool
is TRUE
public static BufferedImage rotateCw( BufferedImage img )
{
int width = img.getWidth();
int height = img.getHeight();
BufferedImage newImage = new BufferedImage( height, width, img.getType() );
for( int i=0 ; i < width ; i++ )
for( int j=0 ; j < height ; j++ )
newImage.setRGB( height-1-j, i, img.getRGB(i,j) );
return newImage;
}
from https://coderanch.com/t/485958/java/Rotating-buffered-image
Updated answer for ES6+ is here.
arr = [1, 2, 3];
arr.forEach(function(i, idx, array){
if (idx === array.length - 1){
console.log("Last callback call at index " + idx + " with value " + i );
}
});
would output:
Last callback call at index 2 with value 3
The way this works is testing arr.length
against the current index of the array, passed to the callback function.
The above mentioned comments are very useful but they are a bit difficult to implement. Below steps you can try, I also tried it and it worked:
Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.
this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();
Use the -1
option (note this is a "one" digit, not a lowercase letter "L"), like this:
ls -1a
First, though, make sure your ls
supports -1
. GNU coreutils (installed on standard Linux systems) and Solaris do; but if in doubt, use man ls
or ls --help
or check the documentation. E.g.:
$ man ls
...
-1 list one file per line. Avoid '\n' with -q or -b
You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):
Function GetFillColor(Rng As Range) As Long
GetFillColor = Rng.Interior.ColorIndex
End Function
Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel
In your worksheet, you can use the following: =GetFillColor(B5)
Acepted solution implemented in PyQt5
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.le.setText("Host")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("Connect")
self.pb.clicked.connect(self.button_click)
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.pb)
self.setLayout(layout)
self.setWindowTitle("Learning")
def button_click(self):
# shost is a QString object
shost = self.le.text()
print (shost)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
If you have python various versions of python installed,you can launch any of them using pythonx.x.x
where x.x.x
represents your versions.
I have fumbled around sometime to reach these considerations:
1- If my application access the database, why the test should not? What if there is something wrong with data access? The tests must know it beforehand and alert myself about the problem.
2- The Repository Pattern is somewhat hard and time consuming.
So I came up with this approach, that I don't think is the best, but fulfilled my expectations:
Use TransactionScope in the tests methods to avoid changes in the database.
To do it it's necessary:
1- Install the EntityFramework into the Test Project. 2- Put the connection string into the app.config file of Test Project. 3- Reference the dll System.Transactions in Test Project.
The unique side effect is that identity seed will increment when trying to insert, even when the transaction is aborted. But since the tests are made against a development database, this should be no problem.
Sample code:
[TestClass]
public class NameValueTest
{
[TestMethod]
public void Edit()
{
NameValueController controller = new NameValueController();
using(var ts = new TransactionScope()) {
Assert.IsNotNull(controller.Edit(new Models.NameValue()
{
NameValueId = 1,
name1 = "1",
name2 = "2",
name3 = "3",
name4 = "4"
}));
//no complete, automatically abort
//ts.Complete();
}
}
[TestMethod]
public void Create()
{
NameValueController controller = new NameValueController();
using (var ts = new TransactionScope())
{
Assert.IsNotNull(controller.Create(new Models.NameValue()
{
name1 = "1",
name2 = "2",
name3 = "3",
name4 = "4"
}));
//no complete, automatically abort
//ts.Complete();
}
}
}
Go to ORACLE_HOME/bin and run 'file sqlplus'. see output below.
64-Bit:- cd /tech/oracle/product/v11/bin
$ file sqlplus
sqlplus: **ELF 64-bit** LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, not stripped
32-Bit $ cd /tech/oracle/product/11204_32bit/bin
$ file sqlplus
sqlplus: **ELF 32-bit** LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, not stripped
Well, In Mapreduce there are two important phrases called Mapper and reducer both are too important, but Reducer is mandatory. In some programs reducers are optional. Now come to your question. Shuffling and sorting are two important operations in Mapreduce. First Hadoop framework takes structured/unstructured data and separate the data into Key, Value.
Now Mapper program separate and arrange the data into keys and values to be processed. Generate Key 2 and value 2 values. This values should process and re arrange in proper order to get desired solution. Now this shuffle and sorting done in your local system (Framework take care it) and process in local system after process framework cleanup the data in local system. Ok
Here we use combiner and partition also to optimize this shuffle and sort process. After proper arrangement, those key values passes to Reducer to get desired Client's output. Finally Reducer get desired output.
K1, V1 -> K2, V2 (we will write program Mapper), -> K2, V' (here shuffle and soft the data) -> K3, V3 Generate the output. K4,V4.
Please note all these steps are logical operation only, not change the original data.
Your question: What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?
Short answer: To process the data to get desired output. Shuffling is aggregate the data, reduce is get expected output.
Anyone who wants to do a deep copy (e.g. if your array contains objects) can use:
let arrCopy = JSON.parse(JSON.stringify(arr))
Then you can sort arrCopy
without changing arr
.
arrCopy.sort((obj1, obj2) => obj1.id > obj2.id)
Please note: this can be slow for very large arrays.
The traditional way to transform a string to a UTF-8 string is as follows:
StrConv("hello world",vbFromUnicode)
So put simply:
Dim fnum As Integer
fnum = FreeFile
Open "myfile.txt" For Output As fnum
Print #fnum, StrConv("special characters: äöüß", vbFromUnicode)
Close fnum
No special COM objects required
Not possible.
This a little counter-intuitive.
You're encountering the "Apple is-a fruit" but "Every Fruit is not an Apple"
Go for creating a new map and checking with instance of with String
Surprisingly, square brackets in DocumentRoot (and related, like <Directory>) paths can also cause error 403:
DocumentRoot "P:/TRY/web/fatfree/from_github/fatfree-master[bang]"
failed with 403, whileDocumentRoot "P:/TRY/web/fatfree/from_github/fatfree-master"
worked fine.(I didn't bother figuring out the Apache path escaping, if any, just renamed the path instead. If anyone knows, comments are welcome.)
Jumping off from Alex Montoya's approach for multiple file input elements
const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();
for (const file of inputFiles) {
formData.append(file.name, file.files[0]);
}
fetch(url, {
method: 'POST',
body: formData })
To save LogCat log to file programmatically on your device use for example this code:
String filePath = Environment.getExternalStorageDirectory() + "/logcat.txt";
Runtime.getRuntime().exec(new String[]{"logcat", "-f", filepath, "MyAppTAG:V", "*:S"});
"MyAppTAG:V"
sets the priority level for all tags to Verbose (lowest priority)
"*:S"
sets the priority level for all tags to "silent"
More information about logcat here.
A lot of these answers are incomplete. Although this is in Objective-C, this is the best compilation of all of them that I could put together for right now, as a non-recursive block:
Link to Gist, in case it gets revised: https://gist.github.com/benguild/0d149bb3caaabea2dac3d2dca58c0816
Code for reference/comparison:
UIViewController *(^topmostViewControllerForFrontmostNormalLevelWindow)(void) = ^UIViewController *{
// NOTE: Adapted from various stray answers here:
// https://stackoverflow.com/questions/6131205/iphone-how-to-find-topmost-view-controller/20515681
UIViewController *viewController;
for (UIWindow *window in UIApplication.sharedApplication.windows.reverseObjectEnumerator.allObjects) {
if (window.windowLevel == UIWindowLevelNormal) {
viewController = window.rootViewController;
break;
}
}
while (viewController != nil) {
if ([viewController isKindOfClass:[UITabBarController class]]) {
viewController = ((UITabBarController *)viewController).selectedViewController;
} else if ([viewController isKindOfClass:[UINavigationController class]]) {
viewController = ((UINavigationController *)viewController).visibleViewController;
} else if (viewController.presentedViewController != nil && !viewController.presentedViewController.isBeingDismissed) {
viewController = viewController.presentedViewController;
} else if (viewController.childViewControllers.count > 0) {
viewController = viewController.childViewControllers.lastObject;
} else {
BOOL repeat = NO;
for (UIView *view in viewController.view.subviews.reverseObjectEnumerator.allObjects) {
if ([view.nextResponder isKindOfClass:[UIViewController class]]) {
viewController = (UIViewController *)view.nextResponder;
repeat = YES;
break;
}
}
if (!repeat) {
break;
}
}
}
return viewController;
};
If you want to install requests directly you can use the "-m" (module) option available to python.
python.exe -m pip install requests
You can do this directly in PowerShell, though you may need to use the full python path (eg. C:\Python27\python.exe
) instead of just python.exe
.
As mentioned in the comments, if you have added Python to your path you can simply do:
python -m pip install requests
Python has more than one way to do strings. The following string syntax would allow you to use double quotes:
'''what"ever'''
public ActionResult Index(string username, string password, string rememberMe)
{
if (!string.IsNullOrEmpty(username))
{
bool remember = bool.Parse(rememberMe);
//...
}
return View();
}
Following commands will connect to any MySQL database
shell> mysql --host=localhost --user=myname --password=mypass mydb
or
shell> mysql -h localhost -u myname -pmypass mydb
Since it shows the password in plain text, you can type password later as prompted. So, the command will be as follows
shell> mysql --host=localhost --user=myname --password mydb
shell> mysql -h localhost -u myname -p mydb
You can annotate your bean with jaxb annotations.
@XmlRootElement
public class MyJaxbBean {
public String name;
public int age;
public MyJaxbBean() {} // JAXB needs this
public MyJaxbBean(String name, int age) {
this.name = name;
this.age = age;
}
}
and then your method would look like this:
@GET @Produces("application/json")
public MyJaxbBean getMyBean() {
return new MyJaxbBean("Agamemnon", 32);
}
There is a chapter in the latest documentation that deals with this:
https://jersey.java.net/documentation/latest/user-guide.html#json
Try a different cable, ideally an official Samsung one.
I had tried a crappy USB cable I had lying around and then tried another which was Samsung and works perfectly now.
Not sure why they would be different though but worked for me.
I ran into this exact problem too. In my case, adding parenthesis around any internal functions (to get them to evaluate first) seemed to do the trick:
Changed
=SUM(A1, SUBSTITUTE(A2,"x","3",1), A3)
to
=SUM(A1, (SUBSTITUTE(A2,"x","3",1)), A3)
When onsubmit (or any other event) is supplied as an HTML attribute, the string value of the attribute (e.g. "return validate();"
) is injected as the body of the actual onsubmit handler function when the DOM object is created for the element.
Here's a brief proof in the browser console:
var p = document.createElement('p');
p.innerHTML = '<form onsubmit="return validate(); // my statement"></form>';
var form = p.childNodes[0];
console.log(typeof form.onsubmit);
// => function
console.log(form.onsubmit.toString());
// => function onsubmit(event) {
// return validate(); // my statement
// }
So in case the return
keyword is supplied in the injected statement; when the submit handler is triggered the return value received from validate
function call will be passed over as the return value of the submit handler and thus take effect on controlling the submit behavior of the form.
Without the supplied return
in the string, the generated onsubmit
handler would not have an explicit return statement and when triggered it would return undefined
(the default function return value) irrespective of whether validate()
returns true
or false
and the form would be submitted in both cases.
well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor
function. You can get current theme with getTheme()
.
This will do the trick in fragment, you can replace getActivity()
with getBaseContext()
, yourContext
, etc which hold your current context
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}
*p.s : color is deprecated in M, but drawable is deprecated in L
Here, There are two things inside the domain
So you want to style those two sections as follows,
1. Style for the iFrame Section
It can style using CSS with that respected id
or class
name. You can just style it in your parent Style sheets also.
<style>
#my_iFrame{
height: 300px;
width: 100%;
position:absolute;
top:0;
left:0;
border: 1px black solid;
}
</style>
<iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>
2. Style the Page Loaded inside the iFrame
This Styles can be loaded from the parent page with the help of Javascript
var cssFile = document.createElement("link")
cssFile.rel = "stylesheet";
cssFile.type = "text/css";
cssFile.href = "iFramePage.css";
then set that CSS file to the respected iFrame section
//to Load in the Body Part
frames['my_iFrame'].document.body.appendChild(cssFile);
//to Load in the Head Part
frames['my_iFrame'].document.head.appendChild(cssFile);
Here, You can edit the Head Part of the Page inside the iFrame using this way also
var $iFrameHead = $("#my_iFrame").contents().find("head");
$iFrameHead.append(
$("<link/>",{
rel: "stylesheet",
href: urlPath,
type: "text/css" }
));
Add a Console.ReadKey
call to your program to force it to wait for you to press a key before exiting.
SQL SERVER 2005:
print upper('hello');
print lower('HELLO');
Add A Tap Gesture Recognizer to your view.And define it ibaction
your .m file will be like
- (IBAction)hideKeyboardGesture:(id)sender {
NSArray *windows = [UIApplication sharedApplication].windows;
for(UIWindow *window in windows) [window endEditing:true];
[[UIApplication sharedApplication].keyWindow endEditing:true];
}
It's worked for me
Your android studio may be forgot to put : buildToolsVersion "26.0.0" you need 'buildTools' to develop related design and java file. And if there is no any buildTools are installed in Android->sdk->build-tools directory then download first.
In SQL server, a cursor is used when you need Instead of the T-SQL commands that operate on all the rows in the result set one at a time, we use a cursor when we need to update records in a database table in a singleton fashion, in other words row by row.to fetch one row at a time or row by row.
Working with cursors consists of several steps:
Declare - Declare is used to define a new cursor. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor. Fetch - When the cursor is opened, rows can be retrieved from the cursor one by one. Close - After data operations, we should close the cursor explicitly. Deallocate - Finally, we need to delete the cursor definition and release all the system resources associated with the cursor. Syntax
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING] FOR select_statement [FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]
do not turn off firewall, Go Control Panel\System and Security\Windows Firewall then Advanced settings then Inbound Rules->From right pan choose New Rule-> Port-> TCP and type in port number 80 then give a name in next window, that's it.
Using Qt in Python is a really pleasant experience: http://wiki.python.org/moin/PyQt
For the quick tutorial: http://zetcode.com/tutorials/pyqt4/
You can also add prompt option like this.
<%= f.select(:object_field, ['Item 1', 'Item 2'], {include_blank: "Select something"}, { :class => 'my_style_class' }) %>
I did this by creating a new XML file res/values/style.xml
as follows:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="boldText">
<item name="android:textStyle">bold|italic</item>
<item name="android:textColor">#FFFFFF</item>
</style>
<style name="normalText">
<item name="android:textStyle">normal</item>
<item name="android:textColor">#C0C0C0</item>
</style>
</resources>
I also have an entries in my "strings.xml" file like this:
<color name="highlightedTextViewColor">#000088</color>
<color name="normalTextViewColor">#000044</color>
Then, in my code I created a ClickListener to trap the tap event on that TextView: EDIT: As from API 23 'setTextAppearance' is deprecated
myTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
//highlight the TextView
//myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
if (Build.VERSION.SDK_INT < 23) {
myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
} else {
myTextView.setTextAppearance(R.style.boldText);
}
myTextView.setBackgroundResource(R.color.highlightedTextViewColor);
}
});
To change it back, you would use this:
if (Build.VERSION.SDK_INT < 23) {
myTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
} else{
myTextView.setTextAppearance(R.style.normalText);
}
myTextView.setBackgroundResource(R.color.normalTextViewColor);
Execution of a python script would cause the byte code to be generated in memory and kept until the program is shutdown. In case a module is imported, for faster reusability, Python would create a cache .pyc (PYC is 'Python' 'Compiled') file where the byte code of the module being imported is cached. Idea is to speed up loading of python modules by avoiding re-compilation ( compile once, run multiple times policy ) when they are re-imported.
The name of the file is the same as the module name. The part after the initial dot indicates Python implementation that created the cache (could be CPython) followed by its version number.
To answer your direct question: neither of these is the preferred method. Use a separate file.
Inline styles should only be used as a last resort, or set by Javascript code. Inline styles have the highest level of specificity, so override your actual stylesheets. This can make them hard to control (you should avoid !important
as well for the same reason).
An embedded <style>
block is not recommended, because you lose the browser's ability to cache the stylesheet across multiple pages on your site.
So in short, wherever possible, you should put your styles into a separate CSS file.
Your method looks like this:
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
This adds an extension onto object
- the base class of everything. When you call this extension you're passing it a Type
:
var res = typeof(MyClass).HasProperty("Label");
Your method expects an instance of a class, not a Type
. Otherwise you're essentially doing
typeof(MyClass) - this gives an instanceof `System.Type`.
Then
type.GetType() - this gives `System.Type`
Getproperty('xxx') - whatever you provide as xxx is unlikely to be on `System.Type`
As @PeterRitchie correctly points out, at this point your code is looking for property Label
on System.Type
. That property does not exist.
The solution is either
a) Provide an instance of MyClass to the extension:
var myInstance = new MyClass()
myInstance.HasProperty("Label")
b) Put the extension on System.Type
public static bool HasProperty(this Type obj, string propertyName)
{
return obj.GetProperty(propertyName) != null;
}
and
typeof(MyClass).HasProperty("Label");
Pros
Cons
You can reset by update sequence after deleted rows in your-table
UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';
If you want to selectively remove links without having to copy/edit entire xml files, a nice solution can be found in this post in the magento forums
In this solution, you override the Mage_Customer_Block_Account_Navigation
block with a local version, that adds a removeLinkByName
method, which you then use in your layout.xml
files, like so:
<?xml version="1.0"?>
<layout version="0.1.0">
<customer_account>
<reference name="customer_account_navigation" >
<!-- remove the link using your custom method -->
<action method="removeLinkByName">
<name>recurring_profiles</name>
</action>
<action method="removeLinkByName">
<name>billing_agreements</name>
</action>
</reference>
</customer_account>
</layout>
Yes. Which platform are you writing for? ASP.NET C#?
List<string> myList = new List<string>();
Session["var"] = myList;
Then, to retrieve:
myList = (List<string>)Session["var"];
You can use the following query for MYSQL:
SHOW `columns` FROM `your-table`;
Below is the example code which shows How to implement above syntax in php to list the names of columns:
$sql = "SHOW COLUMNS FROM your-table";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row['Field']."<br>";
}
For Details about output of SHOW COLUMNS FROM TABLE
visit: MySQL Refrence.
To avoid AmbiguousMatchException
, I would rather say
objectToCheck.GetType().GetMethods().Count(m => m.Name == method) > 0
If you want passing parameter and your .exe file in test folder of c: drive
start "parameter" "C:\test\test1.exe" -pc My Name-PC -launch
If you won't want passing parameter and your .exe file in test folder of c: drive
start "" "C:\test\test1.exe" -pc My Name-PC -launch
If you won't want passing parameter and your .exe file in test folder of H: (Any Other)drive
start "" "H:\test\test1.exe" -pc My Name-PC -launch
Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into the existing table. You can add a line to drop the temp table created by the import wizard as the last step upon successful completion of the script.
I believe your original issue is in fact related to Sql Server 64 bit and is due to your having a 32 bit Excel and these drivers don't play well together. I did run into a very similar issue when first using 64 bit excel.
If you want to dump all tables from all databases and with no data (only database and table structures) you may use:
mysqldump -P port -h hostname_or_ip -u username -p --no-data --all-databases > db_backup.sql
This will produce a .sql file that you can load onto a mysql server to create a fresh database. Use cases for this are not many in a production environment, but I do this on a weekly basis to reset servers which are linked to demo websites, so whatever the users do during the week, on sunday nights everything rolls back to "new" :)
You can give a function expression a name that is actually private and is only visible from inside of the function ifself:
var factorial = function myself (n) {
if (n <= 1) {
return 1;
}
return n * myself(n-1);
}
typeof myself === 'undefined'
Here myself
is visible only inside of the function itself.
You can use this private name to call the function recursively.
See 13. Function Definition
of the ECMAScript 5 spec:
The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.
Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).
Alternatively you could use arguments.callee
to refer to the current function:
var factorial = function (n) {
if (n <= 1) {
return 1;
}
return n * arguments.callee(n-1);
}
The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode, however:
(From MDN): In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws when set or retrieved.
You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:
listy = [[] for i in range(3)]
Running your example code now gives the result you probably expected:
>>> listy = [[] for i in range(3)]
>>> listy[1] = [1,2]
>>> listy
[[], [1, 2], []]
>>> listy[1].append(3)
>>> listy
[[], [1, 2, 3], []]
>>> listy[2].append(1)
>>> listy
[[], [1, 2, 3], [1]]
I got it with an import loop:
---FILE B.h
#import "A.h"
@interface B{
A *a;
}
@end
---FILE A.h
#import "B.h"
@interface A{
}
@end
-- Disable the constraints on a table called tableName:
ALTER TABLE tableName NOCHECK CONSTRAINT ALL
-- Re-enable the constraints on a table called tableName:
ALTER TABLE tableName WITH CHECK CHECK CONSTRAINT ALL
---------------------------------------------------------
-- Disable constraints for all tables:
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
-- Re-enable constraints for all tables:
EXEC sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'
---------------------------------------------------------
The following are methods to help you:
:app
For those who have the similar problem trying to connect to local db and trying like
con = psycopg2.connect(database="my_db", user="my_name", password="admin")
, try to pass the additional parameter, so the following saved me a day:
con = psycopg2.connect(database="my_db", user="my_name", password="admin", host="localhost")
you should also be able to use groovy and do what textfinder did
marking a build as un-stable with groovy post-build plugin
if(manager.logContains("Could not login to FTP server")) {
manager.addWarningBadge("FTP Login Failure")
manager.createSummary("warning.gif").appendText("<h1>Failed to login to remote FTP Server!</h1>", false, false, false, "red")
manager.buildUnstable()
}
Also see Groovy Postbuild Plugin
Here is my javascript, tested on firefox and chrome only
<html>
<header>
<script>
function addCommas(str){
return str.replace(/^0+/, '').replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function test(){
var val = document.getElementById('test').value;
document.getElementById('test').value = addCommas(val);
}
</script>
</header>
<body>
<input id="test" onkeyup="test();">
</body>
</html>
Using DISTINCT should do it:
SELECT DISTINCT id, uname, tel
FROM YourTable
Though you could really do with having a primary key on that table, a way to uniquely identify each record. I'd be considering sticking an IDENTITY column on the table
With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
class SampleController extends Controller
{
public function indexAction(Request $request) {
var_dump($request->request->all());
}
}
Try this:
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Your asking")) {
confirm_value.value = "Yes";
document.forms[0].appendChild(confirm_value);
}
else {
confirm_value.value = "No";
document.forms[0].appendChild(confirm_value);
}
}
In Button call function:
<asp:Button ID="btnReprocessar" runat="server" Text="Reprocessar" Height="20px" OnClick="btnReprocessar_Click" OnClientClick="Confirm()"/>
In class .cs call method:
protected void btnReprocessar_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
}
}
Try to use Zip
df = pd.read_csv("file")
d= dict([(i,[a,b,c ]) for i, a,b,c in zip(df.ID, df.A,df.B,df.C)])
print d
Output:
{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}
If You want make json object from yor model do like this :
foreach (var item in Persons)
{
var jsonObj=["FirstName":"@item.FirstName"]
}
Or Use Json.Net to make json from your model :
string json = JsonConvert.SerializeObject(person);
some resources:
ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:
arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]
or using fromELF utility(built in most IDEs such as ADS though):
fromelf -bin -o [binary-output-file] [elf-input-file]
I am using Cent OS 6.6 with Apache and for me error log files are in
/usr/local/apache/log
It's as easy as:
delete object.keyname;
or
delete object["keyname"];
I started to write a Script to read OS and browser version that can be tested on Fiddle. Feel free to use and extend.
Breaking Change:
Since September 2020 the new Edge gets detected. So 'Microsoft Edge' is the new version based on Chromium and the old Edge is now detected as 'Microsoft Legacy Edge'!
/**
* JavaScript Client Detection
* (C) viazenetti GmbH (Christian Ludwig)
*/
(function (window) {
{
var unknown = '-';
// screen
var screenSize = '';
if (screen.width) {
width = (screen.width) ? screen.width : '';
height = (screen.height) ? screen.height : '';
screenSize += '' + width + " x " + height;
}
// browser
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browser = navigator.appName;
var version = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset, ix;
// Opera
if ((verOffset = nAgt.indexOf('Opera')) != -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 6);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// Opera Next
if ((verOffset = nAgt.indexOf('OPR')) != -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 4);
}
// Legacy Edge
else if ((verOffset = nAgt.indexOf('Edge')) != -1) {
browser = 'Microsoft Legacy Edge';
version = nAgt.substring(verOffset + 5);
}
// Edge (Chromium)
else if ((verOffset = nAgt.indexOf('Edg')) != -1) {
browser = 'Microsoft Edge';
version = nAgt.substring(verOffset + 4);
}
// MSIE
else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(verOffset + 5);
}
// Chrome
else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
browser = 'Chrome';
version = nAgt.substring(verOffset + 7);
}
// Safari
else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
browser = 'Safari';
version = nAgt.substring(verOffset + 7);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// Firefox
else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
browser = 'Firefox';
version = nAgt.substring(verOffset + 8);
}
// MSIE 11+
else if (nAgt.indexOf('Trident/') != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(nAgt.indexOf('rv:') + 3);
}
// Other browsers
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
browser = nAgt.substring(nameOffset, verOffset);
version = nAgt.substring(verOffset + 1);
if (browser.toLowerCase() == browser.toUpperCase()) {
browser = navigator.appName;
}
}
// trim the version string
if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);
majorVersion = parseInt('' + version, 10);
if (isNaN(majorVersion)) {
version = '' + parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion, 10);
}
// mobile version
var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);
// cookie
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
document.cookie = 'testcookie';
cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
}
// system
var os = unknown;
var clientStrings = [
{s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
{s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
{s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
{s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
{s:'Windows Vista', r:/Windows NT 6.0/},
{s:'Windows Server 2003', r:/Windows NT 5.2/},
{s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
{s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
{s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
{s:'Windows 98', r:/(Windows 98|Win98)/},
{s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
{s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
{s:'Windows CE', r:/Windows CE/},
{s:'Windows 3.11', r:/Win16/},
{s:'Android', r:/Android/},
{s:'Open BSD', r:/OpenBSD/},
{s:'Sun OS', r:/SunOS/},
{s:'Chrome OS', r:/CrOS/},
{s:'Linux', r:/(Linux|X11(?!.*CrOS))/},
{s:'iOS', r:/(iPhone|iPad|iPod)/},
{s:'Mac OS X', r:/Mac OS X/},
{s:'Mac OS', r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
{s:'QNX', r:/QNX/},
{s:'UNIX', r:/UNIX/},
{s:'BeOS', r:/BeOS/},
{s:'OS/2', r:/OS\/2/},
{s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
];
for (var id in clientStrings) {
var cs = clientStrings[id];
if (cs.r.test(nAgt)) {
os = cs.s;
break;
}
}
var osVersion = unknown;
if (/Windows/.test(os)) {
osVersion = /Windows (.*)/.exec(os)[1];
os = 'Windows';
}
switch (os) {
case 'Mac OS':
case 'Mac OS X':
case 'Android':
osVersion = /(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([\.\_\d]+)/.exec(nAgt)[1];
break;
case 'iOS':
osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
break;
}
// flash (you'll need to include swfobject)
/* script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" */
var flashVersion = 'no check';
if (typeof swfobject != 'undefined') {
var fv = swfobject.getFlashPlayerVersion();
if (fv.major > 0) {
flashVersion = fv.major + '.' + fv.minor + ' r' + fv.release;
}
else {
flashVersion = unknown;
}
}
}
window.jscd = {
screen: screenSize,
browser: browser,
browserVersion: version,
browserMajorVersion: majorVersion,
mobile: mobile,
os: os,
osVersion: osVersion,
cookies: cookieEnabled,
flashVersion: flashVersion
};
}(this));
alert(
'OS: ' + jscd.os +' '+ jscd.osVersion + '\n' +
'Browser: ' + jscd.browser +' '+ jscd.browserMajorVersion +
' (' + jscd.browserVersion + ')\n' +
'Mobile: ' + jscd.mobile + '\n' +
'Flash: ' + jscd.flashVersion + '\n' +
'Cookies: ' + jscd.cookies + '\n' +
'Screen Size: ' + jscd.screen + '\n\n' +
'Full User Agent: ' + navigator.userAgent
);
Use the built-in sp_msforeachtable stored procedure.
To disable all constraints:
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL";
To enable all constraints:
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL";
To drop all the tables:
EXEC sp_msforeachtable "DROP TABLE ?";
This code works for me:
$rootScope.$$listeners.nameOfYourEvent=[];
I used this code:
public static async Task<IEnumerable<TResult>> SelectAsync<TSource,TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> method)
{
return await Task.WhenAll(source.Select(async s => await method(s)));
}
like this:
var result = await sourceEnumerable.SelectAsync(async s=>await someFunction(s,other params));
Before Java 7:
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Since Java 7, there is no need to close the stream, because it implements autocloseable
try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
><
by >\n<
with Regular Expressions enabledIf you prefer to use pure Node.js then you might extract POST data like it is shown below:
// Dependencies_x000D_
const StringDecoder = require('string_decoder').StringDecoder;_x000D_
const http = require('http');_x000D_
_x000D_
// Instantiate the HTTP server._x000D_
const httpServer = http.createServer((request, response) => {_x000D_
// Get the payload, if any._x000D_
const decoder = new StringDecoder('utf-8');_x000D_
let payload = '';_x000D_
_x000D_
request.on('data', (data) => {_x000D_
payload += decoder.write(data);_x000D_
});_x000D_
_x000D_
request.on('end', () => {_x000D_
payload += decoder.end();_x000D_
_x000D_
// Parse payload to object._x000D_
payload = JSON.parse(payload);_x000D_
_x000D_
// Do smoething with the payload...._x000D_
});_x000D_
};_x000D_
_x000D_
// Start the HTTP server._x000D_
const port = 3000;_x000D_
httpServer.listen(port, () => {_x000D_
console.log(`The server is listening on port ${port}`);_x000D_
});
_x000D_
To add my two cents to the conversation a process can have simultaneously open a number of sockets connected equal to this number (in Linux type sytems) /proc/sys/net/core/somaxconn
cat /proc/sys/net/core/somaxconn
This number can be modified on the fly (only by root user of course)
echo 1024 > /proc/sys/net/core/somaxconn
But entirely depends on the server process, the hardware of the machine and the network, the real number of sockets that can be connected before crashing the system
Spinner mySpinner = (Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
ORA-12154: TNS:could not resolve the connect identifier specified?
In case the TNS is not defined you can also try this one:
If you are using C#.net 2010
or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:
static string constr = @"Data Source=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
User Id=system ;Password=yourpasswrd";
After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified
then first you have to do restart your system and run your project.
And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:
Oracle Data Provider for .NET 2.0
Oracle Providers for ASP.NET
Oracle Developer Tools for Visual Studio
Oracle Instant Client
And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......
Quick one in TSQL
SELECT a.*
FROM emails a
INNER JOIN
(SELECT email,
MIN(id) as id
FROM emails
GROUP BY email
) AS b
ON a.email = b.email
AND a.id = b.id;
@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs
sizes so you won't notice, but if you used anything else (e.g. col-sm
, col-md
, etc), you'd understand.
Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/
.left-side {
background-color: blue;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.something {
height: 100%;
background-color: red;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.row {
background-color: green;
overflow: hidden;
}
writelines
expects an iterable of stringswrite
expects a single string. line1 + "\n" + line2
merges those strings together into a single string before passing it to write
.
Note that if you have many lines, you may want to use "\n".join(list_of_lines)
.
If i understand what you mean, you have to initialize your controller with that style. Something like:
myTVContoller = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
Additional to Jerry Coffin's first paragraph. Ie, ARM design gives lower power consumption.
The company ARM
, only licenses the CPU technology. They don't make physical chips. This allows other companies to add various peripheral technologies, typically called SOC or system-on-chip. Whether the device is a tablet, a cell phone, or an in-car entertainment system. This allows chip vendors to tailor the rest of the chip to a particular application. This has additional benefits,
ARM
supports SOC vendors with AMBA, allowing SOC implementers to purchase off the shelf 3rd party modules; like an Ethernet, memory and interrupt controllers. Some other CPU platforms support this, like MIPS, but MIPS is not as power conscious.
All of these are beneficial to a handheld/battery operated design. Some are just good all around. As well, ARM
has a history of battery operated devices; Apple Newton, Psion Organizers. The PDA software infra-structure was leveraged by some companies to create smart phone type devices. Although, more success was had by those who re-invented the GUI for use with a smart phone.
The rise of Open source
tool sets and operating systems
also facilitated the various SOC
chips. A closed organization would have issues trying to support all the various devices available for the ARM. The two most popular cellular platforms, Andriod and OSx/IOS, are based up Linux and FreeBSD, Mach and NetBSD os's. Open Source
helps SOC
vendors provide software support for their chip sets.
Hopefully, why x86 is used for the keyboard is self-evident. It has the software, and more importantly people trained to use that software. Netwinder is one ARM
system that was originally designed for the keyboard. Also, manufacturer's are currently looking at ARM64 for the server market. Power/heat is a concern at 24/7 data centers.
So I would say that the ecosystem that grows around these chips is as important as features like low power consumption. ARM
has been striving for low power, higher performance computing for some time (mid to late 1980's) and they have a lot of people on board.
Note1: Multiple chips need bus drivers to inter-communicate at known voltages and drive. Also, typically separate chips need support capacitors and other power components which can be shared in an SOC system.
This may also happen if you have a faulty or accidental equation in your csv file. i.e - One of the cells in your csv file starts with an equals sign (=) (An excel equation) which will, in turn throw an error. If you fix, or remove this equation by getting rid of the equals sign, it should solve the ORA-06502 error.
I am going to answer my own question.
I added the following lines of code to my Makefile and it fixed the "clock skew" problem:
clean:
find . -type f | xargs touch
rm -rf $(OBJS)
it means "append "THIS" to the current value"
example:
a = "hello"; a += " world";
printing a now will output: "hello world"
Scanner sc = new Scanner (System.in)
char c = sc.next().trim().charAt(0);
Increased cohesion and decreased coupling do lead to good software design.
Cohesion partitions your functionality so that it is concise and closest to the data relevant to it, whilst decoupling ensures that the functional implementation is isolated from the rest of the system.
Decoupling allows you to change the implementation without affecting other parts of your software.
Cohesion ensures that the implementation more specific to functionality and at the same time easier to maintain.
The most effective method of decreasing coupling and increasing cohesion is design by interface.
That is major functional objects should only 'know' each other through the interface(s) that they implement. The implementation of an interface introduces cohesion as a natural consequence.
Whilst not realistic in some senarios it should be a design goal to work by.
Example (very sketchy):
public interface IStackoverFlowQuestion
void SetAnswered(IUserProfile user);
void VoteUp(IUserProfile user);
void VoteDown(IUserProfile user);
}
public class NormalQuestion implements IStackoverflowQuestion {
protected Integer vote_ = new Integer(0);
protected IUserProfile user_ = null;
protected IUserProfile answered_ = null;
public void VoteUp(IUserProfile user) {
vote_++;
// code to ... add to user profile
}
public void VoteDown(IUserProfile user) {
decrement and update profile
}
public SetAnswered(IUserProfile answer) {
answered_ = answer
// update u
}
}
public class CommunityWikiQuestion implements IStackoverflowQuestion {
public void VoteUp(IUserProfile user) { // do not update profile }
public void VoteDown(IUserProfile user) { // do not update profile }
public void SetAnswered(IUserProfile user) { // do not update profile }
}
Some where else in your codebase you could have a module that processes questions regardless of what they are:
public class OtherModuleProcessor {
public void Process(List<IStackoverflowQuestion> questions) {
... process each question.
}
}
Table names in MySQL are file system entries, so they are case insensitive if the underlying file system is.
N+1 select issue is a pain, and it makes sense to detect such cases in unit tests. I have developed a small library for verifying the number of queries executed by a given test method or just an arbitrary block of code - JDBC Sniffer
Just add a special JUnit rule to your test class and place annotation with expected number of queries on your test methods:
@Rule
public final QueryCounter queryCounter = new QueryCounter();
@Expectation(atMost = 3)
@Test
public void testInvokingDatabase() {
// your JDBC or JPA code
}
In my case, the dump file I restored had these commands.
CREATE SCHEMA employees;
SET search_path = employees, pg_catalog;
I've commented those and restored again. The issue got resolved
You are putting there a two-digits year. The first century. And the Gregorian calendar started in the 16th century. I think you should add 2000 to the year.
Month in the function new GregorianCalendar(year, month, days)
is 0-based. Subtract 1 from the month there.
Change the body of the second function as follows:
String dateFormatted = null;
SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
try {
dateFormatted = fmt.format(date);
}
catch ( IllegalArgumentException e){
System.out.println(e.getMessage());
}
return dateFormatted;
After debugging, you'll see that simply GregorianCalendar
can't be an argument of the fmt.format();
.
Really, nobody needs GregorianCalendar
as output, even you are told to return "a string".
Change the header of your format function to
public static String format(final Date date)
and make the appropriate changes. fmt.format()
will take the Date
object gladly.
If you are at a certain branch mybranch
, just go ahead and git checkout commit_hash
. Then you can return to your branch by git checkout mybranch
. I had the same game bisecting a bug today :) Also, you should know about git bisect.
We use object-scan for most of our data processing. It's conceptually very simple, but allows for a lot of cool stuff. Here is how you would solve your question
// const objectScan = require('object-scan');
const findDinner = (dinner, data) => objectScan(['*'], {
abort: true,
rtn: 'value',
filterFn: ({ value }) => value.dinner === dinner
})(data);
const data = { 1: { name: 'bob', dinner: 'pizza' }, 2: { name: 'john', dinner: 'sushi' }, 3: { name: 'larry', dinner: 'hummus' } };
console.log(findDinner('sushi', data));
// => { name: 'john', dinner: 'sushi' }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
If you don't mention the random_state in the code, then whenever you execute your code a new random value is generated and the train and test datasets would have different values each time.
However, if you use a particular value for random_state(random_state = 1 or any other value) everytime the result will be same,i.e, same values in train and test datasets. Refer below code:
import pandas as pd
from sklearn.model_selection import train_test_split
test_series = pd.Series(range(100))
size30split = train_test_split(test_series,random_state = 1,test_size = .3)
size25split = train_test_split(test_series,random_state = 1,test_size = .25)
common = [element for element in size25split[0] if element in size30split[0]]
print(len(common))
Doesn't matter how many times you run the code, the output will be 70.
70
Try to remove the random_state and run the code.
import pandas as pd
from sklearn.model_selection import train_test_split
test_series = pd.Series(range(100))
size30split = train_test_split(test_series,test_size = .3)
size25split = train_test_split(test_series,test_size = .25)
common = [element for element in size25split[0] if element in size30split[0]]
print(len(common))
Now here output will be different each time you execute the code.
In the case where you presented a UIViewController
from within a UIViewController
i.e...
// Main View Controller
self.present(otherViewController, animated: true)
Simply call the dismiss
function:
// Other View Controller
self.dismiss(animated: true)
Rails 4
scope :combined_scope, -> { where("name = ? or name = ?", 'a', 'b') }
I like this for a simple check from the shell:
mysql -p<password> -D<database> -B -e "SHOW TABLES LIKE 'User%'" \
| awk 'NR != 1 {print "CHECK TABLE "$1";"}' \
| mysql -p<password> -D<database>
I prefer to use a DOS function. Feels cleaner to me.
SET SIZELIMIT=1000
CALL :FileSize %1 FileSize
IF %FileSize% GTR %SIZELIMIT% Echo Large file
GOTO :EOF
:FileSize
SET %~2=%~z1
GOTO :EOF
Using the DB2 commands (no SQL) there is the possibility of executing
db2 LIST TABLES FOR ALL
This shows all the tables in all the schemas in the database.
Enable Microsoft ActiveX Data Objects 2.8 Library
Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & _
"DATABASE=yourdatabase;" & _
"USER=yourdbusername;" & _
"PASSWORD=yourdbpassword;" & _
"Option=3"
End Sub
There rest is here: http://www.heritage-tech.net/908/inserting-data-into-mysql-from-excel-using-vba/
If you want to process your String one character at a time. you have various options.
uhello = u'Hello\u0020World'
Using List comprehension:
print([x for x in uhello])
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Using map:
print(list(map(lambda c2: c2, uhello)))
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Calling Built in list function:
print(list(uhello))
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Using for loop:
for c in uhello:
print(c)
Output:
H
e
l
l
o
W
o
r
l
d
I would move the function handle change and add an index parameter
handleChange: function (index) {
var items = this.state.items;
items[index].name = 'newName';
this.setState({items: items});
},
to the Dynamic form component and pass it to the PopulateAtCheckboxes component as a prop. As you loop over your items you can include an additional counter (called index in the code below) to be passed along to the handle change as shown below
{ Object.keys(this.state.items).map(function (key, index) {
var item = _this.state.items[key];
var boundHandleChange = _this.handleChange.bind(_this, index);
return (
<div>
<PopulateAtCheckboxes this={this}
checked={item.populate_at} id={key}
handleChange={boundHandleChange}
populate_at={data.populate_at} />
</div>
);
}, this)}
Finally you can call your change listener as shown below here
<input type="radio" name={'populate_at'+this.props.id} value={value} onChange={this.props.handleChange} checked={this.props.checked == value} ref="populate-at"/>
If you are using xcode 4.3
, you have to add the font
to the Build Phase
under Copy Bundle Resources
, according to https://stackoverflow.com/users/1292829/arne in the thread, Custom Fonts Xcode 4.3. This worked for me, here are the steps I took for custom fonts to work in my app:
OTF
(or TTF
) files to a new group I created and accepted xcode's choice of copying the files over to the project folder
.UIAppFonts
array with your fonts listed as items within the array. Just the names
, not the extension (e.g. "GothamBold
", "GothamBold-Italic
").project name
way at the top of the Project Navigator
on the left side of the screen.Build Phases
tab that appears in the main area of xcode.Copy Bundle Resources
" section and click on "+"
to add the font."+"
.add to the project
.In SQL Server Enterprise Manager, open \Server Objects\Linked Servers\Providers
, right click on the OraOLEDB.Oracle
provider, select properties and check the "Allow inprocess"
option. Recreate your linked server and test again.
You can also execute the following query if you don't have access to SQL Server Management Studio :
EXEC master.dbo.sp_MSset_oledb_prop N'OraOLEDB.Oracle', N'AllowInProcess', 1
Here are a few ways to create a list with N of continuous natural numbers starting from 1.
1 range:
def numbers(n):
return range(1, n+1);
2 List Comprehensions:
def numbers(n):
return [i for i in range(1, n+1)]
You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!
Swift is statically typed so the performSelector:
methods are to fall by the wayside.
Instead, use GCD to dispatch a suitable block to the relevant queue — in this case it'll presumably be the main queue since it looks like you're doing UIKit work.
EDIT: the relevant performSelector:
is also notably missing from the Swift version of the NSRunLoop
documentation ("1 Objective-C symbol hidden") so you can't jump straight in with that. With that and its absence from the Swiftified NSObject
I'd argue it's pretty clear what Apple is thinking here.
If you use Kotlin, you can add an extension method to Image in the same manner Sri Harsha Chilakapati suggests.
fun Image.toBufferedImage(): BufferedImage {
if (this is BufferedImage) {
return this
}
val bufferedImage = BufferedImage(this.getWidth(null), this.getHeight(null), BufferedImage.TYPE_INT_ARGB)
val graphics2D = bufferedImage.createGraphics()
graphics2D.drawImage(this, 0, 0, null)
graphics2D.dispose()
return bufferedImage
}
And use it like this:
myImage.toBufferedImage()
reinterpret_cast
cannot be used for this conversion, the code will not compile. According to C++03 standard section 5.2.10-1:
Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
This conversion is not listed in that section. Even this is invalid:
long l = reinterpret_cast<long>(i)
static_cast
is the one which has to be used here. See this and this SO questions.
Code to add audio to video using ffmpeg.
If audio length is greater than video length it will cut the audio to video length. If you want full audio in video remove -shortest from the cmd.
String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy", ,outputFile.getPath()};
private void execFFmpegBinaryShortest(final String[] command) {
final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");
String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};
try {
ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
@Override
public void onFailure(String s) {
System.out.println("on failure----"+s);
}
@Override
public void onSuccess(String s) {
System.out.println("on success-----"+s);
}
@Override
public void onProgress(String s) {
//Log.d(TAG, "Started command : ffmpeg "+command);
System.out.println("Started---"+s);
}
@Override
public void onStart() {
//Log.d(TAG, "Started command : ffmpeg " + command);
System.out.println("Start----");
}
@Override
public void onFinish() {
System.out.println("Finish-----");
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
System.out.println("exceptio :::"+e.getMessage());
}
}
Pfft! Microseconds! Never solve a problem in microseconds that can be solved in nanoseconds.
Note that the accepted answer:
A better solution is to return True immediately when NAN is found:
import numba
import numpy as np
NAN = float("nan")
@numba.njit(nogil=True)
def _any_nans(a):
for x in a:
if np.isnan(x): return True
return False
@numba.jit
def any_nans(a):
if not a.dtype.kind=='f': return False
return _any_nans(a.flat)
array1M = np.random.rand(1000000)
assert any_nans(array1M)==False
%timeit any_nans(array1M) # 573us
array1M[0] = NAN
assert any_nans(array1M)==True
%timeit any_nans(array1M) # 774ns (!nanoseconds)
and works for n-dimensions:
array1M_nd = array1M.reshape((len(array1M)/2, 2))
assert any_nans(array1M_nd)==True
%timeit any_nans(array1M_nd) # 774ns
Compare this to the numpy native solution:
def any_nans(a):
if not a.dtype.kind=='f': return False
return np.isnan(a).any()
array1M = np.random.rand(1000000)
assert any_nans(array1M)==False
%timeit any_nans(array1M) # 456us
array1M[0] = NAN
assert any_nans(array1M)==True
%timeit any_nans(array1M) # 470us
%timeit np.isnan(array1M).any() # 532us
The early-exit method is 3 orders or magnitude speedup (in some cases). Not too shabby for a simple annotation.
I had this same question, and after a lot of research, it looks like it's not possible.
The answer from cgat is on the right track, but you can't actually concatenate references like that.
Here are things you can do with "variables" in YAML (which are officially called "node anchors" when you set them and "references" when you use them later):
default: &default_title This Post Has No Title
title: *default_title
{ or }
example_post: &example
title: My mom likes roosters
body: Seriously, she does. And I don't know when it started.
date: 8/18/2012
first_post: *example
second_post:
title: whatever, etc.
For more info, see this section of the wiki page about YAML: http://en.wikipedia.org/wiki/YAML#References
default: &DEFAULT
URL: stooges.com
throw_pies?: true
stooges: &stooge_list
larry: first_stooge
moe: second_stooge
curly: third_stooge
development:
<<: *DEFAULT
URL: stooges.local
stooges:
shemp: fourth_stooge
test:
<<: *DEFAULT
URL: test.stooges.qa
stooges:
<<: *stooge_list
shemp: fourth_stooge
This is taken directly from a great demo here: https://gist.github.com/bowsersenior/979804
If you use resources extensively, you might consider using Commons VFS.
Also supports: * Local Files * FTP, SFTP * HTTP and HTTPS * Temporary Files "normal FS backed) * Zip, Jar and Tar (uncompressed, tgz or tbz2) * gzip and bzip2 * resources * ram - "ramdrive" * mime
There's also JBoss VFS - but it's not much documented.
There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...
This is a simple copy, just like you would do with memcpy()
(indeed, some compilers actually produce a call to memcpy()
for that code). There is no "string" in C, only pointers to a bunch a chars. If your source structure contains such a pointer, then the pointer gets copied, not the chars themselves.
How can I undo every change made to my directory after the last commit, including deleting added files, resetting modified files, and adding back deleted files?
You can undo changes to tracked files with:
git reset HEAD --hard
You can remove untracked files with:
git clean -f
You can remove untracked files and directories with:
git clean -fd
but you can't undo change to untracked files.
You can remove ignored and untracked files and directories
git clean -fdx
but you can't undo change to ignored files.
You can also set clean.requireForce
to false
:
git config --global --add clean.requireForce false
to avoid using -f
(--force
) when you use git clean
.
I'm surprised anyone hasn't said this yet.
Since the asker came from a Java background (and so did I), here's an analogy that helps.
Classes are simply like Java classes.
Modules are like Java static classes. Think about Math
class in Java. You don't instantiate it, and you reuse the methods in the static class (eg. Math.random()
).
The best I've seen is Zend Guard.
Use o parameter of pgsql command.
-o, --output=FILENAME send query results to file (or |pipe)
psql -d DatabaseName -U UserName -c "SELECT * FROM TABLE" -o /root/Desktop/file.txt
I would suggest using the duplicated method on the Pandas Index itself:
df3 = df3[~df3.index.duplicated(keep='first')]
While all the other methods work, the currently accepted answer is by far the least performant for the provided example. Furthermore, while the groupby method is only slightly less performant, I find the duplicated method to be more readable.
Using the sample data provided:
>>> %timeit df3.reset_index().drop_duplicates(subset='index', keep='first').set_index('index')
1000 loops, best of 3: 1.54 ms per loop
>>> %timeit df3.groupby(df3.index).first()
1000 loops, best of 3: 580 µs per loop
>>> %timeit df3[~df3.index.duplicated(keep='first')]
1000 loops, best of 3: 307 µs per loop
Note that you can keep the last element by changing the keep argument to 'last'
.
It should also be noted that this method works with MultiIndex
as well (using df1 as specified in Paul's example):
>>> %timeit df1.groupby(level=df1.index.names).last()
1000 loops, best of 3: 771 µs per loop
>>> %timeit df1[~df1.index.duplicated(keep='last')]
1000 loops, best of 3: 365 µs per loop
let startDate = "2019-01-16T20:00:00.000";
let endDate = "2019-02-11T20:00:00.000";
let sDate = new Date(startDate);
let eDate = new Date(endDate);
startDate = moment(sDate);
endDate = moment(eDate);
I like the solution posted by user1786647, and I've updated it a little to change the timezone to a function argument and add optional support for passing either a Unix time or datetime string to use for the returned datestamp.
It also includes a fallback for "setTimestamp" for users running version lower than PHP 5.3:
function DateStamp($strDateTime = null, $strTimeZone = "Europe/London") {
$objTimeZone = new DateTimeZone($strTimeZone);
$objDateTime = new DateTime();
$objDateTime->setTimezone($objTimeZone);
if (!empty($strDateTime)) {
$fltUnixTime = (is_string($strDateTime)) ? strtotime($strDateTime) : $strDateTime;
if (method_exists($objDateTime, "setTimestamp")) {
$objDateTime->setTimestamp($fltUnixTime);
}
else {
$arrDate = getdate($fltUnixTime);
$objDateTime->setDate($arrDate['year'], $arrDate['mon'], $arrDate['mday']);
$objDateTime->setTime($arrDate['hours'], $arrDate['minutes'], $arrDate['seconds']);
}
}
return $objDateTime->format("Y-m-d H:i:s");
}
You can use the rather sensibly named xpath function called concat here
<a>
<xsl:attribute name="href">
<xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
</xsl:attribute>
</a>
Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.
Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression
<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>
Is there an easy way to view all methods which contain this comment? Some sort of menu option?
Yes, choose one of the following:
Go to Window ? Show View ? Tasks (Not TaskList). The new view will show up where the "Console" and "Problems" tabs are by default.
As mentioned elsewhere, you can see them next to the scroll bar as little blue rectangles if you have the source file in question open.
If you just want the // TODO Auto-generated method stub
messages (rather than all // TODO
messages) you should use the search function (Ctrl-F for ones in this file Search ? Java Search ? Search string for the ability to specify this workspace, that file, this project, etc.)
Dockerfile (custom name and folder):
docker/app.Dockerfile
docker/nginx.Dockerfile
Build:
docker build -f ./docker/app.Dockerfile .
docker build -f ./docker/nginx.Dockerfile .
If you turn things around, you can declare your base class abstract, and have descendants declare setUp and tearDown methods (without annotations) that are called in the base class' annotated setUp and tearDown methods.
Using undefined
to make a decision is usually a sign of bad design in Javascript. You might consider doing something else.
However, to answer your question: I think the best way of doing so would be adding a helper function.
$scope.isUndefined = function (thing) {
return (typeof thing === "undefined");
}
and in the template
<div ng-show="isUndefined(foo)"></div>
The results might seem similar, but that is just because of the Taylor expansion for the logarithm. Since log(1 + x) ~ x, the results can be similar.
However,
I am using the following code to get logarithmic returns, but it gives the exact same values as the pct.change() function.
is not quite correct.
import pandas as pd
df = pd.DataFrame({'p': range(10)})
df['pct_change'] = df.pct_change()
df['log_stuff'] = \
np.log(df['p'].astype('float64')/df['p'].astype('float64').shift(1))
df[['pct_change', 'log_stuff']].plot();
My case is the page is sending multiple requests with different parameters when it was open. So most are being "stalled". Following requests immediately sent gets "stalled". Avoiding unnecessary requests would be better (to be lazy...).
My opinionated solution:
function objFilter(obj, filter, nonstrict){
r = {}
if (!filter) return {}
if (typeof filter == 'string') return {[filter]: obj[filter]}
for (p in obj) {
if (typeof filter == 'object' && nonstrict && obj[p] == filter[p]) r[p] = obj[p]
else if (typeof filter == 'object' && !nonstrict && obj[p] === filter[p]) r[p] = obj[p]
else if (typeof filter == 'function'){ if (filter(obj[p],p,obj)) r[p] = obj[p]}
else if (filter.length && filter.includes(p)) r[p] = obj[p]
}
return r
}
Test cases:
obj = {a:1, b:2, c:3}
objFilter(obj, 'a') // returns: {a: 1}
objFilter(obj, ['a','b']) // returns: {a: 1, b: 2}
objFilter(obj, {a:1}) // returns: {a: 1}
objFilter(obj, {'a':'1'}, true) // returns: {a: 1}
objFilter(obj, (v,k,o) => v%2===1) // returns: {a: 1, c: 3}
https://gist.github.com/bernardoadc/872d5a174108823159d845cc5baba337
If you want to specify a list of files on the command line, and get the whole thing done in a single atomic command, try:
git apply --3way <(git show -- list-of-files)
--3way
: If a patch does not apply cleanly, Git will create a merge conflict so you can run git mergetool
. Omitting --3way
will make Git give up on patches which don't apply cleanly.
std::queue<myclass*> my_queue;
will do the job.
See here for more information on this container.
Check you have <meta charset="utf-8">
inside head block.
It might not work correctly when using a program that is not attached to the console, because that app might still be running while you think you have the exit code. A solution to do it in C++ looks like below:
#include "stdafx.h"
#include "windows.h"
#include "stdio.h"
#include "tchar.h"
#include "stdio.h"
#include "shellapi.h"
int _tmain( int argc, TCHAR *argv[] )
{
CString cmdline(GetCommandLineW());
cmdline.TrimLeft('\"');
CString self(argv[0]);
self.Trim('\"');
CString args = cmdline.Mid(self.GetLength()+1);
args.TrimLeft(_T("\" "));
printf("Arguments passed: '%ws'\n",args);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc < 2 )
{
printf("Usage: %s arg1,arg2....\n", argv[0]);
return -1;
}
CString strCmd(args);
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
(LPTSTR)(strCmd.GetString()), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d)\n", GetLastError() );
return GetLastError();
}
else
printf( "Waiting for \"%ws\" to exit.....\n", strCmd );
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
int result = -1;
if(!GetExitCodeProcess(pi.hProcess,(LPDWORD)&result))
{
printf("GetExitCodeProcess() failed (%d)\n", GetLastError() );
}
else
printf("The exit code for '%ws' is %d\n",(LPTSTR)(strCmd.GetString()), result );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return result;
}
You can try the enable/disable methods instead of using the option method:
$("#txtSearch").datepicker("enable");
$("#txtSearch").datepicker("disable");
This disables the entire textbox. So may be you can use datepicker.destroy()
instead:
$(document).ready(function() {
$("#ddlSearchType").change(function() {
if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
$("#txtSearch").datepicker();
}
else {
$("#txtSearch").datepicker("destroy");
}
}).change();
});
In my opinion, turning off the -e
option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e
Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.
If you have a line in your script where failure is expected, like a grep or a find, then just add || true
to the end of that line. That ensures that line will always return success.
If you need to use that exit code, you can either hoist the command into your if statement:
grep foo bar; if [ $? == 0 ]; then ... --> if grep foo bar; then ...
Or you can capture the return code in your ||
clause:
grep foo bar || ret=$?
You need to put the files into an array in order to sort and find the last modified file.
$files = array();
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);
// sort
ksort($files);
// find the last modification
$reallyLastModified = end($files);
foreach($files as $file) {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
if ($file == $reallyLastModified) {
// do stuff for the real last modified file
}
echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
}
}
}
Not tested, but that's how to do it.
Both John Conde's and ryeballar's answers are correct and will work.
If you want to get too geeky:
John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center
and it has to decide whether to add/remove left
), when clearly only one is needed.
Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)
So, you can do the following as an alternative:
ng-class="{true:'center',false:'left'}[page.isSelected(1)]"
You can create an array with all elements from a given Swift
Set
simply with
let array = Array(someSet)
This works because Set
conforms to the SequenceType
protocol
and an Array
can be initialized with a sequence. Example:
let mySet = Set(["a", "b", "a"]) // Set<String>
let myArray = Array(mySet) // Array<String>
print(myArray) // [b, a]
IPA Format:
xcodebuild -exportArchive -exportFormat IPA -archivePath MyMobileApp.xcarchive -exportPath MyMobileApp.ipa -exportProvisioningProfile 'MyMobileApp Distribution Profile'
Exports the archive MyMobileApp.xcarchive as an IPA file to the path MyMobileApp.ipa using the provisioning profile MyMobileApp Distribution Profile.
APP Format:
xcodebuild -exportArchive -exportFormat APP -archivePath MyMacApp.xcarchive -exportPath MyMacApp.pkg -exportSigningIdentity 'Developer ID Application: My Team'
Exports the archive MyMacApp.xcarchive as a PKG file to the path MyMacApp.pkg using the appli-cation application cation signing identity Developer ID Application: My Team. The installer signing identity Developer ID Installer: My Team is implicitly used to sign the exported package.
Use : '
to open and '
to close.
For example:
: '
This is a
very neat comment
in bash
'
Here is a single line solution using the XElements. I use it in a very small tool. I don't need it a second time so I keep it this way. (Its dirdy doug)
StrVal = (<x a=<%= StrVal %>>END</x>).ToString().Replace("<x a=""", "").Replace(">END</x>", "")
Oh and it only works in VB not in C#
import datetime from datetime
now = datetime.now()
print "%0.2d:%0.2d:%0.2d" % (now.hour, now.minute, now.second)
You can do the same with day & month etc.
Adapted from here, building on scunliffe's answer:
function getStyle(className) {
var cssText = "";
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == className) {
cssText += classes[x].cssText || classes[x].style.cssText;
}
}
return cssText;
}
alert(getStyle('.test'));
You put <=
and it will catch the given date too. You can replace it with <
only.
You also need to compile PHP with zip support. The manual says the following:
In order to use these functions you must compile PHP with zip support by using the --enable-zip configure option.
It's not enough to simply install the correct extensions on the server. Have a look at the installation instructions link Pekka posted earlier. My answer is just a clarification of his.
Let me post a solution here for C++03 that I consider the cleanest possible.*
#define DECLARE_LAMBDA(NAME, RETURN_TYPE, FUNCTION) \
struct { RETURN_TYPE operator () FUNCTION } NAME;
...
int main(){
DECLARE_LAMBDA(demoLambda, void, (){ cout<<"I'm a lambda!"<<endl; });
demoLambda();
DECLARE_LAMBDA(plus, int, (int i, int j){
return i+j;
});
cout << "plus(1,2)=" << plus(1,2) << endl;
return 0;
}
(*) in the C++ world using macros is never considered clean.
Here's an HTML5 alternative to homebrew: http://www.rgraph.net/ You might be able to reverse engineer their methods....
You might also consider something like Flot (http://code.google.com/p/flot/) or GCharts: (http://www.maxb.net/scripts/jgcharts/include/demo/#1) It's not quite as cool, but fully backwards compatible and scary easy to implement.
Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit.
I was getting this Error due to incorrect syntax using in the terminal. I was using java - version. But its actually is java -version. there is no space between - and version. you can also cross check by using java -help.
i hope this will help.
For me, the menu item Inspect Devices wasn't available (not shown at all). But, simply browsing to chrome://inspect/#devices showed me my device and I was able to use the port forward etc. I have no idea why the menu item is not displayed.
Phone: Android Galaxy S4
OS: Mac OS X
If you use IntelliJ IDEA you can browse all maven goals/tasks (including plugins) in Maven Projects
tab:
$customer_id = get_current_user_id();
print get_user_meta( $customer_id, 'billing_first_name', true );
In python 3.0 zip returns a zip object. You can get a list out of it by calling list(zip(a, b))
.
I faced the same problem. I found two solutions: (1) Editing the jar file manually:
Open the jar file with WinRar (or similar tools). Go to Meta-info > services , and edit "org.apache.hadoop.fs.FileSystem" by appending:
org.apache.hadoop.fs.LocalFileSystem
(2) Changing the order of my dependencies as follow
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.2.1</version>
</dependency>
</dependencies>
The best way to do this in Angular and keep the code simple is to use this project.
https://www.npmjs.com/package/ngx-clipboard
<fa-icon icon="copy" ngbTooltip="Copy to Clipboard" aria-hidden="true"
ngxClipboard [cbContent]="target value here"
(cbOnSuccess)="copied($event)"></fa-icon>
you can set the opacity by the last parameter of rgb
function.
the opacity is 0.5
in the example
.modal-backdrop {
background-color: rgb(0, 0, 0, 0.5);
}
as zsolt mentioned, some regex engines support recursion -- of course, these are typically the ones that use a backtracking algorithm so it won't be particularly efficient. example: /(?>[^{}]*){(?>[^{}]*)(?R)*(?>[^{}]*)}/sm
I need to run on localhost, not some weird IP.
1) From your Mac terminal, do iconfig -a
to find your local IP address. It's probably the last one.
en7: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=10b<RXCSUM,TXCSUM,VLAN_HWTAGGING,AV>
ether 38:c9:86:32:0e:69
inet6 fe80::ea:393e:a54f:635%en7 prefixlen 64 secured scopeid 0xe
inet 10.1.5.60 netmask 0xfffffe00 broadcast 10.1.5.255
nd6 options=201<PERFORMNUD,DAD>
media: autoselect (1000baseT <full-duplex,flow-control>)
status: active
e.g. 10.1.5.60
2) boot up your windows image. start > type cmd
to get a terminal
3) notepad c:\windows\system32\drivers\etc\hosts
4) add the following line
10.1.5.60 localhost
5) open IE, and the following url should hit the server running on your mac: http://localhost:3000/
This error consumed my whole day so thought of writing what really worked for me
"DO NOT DELETE PODFILE"
After all this, CLEAN(OPTION + SHIFT + CMD + K) --> BUILD(CMD + B) --> RUN(CMD + R)
I hope this really works for you :)
If you want the changes for the last n
commits, you can use the following:
git diff HEAD~n
So for the last 5 commits (count including your current commit) from the current commit, it would be:
git diff HEAD~5
dstat
- Combines vmstat, iostat, ifstat, netstat information and more iftop
- Amazing network bandwidth utility to analyse what is really happening on your eth netio
- Measures the net throughput of a network via TCP/IP inq
- CLI troubleshooting utility that displays info on storage, typically Symmetrix. By default, INQ returns the device name, Symmetrix ID, Symmetrix LUN, and capacity.send_arp
- Sends out an arp broadcast on the specified network device (defaults to eth0), reporting an old and new IP address mapping to a MAC address.EtherApe
- is a graphical network monitor for Unix modeled after etherman. Featuring link layer, IP and TCP modes, it displays network activity graphically.iptraf
- An IP traffic monitor that shows information on the IP traffic passing over your network.More details: http://felipeferreira.net/?p=1194
I know this is in the above answers, but my point is that I think all you need is
new Date(collectionDate);
if your goal is to convert a date string into a date (as per the OP "How do I convert it to a date object?").
It can also be used as below:
from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)
new
will initialise the default values of the struct and correctly links the references in it to itself.
E.g.
struct test_s {
int some_strange_name = 1;
int &easy = some_strange_name;
}
So new struct test_s
will return an initialised structure with a working reference, while the malloc'ed version has no default values and the intern references aren't initialised.
if you need to change form action with Javascript you will have the same problem
1.first you need to use instead of {!!Form::open() !!} {!! close() !!}
in laravel
2.second you most begin your action with https://www.example.com +your Route
Do not Forget www in your url!!!
How about this (in you don't want an one liner) ?
for row in df.collect():
d = row.asDict()
s = "%d\t%s\t%s\n" % (d["int_column"], d["string_column"], d["string_column"])
f.write(s)
f is a opened file descriptor. Also the separator is a TAB char, but it's easy to change to whatever you want.
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
I suppose you could roll your own:
def parse(string):
retval = ''
for char in string:
retval += char if not char == '\n' else ''
if char == '\n':
yield retval
retval = ''
if retval:
yield retval
I'm not sure how efficient this implementation is, but that will only iterate over your string once.
Mmm, generators.
Edit:
Of course you'll also want to add in whatever type of parsing actions you want to take, but that's pretty simple.
System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
or
typeof(Program).Assembly.GetName().Name;
You can very easily override the val
function to trigger change by replacing it with a proxy to the original val
function.
just add This code somewhere in your document (after loading jQuery)
(function($){
var originalVal = $.fn.val;
$.fn.val = function(){
var result =originalVal.apply(this,arguments);
if(arguments.length>0)
$(this).change(); // OR with custom event $(this).trigger('value-changed');
return result;
};
})(jQuery);
A working example: here
(Note that this will always trigger change
when val(new_val)
is called even if the value didn't actually changed.)
If you want to trigger change ONLY when the value actually changed, use this one:
//This will trigger "change" event when "val(new_val)" called
//with value different than the current one
(function($){
var originalVal = $.fn.val;
$.fn.val = function(){
var prev;
if(arguments.length>0){
prev = originalVal.apply(this,[]);
}
var result =originalVal.apply(this,arguments);
if(arguments.length>0 && prev!=originalVal.apply(this,[]))
$(this).change(); // OR with custom event $(this).trigger('value-changed')
return result;
};
})(jQuery);
Live example for that: http://jsfiddle.net/5fSmx/1/
There is no col-??-offset-0. All "rows" assume there is no offset unless it has been specified. I think you are wanting 3 rows on a small screen and 1 row on a medium screen.
To get the result I believe you are looking for try this:
<div class="container">
<div class="row">
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
</div>
</div>
Keep in mind you will only see a difference on a small tablet with what you described. Medium, large, and extra small screens the columns are spanning 12.
Hope this helps.
This self calling function will iterate over replacerItems using an index, and change replacerItems[index] globally on the string with each pass.
const replacerItems = ["a", "b", "c"];
function replacer(str, index){
const item = replacerItems[index];
const regex = new RegExp(`[${item}]`, "g");
const newStr = str.replace(regex, "z");
if (index < replacerItems.length - 1) {
return replacer(newStr, index + 1);
}
return newStr;
}
// console.log(replacer('abcdefg', 0)) will output 'zzzdefg'
I rather use Virtualenv to install such packages rather than the entire system, saves time and effort rather than building from source.
I use virtualenvwrapper
Windows user can download
pip install virtualenvwrapper-win
https://pypi.org/project/virtualenvwrapper-win/
Linux follow
pip install opencv-python
If processing a video is required
pip install opencv-contrib-python
If you do not need GUI in Opencv
pip install opencv-contrib-python-headless
In my case it was happening during json serialization of a web api return payload - I had a 'circular' reference in my Entity Framework model, I was returning a simple one-to-many object graph back but the child had a reference back to the parent, which apparently the json serializer doensn't like. Removing the property on the child that was referencing the parent did the trick.
Hope this helps someone who might have a similar issue.
Try this out. The basic strategy is to sort the particular column independently and remember the original row of the entry. The rest of the code will cycle through the sorted column data and swap out the rows in the array. The tricky part is remembing to update the original column as the swap portion will effectively alter the original column.
public class Pair<T> {
public int Index;
public T Value;
public Pair(int i, T v) {
Index = i;
Value = v;
}
}
static IEnumerable<Pair<T>> Iterate<T>(this IEnumerable<T> source) {
int index = 0;
foreach ( var cur in source) {
yield return new Pair<T>(index,cur);
index++;
}
}
static void Sort2d(string[][] source, IComparer comp, int col) {
var colValues = source.Iterate()
.Select(x => new Pair<string>(x.Index,source[x.Index][col])).ToList();
colValues.Sort((l,r) => comp.Compare(l.Value, r.Value));
var temp = new string[source[0].Length];
var rest = colValues.Iterate();
while ( rest.Any() ) {
var pair = rest.First();
var cur = pair.Value;
var i = pair.Index;
if (i == cur.Index ) {
rest = rest.Skip(1);
continue;
}
Array.Copy(source[i], temp, temp.Length);
Array.Copy(source[cur.Index], source[i], temp.Length);
Array.Copy(temp, source[cur.Index], temp.Length);
rest = rest.Skip(1);
rest.Where(x => x.Value.Index == i).First().Value.Index = cur.Index;
}
}
public static void Test1() {
var source = new string[][]
{
new string[]{ "foo", "bar", "4" },
new string[] { "jack", "dog", "1" },
new string[]{ "boy", "ball", "2" },
new string[]{ "yellow", "green", "3" }
};
Sort2d(source, StringComparer.Ordinal, 2);
}
Actually maybe you should choose the function update
is better.
Here's the document of function update
http://api.highcharts.com/highcharts#Series.update
You can just type code like below:
chart.series[0].update({data: [1,2,3,4,5]})
These code will merge the origin option, and update the changed data.
LUBUNTU 19.10 / Same issue running: $ npm start
dump: Error: EACCES: permission denied, open '/home/simon/xxx/pagebuilder/resources/scripts/registration/node_modules/.cache/@babel/register/.babel.7.4.0.development.json' at Object.fs.openSync (fs.js:646:18) at Object.fs.writeFileSync (fs.js:1299:33) at save (/home/simon/xxx/pagebuilder/resources/scripts/registration/node_modules/@babel/register/lib/cache.js:52:15) at _combinedTickCallback (internal/process/next_tick.js:132:7) at process._tickCallback (internal/process/next_tick.js:181:9) at Function.Module.runMain (module.js:696:11) at Object. (/home/simon/xxxx/pagebuilder/resources/scripts/registration/node_modules/@babel/node/lib/_babel-node.js:234:23) at Module._compile (module.js:653:30) at Object.Module._extensions..js (module.js:664:10) at Module.load (module.js:566:32)
Looks like my default user (administrator) didn't have rights on node-module directories.
This fixed it for me!
$ sudo chmod a+w node_modules -R ## from project root
((DefaultTableModel)jTable3.getModel()).setNumRows(0); // delet all table row
Try This:
A picture is worth a thousand words:
==
equality chart:===
Equality chart:Source code to create these images:
https://github.com/sentientmachine/php_equality_charts
Those who wish to keep their sanity, read no further because none of this will make any sense, except to say that this is how the insanity-fractal, of PHP was designed.
NAN != NAN
but NAN == true
.
==
will convert left and right operands to numbers if left is a number. So 123 == "123foo"
, but "123" != "123foo"
A hex string in quotes is occasionally a float, and will be surprise cast to float against your will, causing a runtime error.
==
is not transitive because "0"== 0
, and 0 == ""
but "0" != ""
PHP Variables that have not been declared yet are false, even though PHP has a way to represent undefined variables, that feature is disabled with ==
.
"6" == " 6"
, "4.2" == "4.20"
, and "133" == "0133"
but 133 != 0133
. But "0x10" == "16"
and "1e3" == "1000"
exposing that surprise string conversion to octal will occur both without your instruction or consent, causing a runtime error.
False == 0
, ""
, []
and "0"
.
If you add 1 to number and they are already holding their maximum value, they do not wrap around, instead they are cast to infinity
.
A fresh class is == to 1.
False is the most dangerous value because False is == to most of the other variables, mostly defeating it's purpose.
If you are using PHP, Thou shalt not use the double equals operator because if you use triple equals, the only edge cases to worry about are NAN and numbers so close to their datatype's maximum value, that they are cast to infinity. With double equals, anything can be surprise ==
to anything or, or can be surprise casted against your will and !=
to something of which it should obviously be equal.
Anywhere you use ==
in PHP is a bad code smell because of the 85 bugs in it exposed by implicit casting rules that seem designed by millions of programmers programming by brownian motion.
If you are going to do it in pure CSS (using scss) but you have different elements/classes inside the same parent class you can use this version!!
&:first-of-type:nth-last-of-type(1) {
max-width: 100%;
}
@for $i from 2 through 10 {
&:first-of-type:nth-last-of-type(#{$i}),
&:first-of-type:nth-last-of-type(#{$i}) ~ & {
max-width: (100% / #{$i});
}
}
It's compiler dependent. That said, in general using "
prioritizes headers in the current working directory over system headers. <>
usually is used for system headers. From to the specification (Section 6.10.2):
A preprocessing directive of the form
# include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the
<
and>
delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.A preprocessing directive of the form
# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the
"
delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read# include <h-char-sequence> new-line
with the identical contained sequence (including
>
characters, if any) from the original directive.
So on most compilers, using the ""
first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <>
starts the search with system headers.
To get properties from dynamic doc
when .GetType()
returns null
, try this:
var keyValuePairs = ((System.Collections.Generic.IDictionary<string, object>)doc);
var val = keyValuePairs["propertyName"].ToObject<YourModel>;
Try using an absolute path for the filename. And if you are using Windows, use getlasterror() to see the actual error message.
The best solution, to me anyway, is buried in the comments of @ephemient's answer. I am just pulling it up here so that it doesn't go unnoticed. The credit for this should go to @FRoZeN (and @ephemient).
git diff --shortstat `git hash-object -t tree /dev/null`
returns the total of files and lines in the working directory of a repo, without any additional noise. As a bonus, only the source code is counted - binary files are excluded from the tally.
The command above works on Linux and OS X. The cross-platform version of it is
git diff --shortstat 4b825dc642cb6eb9a060e54bf8d69288fbee4904
That works on Windows, too.
For the record, the options for excluding blank lines,
-w
/--ignore-all-space
, -b
/--ignore-space-change
, --ignore-blank-lines
, --ignore-space-at-eol
don't have any effect when used with --shortstat
. Blank lines are counted.
You already have a process running. You can kill it with the command :
killall mongod
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
There is very easy way to do it, from your laravel query just rename any column name, it will show you an error with your query.. :)
In addition to the answer given by @l0b0 I just had the situation where I needed to both keep any trailing newlines output by the script and check the script's return code. And the problem with l0b0's answer is that the 'echo x' was resetting $? back to zero... so I managed to come up with this very cunning solution:
RESULTX="$(./myscript; echo x$?)"
RETURNCODE=${RESULTX##*x}
RESULT="${RESULTX%x*}"
The compiler may well optimize the second form into the first form, but it doesn't have to.
#include <iostream>
class A
{
public:
A() { std::cerr << "Empty constructor" << std::endl; }
A(const A&) { std::cerr << "Copy constructor" << std::endl; }
A(const char* str) { std::cerr << "char constructor: " << str << std::endl; }
~A() { std::cerr << "destructor" << std::endl; }
};
void direct()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void assignment()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a = A(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void prove_copy_constructor_is_called()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
A b = a;
static_cast<void>(b); // avoid warnings about unused variables
}
int main()
{
direct();
assignment();
prove_copy_constructor_is_called();
return 0;
}
Output from gcc 4.4:
TEST: direct
char constructor: direct
destructor
TEST: assignment
char constructor: assignment
destructor
TEST: prove_copy_constructor_is_called
char constructor: prove_copy_constructor_is_called
Copy constructor
destructor
destructor