https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects
To create and save an object in a single step, use the
create()
method.
Just use the splitlines() functions. Here is an example.
inp = "file.txt"
data = open(inp)
dat = data.read()
lst = dat.splitlines()
print lst
# print(lst) # for python 3
In the output you will have the list of lines.
Here is a function that will do that.
CREATE FUNCTION count_str(haystack TEXT, needle VARCHAR(32))
RETURNS INTEGER DETERMINISTIC
BEGIN
RETURN ROUND((CHAR_LENGTH(haystack) - CHAR_LENGTH(REPLACE(haystack, needle, ""))) / CHAR_LENGTH(needle));
END;
You can also rotate the ImageView
using a RotateAnimation
:
RotateAnimation rotateAnimation = new RotateAnimation(from, to,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(ANIMATION_DURATION);
rotateAnimation.setFillAfter(true);
imageView.startAnimation(rotateAnimation);
This typically is caused by the mount directory being left mounted due to a crash of your filesystem. Go to the parent directory of the mount point and enter fusermount -u YOUR_MNT_DIR
.
If this doesn't do the trick, do sudo umount -l YOUR_MNT_DIR
.
Try to type in cmd: php artisan key:generate the problems will be solved
Using a #t=10,20
fragment worked for me.
One special case for this is if you have used a construction like the following in your ~/.muttrc:
# Reset From email to default
send-hook . "my_hdr From: Real Name <[email protected]>"
This send-hook will override either of these:
mutt -e "set [email protected]"
mutt -e "my_hdr From: Other Name <[email protected]>"
Your emails will still go out with the header:
From: Real Name <[email protected]>
In this case, the only command line solution I've found is actually overriding the send-hook itself:
mutt -e "send-hook . \"my_hdr From: Other Name <[email protected]>\""
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
See this: Demo
$('#cat_icon,.panel_title').click(function () {
$('#categories,#cat_icon').stop().slideToggle('slow');
});
Update : To slide from left to right: Demo2
Note: Second one uses jquery-ui also
Use PREPARE
/EXECUTE
and querying the schema.
The host doesn't need to have permission to create or run procedures :
SET @dbname = DATABASE();
SET @tablename = "tableName";
SET @columnname = "colName";
SET @preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = @tablename)
AND (table_schema = @dbname)
AND (column_name = @columnname)
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " INT(11);")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
I have a very dumb but working option. if you have the String fullDate = "11/15/2013 08:00:00";
String finalDate = fullDate.split(" ")[0];
That should work easy and fast. :)
The most important thing is to avoid creating a problem
, so I believe that you should use a direct relation to avoid having a cycle.
As @markmywords said, #include "fritzl.h".
Finally I have to say recheck your data structure
. Maybe something is going wrong over there (maybe a bidirectional linked list solves your problem).
The problem was that I had hexadecimal data that needed to be converted to binary before being base64encoded.
in PHP:
base64_encode(pack("H*", $subvalue))
I should tell you the basic steps and rest depends upon your own effort. You need to perform following steps.
Do not forget to open and close connection. follow this link for more under standing.
You can use the begin
and end
functions from the Boost range library to easily find the ends of a primitive array, and unlike the macro solution, this will give a compile error instead of broken behaviour if you accidentally apply it to a pointer.
const char* array[] = { "cat", "dog", "horse" };
vector<string> vec(begin(array), end(array));
The main difference is that Boolean is an object and boolean is an primitive.
You need to escape the backslash \
:
println yourString.replace("\\", "/")
I know it has been a long time since the original question was posted. But i think for slow ones like me a bit of explanation of @Heisenberg's answer would help.
Declare two variable in the adapter class as
private int mExpandedPosition= -1;
private RecyclerView recyclerView = null;
Then in onBindViewHolder following as given in the original answer.
// This line checks if the item displayed on screen
// was expanded or not (Remembering the fact that Recycler View )
// reuses views so onBindViewHolder will be called for all
// items visible on screen.
final boolean isExpanded = position==mExpandedPosition;
//This line hides or shows the layout in question
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
// I do not know what the heck this is :)
holder.itemView.setActivated(isExpanded);
// Click event for each item (itemView is an in-built variable of holder class)
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if the clicked item is already expaned then return -1
//else return the position (this works with notifyDatasetchanged )
mExpandedPosition = isExpanded ? -1:position;
// fancy animations can skip if like
TransitionManager.beginDelayedTransition(recyclerView);
//This will call the onBindViewHolder for all the itemViews on Screen
notifyDataSetChanged();
}
});
And lastly to get the recyclerView object in the adapter override
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
this.recyclerView = recyclerView;
}
Hope this Helps.
float s = sin(angle); // angle is in radians
float c = cos(angle); // angle is in radians
For clockwise rotation :
float xnew = p.x * c + p.y * s;
float ynew = -p.x * s + p.y * c;
For counter clockwise rotation :
float xnew = p.x * c - p.y * s;
float ynew = p.x * s + p.y * c;
What is a monkey patch?
Simply put, monkey patching is making changes to a module or class while the program is running.
There's an example of monkey-patching in the Pandas documentation:
import pandas as pd
def just_foo_cols(self):
"""Get a list of column names containing the string 'foo'
"""
return [x for x in self.columns if 'foo' in x]
pd.DataFrame.just_foo_cols = just_foo_cols # monkey-patch the DataFrame class
df = pd.DataFrame([list(range(4))], columns=["A","foo","foozball","bar"])
df.just_foo_cols()
del pd.DataFrame.just_foo_cols # you can also remove the new method
To break this down, first we import our module:
import pandas as pd
Next we create a method definition, which exists unbound and free outside the scope of any class definitions (since the distinction is fairly meaningless between a function and an unbound method, Python 3 does away with the unbound method):
def just_foo_cols(self):
"""Get a list of column names containing the string 'foo'
"""
return [x for x in self.columns if 'foo' in x]
Next we simply attach that method to the class we want to use it on:
pd.DataFrame.just_foo_cols = just_foo_cols # monkey-patch the DataFrame class
And then we can use the method on an instance of the class, and delete the method when we're done:
df = pd.DataFrame([list(range(4))], columns=["A","foo","foozball","bar"])
df.just_foo_cols()
del pd.DataFrame.just_foo_cols # you can also remove the new method
If you're using name-mangling (prefixing attributes with a double-underscore, which alters the name, and which I don't recommend) you'll have to name-mangle manually if you do this. Since I don't recommend name-mangling, I will not demonstrate it here.
How can we use this knowledge, for example, in testing?
Say we need to simulate a data retrieval call to an outside data source that results in an error, because we want to ensure correct behavior in such a case. We can monkey patch the data structure to ensure this behavior. (So using a similar method name as suggested by Daniel Roseman:)
import datasource
def get_data(self):
'''monkey patch datasource.Structure with this to simulate error'''
raise datasource.DataRetrievalError
datasource.Structure.get_data = get_data
And when we test it for behavior that relies on this method raising an error, if correctly implemented, we'll get that behavior in the test results.
Just doing the above will alter the Structure
object for the life of the process, so you'll want to use setups and teardowns in your unittests to avoid doing that, e.g.:
def setUp(self):
# retain a pointer to the actual real method:
self.real_get_data = datasource.Structure.get_data
# monkey patch it:
datasource.Structure.get_data = get_data
def tearDown(self):
# give the real method back to the Structure object:
datasource.Structure.get_data = self.real_get_data
(While the above is fine, it would probably be a better idea to use the mock
library to patch the code. mock
's patch
decorator would be less error prone than doing the above, which would require more lines of code and thus more opportunities to introduce errors. I have yet to review the code in mock
but I imagine it uses monkey-patching in a similar way.)
I find this code useful when I need a path outside of a controller, such as when I'm initializing components in Global.asax.cs:
HostingEnvironment.MapPath("~/Data/data.html")
I would suggest using closest
, which selects the closest matching parent element:
$('input[name="submitButton"]').closest("form");
Instead of filtering by the name, I would do this:
$('input[type=submit]').closest("form");
This would be valid for radio buttons sharing the same name, no JQuery needed.
var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked })[0];
If we are talking about checkboxes and we want a list with the checkboxes checked sharing a name:
var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked });
I usually do it like this.. Works every time..
var loc = ctrl.PointToScreen(Point.Empty);
To access an array member you use $array['KEY'];
To access an object member you use $obj->KEY;
To access an object member inside an array of objects:
$array[0]
// Get the first object in the array
$array[0]->KEY
// then access its key
You may also loop over an array of objects like so:
foreach ($arrayOfObjs as $key => $object) {
echo $object->object_property;
}
Think of an array as a collection of things. It's a bag where you can store your stuff and give them a unique id (key) and access them (or take the stuff out of the bag) using that key. I want to keep things simple here, but this bag can contain other bags too :)
An array contains 'key
' and 'value
' pairs. Providing a key for an array member is optional and in this case it is automatically assigned a numeric key which starts with 0 and keeps on incrementing by 1 for each additional member. We can retrieve a 'value' from the array by it's 'key
'.
So we can define an array in the following ways (with respect to keys):
$colorPallete = ['red', 'blue', 'green'];
The above array will be assigned numeric keys automatically. So the key assigned to red will be 0, for blue 1 and so on.
$colorPallete[0]; // will output 'red'
$colorPallete[1]; // will output 'blue'
$colorPallete[2]; // will output 'green'
$colorPallete = ['love' => 'red', 'trust' => 'blue', 'envy' => 'green']; // we expliicitely define the keys ourself.
$colorPallete['love']; // will output 'red'
$colorPallete['trust']; // will output 'blue'
$colorPallete['envy']; // will output 'green'
You might be able to resize the image with canvas
and export it using dataURI. Not sure about compression, though.
Take a look at this: Resizing an image in an HTML5 canvas
For me it worked like I had images in icons
folder under src
and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));
char[] result = "Stack Me 123 Heppa1 oeu".toCharArray();
Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.
You can use the gulp-filenames module to get the array of paths. You can even group them by namespaces:
var filenames = require("gulp-filenames");
gulp.src("./src/*.coffee")
.pipe(filenames("coffeescript"))
.pipe(gulp.dest("./dist"));
gulp.src("./src/*.js")
.pipe(filenames("javascript"))
.pipe(gulp.dest("./dist"));
filenames.get("coffeescript") // ["a.coffee","b.coffee"]
// Do Something With it
I fixed it writing the following:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Why <AllowedHeader>*</AllowedHeader>
is working and <AllowedHeader>Authorization</AllowedHeader>
not?
you can center any object in viewport, here is an example using jquery
$(document).ready(function()
{
posicionar("#midiv");
$(window).on("resize", function() {
posicionar("#midiv");
});
function posicionar(elemento){
var altoDocumento = $(window).height();//alto
var anchoDocumento = $(window).width();
//console.log(altoDocumento);
//console.log(anchoDocumento);
var centroXDocumento = anchoDocumento / 2;
var centroYDocumento = altoDocumento / 2;
//console.log(centroXDocumemnto,centroYDocumento);
var altoElemento = $(elemento).outerHeight(true);//ancho real del elemento
var anchoElemento = $(elemento).outerWidth(true);//alto
var centroXElemento = anchoElemento / 2;// centro x del elemento
var centroYElemento = altoElemento / 2; // centro y del elemento
var posicionXElemento = centroXDocumento - centroXElemento;
var posicionYElemento = centroYDocumento - centroYElemento;
$(elemento).css("position","absolute");
$(elemento).css("top", posicionYElemento);
$(elemento).css("left", posicionXElemento);
}
});
the html
<div id="midiv"></div>
Note: you must execute the function onDomReady and when the window resizes.
here is de jsfiddle http://jsfiddle.net/geomorillo/v82x6/
This can also be caused if the application was built from different PCs. You can make it easier for your whole team if you copy a debug.keystore
from someone's machine into a /cert
folder at the top of your project and then add a signingConfigs
section to your app/build.gradle
:
signingConfigs {
debug {
storeFile file("cert/debug.keystore")
}
}
Then tell your debug build how to sign the application:
buildTypes {
debug {
// Other values
signingConfig signingConfigs.debug
}
}
Check this file into source control. This will allow for the seamless install/upgrade process across your entire development team and will make your project resilient against future machine upgrades too.
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
//Create the SqlCommand object
SqlCommand cmd = new SqlCommand(“spAddEmployee”, con);
//Specify that the SqlCommand is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//Add the input parameters to the command object
cmd.Parameters.AddWithValue(“@Name”, txtEmployeeName.Text);
cmd.Parameters.AddWithValue(“@Gender”, ddlGender.SelectedValue);
cmd.Parameters.AddWithValue(“@Salary”, txtSalary.Text);
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = “@EmployeeId”;
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
//Open the connection and execute the query
con.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string EmployeeId = outPutParameter.Value.ToString();
}
Font http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output
ErrorCode # 1932 Worked for me on Ubuntu 14.04 Trusty
$cfg['Servers'][$i]['pma__bookmark'] = 'pma__bookmark';
$cfg['Servers'][$i]['pma__relation'] = 'pma__relation';
$cfg['Servers'][$i]['pma__table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['pma__table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pma__pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['pma__column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['pma__table_uiprefs'] = 'pma__history';
$cfg['Servers'][$i]['pma__table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['pma__tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['pma__userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['pma__recent'] = 'pma__recent';
$cfg['Servers'][$i]['pma__users'] = 'pma__users';
$cfg['Servers'][$i]['pma__usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['pma__navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['pma__savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['pma__central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['pma__designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['pma__designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['pma__export_templates'] = 'pma__export_templates';
$cfg['Servers'][$i]['pma__favorite'] = 'pma__favorite';
You access the property in the wrong way. With the $this->$my_value = ..
syntax, you set the property with the name of the value in $my_value. What you want is $this->my_value = ..
$var = "my_value";
$this->$var = "test";
is the same as
$this->my_value = "test";
To fix a few things from your example, the code below is a better aproach
class my_class {
public $my_value = array();
function __construct ($value) {
$this->my_value[] = $value;
}
function set_value ($value) {
if (!is_array($value)) {
throw new Exception("Illegal argument");
}
$this->my_value = $value;
}
function add_value($value) {
$this->my_value = $value;
}
}
$a = new my_class ('a');
$a->my_value[] = 'b';
$a->add_value('c');
$a->set_value(array('d'));
This ensures, that my_value won't change it's type to string or something else when you call set_value. But you can still set the value of my_value direct, because it's public. The final step is, to make my_value private and only access my_value over getter/setter methods
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
Hope it helps
I've got a solution that should work in IE6 (and definitely works in 7+ & FireFox/Chrome).
You were on the right track using a span
, but the use of a ul
was wrong and the css wasn't right.
<a class="htooltip" href="#">
Notes
<span>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
</span>
</a>
.htooltip, .htooltip:visited, .tooltip:active {
color: #0077AA;
text-decoration: none;
}
.htooltip:hover {
color: #0099CC;
}
.htooltip span {
display : none;
position: absolute;
background-color: black;
color: #fff;
padding: 5px 10px 5px 40px;
text-decoration: none;
width: 350px;
z-index: 10;
}
.htooltip:hover span {
display: block;
}
Everyone was going about this the wrong way. The code isn't valid, ul
's cant go in a
's, p
's can't go in a
's, div
's cant go in a
's, just use a span
(remembering to make it display
as a block
so it will wrap as if it were a div
/p
etc).
You might also consider running the (non-python) program xls2csv. Feed it an xls file, and you should get back a csv.
I believe best practice these days is H/5 * * * *
, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.
Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.
Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY();
rule.
If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?
This can be achieved by using the following CSS:
.dynamic-height {
-webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
margin-top: -10px;
}
In this instance, it is important to remember that translateY(100%)
will move the element in question downwards by a total of it's own length.
The problem with this route is that it will not push element below it out of the way, where a margin would.
If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.
jQuery(document).ready(function($){ //wait for the document to load
$('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
$(this).css({
'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
});
});
});
It was trying to connect to an older version of MySQL ('version', '5.1.73' ); when you use a newer driver version you get an error that tells you to use the "com.mysql.cj.jdbc.Driver or even that you don't have to especify which one you use:
Loading class
com.mysql.jdbc.Driver'. This is deprecated. The new driver class is
com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
I changed the declaration to use 5.1.38 version of the mysql-connector-java and, in the code, I kept the com.mysql.jdbc.Driver.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
All started when I saw the Ankit Jain's answer
If you have ArrayList then convert into Array[Object]
ArrayList<String> list = new ArrayList<String>();
PreparedStatement pstmt =
conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", list.toArray());
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();
You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.
string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');
if (lnSpace > -1)
{
string lcFirst = lcStart.Substring(0, lnSpace);
string lcRest = lcStart.Substring(lnSpace + 1);
}
You can use set the layout_width
or layout_width
to 0dp
(By the orientation you want to fill remaining space).
Then use the layout_weight
to make it fill remaining space.
Variables declared inside a function are local to that function. For instance:
foo <- function() {
bar <- 1
}
foo()
bar
gives the following error: Error: object 'bar' not found
.
If you want to make bar
a global variable, you should do:
foo <- function() {
bar <<- 1
}
foo()
bar
In this case bar
is accessible from outside the function.
However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:
if (x > 10) {
y <- 0
}
else {
y <- 1
}
y
remains accessible after the if-else
statement.
As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:
Here you have a small example:
test.env <- new.env()
assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100
get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found
DateTimeFormat
, introduced in java 8:The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.
Your input format looks quite standard, except the trailing Z
. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
. The trailing 'Z'
is the interesting part. Usually there's time zone data here, like -0700
. So the pattern would be ...Z
, i.e. without apostrophes.
The output format is way more simple: "dd-MM-yyyy"
. Mind the small y
-s.
Here is the example code:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018
SimpleDateFormat
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018
<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">
Total: {{num1 + num2}}
and in js :
parseInt($scope.num1) + parseInt($scope.num2)
May be the storage folder doesn't have the app and framework folder and necessary permission. Inside framework folder it contains cache, sessions, testing and views. use following command this will works.
Use command line to go to your project root:
cd {your_project_root_directory}
Now copy past this command as it is:
cd storage && mkdir app && cd app && mkdir public && cd ../ && mkdir framework && cd framework && mkdir cache && mkdir sessions && mkdir testing && mkdir views && cd ../../ && sudo chmod -R 777 storage/
I hope this will solve your use.
I get this error all the time and consider it normal.
It happens when one side tries to read when the other side has already hung up. Thus depending on the protocol this may or may not designate a problem. If my client code specifically indicates to the server that it is going to hang up, then both client and server can hang up at the same time and this message would not happen.
The way I implement my code is for the client to just hang up without saying goodbye. The server can then catch the error and ignore it. In the context of HTTP, I believe one level of the protocol allows more then one request per connection while the other doesn't.
Thus you can see how potentially one side could keep hanging up on the other. I doubt the error you are receiving is of any piratical concern and you could simply catch it to keep it from filling up your log files.
By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:
Way1
names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end
Way2
names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end
Way1 uses the table index/key
, on your table names
each element has a key starting from 1, for example:
names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John
So you just make i
go from 1 to 3.
On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:
names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end
prints the following:
1 John
2 Joe
myKey myValue
I had this issue. Mine wasn't working because I was putting my files in the .git folder inside my project.
You can easily install 1.8 via PPA. Which can be done by:
$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-java8-installer
Then check the running version:
$ java -version
If you must do it manually there's already an answer for that on AskUbuntu here.
JSON.stringify(validation_messages,(field,value)=>{
if(!field) return value;
// ... your code
return value;
})
In this solution we use replacer which allows to deep traverse whole object and nested objects - on each level you will get all fields and values. If you need to get full path to each field look here
var validation_messages = {
"key_1": {
"your_name": "jimmy",
"your_msg": "hello world"
},
"key_2": {
"your_name": "billy",
"your_msg": "foo equals bar",
"deep": {
"color": "red",
"size": "10px"
}
}
}
JSON.stringify(validation_messages,(field,value)=>{
if(!field) return value;
console.log(`key: ${field.padEnd(11)} - value: ${value}`);
return value;
})
_x000D_
Setting the indentation in preferences isn't allways the solution. Most of the time the indentation is right except you happen to copy some code code from other sources or your collegue make something for you and has different settings. Then you want to just quickly convert the indentation from 2 to 4 or the other way round.
Two choices:
% git rev-parse --abbrev-ref --symbolic-full-name @{u}
origin/mainline
or
% git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"
origin/mainline
Basically the difference between them are performance characteristics and blocking behavior.
Taking the easiest first, ArrayBlockingQueue
is a queue of a fixed size. So if you set the size at 10, and attempt to insert an 11th element, the insert statement will block until another thread removes an element. The fairness issue is what happens if multiple threads try to insert and remove at the same time (in other words during the period when the Queue was blocked). A fairness algorithm ensures that the first thread that asks is the first thread that gets. Otherwise, a given thread may wait longer than other threads, causing unpredictable behavior (sometimes one thread will just take several seconds because other threads that started later got processed first). The trade-off is that it takes overhead to manage the fairness, slowing down the throughput.
The most important difference between LinkedBlockingQueue
and ConcurrentLinkedQueue
is that if you request an element from a LinkedBlockingQueue
and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue
will return right away with the behavior of an empty queue.
Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.
MySQL is different from most DBMSs use of +
or ||
for concatenation. It uses the CONCAT
function:
SELECT CONCAT(first_name, " ", last_name) AS Name FROM test.student
As @eggyal pointed out in comments, you can enable string concatenation with the ||
operator in MySQL by setting the PIPES_AS_CONCAT
SQL mode.
You only need []
to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.
The same thing applies at the first level in your loop. It is merely an array and []
is a new empty array - job done.
As for the second level, if Thing
is a class then new Thing()
will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.
class Something {
private things: Thing[][];
constructor() {
this.things = [];
for(var i: number = 0; i < 10; i++) {
this.things[i] = [];
for(var j: number = 0; j< 10; j++) {
this.things[i][j] = new Thing();
}
}
}
}
Casting in Java isn't magic, it's you telling the compiler that an Object of type A is actually of more specific type B, and thus gaining access to all the methods on B that you wouldn't have had otherwise. You're not performing any kind of magic or conversion when performing casting, you're essentially telling the compiler "trust me, I know what I'm doing and I can guarantee you that this Object at this line is actually an <Insert cast type here>." For example:
Object o = "str";
String str = (String)o;
The above is fine, not magic and all well. The object being stored in o is actually a string, and therefore we can cast to a string without any problems.
There's two ways this could go wrong. Firstly, if you're casting between two types in completely different inheritance hierarchies then the compiler will know you're being silly and stop you:
String o = "str";
Integer str = (Integer)o; //Compilation fails here
Secondly, if they're in the same hierarchy but still an invalid cast then a ClassCastException
will be thrown at runtime:
Number o = new Integer(5);
Double n = (Double)o; //ClassCastException thrown here
This essentially means that you've violated the compiler's trust. You've told it you can guarantee the object is of a particular type, and it's not.
Why do you need casting? Well, to start with you only need it when going from a more general type to a more specific type. For instance, Integer
inherits from Number
, so if you want to store an Integer
as a Number
then that's ok (since all Integers are Numbers.) However, if you want to go the other way round you need a cast - not all Numbers are Integers (as well as Integer we have Double
, Float
, Byte
, Long
, etc.) And even if there's just one subclass in your project or the JDK, someone could easily create another and distribute that, so you've no guarantee even if you think it's a single, obvious choice!
Regarding use for casting, you still see the need for it in some libraries. Pre Java-5 it was used heavily in collections and various other classes, since all collections worked on adding objects and then casting the result that you got back out the collection. However, with the advent of generics much of the use for casting has gone away - it has been replaced by generics which provide a much safer alternative, without the potential for ClassCastExceptions (in fact if you use generics cleanly and it compiles with no warnings, you have a guarantee that you'll never get a ClassCastException.)
You should check that fractional part of the number is 0. Use
x==Math.ceil(x)
or
x==Math.round(x)
or something like that
None of the previous answers efficiently provide the required output, which is a tuple of lists, rather than a list of tuples. For the former, you can use tuple
with map
. Here's the difference:
res1 = list(zip(*original)) # [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
res2 = tuple(map(list, zip(*original))) # (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
In addition, most of the previous solutions assume Python 2.7, where zip
returns a list rather than an iterator.
For Python 3.x, you will need to pass the result to a function such as list
or tuple
to exhaust the iterator. For memory-efficient iterators, you can omit the outer list
and tuple
calls for the respective solutions.
printf("\nmaximum of %d and %d is = %d",a,b,c);
In Rails 3
Adding Rails.env = ActiveSupport::StringInquirer.new('production')
into the application.rb and rails s
will work same as rails server -e production
module BlacklistAdmin
class Application < Rails::Application
config.encoding = "utf-8"
Rails.env = ActiveSupport::StringInquirer.new('production')
config.filter_parameters += [:password]
end
end
rem out the @ECHO OFF and call your batch file redirectin ALL output to a log file..
c:> yourbatch.bat (optional parameters) > yourlogfile.txt 2>&1
found at http://www.robvanderwoude.com/battech_debugging.php
IT WORKS!! don't forget the 2>&1...
WIZ
In 2018, you can program the "usual" style using async
and await
in Node.js.
Below is an example, that wraps request callback in a promise and then uses await
to get the resolved value.
const request = require('request');
// wrap a request in an promise
function downloadPage(url) {
return new Promise((resolve, reject) => {
request(url, (error, response, body) => {
if (error) reject(error);
if (response.statusCode != 200) {
reject('Invalid status code <' + response.statusCode + '>');
}
resolve(body);
});
});
}
// now to program the "usual" way
// all you need to do is use async functions and await
// for functions returning promises
async function myBackEndLogic() {
try {
const html = await downloadPage('https://microsoft.com')
console.log('SHOULD WORK:');
console.log(html);
// try downloading an invalid url
await downloadPage('http:// .com')
} catch (error) {
console.error('ERROR:');
console.error(error);
}
}
// run your async function
myBackEndLogic();
Even more meaningful :
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
// ...
verify(dependency, never()).someMethod();
The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never
javadoc is here.
If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:
[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];
CStr(45)
is all you need (the Convert String function)
If you have a numpy array, you can do the following:
>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()
'8535eaf1'
In addition to the correct answer by mdma, you can also use the mail command as follows:
mail [email protected] -s"Subject Here" -a"Content-Type: text/html; charset=\"us-ascii\""
you will get what you're looking for. Don't forget to put <HTML>
and </HTML>
in the email. Here's a quick script I use to email a daily report in HTML:
#!/bin/sh
(cat /path/to/tomorrow.txt mysql -h mysqlserver -u user -pPassword Database -H -e "select statement;" echo "</HTML>") | mail [email protected] -s"Tomorrow's orders as of now" -a"Content-Type: text/html; charset=\"us-ascii\""
Quoting from Books Online:
Local temporary tables are visible only in the current session; global temporary tables are visible to all sessions.
Temporary tables are automatically dropped when they go out of scope, unless explicitly dropped using DROP TABLE:
Tip: You can also use this method to track certificates that are due to expire soon. This can save your bacon if you discover a cert that is about to expire and can get it fixed in time. Good also for third party companies - for us this is DHL / FedEx. DHL just let a cert expire which is screwing us up 3 days before Thanksgiving. Fortunately I'm around to fix it ... this time!
private static DateTime? _nextCertWarning;
private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
if (error == SslPolicyErrors.None)
{
var cert2 = cert as X509Certificate2;
if (cert2 != null)
{
// If cert expires within 2 days send an alert every 2 hours
if (cert2.NotAfter.AddDays(-2) < DateTime.Now)
{
if (_nextCertWarning == null || _nextCertWarning < DateTime.Now)
{
_nextCertWarning = DateTime.Now.AddHours(2);
ProwlUtil.StepReached("CERT EXPIRING WITHIN 2 DAYS " + cert, cert.GetCertHashString()); // this is my own function
}
}
}
return true;
}
else
{
switch (cert.GetCertHashString())
{
// Machine certs - SELF SIGNED
case "066CF9CAD814DE2097D367F22D3A7E398B87C4D6":
return true;
default:
ProwlUtil.StepReached("UNTRUSTED CERT " + cert, cert.GetCertHashString());
return false;
}
}
}
Check that Apache has execute rights for /root
, /root/site
and /root/site/about
.
Run:
chmod o+x /root /root/site /root/site/about
When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:
- Conceptualize the specific problem as a set of smaller sub-problems.
- Solve each smaller problem.
- Combine the results into a solution of the specific problem.
But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:
- Conceptualize the specific problem as a special case of a more general problem.
- Somehow solve the general problem.
- Adapt the solution of the general problem to the specific problem.
- Eric Lippert
I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.
I've outlined some of the major aspects of the problem
Issue: We need to load data only for the desired language
Solution: For this purpose we save data to a separate files for each language
ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)
Issue: Resource files for each page should be separated so we only get the data we need
Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload
Issue: We need a key/value pair structure to save our data
Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE
Issue: General members should be stored in a public file and all pages should access them
Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'
Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope
Solution: I considered a file for each
Application Structure
root/ Global_Resources/ default.js default.fr.js UserManagementSystem/ Local_Resources/ default.js default.fr.js createUser.js Login.htm CreateUser.htm
The corresponding code for the files:
Global_Resources/default.js
var res = {
Create : "Create",
Update : "Save Changes",
Delete : "Delete"
};
Global_Resources/default.fr.js
var res = {
Create : "créer",
Update : "Enregistrer les modifications",
Delete : "effacer"
};
The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.
UserManagementSystem/Local_Resources/default.js
res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";
UserManagementSystem/Local_Resources/default.fr.js
res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";
UserManagementSystem/Local_Resources/createUser.js
// Override res.Create on Global_Resources/default.js
res.Create = "Create User";
UserManagementSystem/Local_Resources/createUser.fr.js
// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";
manager.js file (this file should be load last)
res.lang = "fr";
var globalResourcePath = "Global_Resources";
var resourceFiles = [];
var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;
if(!IsFileExist(currentFile))
currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");
resourceFiles.push(currentFile);
// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";
if(!IsExist(currentFile))
currentFile = folder + "\\Local_Resource\\default.js";
if(!IsExist(currentFile)) throw new Exception("File Not Found");
resourceFiles.push(currentFile);
}
for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }
// Get current page name
var pageNameWithoutExtension = "SomePage";
currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;
if(!IsExist(currentFile))
currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");
Hope it helps :)
Your best bet is probably to use pygame/SDL. It's an external library, but it has great support across platforms.
pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()
You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation
Probably way too late but this is another option:
$('body').popover({
selector: '[rel=popover]',
trigger: 'hover',
html: true,
content: function () {
return $(this).parents('.row').first().find('.metaContainer').html();
}
});
Just use indexer
var valueAtIndex1 = myValues[1];
This is the simplest way, I think:
var listOfStrings = (new [] { "4", "5", "6" }).ToList();
var listOfInts = listOfStrings.Select<string, int>(q => Convert.ToInt32(q));
You can use JavaScript's encodeURIComponent
:
encodeURIComponent('select * from table where i()')
giving
'select%20*%20from%20table%20where%20i()'
You can try this :
unzip -v /your/jar.jar
This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class
As stated by alfo888_ibg:
@Override
public void onClick(View arg0) {
Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}
Just do:
Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();
this worked for me.
Assuming you have referenced and correctly integrated your font to your site (presumably using an @font-face kit) it should be alright to just reference yours the way you do. Presumably it is like this so they have fall backs incase some browsers do not render the fonts correctly
You should be able to do it using the X-UA meta tag:
<meta http-equiv="X-UA-Compatible" content="IE=9" />
However, if you find yourself having to do this, you're probably doing something wrong and should take a look at what you're doing and see if you can do it a different/better way.
Here's a cleaner way using the PackageManager
final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, "Installed package :" + packageInfo.packageName);
Log.d(TAG, "Source dir : " + packageInfo.sourceDir);
Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));
}
// the getLaunchIntentForPackage returns an intent that you can use with startActivity()
More info here http://qtcstation.com/2011/02/how-to-launch-another-app-from-your-app/
git checkout -f your_branch_name
if you have troubles reverting changes:
git checkout .
if you want to remove untracked directories and files:
git clean -fd
->List all the packages by :
adb shell su 0 pm list packages -f
->Search for your package name by holding keys "ctrl+alt+f".
->Once found, look for the location associated with it.
>>> a={ 'a': 1, 'b': 2, 'c': 3 } >>> [(x,a[x]) for x in a.keys() ] [('a', 1), ('c', 3), ('b', 2)] >>> [(a[x],x) for x in a.keys() ] [(1, 'a'), (3, 'c'), (2, 'b')]
Yeah Regex is cool, but there are other alternative.
This allows you to edit multiple lines at once. Now you can add *Quotes (") or anything * at start and end of each lines.
try converting the date first.
$date = "2012-08-06";
mysql_query("INSERT INTO data_table (title, date_of_event)
VALUES('" . $_POST['post_title'] . "',
'" . $date . "')")
or die(mysql_error());
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
This behaviour is terminal-specific and specified by the terminal emulator you use (e.g. xterm
) and the semantics of terminal that it provides. The terminal behaviour has been very stable for the last 20 years, and you can reasonably rely on the semantics of \b
.
Elaborating on yasaluyari
's answer I would stick with something like this:
We can just modify our mysql_query as follows:
function mysql_catchquery($query,$emsg='Error submitting the query'){
if ($result=mysql_query($query)) return $result;
else throw new Exception($emsg);
}
Now we can simply use it like this, some good example:
try {
mysql_catchquery('CREATE TEMPORARY TABLE a (ID int(6))');
mysql_catchquery('insert into a values(666),(418),(93)');
mysql_catchquery('insert into b(ID, name) select a.ID, c.name from a join c on a.ID=c.ID');
$result=mysql_catchquery('select * from d where ID=7777777');
while ($tmp=mysql_fetch_assoc($result)) { ... }
} catch (Exception $e) {
echo $e->getMessage();
}
Note how beautiful it is. Whenever any of the qq fails we gtfo with our errors. And you can also note that we don't need now to store the state of the writing queries into a $result
variable for verification, because our function now handles it by itself. And the same way it handles the selects, it just assigns the result to a variable as does the normal function, yet handles the errors within itself.
Also note, we don't need to show the actual errors since they bear huge security risk, especially so with this outdated extension. That is why our default will be just fine most of the time. Yet, if we do want to notify the user for some particular query error, we can always pass the second parameter to display our custom error message.
One difference is for r+
if the files does not exist, it'll not be created and open fails. But in case of a+
the file will be created if it does not exist.
Use the following
SELECT timestamp, value, card
FROM my_table
ORDER BY timestamp DESC
LIMIT 1
C# is a programming language, .NET is a blanket term that tends to cover both the .NET Framework (an application framework library) and the Common Language Runtime which is the runtime in which .NET assemblies are run.
Microsoft's implementation of C# is heavily integrated with the .NET Framework so it is understandable that the two concepts would be confused. However it is important to understand that they are two very different things.
Here is a class written in C#:
class Example { }
Here is a class written in C# that explicitly uses a .NET framework assembly, type, and method:
class Example
{
static void Main()
{
// Here we call into the .NET framework to
// write to the output console
System.Console.Write("hello, world");
}
}
As I mentioned before, it is very difficult to use Microsoft's implementation of C# without using the .NET framework as well. My first Example
implementation above even uses the .NET framework (implicitly, yes, but it does use it nonetheless) because Example
inherits from System.Object
.
Also, the reason I use the phrase Microsoft's implementation of C# is because there are other implementations of C# available.
I've done something like this:
class Cow extends React.Component {
constructor (props) {
super(props);
this.state = {text: 'hello'};
}
componentDidMount () {
if (this.props.onMounted) {
this.props.onMounted({
say: text => this.say(text)
});
}
}
render () {
return (
<pre>
___________________
< {this.state.text} >
-------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
</pre>
);
}
say (text) {
this.setState({text: text});
}
}
And then somewhere else:
class Pasture extends React.Component {
render () {
return (
<div>
<Cow onMounted={callbacks => this.cowMounted(callbacks)} />
<button onClick={() => this.changeCow()} />
</div>
);
}
cowMounted (callbacks) {
this.cowCallbacks = callbacks;
}
changeCow () {
this.cowCallbacks.say('moo');
}
}
I haven't tested this exact code, but this is along the lines of what I did in a project of mine and it works nicely :). Of course this is a bad example, you should just use props for this, but in my case the sub-component did an API call which I wanted to keep inside that component. In such a case this is a nice solution.
If I'm understanding you correctly, you should be able to do this in one query, joining table1 and table2 together:
INSERT INTO table3 { name, age, sex, city, id, number}
SELECT p.name, p.age, p.sex, p.city, p.id, c.number
FROM table1 p
INNER JOIN table2 c ON c.Id = p.Id
My machine configurations :
Operating System : Windows 10 Version 1703 (x64)
I faced this error while debugging my C# .Net project in Visual Studio 2017 Community edition. I was calling a native method by performing p/invoke on a C++ assembly loaded at run-time. I encountered the very same error reported by OP.
I realized that Visual Studio was launched with a user account which was not an administrator on the machine. Then I relaunched Visual Studio under a different user account which was an administrator on the machine. That's all. My problem got resolved and I didn't face the issue again.
One thing to note is that the method which was being invoked on C++ assembly was supposed to write few things in registry. I didn't go debugging the C++ code to do some RCA but I see a possibility that the whole thing was failing as administrative privileges are required to write registry in Windows 10 operating system. So earlier when Visual Studio was running under a user account which didn't have administrative privileges on the machine, then the native calls were failing.
For Java, from a command line:
java -version
will indicate whether it's 64-bit or not.
Output from the console on my Ubuntu box:
java version "1.6.0_12-ea"
Java(TM) SE Runtime Environment (build 1.6.0_12-ea-b03)
Java HotSpot(TM) 64-Bit Server VM (build 11.2-b01, mixed mode)
IE will indicate 64-bit versions in the About dialog, I believe.
Use WSDL.EXE utility to generate a Web Service proxy from WSDL.
You'll get a long C# source file that contains a class that looks like this:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="MyService", Namespace="http://myservice.com/myservice")]
public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
...
}
In your client-side, Web-service-consuming code:
I would suggest adding class no-js
to your html to nest your CSS selectors under it like:
.loading {
display: none;
}
.no-js .loading {
display: block;
//....
}
and when you finish loading your credit code remove it:
$('html').removeClass('no-js');
This will hide your loading spinner as there's no no-js
class in html it means you already loaded your credit code
Taking Darin's answer but jQuery style. (I know the user asked for javascript).
$(document).ready ( function(){
alert('ok');
});?
I was having a problem running sudo pip install cryptography
because it would not find ffi when trying to compile. (OSX - Yosemite)
I solved it by downloading libffi and setting up the env var.
$ brew install pkg-config libffi
$ export PKG_CONFIG_PATH=/usr/local/Cellar/libffi/3.0.13/lib/pkgconfig/
$ pip install cryptography
Maybe I'm misunderstanding, but if you want truly readonly Ids why not use an actual readonly field?
public class Person
{
public Person(int id)
{
m_id = id;
}
readonly int m_id;
public int Id { get { return m_id; } }
}
Use ::ng-deep with caution. I used it throughout my app to set the material design toolbar color to different colors throughout my app only to find that when the app was in testing the toolbar colors step on each other. Come to find out it is because these styles becomes global, see this article Here is a working code solution that doesn't bleed into other components.
<mat-toolbar #subbar>
...
</mat-toolbar>
export class BypartSubBarComponent implements AfterViewInit {
@ViewChild('subbar', { static: false }) subbar: MatToolbar;
constructor(
private renderer: Renderer2) { }
ngAfterViewInit() {
this.renderer.setStyle(
this.subbar._elementRef.nativeElement, 'backgroundColor', 'red');
}
}
On Mac OS X (MBP), the following (taken from another answer found herein) resolved my issues:
C02L257NDV33:~ jjohnson$ brew install pip
Error: No available formula for pip
Homebrew provides pip via: `brew install python`. However you will then
have two Pythons installed on your Mac, so alternatively you can:
sudo easy_install pip
C02L257NDV33:~ jjohnson$ sudo easy_install pip
Clearly the root cause here is having a secondary method by which to install python (in my case Homebrew). Hopefully, the people responsible for the pip script can remedy this issue since its still relevant 2 years after first being reported on Stack Overflow.
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
must declare a body because it is not marked abstract, extern, or partialI had the same problem here:
private static void swapMth(ref int x, ref int y);
{
int num = x;
x = y;
y = num;
}
private void button_Click(object sender, EventArgs e)
{
int x = 10;
int y = 20;
labelResult.Text = $"Befor n1 = {x} , n2={y} ";
swapMth(ref x, ref y);
labelResult.Text += $"\n After n1 = {x} , n2={y}";
}
And it was solved by deleting ";" from the method line:
private static void swapMth(ref int x, ref int y); PROBLEM
to
private static void swapMth(ref int x, ref int y) SOLVED
I know it is basic mistake, hope someone could get help by this note.
private static void swapMth(ref int x, ref int y)
{
int num = x;
x = y;
y = num;
}
private void button_Click(object sender, EventArgs e)
{
int x = 10;
int y = 20;
labelResult.Text = $"Befor n1 = {x} , n2={y} ";
swapMth(ref x, ref y);
labelResult.Text += $"\n After n1 = {x} , n2={y}";
}
Annoying error. I solved it by plugging the cable directly into the iPad. For some reason the process would never finish if I had the iPad in Apple's pass-through stand.
This is NON-BLOCKING, reads a key and and stores it in keypress.key.
import Tkinter as tk
class Keypress:
def __init__(self):
self.root = tk.Tk()
self.root.geometry('300x200')
self.root.bind('<KeyPress>', self.onKeyPress)
def onKeyPress(self, event):
self.key = event.char
def __eq__(self, other):
return self.key == other
def __str__(self):
return self.key
in your programm
keypress = Keypress()
while something:
do something
if keypress == 'c':
break
elif keypress == 'i':
print('info')
else:
print("i dont understand %s" % keypress)
It's been the third time that I install Windows and npp and after some time I realize the tidy function no longer work. So I google for a solution, come to this thread, then with the help of few more so threads I finally fix it. I'll put a summary of all my actions once and for all.
Install TextFX plugin: Plugins -> Plugin Manager -> Show Plugin Manager. Select TextFX Characters and install. After a restart of npp, the menu 'TextFX' should be visible. (credits: @remipod).
Install libtidy.dll by pasting the Config folder from an old npp package: Follow instructions in this answer.
After having a Config folder in your latest npp installation destination (typically C:\Program Files (x86)\Notepad++\plugins), npp needs write access to that folder. Right click Config folder -> Properties -> Security tab -> select Users, click Edit -> check Full control to allow read/write access. Note that you need administrator privileges to do that.
Restart npp and verify TextFX -> TextFX HTML Tidy -> Tidy: Reindent XML works.
Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:
def rps():
# Code to determine if player wins
if player_wins:
return True
return False
Then, just assign a value to the variable outside this function like so:
player_wins = rps()
It will be assigned the return value (either True or False) of the function you just called.
After the comments, I decided to add that idiomatically, this would be better expressed thus:
def rps():
# Code to determine if player wins, assigning a boolean value (True or False)
# to the variable player_wins.
return player_wins
pw = rps()
This assigns the boolean value of player_wins
(inside the function) to the pw
variable outside the function.
A common reason for this type of error is that you might have changed the name of your IBOutlet or IBAction you can simply check this by going to source code.
Click on the main.storyboard and then select open as and then select source code
source code will open
and then check whether there is the name of the iboutlet or ibaction that you have changed , if there is then select the part and delete it and then again create iboutlet or ibaction. This should resolve your problem
Try the Arrays.deepToString method.
Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings
The best answer I have ever seen is How to run 32-bit applications on Ubuntu 64-bit?
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386
sudo ./adb
You need selector like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- State when a row is being pressed, but hasn't yet been activated (finger down) -->
<item android:drawable="@color/app_primary_color_light" android:state_pressed="true" />
<!-- Used when the view is "activated". -->
<item android:drawable="@color/app_primary_color" android:state_activated="true" />
<!-- Default, "just hangin' out" state. -->
<item android:drawable="@android:color/transparent" /></selector>
And then set android:choiceMode="singleChoice"
to your ListView.
To truly force maven to only use your local repo, you can run with mvn <goals> -o
. The -o
tells maven to let you work "offline", and it will stay off the network.
sample fiddle: http://jsfiddle.net/z68VD/
html:
<form id="uguu" action="http://google.ca">
<input type="submit" value="text 1" />
</form>
jquery:
$("#uguu").submit(function() {
if ($("input[type='submit']").val() == "text 1") {
alert("Please confirm if everything is correct");
$("input[type='submit']").val("text 2");
return false;
}
});
Use jquery cookie https://github.com/carhartl/jquery-cookie and then you can be sure the class will stay on page refresh.
Stores the id of the clicked element in the cookie and then uses that to add the class on refresh.
//Get cookie value and set active
var tab = $.cookie('active');
$('#' + tab).addClass('active');
//Set cookie active tab value on click
//Done this way to preserve after page refresh
$('.topTab').click(function (event) {
var clickedTab = event.target.id;
$.removeCookie('active', { path: '/' });
$( '.active' ).removeClass( 'active' );
$.cookie('active', clickedTab, { path: '/' });
});
Hi! In order to use percentage(%), you must define the % of it parent element. If you use body{height: 100%} it will not work because it parent have no percentage in height. In that case in order to work that body height you must add this in html{height:100%}
In other case to get rid of that defining parent percentage you can use
body{height:100vh}
vh stands for viewport height
I think it help
First, create a folder named “menu” in the “res” folder.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"/>
<item
android:id="@+id/add"
android:icon="@android:drawable/ic_menu_add"
android:title="Add"/>
<item
android:id="@+id/edit"
android:icon="@android:drawable/ic_menu_edit"
android:title="Edit">
<menu>
<item
android:id="@+id/share"
android:icon="@android:drawable/ic_menu_share"
android:title="Share"/>
</menu>
</item>
</menu>
Then, create your Activity Class:
public class PopupMenu1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_menu_1);
}
public void onPopupButtonClick(View button) {
PopupMenu popup = new PopupMenu(this, button);
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(PopupMenu1.this,
"Clicked popup menu item " + item.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
}
In Python3 iteritems()
is no longer supported
Use .items
for field, possible_values in fields.items():
print(field, possible_values)
I found a good alternative for requesting amazon product information here: http://api-doc.axesso.de/
Its an free rest api which return alle relevant information related to the requested product.
The ES6 way of require is import
. You can export
your class and import it somewhere else using import { ClassName } from 'path/to/ClassName'
syntax.
import fs from 'fs';
export default class Animal {
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
import Animal from 'path/to/Animal.js';
I am adding this for completeness as this post hits high in Google search results.
You can actually copy all from a regex search, just not in one step.
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.send("")
Alternatively, for greater control over the HTTP request you can use WinHttp.WinHttpRequest.5.1
in place of MSXML2.ServerXMLHTTP
.
#include <sstream>
and use the fully qualified name i.e. std::stringstream ss;
You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a private one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:
class Foo {
protected function stuff() {
// secret stuff, you want to test
}
}
class SubFoo extends Foo {
public function exposedStuff() {
return $this->stuff();
}
}
Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.
I like to write a small plugin to make things cleaner:
$.fn.setClass = function(classes) {
this.attr('class', classes);
return this;
};
That way you can simply do
$('button').setClass('btn btn-primary');
The plugin developed by @dubrox is very lightweight and works almost identical to jQuery UI. My requirement was to have the ability to restrict the number of dates selected.
Intuitively, the maxPicks
property seems to have been provided for this purpose, but it doesn't work unfortunately.
For those of you looking for this fix, here it is:
First up, you need to patch jquery.ui.multidatespicker.js
. I have submitted a pull request on github. You can use that until dubrox merges it with the master or comes up with a fix of his own.
Usage is really straightforward. The below code causes the date picker to not select any dates once the specified number of dates (maxPicks
) has been already selected. If you unselect any previously selected date, it will let you select again until you reach the limit once again.
$("#mydatefield").multiDatesPicker({maxPicks: 3});
If you are running IIS 8 with windows server 2012 you need to do the following:
from then on your application should start running
extension UIViewController {
func removeFromNavigationController() { navigationController?.removeController(.last) { self == $0 } }
}
extension UINavigationController {
enum ViewControllerPosition { case first, last }
enum ViewControllersGroupPosition { case first, last, all }
func removeController(_ position: ViewControllerPosition, animated: Bool = true,
where closure: (UIViewController) -> Bool) {
var index: Int?
switch position {
case .first: index = viewControllers.firstIndex(where: closure)
case .last: index = viewControllers.lastIndex(where: closure)
}
if let index = index { removeControllers(animated: animated, in: Range(index...index)) }
}
func removeControllers(_ position: ViewControllersGroupPosition, animated: Bool = true,
where closure: (UIViewController) -> Bool) {
var range: Range<Int>?
switch position {
case .first: range = viewControllers.firstRange(where: closure)
case .last:
guard let _range = viewControllers.reversed().firstRange(where: closure) else { return }
let count = viewControllers.count - 1
range = .init(uncheckedBounds: (lower: count - _range.min()!, upper: count - _range.max()!))
case .all:
let viewControllers = self.viewControllers.filter { !closure($0) }
setViewControllers(viewControllers, animated: animated)
return
}
if let range = range { removeControllers(animated: animated, in: range) }
}
func removeControllers(animated: Bool = true, in range: Range<Int>) {
var viewControllers = self.viewControllers
viewControllers.removeSubrange(range)
setViewControllers(viewControllers, animated: animated)
}
func removeControllers(animated: Bool = true, in range: ClosedRange<Int>) {
removeControllers(animated: animated, in: Range(range))
}
}
private extension Array {
func firstRange(where closure: (Element) -> Bool) -> Range<Int>? {
guard var index = firstIndex(where: closure) else { return nil }
var indexes = [Int]()
while index < count && closure(self[index]) {
indexes.append(index)
index += 1
}
if indexes.isEmpty { return nil }
return Range<Int>(indexes.min()!...indexes.max()!)
}
}
removeFromParent()
navigationController?.removeControllers(in: 1...3)
navigationController?.removeController(.first) { $0 != self }
navigationController?.removeController(.last) { $0 != self }
navigationController?.removeControllers(.all) { $0.isKind(of: ViewController.self) }
navigationController?.removeControllers(.first) { !$0.isKind(of: ViewController.self) }
navigationController?.removeControllers(.last) { $0 != self }
Do not forget to paste here the solution code
import UIKit
class ViewController2: ViewController {}
class ViewController: UIViewController {
private var tag: Int = 0
deinit { print("____ DEINITED: \(self), tag: \(tag)" ) }
override func viewDidLoad() {
super.viewDidLoad()
print("____ INITED: \(self)")
let stackView = UIStackView()
stackView.axis = .vertical
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackView.addArrangedSubview(createButton(text: "Push ViewController() white", selector: #selector(pushWhiteViewController)))
stackView.addArrangedSubview(createButton(text: "Push ViewController() gray", selector: #selector(pushGrayViewController)))
stackView.addArrangedSubview(createButton(text: "Push ViewController2() green", selector: #selector(pushController2)))
stackView.addArrangedSubview(createButton(text: "Push & remove previous VC", selector: #selector(pushViewControllerAndRemovePrevious)))
stackView.addArrangedSubview(createButton(text: "Remove first gray VC", selector: #selector(dropFirstGrayViewController)))
stackView.addArrangedSubview(createButton(text: "Remove last gray VC", selector: #selector(dropLastGrayViewController)))
stackView.addArrangedSubview(createButton(text: "Remove all gray VCs", selector: #selector(removeAllGrayViewControllers)))
stackView.addArrangedSubview(createButton(text: "Remove all VCs exept Last", selector: #selector(removeAllViewControllersExeptLast)))
stackView.addArrangedSubview(createButton(text: "Remove all exept first and last VCs", selector: #selector(removeAllViewControllersExeptFirstAndLast)))
stackView.addArrangedSubview(createButton(text: "Remove all ViewController2()", selector: #selector(removeAllViewControllers2)))
stackView.addArrangedSubview(createButton(text: "Remove first VCs where bg != .gray", selector: #selector(dropFirstViewControllers)))
stackView.addArrangedSubview(createButton(text: "Remove last VCs where bg == .gray", selector: #selector(dropLastViewControllers)))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if title?.isEmpty ?? true { title = "First" }
}
private func createButton(text: String, selector: Selector) -> UIButton {
let button = UIButton()
button.setTitle(text, for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(self, action: selector, for: .touchUpInside)
return button
}
}
extension ViewController {
private func createViewController<VC: ViewController>(backgroundColor: UIColor = .white) -> VC {
let viewController = VC()
let counter = (navigationController?.viewControllers.count ?? -1 ) + 1
viewController.tag = counter
viewController.title = "Controller \(counter)"
viewController.view.backgroundColor = backgroundColor
return viewController
}
@objc func pushWhiteViewController() {
navigationController?.pushViewController(createViewController(), animated: true)
}
@objc func pushGrayViewController() {
navigationController?.pushViewController(createViewController(backgroundColor: .lightGray), animated: true)
}
@objc func pushController2() {
navigationController?.pushViewController(createViewController(backgroundColor: .green) as ViewController2, animated: true)
}
@objc func pushViewControllerAndRemovePrevious() {
navigationController?.pushViewController(createViewController(), animated: true)
removeFromNavigationController()
}
@objc func removeAllGrayViewControllers() {
navigationController?.removeControllers(.all) { $0.view.backgroundColor == .lightGray }
}
@objc func removeAllViewControllersExeptLast() {
navigationController?.removeControllers(.all) { $0 != self }
}
@objc func removeAllViewControllersExeptFirstAndLast() {
guard let navigationController = navigationController, navigationController.viewControllers.count > 1 else { return }
let lastIndex = navigationController.viewControllers.count - 1
navigationController.removeControllers(in: 1..<lastIndex)
}
@objc func removeAllViewControllers2() {
navigationController?.removeControllers(.all) { $0.isKind(of: ViewController2.self) }
}
@objc func dropFirstViewControllers() {
navigationController?.removeControllers(.first) { $0.view.backgroundColor != .lightGray }
}
@objc func dropLastViewControllers() {
navigationController?.removeControllers(.last) { $0.view.backgroundColor == .lightGray }
}
@objc func dropFirstGrayViewController() {
navigationController?.removeController(.first) { $0.view.backgroundColor == .lightGray }
}
@objc func dropLastGrayViewController() {
navigationController?.removeController(.last) { $0.view.backgroundColor == .lightGray }
}
}
In my situation it was matter of the permissions:
sudo chmod -R +777 <your_folder_path>
I ran into this issue myself recently and found that I wasn't getting the right pip for Python 3, on my Linux system that also has Python 2.
First you must ensure that you have installed pip for your python version:
For Python 2:
sudo apt-get install python-pip
For Python 3:
sudo apt-get install python3-pip
Then to install packages for one version of Python or the other, simply use the following for Python 2:
pip install <package>
or for Python 3:
pip3 install <package>
I hope I understood the question right, which is: how to download a file from a server when the URL is stored in a string type?
I download files and save it locally using the below code:
import requests
url = 'https://www.python.org/static/img/python-logo.png'
fileName = 'D:\Python\dwnldPythonLogo.png'
req = requests.get(url)
file = open(fileName, 'wb')
for chunk in req.iter_content(100000):
file.write(chunk)
file.close()
At least for Ubuntu (maybe also others) works this (inspired by a previous post in this thread):
printf "Installed with pip:";
pip list 2>/dev/null | gawk '{print $1;}' | while read; do pip show "${REPLY}" 2>/dev/null | grep 'Location: /usr/local/lib/python2.7/dist-packages' >/dev/null; if (( $? == 0 )); then printf " ${REPLY}"; fi; done; echo
For angular 4+ versions you can try
<input [readonly]="true" type="date" name="date" />
public class GetStudentAdapter extends
RecyclerView.Adapter<GetStudentAdapter.MyViewHolder> {
private List<GetStudentModel> getStudentList;
Context context;
RecyclerView recyclerView;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textStudentName;
RadioButton rbSelect;
public MyViewHolder(View view) {
super(view);
textStudentName = (TextView) view.findViewById(R.id.textStudentName);
rbSelect = (RadioButton) view.findViewById(R.id.rbSelect);
}
}
public GetStudentAdapter(Context context, RecyclerView recyclerView, List<GetStudentModel> getStudentList) {
this.getStudentList = getStudentList;
this.recyclerView = recyclerView;
this.context = context;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.select_student_list_item, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.textStudentName.setText(getStudentList.get(position).getName());
holder.rbSelect.setChecked(getStudentList.get(position).isSelected());
holder.rbSelect.setTag(position); // This line is important.
holder.rbSelect.setOnClickListener(onStateChangedListener(holder.rbSelect, position));
}
@Override
public int getItemCount() {
return getStudentList.size();
}
private View.OnClickListener onStateChangedListener(final RadioButton checkBox, final int position) {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkBox.isChecked()) {
for (int i = 0; i < getStudentList.size(); i++) {
getStudentList.get(i).setSelected(false);
}
getStudentList.get(position).setSelected(checkBox.isChecked());
notifyDataSetChanged();
} else {
}
}
};
}
}
I had the same issue with gcc "gnat1" and it was due to the path being wrong. Gnat1 was on version 4.6 but I was executing version 4.8.1, which I had installed. As a temporary solution, I copied gnat1 from 4.6 and pasted under the 4.8.1 folder.
The path to gcc on my computer is /usr/lib/gcc/i686-linux-gnu/
You can find the path by using the find command:
find /usr -name "gnat1"
In your case you would look for cc1plus:
find /usr -name "cc1plus"
Of course, this is a quick solution and a more solid answer would be fixing the broken path.
My terminal pops out the same message due to deleting some simulators I don't use in Xcode.
If you run react-native run-ios
with no specific parameters, react-native will run the default simulator which is iPhone 6 with iOS 10.3.1 in my case and I deleted this simulator by chance.
Here comes my error messages:
xcodebuild: error: Unable to find a destination matching the provided destination specifier:
{ id:F3A7BF54-B827-4517-A30D-8B3241C8EBF8 }
Available destinations for the "albums" scheme:
{ platform:iOS Simulator, id:CD64F26B-045A-4E27-B05A-5255924095FB, OS:10.3.1, name:iPad Pro (9.7 inch) }
{ platform:iOS Simulator, id:8FC41950-9E60-4264-B8B6-20E62FAB3BD0, OS:10.3.1, name:iPad Pro (10.5-inch) }
{ platform:iOS Simulator, id:991C8B5F-49E2-4BB7-BBB6-2F5D1776F8D2, OS:10.3.1, name:iPad Pro (12.9 inch) }
{ platform:iOS Simulator, id:B9A80D04-E43F-43E3-9CA5-21137F7C673D, OS:10.3.1, name:iPhone 7 }
{ platform:iOS Simulator, id:58F6514E-185B-4B12-9336-B8A1D4E901F8, OS:10.3.1, name:iPhone 7 Plus }
. . .
Installing build/Build/Products/Debug-iphonesimulator/myapp.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/myapp.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist
In order to get rid of these, open up your Xcode and check for available simulators (as same as terminal listed) and run react-native run-ios --simulator="your device name"
For my case, I run react-native run-ios --simulator="iPhone 7"
, the problem solved.
I was unable to find the direct download detailed in davidnr's post. You can download the ISO directly from the Microsoft Download Center here: https://download.microsoft.com/download/b/e/d/bedddfc4-55f4-4748-90a8-ffe38a40e89f/vs2015.3.com_enu.iso.
Stopping (Killing) a thread mid-way is not recommended. The API is actually deprecated.
However,you can get more details including workarounds here: How do you kill a thread in Java?
You can use this example for dynamically calling the Where NOT IN
$user = User::where('company_id', '=', 1)->select('id)->get()->toArray(); $otherCompany = User::whereNotIn('id', $user)->get();
Some "data mining" accounts for that src/main/resources
is the typical place.
Results on Google Code Search:
src/main/resources/log4j.properties
: 4877src/main/java/log4j.properties
: 215 This worked for me .
I am taking Stephen Grider's React Native on Udemy and one of the students posted this in Lecture 50. Pasted verbatim in the command line (w/o '$' of course).
$ export "ANDROID_HOME=/usr/local/opt/android-sdk" >~/.bash_profile
No. If you don't have access to the php.ini, you can't guarantee that changes would have any effect.
I doubt you need to extend your sessions time though.
It has pretty sensible timeout at the moment and there are no reasons to extend it.
The linked docs give the following example:
cursor.execute ("""
UPDATE animal SET name = %s
WHERE name = %s
""", ("snake", "turtle"))
print "Number of rows updated: %d" % cursor.rowcount
So you just need to adapt this to your own code - example:
cursor.execute ("""
INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation)
VALUES
(%s, %s, %s, %s, %s, %s)
""", (var1, var2, var3, var4, var5, var6))
(If SongLength is numeric, you may need to use %d instead of %s).
Typescript is (a superset of) javascript, so you just use JSON.parse
as you would in javascript:
let obj = JSON.parse(jsonString);
Only that in typescript you can have a type to the resulting object:
interface MyObj {
myString: string;
myNumber: number;
}
let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);
Plenty of good ideas on this thread. I have a lot of popups in my page for handling user input. What I use, is a combination of disabling the mousewheel and hiding the scrollbar:
this.disableScrollFn= function(e) {
e.preventDefault(); e.stopPropagation()
};
document.body.style.overflow = 'hidden';
$('body').on('mousewheel', this.disableScrollFn);
Advantage of this is we stop the user from scrolling in any possible way, and without having to change css position and top properties. I'm not concerened about touch events, since touch outside would close the popup.
To disable this, upon closing the popup I do the following.
document.body.style.overflow = 'auto';
$('body').off('mousewheel', this.disableScrollFn);
Note, I store a reference to my disableScrollFn on the existing object (in my case a PopupViewModel), for that gets triggered upon closing the popup to have access to disableScrollFn.
have you tried SQL> alter database open; ? after first login?
Here is a simple example taken from 'Modern C++ Design - Generic Programming and Design Patterns Applied' by Andrei Alexandrescu:
He uses a classes with template template parameters in order to implement the policy pattern:
// Library code
template <template <class> class CreationPolicy>
class WidgetManager : public CreationPolicy<Widget>
{
...
};
He explains: Typically, the host class already knows, or can easily deduce, the template argument of the policy class. In the example above, WidgetManager always manages objects of type Widget, so requiring the user to specify Widget again in the instantiation of CreationPolicy is redundant and potentially dangerous.In this case, library code can use template template parameters for specifying policies.
The effect is that the client code can use 'WidgetManager' in a more elegant way:
typedef WidgetManager<MyCreationPolicy> MyWidgetMgr;
Instead of the more cumbersome, and error prone way that a definition lacking template template arguments would have required:
typedef WidgetManager< MyCreationPolicy<Widget> > MyWidgetMgr;
You can use a library I wrote, FormPersistence.js which handles form (de)serialization by saving values to local/session storage. This approach is similar to that linked in another answer but it does not require jQuery and does not save plaintext passwords to web storage.
let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm, true)
The optional second parameter of each FormPersistence
function defines whether to use local storage (false
) or session storage (true
). In your case, session storage is likely more appropriate.
The form data by default will be cleared from storage upon submission, unless you pass false
as the third parameter. If you have special value handling functions (such as inserting an element) then you can pass those as the fourth parameter. See the repository for complete documentation.
To create a new screen with the name foo
, use
screen -S foo
Then to reattach it, run
screen -r foo # or use -x, as in
screen -x foo # for "Multi display mode" (see the man page)
Here is an example of drawing a table using raphael.js. We can draw tables directly to the canvas of the browser using Raphael.js Raphael.js is a javascript library designed specifically for artists and graphic designers.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id='panel'></div>
</body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
paper = new Raphael(0,0,500,500);// width:500px, height:500px
var x = 100;
var y = 50;
var height = 50
var width = 100;
WriteTableRow(x,y,width*2,height,paper,"TOP Title");// draw a table header as merged cell
y= y+height;
WriteTableRow(x,y,width,height,paper,"Score,Player");// draw table header as individual cells
y= y+height;
for (i=1;i<=4;i++)
{
var k;
k = Math.floor(Math.random() * (10 + 1 - 5) + 5);//prepare table contents as random data
WriteTableRow(x,y,width,height,paper,i+","+ k + "");// draw a row
y= y+height;
}
function WriteTableRow(x,y,width,height,paper,TDdata)
{ // width:cell width, height:cell height, paper: canvas, TDdata: texts for a row. Separated each cell content with a comma.
var TD = TDdata.split(",");
for (j=0;j<TD.length;j++)
{
var rect = paper.rect(x,y,width,height).attr({"fill":"white","stroke":"red"});// draw outline
paper.text(x+width/2, y+height/2, TD[j]) ;// draw cell text
x = x + width;
}
}
</script>
</html>
Please check the preview image: https://i.stack.imgur.com/RAFhH.png
If you ever upgrade to XPath 2.0, note that it provides function index-of, it solves problem this way:
index-of(//b, //b[.='tsr'])
Where:
Crawlers (or bots) are designed to crawl HTML content of web pages but due to AJAX operations for asynchronous data fetching, this became a problem as it takes sometime to render page and show dynamic content on it. Similarly, AngularJS
also use asynchronous model, which creates problem for Google crawlers.
Some developers create basic html pages with real data and serve these pages from server side at the time of crawling. We can render same pages with PhantomJS
on serve side which has _escaped_fragment_
(Because Google looks for #!
in our site urls and then takes everything after the #!
and adds it in _escaped_fragment_
query parameter). For more detail please read this blog .
Type punning via pointer casts (as opposed to using a union) is a major example of breaking strict aliasing.
Your code could look more like:
<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if(isset($_POST["sub"])) {
$validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
if(!$validUser) $errorMsg = "Invalid username or password.";
else $_SESSION["login"] = true;
}
if($validUser) {
header("Location: /login-success.php"); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Login</title>
</head>
<body>
<form name="input" action="" method="post">
<label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" />
<label for="password">Password:</label><input type="password" value="" id="password" name="password" />
<div class="error"><?= $errorMsg ?></div>
<input type="submit" value="Home" name="sub" />
</form>
</body>
</html>
Now, when the page is redirected based on the header('LOCATION:wherever.php)
, put session_start()
at the top of the page and test to make sure $_SESSION['login'] === true
. Remember that ==
would be true if $_SESSION['login'] == 1
as well.
Of course, this is a bad idea for security reasons, but my example may teach you a different way of using PHP.
According the android.com, you only need to set it in the AndroidManifest.xml file:
http://developer.android.com/guide/topics/ui/themes.html#ApplyATheme
Adding the theme attribute to your application element worked for me:
--AndroidManifest.xml--
...
<application ...
android:theme="@android:style/Theme.Holo"/>
...
</application>
It is quite easy. Assuming you have a field(dateposted) with the type "timestamp" in your database table already queried and you want to display it, have it formated and also have the AM/PM, all you need do is shown below.
<?php
echo date("F j, Y h:m:s A" ,strtotime($row_rshearing['dateposted']));
?>
Note: Your OUTPUT should look some what like this depending on the date posted
May 21, 2014 03:05:27 PM
you can use arraylist object from collections class
using System.Collections;
static void Main()
{
ArrayList arr = new ArrayList();
}
when you want to add elements you can use
arr.Add();
They don't really have any formal meaning. A folder is a folder to SVN. They are a generally accepted way to organize your project.
The trunk is where you keep your main line of developmemt. The branch folder is where you might create, well, branches, which are hard to explain in a short post.
A branch is a copy of a subset of your project that you work on separately from the trunk. Maybe it's for experiments that might not go anywhere, or maybe it's for the next release, which you will later merge back into the trunk when it becomes stable.
And the tags folder is for creating tagged copies of your repository, usually at release checkpoints.
But like I said, to SVN, a folder is a folder. branch
, trunk
and tag are just a convention.
I'm using the word 'copy' liberally. SVN doesn't actually make full copies of things in the repository.
After adding new item to persons
add:
myGrid.DataSource = null;
myGrid.DataSource = persons;
The Immediate window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging.
To display Immediate Window, choose Debug >Windows >Immediate or press Ctrl-Alt-I
Here is an example with Immediate Window:
int Sum(int x, int y) { return (x + y);}
void main(){
int a, b, c;
a = 5;
b = 7;
c = Sum(a, b);
char temp = getchar();}
add breakpoint
call commands
It looks like you are trying to parse each line. You've been shown by another answer how to use getline
in a loop to seperate each line. The other tool you are going to want is istringstream
, to seperate each token.
std::string line;
while(std::getline(file, line))
{
std::istringstream iss(line);
std::string token;
while (iss >> token)
{
// do something with token
}
}
For inner joins I have not really noticed a difference (but as with all performance tuning, you need to check against your database under your conditions).
However where you put the condition makes a huge difference if you are using left or right joins. For instance consider these two queries:
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderDate >'20090515'
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
AND ORD.OrderDate >'20090515'
The first will give you only those records that have an order dated later than May 15, 2009 thus converting the left join to an inner join.
The second will give those records plus any customers with no orders. The results set is very different depending on where you put the condition. (Select * is for example purposes only, of course you should not use this in production code.)
The exception to this is when you want to see only the records in one table but not the other. Then you use the where clause for the condition not the join.
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderID is null
For Firefox you can apply the CSS declaration "-moz-user-select" to "none". Check out their documentation, user-select.
It's a "preview" of the future "user-select" as they say, so maybe Opera or WebKit-based browsers will support that. I also recall finding something for Internet Explorer, but I don't remember what :).
Anyway, unless it's a specific situation where text-selecting makes some dynamic functionality fail, you shouldn't really override what users are expecting from a webpage, and that is being able to select any text they want.
Try this:
DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");
zzz
is the timezone offset.
to make anything a string in swift except maybe enum values simply do what you do in the println() method
for example:
var stringOfDBL = "\(myDouble)"
It looks like what you want to do is remove your first merge. You could follow the following procedure:
git checkout master # Let's make sure we are on master branch
git reset --hard master~ # Let's get back to master before the merge
git pull # or git merge remote/master
git merge topic
That would give you what you want.
$(document).ready(function(){
$("#form_id").submit(function(){
return condition;
});
});
This one automatically excludes the trailing comma, unlike most of the other answers.
DECLARE @csv VARCHAR(1000)
SELECT @csv = COALESCE(@csv + ',', '') + ModuleValue
FROM Table_X
WHERE ModuleID = @ModuleID
(If the ModuleValue
column isn't already a string type then you might need to cast it to a VARCHAR
.)
A language itself is neither compiled nor interpreted, only a specific implementation of a language is. Java is a perfect example. There is a bytecode-based platform (the JVM), a native compiler (gcj) and an interpeter for a superset of Java (bsh). So what is Java now? Bytecode-compiled, native-compiled or interpreted?
Other languages, which are compiled as well as interpreted, are Scala, Haskell or Ocaml. Each of these languages has an interactive interpreter, as well as a compiler to byte-code or native machine code.
So generally categorizing languages by "compiled" and "interpreted" doesn't make much sense.
it's better if you define a class with a different colour, then you switch the class
$('#checkbox').click(function(){
var chk = $(this);
$('p').toggleClass('selected', chk.attr('checked'));
})
in this way your code it's cleaner because you don't have to specify all css properties (let's say you want to add a border, a text style or other...) but you just switch a class
List<String> stringList = new ArrayList<String>(Arrays.asList(arr.split(",")));
List<Integer> intList = new ArrayList<Integer>();
for (String s : stringList)
intList.add(Integer.valueOf(s));
Frames have been deprecated because they caused trouble for url navigation and hyperlinking, because the url would just take to you the index page (with the frameset) and there was no way to specify what was in each of the frame windows. Today, webpages are often generated by server-side technologies such as PHP, ASP.NET, Ruby etc. So instead of using frames, pages can simply be generated by merging a template with content like this:
Template File
<html>
<head>
<title>{insert script variable for title}</title>
</head>
<body>
<div class="menu">
{menu items inserted here by server-side scripting}
</div>
<div class="main-content">
{main content inserted here by server-side scripting}
</div>
</body>
</html>
If you don't have full support for a server-side scripting language, you could also use server-side includes (SSI). This will allow you to do the same thing--i.e. generate a single web page from multiple source documents.
But if you really just want to have a section of your webpage be a separate "window" into which you can load other webpages that are not necessarily located on your own server, you will have to use an iframe.
You could emulate your example like this:
Frames Example
<html>
<head>
<title>Frames Test</title>
<style>
.menu {
float:left;
width:20%;
height:80%;
}
.mainContent {
float:left;
width:75%;
height:80%;
}
</style>
</head>
<body>
<iframe class="menu" src="menu.html"></iframe>
<iframe class="mainContent" src="events.html"></iframe>
</body>
</html>
There are probably better ways to achieve the layout. I've used the CSS float attribute, but you could use tables or other methods as well.
Here is the response I've done to a similar question (Online Code Editor) on programmers:
First, you can take a look to this article:
Wikipedia - Comparison of JavaScript-based source code editors.
For more, here is some tools that seem to fit with your request:
EditArea - Demo as FileEditor who is a Yii Extension - (Apache Software License, BSD, LGPL)
Here is EditArea, a free javascript editor for source code. It allow to write well formated source code with line numerotation, tab support, search & replace (with regexp) and live syntax highlighting (customizable).
CodePress - Demo of Joomla! CodePress Plugin - (LGPL) - It doesn't work in Chrome and it looks like development has ceased.
CodePress is web-based source code editor with syntax highlighting written in JavaScript that colors text in real time while it's being typed in the browser.
CodeMirror - One of the many demo - (MIT-style license + optional commercial support)
CodeMirror is a JavaScript library that can be used to create a relatively pleasant editor interface for code-like content - computer programs, HTML markup, and similar. If a mode has been written for the language you are editing, the code will be coloured, and the editor will optionally help you with indentation
Ace Ajax.org Cloud9 Editor - Demo - (Mozilla tri-license (MPL/GPL/LGPL))
Ace is a standalone code editor written in JavaScript. Our goal is to create a web based code editor that matches and extends the features, usability and performance of existing native editors such as TextMate, Vim or Eclipse. It can be easily embedded in any web page and JavaScript application. Ace is developed as the primary editor for Cloud9 IDE and the successor of the Mozilla Skywriter (Bespin) Project.
To Add a little to the above answers:
If you are wanting to commit a folder like the above
git add foldername
git commit -m "commit operation"
To add the folder you will need to be on the same level as, or above, the folder you are trying to add.
For example: App/Storage/Emails/email.php
If you are trying to add the "Storage" file but you have been working inside it on the email.php document you will not be able to add the "Storage" file unless you have 'changed directory' (cd ../) back up to the same level, or higher, as the Storage file itself
Adding to what @KyleMit said, consider using:
col-md-*
classes for the larger outer columnscol-xs-*
classes for the smaller inner columnsThis will be useful when you view the page on different screen sizes.
On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible
Try using this, this worked fine for me.
json_encode(unserialize(serialize($array)));
While what you want to accomplish may be useful, there is another option which I believe you might be overlooking that is much more simple.
You are correct, the Bootstrap tables act strangely when you have columns which are not fixed height. However, there is a bootstrap class created to combat this issue and perform responsive resets.
simply create an empty <div class="clearfix"></div>
before the start of each new row to allow the floats to reset and the columns to return to their correct positions.
here is a bootply.
UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;
you might want to use CEIL()
if A
is always a floating point value > 0
and <= 2
From what I have found, your query is mostly correct. Just change "select r" to "select r.Text" is all and that should solve the problem. This is how MSDN documented how it should work.
Ex:
var query = (from r in table1 orderby r.Text select r.Text).distinct();
raise ValueError('could not find %c in %s' % (ch,str))
I had the same issue. I just resolved this by updating the assembly via GAC.
To use gacutil on a development machine go to:
Start -> programs -> Microsoft Visual studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010)
.
I used these commands to uninstall and Reinstall respectively.
gacutil /u myDLL
gacutil /i "C:\Program Files\Custom\mydllname.dll"
Note: i have not uninstall my dll in my case i have just updated dll with current path.
try this
<html>
<head>
<script type="text/javascript">
function openWin()
{
myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.focus();
print(myWindow);
}
</script>
</head>
<body>
<input type="button" value="Open window" onclick="openWin()" />
</body>
</html>
Cygwin grep and more ;)
I just found a solution for jaxrs-ri-2.16 - simply use
String output = response.readEntity(String.class)
this delivers the content as expected.
Once you've found your jar through mvnrepository.com, hover the "download (JAR)" link, and you'll see the link to the repository which contains your jar (you can probably Right clic and "Copy link URL" to get the URL, what ever your browser is).
Then, you have to add this repository to the repositories used by your project, in your pom.xml :
<project>
...
<repositories>
<repository>
<id>my-alternate-repository</id>
<url>http://myrepo.net/repo</url>
</repository>
</repositories>
...
</project>
EDIT : now MVNrepository.com has evolved : You can find the link to the repository in the "Repositories" section :
License
Categories
HomePage
Date
Files
Repositories
FWIW regarding Apache 2.2 VirtualHosting and mod_mime tested on Debian Linux and OS X Leopard and Snow Leopard:
If you have a VirtualHost configuration you will want to add the types via the AddType Directive as follows at least at the bottom of the configuration as follows:
....
AddType font/opentype .otf
AddType font/ttf .ttf
</VirtualHost>
Tested against Chrome Unstable/Trunk and Safari WebKit Nightly which eliminates the mime octet-stream warnings for both the ttf and otf font types.
Note: .htaccess has zero effect when dealing with VirtualHosting. If you're developing for several sites you'll be using VirtualHosting development and each configuration will need these AddType additions.
Answer from official website
https://datatables.net/reference/option/columns.width
$('#example').dataTable({
"columnDefs": [
{
"width": "20%",
"targets": 0
}
]
});
Add /Q
for quiet mode and it should remove the prompt.
On Windows 10 with Vagrant 2.2.2, setting the environment variable VAGRANT_HOME
will ensure that boxes are downloaded to a subfolder of the folder specified for VAGRANT_HOME
.
In my case I set VAGRANT_HOME
to e:\vagrant_home
, and the boxes get stored under e:\vagrant_home\boxes
.
This works for me.
That's where the boxes are stored. The virtual machines are being created in the folder configured in Virtual Box. To set the VirtualBox VM storage folder, go to: VirtualBox GUI --> File --> Preferences --> General --> Default Machine Folder
.
Assuming that we know Struct is a value type and Class is a reference type.
If you don't know what a value type and a reference type are then see What's the difference between passing by reference vs. passing by value?
Based on mikeash's post:
... Let's look at some extreme, obvious examples first. Integers are obviously copyable. They should be value types. Network sockets can't be sensibly copied. They should be reference types. Points, as in x, y pairs, are copyable. They should be value types. A controller that represents a disk can't be sensibly copied. That should be a reference type.
Some types can be copied but it may not be something you want to happen all the time. This suggests that they should be reference types. For example, a button on the screen can conceptually be copied. The copy will not be quite identical to the original. A click on the copy will not activate the original. The copy will not occupy the same location on the screen. If you pass the button around or put it into a new variable you'll probably want to refer to the original button, and you'd only want to make a copy when it's explicitly requested. That means that your button type should be a reference type.
View and window controllers are a similar example. They might be copyable, conceivably, but it's almost never what you'd want to do. They should be reference types.
What about model types? You might have a User type representing a user on your system, or a Crime type representing an action taken by a User. These are pretty copyable, so they should probably be value types. However, you probably want updates to a User's Crime made in one place in your program to be visible to other parts of the program. This suggests that your Users should be managed by some sort of user controller which would be a reference type. e.g
struct User {} class UserController { var users: [User] func add(user: User) { ... } func remove(userNamed: String) { ... } func ... }
Collections are an interesting case. These include things like arrays and dictionaries, as well as strings. Are they copyable? Obviously. Is copying something you want to happen easily and often? That's less clear.
Most languages say "no" to this and make their collections reference types. This is true in Objective-C and Java and Python and JavaScript and almost every other language I can think of. (One major exception is C++ with STL collection types, but C++ is the raving lunatic of the language world which does everything strangely.)
Swift said "yes," which means that types like Array and Dictionary and String are structs rather than classes. They get copied on assignment, and on passing them as parameters. This is an entirely sensible choice as long as the copy is cheap, which Swift tries very hard to accomplish. ...
I personally don't name my classes like that. I usually name mine UserManager instead of UserController but the idea is the same
In addition don't use class when you have to override each and every instance of a function ie them not having any shared functionality.
So instead of having several subclasses of a class. Use several structs that conform to a protocol.
Another reasonable case for structs is when you want to do a delta/diff of your old and new model. With references types you can't do that out of the box. With value types the mutations are not shared.
To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
answer = 1 / 0
except Warning as e:
print('error found:', e)
You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.