You need to use the overflow option, but with the following parameters:
.nav {
max-height:300px;
overflow-y:auto;
}
Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.
If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.
Presumably you want something that adapts itself to the content rather then the the opposite.
Hope it may helpful
Create vector, push_back element, then modify it as so:
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub;
//Push back new subject created with default constructor.
sub.push_back(subject());
//Vector now has 1 element @ index 0, so modify it.
sub[0].name = "english";
//Add a new element if you want another:
sub.push_back(subject());
//Modify its name and marks.
sub[1].name = "math";
sub[1].marks = 90;
}
You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.
This:
var foo = new Foo();
and
var foo = Object.create(Foo.prototype);
are quite similar. One important difference is that new Foo
actually runs constructor code, whereas Object.create
will not execute code such as
function Foo() {
alert("This constructor does not run with Object.create");
}
Note that if you use the two-parameter version of Object.create()
then you can do much more powerful things.
For guys on Ubuntu, if you get this error:
Failed to add the host to the list of known hosts
Then simply delete the known_hosts
file, and re-run your ssh. This will regenerate the known_host
file with appropriate permissions, and add the remote host you are trying to ssh into to this file.
Another possibility would be to have a little NSNumber
subclass singleton.
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!
Two notes from experience which might be helpful:
You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.
If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.
I wanted to add a common problem that happens on installation. It is possible that the path installation length is too long. To avoid this change the standard path so that it is shorter than 250 characters.
I realized this when I installed the software and did a custom installation, on a WIN10 operation system. In the custom install, it should be possible to have Python added as PATH variable by the software
this is for ipad
@media all and (device-width: 768px) {
}
this is for ipad pro
@media all and (device-width: 1024px){
}
Check the level of collation that is mismatched (server, database,table,column,character).
If it is the server, these steps helped me once:
Run this command:
sqlservr -m -T4022 -T3659 -s"name_of_insance"
-q "name_of_collation"
Start your sql server:
net start name_of_instance
Check the collation of your server again.
Here is more info:
https://www.mssqltips.com/sqlservertip/3519/changing-sql-server-collation-after-installation/
Just in case, instead of [(ngModel)]
you can use (input)
(is fired when a user writes something in the input <textarea>
) or (blur)
(is fired when a user leaves the input <textarea>
) event,
<textarea cols="30" rows="4" (input)="str = $event.target.value"></textarea>
try with below on powershell:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
import-module [\path\]XMLHelpers.psm1
Instead of [] put the full path
Output debug info to STDERR:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/get?foo=bar',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify debug option
*/
CURLOPT_VERBOSE => true,
]);
curl_exec($curlHandler);
curl_close($curlHandler);
Output debug info to file:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/get?foo=bar',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify debug option.
*/
CURLOPT_VERBOSE => true,
/**
* Specify log file.
* Make sure that the folder is writable.
*/
CURLOPT_STDERR => fopen('./curl.log', 'w+'),
]);
curl_exec($curlHandler);
curl_close($curlHandler);
See https://github.com/andriichuk/php-curl-cookbook#debug-request
I recently blogged about this. My implementation does not use any string operations during the calculations, which makes it very fast. Conversion to any numeral system with base from 2 to 36 is supported:
/// <summary>
/// Converts the given decimal number to the numeral system with the
/// specified radix (in the range [2, 36]).
/// </summary>
/// <param name="decimalNumber">The number to convert.</param>
/// <param name="radix">The radix of the destination numeral system (in the range [2, 36]).</param>
/// <returns></returns>
public static string DecimalToArbitrarySystem(long decimalNumber, int radix)
{
const int BitsInLong = 64;
const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (radix < 2 || radix > Digits.Length)
throw new ArgumentException("The radix must be >= 2 and <= " + Digits.Length.ToString());
if (decimalNumber == 0)
return "0";
int index = BitsInLong - 1;
long currentNumber = Math.Abs(decimalNumber);
char[] charArray = new char[BitsInLong];
while (currentNumber != 0)
{
int remainder = (int)(currentNumber % radix);
charArray[index--] = Digits[remainder];
currentNumber = currentNumber / radix;
}
string result = new String(charArray, index + 1, BitsInLong - index - 1);
if (decimalNumber < 0)
{
result = "-" + result;
}
return result;
}
I've also implemented a fast inverse function in case anyone needs it too: Arbitrary to Decimal Numeral System.
What is the database version? Check out virtual columns in 11g:
Adding Columns with a Default Value http://www.oracle.com/technology/pub/articles/oracle-database-11g-top-features/11g-schemamanagement.html
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
INT
representation:mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
Private Sub Worksheet_Change(ByVal Target As Range)
'data starts on row 3 which has the formulas
'the sheet is protected - input cells not locked - formula cells locked
'this routine is triggered on change of any cell on the worksheet so first check if
' it's a cell that we're interested in - and the row doesn't already have formulas
If Target.Column = 3 And Target.Row > 3 _
And Range("M" & Target.Row).Formula = "" Then
On Error GoTo ERROR_OCCURRED
'unprotect the sheet - otherwise can't copy and paste
ActiveSheet.Unprotect
'disable events - this prevents this routine from triggering again when
'copy and paste below changes the cell values
Application.EnableEvents = False
'copy col D (with validation list) from row above to new row (not locked)
Range("D" & Target.Row - 1).Copy
Range("D" & Target.Row).PasteSpecial
'copy col M to P (with formulas) from row above to new row
Range("M" & Target.Row - 1 & ":P" & Target.Row - 1).Copy
Range("M" & Target.Row).PasteSpecial
'make sure if an error occurs (or not) events are re-enabled and sheet re-protected
ERROR_OCCURRED:
If Err.Number <> 0 Then
MsgBox "An error occurred. Formulas may not have been copied." & vbCrLf & vbCrLf & _
Err.Number & " - " & Err.Description
End If
're-enable events
Application.EnableEvents = True
're-protect the sheet
ActiveSheet.Protect
'put focus back on the next cell after routine was triggered
Range("D" & Target.Row).Select
End If
End Sub
Sorry, afaik, you cannot do that. To update attributes in two different tables, you will need to execute two separate statements. But they can be in a batch ( a set of SQL sent to the server in one round trip)
If you prefer a GUI, DB Browser for SQLite will do this with a few clicks.
DB Browser for SQLite is open source and free. For Linux it is available from the repository.
This one from Google Guava could check out "null and empty String" in the same time.
Strings.isNullOrEmpty("Your string.");
Add a dependency with Maven
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
with Gradle
dependencies {
compile 'com.google.guava:guava:20.0'
}
There is a point to only put commands and options in variables.
#! /bin/bash
if [ $# -ne 2 ]
then
echo "Usage: `basename $0` DIRECTORY BACKUP_DIRECTORY"
exit 1
fi
. standard_tools
directory=$1
backup_directory=$2
current_date=$(date +%Y-%m-%dT%H-%M-%S)
backup_file="${backup_directory}/${current_date}.backup"
${tar_create} "${directory}" | ${openssl} | ${split_1024} "$backup_file"
You can relocate the commands to another file you source, so you can reuse the same commands and options across many scripts. This is very handy when you have a lot of scripts and you want to control how they all use tools. So standard_tools would contain:
export tar_create="tar cv"
export openssl="openssl des3 -salt"
export split_1024="split -b 1024m -"
There definitely is... Use the spawn, expect, and send commands:
spawn test.sh
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes"
There are more examples all over Stack Overflow, see: Help with Expect within a bash script
You may need to install these commands first, depending on your system.
Swift 3:
Set button title:
//for normal state:
my_btn.setTitle("Button Title", for: .normal)
// For highlighted state:
my_btn.setTitle("Button Title2", for: .highlighted)
Try this one to disable width-scrolling just for body
the all document just is body
body{overflow-x: hidden;}
You should use isinstance
isinstance(...)
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
In Java 8 you can do this to add all elements from an Iterable
to Collection
and return it:
public static <T> Collection<T> iterableToCollection(Iterable<T> iterable) {
Collection<T> collection = new ArrayList<>();
iterable.forEach(collection::add);
return collection;
}
Inspired by @Afreys answer.
You should use GlassFish for Java EE enterprise applications. Some things to consider:
A web Server means: Handling HTTP requests (usually from browsers).
A Servlet Container (e.g. Tomcat) means: It can handle servlets & JSP.
An Application Server (e.g. GlassFish) means: *It can manage Java EE applications (usually both servlet/JSP and EJBs).
Tomcat - is run by Apache community - Open source and has two flavors:
No commercial support available (only community support)
JBoss - Run by RedHat This is a full-stack support for JavaEE and it is a certified Java EE container. This includes Tomcat as web container internally. This also has two flavors:
Glassfish - Run by Oracle This is also a full stack certified Java EE Container. This has its own web container (not Tomcat). This comes from Oracle itself, so all new specs will be tested and implemented with Glassfish first. So, always it would support the latest spec. I am not aware of its support models.
I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.
select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
select o.orderID, o.price * o.qty as subtotal
from product p inner join orderitem o on p.ProductID= o.productID
where o.orderID = @OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal
(Latest as of 2020) For version Chrome Version 83.0.4103.61 :
Select the element you want to inspect
Choose the Event Listeners tab
Make sure to check the Framework listeners to show the real javascript file instead of the jquery function.
try this
<?php
$yesterday = date(“d.m.Y”, time()-86400);
echo $yesterday;
I don't know why everyone is using 2 copies of the same list to solve this. This uses too much RAM...
Why not just hide the elements that are not found, and simply store their index in a Set
to be able to restore them later? That's much less RAM especially if your objects are quite large.
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.SampleViewHolders>{
private List<MyObject> myObjectsList; //holds the items of type MyObject
private Set<Integer> foundObjects; //holds the indices of the found items
public MyRecyclerViewAdapter(Context context, List<MyObject> myObjectsList)
{
this.myObjectsList = myObjectsList;
this.foundObjects = new HashSet<>();
//first, add all indices to the indices set
for(int i = 0; i < this.myObjectsList.size(); i++)
{
this.foundObjects.add(i);
}
}
@NonNull
@Override
public SampleViewHolders onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.my_layout_for_staggered_grid, null);
MyRecyclerViewAdapter.SampleViewHolders rcv = new MyRecyclerViewAdapter.SampleViewHolders(layoutView);
return rcv;
}
@Override
public void onBindViewHolder(@NonNull SampleViewHolders holder, int position)
{
//look for object in O(1) in the indices set
if(!foundObjects.contains(position))
{
//object not found => hide it.
holder.hideLayout();
return;
}
else
{
//object found => show it.
holder.showLayout();
}
//holder.imgImageView.setImageResource(...)
//holder.nameTextView.setText(...)
}
@Override
public int getItemCount() {
return myObjectsList.size();
}
public void findObject(String text)
{
//look for "text" in the objects list
for(int i = 0; i < myObjectsList.size(); i++)
{
//if it's empty text, we want all objects, so just add it to the set.
if(text.length() == 0)
{
foundObjects.add(i);
}
else
{
//otherwise check if it meets your search criteria and add it or remove it accordingly
if (myObjectsList.get(i).getName().toLowerCase().contains(text.toLowerCase()))
{
foundObjects.add(i);
}
else
{
foundObjects.remove(i);
}
}
}
notifyDataSetChanged();
}
public class SampleViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener
{
public ImageView imgImageView;
public TextView nameTextView;
private final CardView layout;
private final CardView.LayoutParams hiddenLayoutParams;
private final CardView.LayoutParams shownLayoutParams;
public SampleViewHolders(View itemView)
{
super(itemView);
itemView.setOnClickListener(this);
imgImageView = (ImageView) itemView.findViewById(R.id.some_image_view);
nameTextView = (TextView) itemView.findViewById(R.id.display_name_textview);
layout = itemView.findViewById(R.id.card_view); //card_view is the id of my androidx.cardview.widget.CardView in my xml layout
//prepare hidden layout params with height = 0, and visible layout params for later - see hideLayout() and showLayout()
hiddenLayoutParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
hiddenLayoutParams.height = 0;
shownLayoutParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public void onClick(View view)
{
//implement...
}
private void hideLayout() {
//hide the layout
layout.setLayoutParams(hiddenLayoutParams);
}
private void showLayout() {
//show the layout
layout.setLayoutParams(shownLayoutParams);
}
}
}
And I simply have an EditText
as my search box:
cardsSearchTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
myViewAdapter.findObject(editable.toString().toLowerCase());
}
});
Result:
How could I have figured that out for myself (other than asking this question here)? Can I somehow tell apt-get to list all packages, and grep for ssl? Or do I need to know the "lib*-dev" naming convention?
If you're linking with -lfoo
then the library is likely libfoo.so
. The library itself is probably part of the libfoo
package, and the headers are in the libfoo-dev
package as you've discovered.
Some people use the GUI "synaptic" app (sudo synaptic
) to (locate and) install packages, but I prefer to use the command line. One thing that makes it easier to find the right package from the command line is the fact that apt-get
supports bash completion.
Try typing sudo apt-get install libssl
and then hit tab to see a list of matching package names (which can help when you need to select the correct version of a package that has multiple versions or other variations available).
Bash completion is actually very useful... for example, you can also get a list of commands that apt-get
supports by typing sudo apt-get
and then hitting tab.
Yes, I am fairly sure it is. One method of working around that using the standard library would be:
int index = str.toUpperCase().indexOf("FOO");
Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):
{{ var1 + '-' + var2 + '-' + var3 }}
If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:
e.g. To concatenate our 3 vars, and get a sha512 hash:
{{ (var1 + var2 + var3) | hash('sha512') }}
Note: this works on Ansible 2.3. I haven't tested it on earlier versions.
Gigablast offers a cheap web search API: http://www.gigablast.com/searchfeed.html
In my case, I didnt have the Apple Root certificate. It can be found here:
In the manual for GNU make, they talk about this specific example when describing the value
function:
The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.
The syntax of the value function is:
$(value variable)
Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)
The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:
FOO = $PATH all: @echo $(FOO) @echo $(value FOO)
The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.
I am using the minimist
package and the node startup arguments to control the port.
node server.js --port 4000
or
node server.js -p 4000
Inside server.js, the port can be determined by
var argv = parseArgs(process.argv.slice(2))
const port = argv.port || argv.p || 3000;
console.log(`Listening on port ${port}...`)
//....listen(port);
and it defaults to 3000 if no port is passed as an argument.
You can then use listen on the port
variable.
If you are able to use the bash shell, you can consider simply running the R code from within a bash script and piping the stdout and stderr streams to a file. Here is an example using a heredoc:
File: test.sh
#!/bin/bash
# this is a bash script
echo "Hello World, this is bash"
test1=$(echo "This is a test")
echo "Here is some R code:"
Rscript --slave --no-save --no-restore - "$test1" <<EOF
## R code
cat("\nHello World, this is R\n")
args <- commandArgs(TRUE)
bash_message<-args[1]
cat("\nThis is a message from bash:\n")
cat("\n",paste0(bash_message),"\n")
EOF
# end of script
Then when you run the script with both stderr and stdout piped to a log file:
$ chmod +x test.sh
$ ./test.sh
$ ./test.sh &>test.log
$ cat test.log
Hello World, this is bash
Here is some R code:
Hello World, this is R
This is a message from bash:
This is a test
Other things to look at for this would be to try simply pipping the stdout and stderr right from the R heredoc into a log file; I haven't tried this yet but it will probably work too.
In java/groovy try:
import java.awt.Toolkit;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
...
java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension maximizedScreenSize = new Dimension((int) screenSize.getWidth(), (int) screenSize.getHeight());
driver.manage().window().setPosition(new Point(0, 0));
driver.manage().window().setSize(maximizedScreenSize);
this will open browser in fullscreen
Use the following methods
1: Method one
var count = 123;
var message = $"Rows count is: {count}";
2: Method two
var count = 123;
var message = "Rows count is:" + count;
3: Method three
var count = 123;
var message = string.Format("Rows count is:{0}", count);
4: Method four
var count = 123;
var message = @"Rows
count
is:{0}" + count;
5: Method five
var count = 123;
var message = $@"Rows
count
is: {count}";
The 'is' test will test for identity using the builtin 'id()' function which essentially returns the memory address of the object and therefore isn't overloadable.
However in the case of testing the equality of a class you probably want to be a little bit more strict about your tests and only compare the data attributes in your class:
import types
class ComparesNicely(object):
def __eq__(self, other):
for key, value in self.__dict__.iteritems():
if (isinstance(value, types.FunctionType) or
key.startswith("__")):
continue
if key not in other.__dict__:
return False
if other.__dict__[key] != value:
return False
return True
This code will only compare non function data members of your class as well as skipping anything private which is generally what you want. In the case of Plain Old Python Objects I have a base class which implements __init__, __str__, __repr__ and __eq__ so my POPO objects don't carry the burden of all that extra (and in most cases identical) logic.
<?php
include 'cdb.php';
$show=mysqli_query( $conn,"SELECT *FROM 'reg'");
while($row1= mysqli_fetch_array($show))
{
$id=$row1['id'];
$Name= $row1['name'];
$email = $row1['email'];
$username = $row1['username'];
$password= $row1['password'];
$birthm = $row1['bmonth'];
$birthd= $row1['bday'];
$birthy= $row1['byear'];
$gernder = $row1['gender'];
$phone= $row1['phone'];
$image=$row1['image'];
}
?>
<html>
<head><title>hey</head></title></head>
<body>
<form>
<table border="-2" bgcolor="pink" style="width: 12px; height: 100px;" >
<th>
id<input type="text" name="" style="width: 30px;" value= "<?php echo $row1['id']; ?>" >
</th>
<br>
<br>
<th>
name <input type="text" name="" style="width: 60px;" value= "<?php echo $row1['Name']; ?>" >
</th>
<th>
email<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['email']; ?>" >
</th>
<th>
username<input type="hidden" name="" style="width: 60px;" value= "<?php echo $username['email']; ?>" >
</th>
<th>
password<input type="hidden" name="" style="width: 60px;" value= "<?php echo $row1['password']; ?>">
</ths>
<th>
birthday month<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthm']; ?>">
</th>
<th>
birthday day<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthd']; ?>">
</th>
<th>
birthday year<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthy']; ?>" >
</th>
<th>
gender<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['gender']; ?>">
</th>
<th>
phone number<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['phone']; ?>">
</th>
<th>
<th>
image<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['image']; ?>">
</th>
<th>
<font color="pink"> <a href="update.php">update</a></font>
</th>
</table>
</body>
</form>
</body>
</html>
Anything in the public
folder is accessible at the root path (/
) so change your img tag to read:
<img src="/images/rss.jpg" alt="rss feed" />
If you wanted to use a rails tag, use this:
<%= image_tag("rss.jpg", :alt => "rss feed") %>
Unit testing
- is an approach of testing where the unit(class, method) is under control.
Test double
- is not a primary object(from OOP world). It is a realisation which is created temporary to test, check or during development. Test doubles types:
fake object
is a real implementation of interface(protocol) or an extend which is using an inheritance or other approaches which can be used to create - is
dependency. Usually it is created by developer as a simplest solution to substitute some dependency
stub object
is a bare object(0, nil and methods without logic) with extra state which is predefined(by developer) to define returned values. Usually it is created by framework
mock object
is very similar to stub object
but the extra state is changed during program execution to check if something happened(method was called).
spy object
is a real object with a "partial mocking". It means that you work with a non-double object except mocked behavior
dummy object
is object which is necessary to run a test but no one variable or method of this object is not called.
stub vs mock
There is a difference in that the stub uses state verification while the mock uses behavior verification.
In Android O and later this error happens when you set
android:screenOrientation="portrait"
in Manifest.
Remove that line and use
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
in your activity.
This will fix your issue.
JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();
The field dob
probably has a time component.
To truncate it out:
select * from person
where CAST(dob AS DATE) between '2011-01-01' and '2011-01-31'
As mentioned earlier, CASCADE will delete the record that has a foreign key and references another object that was deleted. So for example if you have a real estate website and have a Property that references a City
class City(models.Model):
# define model fields for a city
class Property(models.Model):
city = models.ForeignKey(City, on_delete = models.CASCADE)
# define model fields for a property
and now when the City is deleted from the database, all associated Properties (eg. real estate located in that city) will also be deleted from the database
Now I also want to mention the merit of other options, such as SET_NULL or SET_DEFAULT or even DO_NOTHING. Basically, from the administration perspective, you want to "delete" those records. But you don't really want them to disappear. For many reasons. Someone might have deleted it accidentally, or for auditing and monitoring. And plain reporting. So it can be a way to "disconnect" the property from a City. Again, it will depend on how your application is written.
For example, some applications have a field "deleted" which is 0 or 1. And all their searches and list views etc, anything that can appear in reports or anywhere the user can access it from the front end, exclude anything that is deleted == 1
. However, if you create a custom report or a custom query to pull down a list of records that were deleted and even more so to see when it was last modified (another field) and by whom (i.e. who deleted it and when)..that is very advantageous from the executive standpoint.
And don't forget that you can revert accidental deletions as simple as deleted = 0
for those records.
My point is, if there is a functionality, there is always a reason behind it. Not always a good reason. But a reason. And often a good one too.
I found this link helpful
$scope.loadSkillTags = function (query) {
var data = {qData: query};
return SkillService.querySkills(data).then(function(response) {
return response.data;
});
};
If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:
var data = context.MyEntities.AsNoTracking().Where(...).ToList();
As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.
The answer above didn't work for me.
I added the following code before my ajax request:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
type: 'POST',
url: '/url/',
});
The simplest solution in general form:
def get_subclasses(cls):
for subclass in cls.__subclasses__():
yield from get_subclasses(subclass)
yield subclass
And a classmethod in case you have a single class where you inherit from:
@classmethod
def get_subclasses(cls):
for subclass in cls.__subclasses__():
yield from subclass.get_subclasses()
yield subclass
setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.
CODE:
var im = document.getElementById("img");
var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;
function changeImage()
{
im.setAttribute("src", images[index]);
index++;
if(index >= images.length)
{
index=0;
}
}
setInterval(changeImage, 30000);
As Darren commented, Apache don't understand php.ini
relative paths in Windows.
To fix it, change the relative paths in your php.ini
to absolute paths.
extension_dir="C:\full\path\to\php\ext\dir"
At the answer from @squicc
if you amend
this line: $topDir = Get-ChildItem -directory "C:\test" with -force
then you will be able to see the hidden directories also. Without this, the size will be different when you run the solution from inside or outside the folder.
To check if a lateinit var
were initialised or not use a .isInitialized
on the reference to that property:
if (foo::bar.isInitialized) {
println(foo.bar)
}
This checking is only available for the properties that are accessible lexically, i.e. declared in the same type or in one of the outer types, or at top level in the same file.
According to the jQuery Plugin Authoring page (http://docs.jquery.com/Plugins/Authoring), it's best not to muddy up the jQuery and jQuery.fn namespaces. They suggest this method:
(function( $ ){
var methods = {
init : function(options) {
},
show : function( ) { },// IS
hide : function( ) { },// GOOD
update : function( content ) { }// !!!
};
$.fn.tooltip = function(methodOrOptions) {
if ( methods[methodOrOptions] ) {
return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
// Default to "init"
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tooltip' );
}
};
})( jQuery );
Basically you store your functions in an array (scoped to the wrapping function) and check for an entry if the parameter passed is a string, reverting to a default method ("init" here) if the parameter is an object (or null).
Then you can call the methods like so...
$('div').tooltip(); // calls the init method
$('div').tooltip({ // calls the init method
foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method
Javascripts "arguments" variable is an array of all the arguments passed so it works with arbitrary lengths of function parameters.
Another sneaky issue related to this is naming your columns with -
instead of _
.
Something like this will trigger an error at the moment your tables are getting created.
@Column(name="verification-token")
using System;
using System.Drawing;
public struct MyColor
{
private byte a, r, g, b;
public byte A
{
get
{
return this.a;
}
}
public byte R
{
get
{
return this.r;
}
}
public byte G
{
get
{
return this.g;
}
}
public byte B
{
get
{
return this.b;
}
}
public MyColor SetAlpha(byte value)
{
this.a = value;
return this;
}
public MyColor SetRed(byte value)
{
this.r = value;
return this;
}
public MyColor SetGreen(byte value)
{
this.g = value;
return this;
}
public MyColor SetBlue(byte value)
{
this.b = value;
return this;
}
public int ToArgb()
{
return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
}
public override string ToString ()
{
return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
}
public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
{
return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
}
public static MyColor FromArgb(byte red, byte green, byte blue)
{
return MyColor.FromArgb(255, red, green, blue);
}
public static MyColor FromArgb(byte alpha, MyColor baseColor)
{
return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
}
public static MyColor FromArgb(int argb)
{
return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
}
public static implicit operator Color(MyColor myColor)
{
return Color.FromArgb(myColor.ToArgb());
}
public static implicit operator MyColor(Color color)
{
return MyColor.FromArgb(color.ToArgb());
}
}
package tPoint;
import java.io.File;
import java.lang.reflect.Method;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class ReadClasses {
public static void main(String[] args) {
try {
Class c = Class.forName("tPoint" + ".Sample");
Object obj = c.newInstance();
Document doc =
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new File("src/datasource.xml"));
Method[] m = c.getDeclaredMethods();
for (Method e : m) {
String mName = e.getName();
if (mName.startsWith("set")) {
System.out.println(mName);
e.invoke(obj, new
String(doc.getElementsByTagName(mName).item(0).getTextContent()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Obviously '12/01/2012 13:16:32.000' doesn't match 'DD-MON-YYYY hh24:mi' format.
Update:
You need 'MM/DD/YYYY hh24:mi:ss.ff' format and to use TO_TIMESTAMP instead of TO_DATE cause dates don't hold millis in oracle.
Step 1) Remove the semi-colon, it's an object you're creating...
a(this).next().css({
left : c,
transition : 'opacity 1s ease-in-out';
});
to
a(this).next().css({
left : c,
transition : 'opacity 1s ease-in-out'
});
Step 2) Vendor-prefixes... no browsers use transition
since it's the standard and this is an experimental feature even in the latest browsers:
a(this).next().css({
left : c,
WebkitTransition : 'opacity 1s ease-in-out',
MozTransition : 'opacity 1s ease-in-out',
MsTransition : 'opacity 1s ease-in-out',
OTransition : 'opacity 1s ease-in-out',
transition : 'opacity 1s ease-in-out'
});
Here is a demo: http://jsfiddle.net/83FsJ/
Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:
$('a').on('click', function () {
var myTransition = ($.browser.webkit) ? '-webkit-transition' :
($.browser.mozilla) ? '-moz-transition' :
($.browser.msie) ? '-ms-transition' :
($.browser.opera) ? '-o-transition' : 'transition',
myCSSObj = { opacity : 1 };
myCSSObj[myTransition] = 'opacity 1s ease-in-out';
$(this).next().css(myCSSObj);
});?
Here is a demo: http://jsfiddle.net/83FsJ/1/
Also note that if you specify in your transition
declaration that the property to animate is opacity
, setting a left
property won't be animated.
You can follow these steps to modify your java class:
There is a new, open source library on GitHub that does ANPR for US and European plates. It looks pretty accurate and it should do exactly what you need (recognize the plate regions). Here is the GitHub project: https://github.com/openalpr/openalpr
Pickle is a module installed for both Python 2 and Python 3 by default. See the standard library for 3.6.4 and 2.7.
Also to prove what I am saying is correct try running this script:
import pickle
print(pickle.__doc__)
This will print out the Pickle documentation showing you all the functions (and a bit more) it provides.
Or you can start the integrated Python 3.6 Module Docs and check there.
As a rule of thumb: if you can import the module without an error being produced then it is installed
The reason for the No matching distribution found for pickle
is because libraries for included packages are not available via pip because you already have them (I found this out yesterday when I tried to install an integrated package).
If it's running without errors but it doesn't work as expected I would think that you made a mistake somewhere (perhaps quickly check the functions you are using in the docs). Python is very informative with it's errors so we generally know if something is wrong.
238! I checked it under Win7 32 bit with the following bat script:
set "fname="
for /l %%i in (1, 1, 27) do @call :setname
@echo %fname%
for /l %%i in (1, 1, 100) do @call :check
goto :EOF
:setname
set "fname=%fname%_123456789"
goto :EOF
:check
set "fname=%fname:~0,-1%"
@echo xx>%fname%
if not exist %fname% goto :eof
dir /b
pause
goto :EOF
This is the answer
(CASE
WHEN
(isnumeric(ts.TimeInSeconds) = 1)
THEN
CAST(ts.TimeInSeconds AS bigint)
ELSE
0
END) AS seconds
Using a DateTime parameter is the best way. However, if you still want to pass a DateTime as a string, then the CAST should not be necessary provided that a language agnostic format is used.
e.g.
Given a table created like :
create table t1 (id int, EndDate DATETIME)
insert t1 (id, EndDate) values (1, GETDATE())
The following should always work :
update t1 set EndDate = '20100525' where id = 1 -- YYYYMMDD is language agnostic
The following will work :
SET LANGUAGE us_english
update t1 set EndDate = '2010-05-25' where id = 1
However, this won't :
SET LANGUAGE british
update t1 set EndDate = '2010-05-25' where id = 1
This is because 'YYYY-MM-DD' is not a language agnostic format (from SQL server's point of view) .
The ISO 'YYYY-MM-DDThh:mm:ss' format is also language agnostic, and useful when you need to pass a non-zero time.
More info : http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes
I know its already answered, but theres a better solution here use this code :
for ( Field f : context.getFields() ) {
if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
//DO String To JSON
}
/// And so on...
}
This way you can access variables from class without manually typing them..
Faster and better .. Hope this helps.
Cheers. :D
First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties
. In a WAR, WEB-INF/classes
is a classpath entry, so it will work just fine.
After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:
<context:property-placeholder location="classpath:config/properties/database.properties"/>
Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties
:
<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>
There's usually not any reason to define them separately, though.
Input the following formula in C1
:
=IF(ISNA(A1),B1,A1*B1
)
Screenshots:
When #N/A:
When not #N/A:
Let us know if this helps.
To load other file(css ,js) and folder(images) , in codeigniter project
we have to follow two simple step:
1.create folder public (can give any name) in your codeigniters folder put your bootstrap files css and js folder in side public folder. https://i.stack.imgur.com/O2gr6.jpg
2.now we have to use two line of code 1.load->helper('url'); ?> 2.
go to your view file
put first line to load base URL
<?php $this->load->helper('url'); ?>
secondly in your html head tag put this
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/public/css/bootstrap.css">
now you can enjoy the bootstrap in your codeigniter
public function number_row()
{
$query = $this->db->select("count(user_details.id) as number")
->get('user_details');
if($query-> num_rows()>0)
{
return $query->row();
}
else
{
return false;
}
}
we are using like this
<label for="1">
<div class="options">
<input type="radio" name="mem" id="1" value="1" checked="checked"/>option one
</div>
</label>
<label for="2">
<div class="options">
<input type="radio" name="mem" id="2" value="1" checked="checked"/>option two
</div></label>
using
<label for="1">
tag and catching is with
id=1
hope this helps.
#include <iostream>
int main()
{
int v[100] = {5,14,2,4,6};
int n = 5;
int mic = v[0];
for(int i = 0; i != n; ++i)
{
if(v[i] < mic)
mic = v[i];
}
std:cout << mic << std::endl;;
}
Use console command:
apksigner verify --print-certs application-development-release.apk
You could find apksigner in ../sdk/build-tools/24.0.3/apksigner.bat. Only for build tools v. 24.0.3 and higher.
Also read google docs: https://developer.android.com/studio/command-line/apksigner.html
SELECT Priority, COALESCE(cnt, 0)
FROM (
SELECT 1 AS Priority
UNION ALL
SELECT 2 AS Priority
UNION ALL
SELECT 3 AS Priority
UNION ALL
SELECT 4 AS Priority
UNION ALL
SELECT 5 AS Priority
) p
LEFT JOIN
(
SELECT Priority, COUNT(*) AS cnt
FROM jobs
GROUP BY
Priority
) j
ON j.Priority = p.Priority
You can start with a blank tuple with something like t = ()
. You can add with +
, but you have to add another tuple. If you want to add a single element, make it a singleton: t = t + (element,)
. You can add a tuple of multiple elements with or without that trailing comma.
>>> t = ()
>>> t = t + (1,)
>>> t
(1,)
>>> t = t + (2,)
>>> t
(1, 2)
>>> t = t + (3, 4, 5)
>>> t
(1, 2, 3, 4, 5)
>>> t = t + (6, 7, 8,)
>>> t
(1, 2, 3, 4, 5, 6, 7, 8)
I'll add my experience. Although using the Loaded event can do the job, I think it may be more suitable to override the OnInitialized method. Loaded occurs after the window is first displayed. OnInitialized gives you chance to make any changes, for example, add controls to the window before it is rendered.
Here is the solution.
The HTML:
<table cellspacing="0" cellpadding="0">
<tr>
<td>
123
</td>
</tr>
</table>
The CSS:
table {
border-spacing:0;
border-collapse:collapse;
}
Hope this helps.
EDIT
td, th {padding:0}
Take a look at this Github issue:
https://github.com/facebook/react-native/issues/231
They are trying to require
non-JSON files, in particular JSON. There is no method of doing this right now, so you either have to use AsyncStorage as @CocoOS mentioned, or you could write a small native module to do what you need to do.
In Swift 5 it looks like this:
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor).isActive = true
In our case, in 2020 using Python3, the solution to this problem was to move the Python installation to the cloud-init
startup script which instantiated the VM.
We had been encountering this same error when we had been trying to install Python using scripts that were called by users later in the VM's life cycle, but moving the same Python installation code to the cloud-init
script eliminated this problem.
Suggested solution from Eclipse m2e documentation:
Use quick-fix on the error in pom.xml and select Permanently mark goal run in pom.xml as ignored in Eclipse build
- this will generate the required boilerplate code for you.
To instruct Eclipse to run your plugin during build - just replace the <ignore/>
tag with <execute/>
tag in the generated configuration:
<action>
<execute/>
</action>
Alternatively you can instruct Eclipse to run the plugin on incremental builds as well:
<action>
<execute>
<runOnIncremental>true</runOnIncremental>
</execute >
</action>
No, you are wrong, but the direction fits ;)
The Output-Buffering buffers the output of a script. Thats (in short) everthing after echo
or print
. The thing with the headers is, that they only can get sent, if they are not already sent. But HTTP says, that headers are the very first of the transmission. So if you output something for the first time (in a request) the headers are sent and you can not set any other headers.
I am using it on this way:
number_to_currency(amount, unit: '€', precision: 2, format: "%u %n")
Of course that the currency symbol, precision, format and so on depends on each currency.
If you want to access members of the collection by one of their properties, you might consider using a Dictionary<T>
or KeyedCollection<T>
instead. This way you don't have to search for the item you're looking for.
Otherwise, you could at least do this:
foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
if (spAssignment.Member.Name == shortName)
{
workspace.RoleAssignments.Remove(spAssignment);
break;
}
}
First, describe nodes and see if it reports anything:
$ kubectl describe nodes
Look for conditions, capacity and allocatable:
Conditions:
Type Status
---- ------
OutOfDisk False
MemoryPressure False
DiskPressure False
Ready True
Capacity:
cpu: 2
memory: 2052588Ki
pods: 110
Allocatable:
cpu: 2
memory: 1950188Ki
pods: 110
If everything is alright here, SSH into the node and observe kubelet
logs to see if it reports anything. Like certificate erros, authentication errors etc.
If kubelet
is running as a systemd service, you can use
$ journalctl -u kubelet
It maybe solve your problem, check your files access level
$ sudo chmod -R 777 /"your files location"
Go to the source folder where your project is.
->Settings.gradle
.':your new project name '
Option 1 Each div is specifically identified, so any other div (without the specific IDs) on the page will not obey the :hover pseudo-class.
<style type="text/css">
#div1, #div2, #div3{
display:none;
}
#div1:hover, #div2:hover, #div3:hover{
display:block;
}
</style>
Option 2 All divs on the page, regardless of IDs, have the hover effect.
<style type="text/css">
div{
display:none;
}
div:hover{
display:block;
}
</style>
For browsers implementing the Object.defineProperty()
method, the code below generates and returns a function that you can bind to any object you own.
This approach has the advantage of not extending Object.prototype
.
The code works by checking if the given object has a __objectID__
property, and by defining it as a hidden (non-enumerable) read-only property if not.
So it is safe against any attempt to change or redefine the read-only obj.__objectID__
property after it has been defined, and consistently throws a nice error instead of silently fail.
Finally, in the quite extreme case where some other code would already have defined __objectID__
on a given object, this value would simply be returned.
var getObjectID = (function () {
var id = 0; // Private ID counter
return function (obj) {
if(obj.hasOwnProperty("__objectID__")) {
return obj.__objectID__;
} else {
++id;
Object.defineProperty(obj, "__objectID__", {
/*
* Explicitly sets these two attribute values to false,
* although they are false by default.
*/
"configurable" : false,
"enumerable" : false,
/*
* This closure guarantees that different objects
* will not share the same id variable.
*/
"get" : (function (__objectID__) {
return function () { return __objectID__; };
})(id),
"set" : function () {
throw new Error("Sorry, but 'obj.__objectID__' is read-only!");
}
});
return obj.__objectID__;
}
};
})();
Single line works just fine:
<a href="http://example.com/"
onclick="return confirm('Please click on OK to continue.');">click me</a>
Adding another line with a different link on the same page works fine too:
<a href="http://stackoverflow.com/"
onclick="return confirm('Click on another OK to continue.');">another link</a>
Use $ne
(for "not equal")
db.collection.find({ "fieldToCheck": { $exists: true, $ne: null } })
declare this code( android:windowSoftInputMode="stateAlwaysHidden") in manifest inside your activity tag .
like this :
<activity android:name=".MainActivity"
android:windowSoftInputMode="stateAlwaysHidden">
This method restores sys.stdout even if there's an exception. It also gets any output before the exception.
import io
import sys
real_stdout = sys.stdout
fake_stdout = io.BytesIO() # or perhaps io.StringIO()
try:
sys.stdout = fake_stdout
# do what you have to do to create some output
finally:
sys.stdout = real_stdout
output_string = fake_stdout.getvalue()
fake_stdout.close()
# do what you want with the output_string
Tested in Python 2.7.10 using io.BytesIO()
Tested in Python 3.6.4 using io.StringIO()
Bob, added for a case if you feel anything from the modified / extended code experimentation might get interesting in any sense, otherwise feel free to delete it
Ad informandum ... a few remarks from extended experimentation during finding some viable mechanics to "grab" outputs, directed by
numexpr.print_versions()
directly to the<stdout>
( upon a need to clean GUI and collecting details into debugging-report )
# THIS WORKS AS HELL: as Bob Stein proposed years ago:
# py2 SURPRISEDaBIT:
#
import io
import sys
#
real_stdout = sys.stdout # PUSH <stdout> ( store to REAL_ )
fake_stdout = io.BytesIO() # .DEF FAKE_
try: # FUSED .TRY:
sys.stdout.flush() # .flush() before
sys.stdout = fake_stdout # .SET <stdout> to use FAKE_
# ----------------------------------------- # + do what you gotta do to create some output
print 123456789 # +
import numexpr # +
QuantFX.numexpr.__version__ # + [3] via fake_stdout re-assignment, as was bufferred + "late" deferred .get_value()-read into print, to finally reach -> real_stdout
QuantFX.numexpr.print_versions() # + [4] via fake_stdout re-assignment, as was bufferred + "late" deferred .get_value()-read into print, to finally reach -> real_stdout
_ = os.system( 'echo os.system() redir-ed' )# + [1] via real_stdout + "late" deferred .get_value()-read into print, to finally reach -> real_stdout, if not ( _ = )-caught from RET-d "byteswritten" / avoided from being injected int fake_stdout
_ = os.write( sys.stderr.fileno(), # + [2] via stderr + "late" deferred .get_value()-read into print, to finally reach -> real_stdout, if not ( _ = )-caught from RET-d "byteswritten" / avoided from being injected int fake_stdout
b'os.write() redir-ed' )# *OTHERWISE, if via fake_stdout, EXC <_io.BytesIO object at 0x02C0BB10> Traceback (most recent call last):
# ----------------------------------------- # ? io.UnsupportedOperation: fileno
#''' ? YET: <_io.BytesIO object at 0x02C0BB10> has a .fileno() method listed
#>>> 'fileno' in dir( sys.stdout ) -> True ? HAS IT ADVERTISED,
#>>> pass; sys.stdout.fileno -> <built-in method fileno of _io.BytesIO object at 0x02C0BB10>
#>>> pass; sys.stdout.fileno()-> Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# io.UnsupportedOperation: fileno
# ? BUT REFUSES TO USE IT
#'''
finally: # == FINALLY:
sys.stdout.flush() # .flush() before ret'd back REAL_
sys.stdout = real_stdout # .SET <stdout> to use POP'd REAL_
sys.stdout.flush() # .flush() after ret'd back REAL_
out_string = fake_stdout.getvalue() # .GET string from FAKE_
fake_stdout.close() # <FD>.close()
# +++++++++++++++++++++++++++++++++++++ # do what you want with the out_string
#
print "\n{0:}\n{1:}{0:}".format( 60 * "/\\",# "LATE" deferred print the out_string at the very end reached -> real_stdout
out_string #
)
'''
PASS'd:::::
...
os.system() redir-ed
os.write() redir-ed
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
123456789
'2.5'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version: 2.5
NumPy version: 1.10.4
Python version: 2.7.13 |Anaconda 4.0.0 (32-bit)| (default, May 11 2017, 14:07:41) [MSC v.1500 32 bit (Intel)]
AMD/Intel CPU? True
VML available? True
VML/MKL version: Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for 32-bit applications
Number of threads used by default: 4 (out of 4 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
>>>
EXC'd :::::
...
os.system() redir-ed
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
123456789
'2.5'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version: 2.5
NumPy version: 1.10.4
Python version: 2.7.13 |Anaconda 4.0.0 (32-bit)| (default, May 11 2017, 14:07:41) [MSC v.1500 32 bit (Intel)]
AMD/Intel CPU? True
VML available? True
VML/MKL version: Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for 32-bit applications
Number of threads used by default: 4 (out of 4 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
io.UnsupportedOperation: fileno
'''
In order to clear all local notifications in iOS 10 apps, you should use the following code:
import UserNotifications
...
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests() // To remove all pending notifications which are not delivered yet but scheduled.
center.removeAllDeliveredNotifications() // To remove all delivered notifications
} else {
UIApplication.shared.cancelAllLocalNotifications()
}
This code handles the clearing of local notifications for iOS 10.x and all preceding versions of iOS. You will need to import UserNotifications
for the iOS 10.x code.
Try to use the func below to add colorbar:
def add_colorbar(mappable):
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
last_axes = plt.gca()
ax = mappable.axes
fig = ax.figure
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = fig.colorbar(mappable, cax=cax)
plt.sca(last_axes)
return cbar
Then you codes need to be modified as:
fig , ( (ax1,ax2) , (ax3,ax4)) = plt.subplots(2, 2,sharex = True,sharey=True)
z1_plot = ax1.scatter(x,y,c = z1,vmin=0.0,vmax=0.4)
add_colorbar(z1_plot)
mysql> SET PASSWORD = PASSWORD('your_new_password');
That works for me.
Because lock is expensive, when you are using synchronized block you lock only if _instance == null
, and after _instance
finally initialized you'll never lock. But when you synchronize on method you lock unconditionally, even after the _instance
is initialized. This is the idea behind double-checked locking optimization pattern http://en.wikipedia.org/wiki/Double-checked_locking.
I just tried with this code, and it worked for me: <link rel="icon" type="image/jpg" href="C:\Users\nrm05\Pictures\logo.jpg" />
Be sure to type type="image/jpg"
for jpg files, and type="image/png"
for PNG files. If you haven't downloaded the image, but you know the image URL, then you can type it in like this: href="image_url"
Hope this answered your question :-)
The XLSB format is also dedicated to the macros embeded in an hidden workbook file located in excel startup folder (XLSTART).
A quick & dirty test with a xlsm or xlsb in XLSTART folder:
Measure-Command { $x = New-Object -com Excel.Application ;$x.Visible = $True ; $x.Quit() }
0,89s with a xlsb (binary) versus 1,3s with the same content in xlsm format (xml in a zip file) ... :)
It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.
Are you doing heavy DOM manipulation? I would use jQuery and Backbone.
Very data driven app? Angular with its nice data binding.
Game programming? None - direct to canvas; maybe a game engine.
For a use case like this, it may be useful to use a string constant so it can be marshaled into a JSON string. In the following example, []Base{A,C,G,T}
would get marshaled to ["adenine","cytosine","guanine","thymine"]
.
type Base string
const (
A Base = "adenine"
C = "cytosine"
G = "guanine"
T = "thymine"
)
When using iota
, the values get marshaled into integers. In the following example, []Base{A,C,G,T}
would get marshaled to [0,1,2,3]
.
type Base int
const (
A Base = iota
C
G
T
)
Here's an example comparing both approaches:
API = Dictionary of available words and their meanings (and the required grammar to combine them)
SDK = A Word processing system… for 2 year old babies… that writes right from ideas
Although you COULD go to school and become a master in your language after a few years, using the SDK will help you write whole meaningful sentences in no time (Forgiving the fact that, in this example, as a baby you haven't even gotten to learn any other language for at least to learn to use the SDK.)
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
for new router >= RC.3
Best and a simple way to do this is!
import { Router } from '@angular/router';
constructor(router: Router) {
router.events.subscribe((url:any) => console.log(url));
console.log(router.url); // to print only path eg:"/login"
}
You should check out OGX.List which has built in filtering methods and extends the standard javascript array (and also grouping, sorting and finding). Here's a list of operators it supports for the filters:
'eq' //Equal to
'eqjson' //For deep objects, JSON comparison, equal to
'neq' //Not equal to
'in' //Contains
'nin' //Doesn't contain
'lt' //Lesser than
'lte' //Lesser or equal to
'gt' //Greater than
'gte' //Greater or equal to
'btw' //Between, expects value to be array [_from_, _to_]
'substr' //Substring mode, equal to, expects value to be array [_from_, _to_, _niddle_]
'regex' //Regex match
You can use it this way
let list = new OGX.List(your_array);
list.addFilter('price', 'btw', 100, 500);
list.addFilter('sqft', 'gte', 500);
let filtered_list = list.filter();
Or even this way
let list = new OGX.List(your_array);
let filtered_list = list.get({price:{btw:[100,500]}, sqft:{gte:500}});
Or as a one liner
let filtered_list = new OGX.List(your_array).get({price:{btw:[100,500]}, sqft:{gte:500}});
Another technique I just found for solving this (even if I deleted origin first, what appears to be a mistake) is manipulating git config directly:
git config remote.origin.url url-to-my-other-remote
simple:
today="$(date '+%Y-%m-%d')"
yesterday="$(date -d yesterday '+%Y-%m-%d')"
To drop rows with indices 1, 2, 4 you can use:
df[~df.index.isin([1, 2, 4])]
The tilde operator ~
negates the result of the method isin
. Another option is to drop indices:
df.loc[df.index.drop([1, 2, 4])]
Generally speaking, the cli/php.ini
file is used when the PHP binary is called from the command-line.
You can check that running php --ini
from the command-line.
fpm/php.ini
will be used when PHP is run as FPM -- which is the case with an nginx installation.
And you can check that calling phpinfo()
from a php page served by your webserver.
cgi/php.ini
, in your situation, will most likely not be used.
Using two distinct php.ini
files (one for CLI, and the other one to serve pages from your webserver) is done quite often, and has one main advantages : it allows you to have different configuration values in each case.
Typically, in the php.ini
file that's used by the web-server, you'll specify a rather short max_execution_time
: web pages should be served fast, and if a page needs more than a few dozen seconds (30 seconds, by default), it's probably because of a bug -- and the page's generation should be stopped.
On the other hand, you can have pretty long scripts launched from your crontab (or by hand), which means the php.ini
file that will be used is the one in cli/
. For those scripts, you'll specify a much longer max_execution_time
in cli/php.ini
than you did in fpm/php.ini
.
max_execution_time
is a common example ; you could do the same with several other configuration directives, of course.
$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['ColumnName'];
}
echo $qty;
I've found that this might also happen if you rebuild a workspace with a project containing a lot of image data (such as a dedicated images project). Might be best to put something like that into its own workspace and handle it separately to the rest of the projects you deal with.
If you can't, then don't clean that project when you clean and rebuild. Only rebuild when necessary.
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
Regarding the performance of the direct operations and the method .equals()
. The .equals()
methods seems to be roughly 4 times slower than ==
.
I ran the following tests..
For the performance of ==
:
public class BooleanPerfCheck {
public static void main(String[] args) {
long frameStart;
long elapsedTime;
boolean heyderr = false;
frameStart = System.currentTimeMillis();
for (int i = 0; i < 999999999; i++) {
if (heyderr == false) {
}
}
elapsedTime = System.currentTimeMillis() - frameStart;
System.out.println(elapsedTime);
}
}
and for the performance of .equals()
:
public class BooleanPerfCheck {
public static void main(String[] args) {
long frameStart;
long elapsedTime;
Boolean heyderr = false;
frameStart = System.currentTimeMillis();
for (int i = 0; i < 999999999; i++) {
if (heyderr.equals(false)) {
}
}
elapsedTime = System.currentTimeMillis() - frameStart;
System.out.println(elapsedTime);
}
}
Total system time for ==
was 1
Total system time for .equals()
varied from 3 - 5
Thus, it is safe to say that .equals()
hinders performance and that ==
is better to use in most cases to compare Boolean
.
Beware of the use of push method, if you don't use indexes, it won't work!
var main2dArray: Things[][] = []
main2dArray.push(someTmp1dArray)
main2dArray.push(someOtherTmp1dArray)
gives only a 1 line array!
use
main2dArray[0] = someTmp1dArray
main2dArray[1] = someOtherTmp1dArray
to get your 2d array working!!!
Other beware! foreach doesn't seem to work with 2d arrays!
None of the above answers worked for me so let me share my experience. I am running nginx in a docker container that has a port mapping (hostPort:containerPort) - 80:80 The above answers are giving me strange console output. Only the good old 'nmap' is working flawlessly even catching the nginx version. The command working for me is:
nmap -sV localhost -p 80
We are doing nmap using the -ServiceVersion switch on the localhost and port: 80. It works great for me.
/*
#No parameters
returns a date with this format DD-MM-YYYY
*/
function now()
{
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = (day<10 ? '0' : '') + day + "-"
+ (month<10 ? '0' : '') + month + '-'
+ d.getFullYear();
return output;
}
You have to resolve the conflict manually (copying the file over) and then commit the file (no matter if you copied it over or used the local version) like this
git commit -a -m "Fix merge conflict in test.foo"
Git normally autocommits after merging, but when it detects conflicts it cannot solve by itself, it applies all patches it figured out and leaves the rest for you to resolve and commit manually. The Git Merge Man Page, the Git-SVN Crash Course or this blog entry might shed some light on how it's supposed to work.
Edit: See the post below, you don't actually have to copy the files yourself, but can use
git checkout --ours -- path/to/file.txt
git checkout --theirs -- path/to/file.txt
to select the version of the file you want. Copying / editing the file will only be necessary if you want a mix of both versions.
Please mark mipadis answer as the correct one.
With Postgres 9.6 this can be done using the option if not exists
ALTER TABLE table_name ADD COLUMN IF NOT EXISTS column_name INTEGER;
The ternary style is generally used to save space. Semantically, they are identical. I prefer to go with the full if/then/else syntax because I don't like to sacrifice readability - I'm old-school and I prefer my braces.
The full if/then/else format is used for pretty much everything. It's especially popular if you get into larger blocks of code in each branch, you have a muti-branched if/else tree, or multiple else/ifs in a long string.
The ternary operator is common when you're assigning a value to a variable based on a simple condition or you are making multiple decisions with very brief outcomes. The example you cite actually doesn't make sense, because the expression will evaluate to one of the two values without any extra logic.
Good ideas:
this > that ? alert(this) : alert(that); //nice and short, little loss of meaning
if(expression) //longer blocks but organized and can be grasped by humans
{
//35 lines of code here
}
else if (something_else)
{
//40 more lines here
}
else if (another_one) /etc, etc
{
...
Less good:
this > that ? testFucntion() ? thirdFunction() ? imlost() : whathappuh() : lostinsyntax() : thisisprobablybrokennow() ? //I'm lost in my own (awful) example by now.
//Not complete... or for average humans to read.
if(this != that) //Ternary would be done by now
{
x = this;
}
else
}
x = this + 2;
}
A really basic rule of thumb - can you understand the whole thing as well or better on one line? Ternary is OK. Otherwise expand it.
In Jenkins 2.60.3 there is a way to delete build artifacts (not the archived artifacts) in order to save hard drive space on the build machine. In the General section, check "Discard old builds" with strategy "Log Rotation" and then go into its Advanced options. Two more options will appear related to keeping build artifacts for the job based on number of days or builds.
The settings that work for me are to enter 1 for "Max # of builds to keep with artifacts" and then to have a post-build action to archive the artifacts. This way, all artifacts from all builds will be archived, all information from builds will be saved, but only the last build will keep its own artifacts.
A method taking into consideration
it takes such a multi-line string which may be messy e.g.
test_str = '\nhej ho \n aaa\r\n a\n '
and produces nice one-line string
>>> ' '.join([line.strip() for line in test_str.strip().splitlines()])
'hej ho aaa a'
UPDATE: To fix multiple new-line character producing redundant spaces:
' '.join([line.strip() for line in test_str.strip().splitlines() if line.strip()])
This works for the following too
test_str = '\nhej ho \n aaa\r\n\n\n\n\n a\n '
Eclipse's compiler can assure that your java sources conform to a given JDK version even if you don't have that version installed. This feature is useful for ensuring backwards compatibility of your code.
Your code will still be compiled and run by the JDK you've selected.
It depends on how and when you want to redirect the user to another page.
If you want to instantly redirect a user to another page without him seeing anything of a site in between, you should use the PHP header
redirect method.
If you have a Javascript and some action of the user has to result in him entering another page, that is when you should use window.location
.
The meta
tag refresh is often used on download sites whenever you see these "Your download should start automatically" messages. You can let the user load a page, wait for a certain amount of time, then redirect him (e.g. to a to-be-downloaded file) without Javascript.
You could go into the designer of the web form and change the "webcontrols" to be "public" instead of "protected" but I'm not sure how safe that is. I prefer to make hidden inputs and have some jQuery set the values into those hidden inputs, then create public properties in the web form's class (code behind), and access the values that way.
Create the opposite dictionary:
PIX1 = {}
for key in PIX0.keys():
PIX1[PIX0.get(key)] = key
Then run the same code on this dictionary instead (using PIX1
instead of PIX0
).
BTW, I'm not sure about Python 3, but in Python 2 you need to use raw_input
instead of input
.
Is it possible that MySql listening on the same port as JBoss?
Is there a port number given in the error message - something like Address already in use: JVM_Bind:8080
You can change the port in JBoss server.xml to test this.
var arr = ["1", "2", "3"];_x000D_
arr = arr.map(Number);_x000D_
console.log(arr); // [1, 2, 3]
_x000D_
To create an empty multidimensional array in NumPy (e.g. a 2D array m*n
to store your matrix), in case you don't know m
how many rows you will append and don't care about the computational cost Stephen Simmons mentioned (namely re-buildinging the array at each append), you can squeeze to 0 the dimension to which you want to append to: X = np.empty(shape=[0, n])
.
This way you can use for example (here m = 5
which we assume we didn't know when creating the empty matrix, and n = 2
):
import numpy as np
n = 2
X = np.empty(shape=[0, n])
for i in range(5):
for j in range(2):
X = np.append(X, [[i, j]], axis=0)
print X
which will give you:
[[ 0. 0.]
[ 0. 1.]
[ 1. 0.]
[ 1. 1.]
[ 2. 0.]
[ 2. 1.]
[ 3. 0.]
[ 3. 1.]
[ 4. 0.]
[ 4. 1.]]
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
For those stumbling upon this from MySQL or Oracle background - MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses ROWNUM.
A good seed initialisation can be done like this
Random rnd = new Random((int)DateTime.Now.Ticks);
The ticks will be unique and the cast into a int with probably a loose of value will be OK.
keyCodes are different from the ASCII values. For a complete keyCode reference, see http://unixpapa.com/js/key.html
For example, Numpad numbers have keyCodes 96 - 105, which corresponds to the beginning of lowercase alphabet in ASCII. This could lead to problems in validating numeric input.
Using quicktype, you can generate C++ serializers and deserializers from JSON sample data.
For example, given the sample JSON:
{
"breed": "Boxer",
"age": 5,
"tail_length": 6.5
}
quicktype generates:
#include "json.hpp"
namespace quicktype {
using nlohmann::json;
struct Dog {
int64_t age;
std::string breed;
double tail_length;
};
inline json get_untyped(const json &j, const char *property) {
if (j.find(property) != j.end()) {
return j.at(property).get<json>();
}
return json();
}
}
namespace nlohmann {
inline void from_json(const json& _j, struct quicktype::Dog& _x) {
_x.age = _j.at("age").get<int64_t>();
_x.breed = _j.at("breed").get<std::string>();
_x.tail_length = _j.at("tail_length").get<double>();
}
inline void to_json(json& _j, const struct quicktype::Dog& _x) {
_j = json{{"age", _x.age}, {"breed", _x.breed}, {"tail_length", _x.tail_length}};
}
}
To parse the Dog JSON data, include the code above, install Boost and json.hpp, then do:
Dog dog = nlohmann::json::parse(jsonString);
My few cents. The forward-slash in the package name (laravel*/*laravel) is matter. If you put back-slash you will get package not found stability error.
public enum MyEnum {
ONE(1),
TWO(2);
private int value;
private MyEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)
As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.
Update: For strings the only difference is that your constructor argument is String
, and you declare enums with TEST("test")
NSDate *date = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"]
NSString *dateString = [df stringFromDate:date];
[df setDateFormat:@"hh:mm:ss"];
NSString *hoursString = [df stringFromDate:date];
Thats it, you got it all you want.
To use npm run
pm2 start npm --name "{app_name}" -- run {script_name}
It sounds as though you're not in a modern document mode. Internet Explorer 11 shows the SVG just fine when you're in Standards Mode. Make sure that if you have an x-ua-compatible
meta tag, you have it set to Edge, rather than an earlier mode.
<meta http-equiv="X-UA-Compatible" content="IE=edge">
You can determine your document mode by opening up your F12 Developer Tools and checking either the document mode dropdown (seen at top-right, currently "Edge") or the emulation tab:
If you do not have an x-ua-compatible
meta tag (or header), be sure to use a doctype that will put the document into Standards mode, such as <!DOCTYPE html>
.
I had the same problem, in fact, I juste forgot to run the service after installation ..
Start mysql server :
/etc/init.d/mysql start
I had the same problem.
The proper way would be setting the 'searchText' to be a property inside an object.
But what if I want to leave it as it is, a string? well, I tried every single method mentioned here, nothing worked.
But then I noticed that the problem is only in the initiation, so I've just set the value attribute and it worked.
<input type="text" ng-model="searchText" value={{searchText}} />
This way the value is just set to '$scope.searchText' value and it's being updated when the input value changes.
I know it's a workaround, but it worked for me..
You can list down the entries (certificates details) with the keytool and even you don't need to mention the store type.
keytool -list -v -keystore cert.p12 -storepass <password>
Keystore type: PKCS12
Keystore provider: SunJSSE
Your keystore contains 1 entry
Alias name: 1
Creation date: Jul 11, 2020
Entry type: PrivateKeyEntry
Certificate chain length: 2
In jsp you can do it like this:
<%
boolean checkboxDisabled = true; //do your logic here
String checkboxState = checkboxDisabled ? "disabled" : "";
%>
<input type="checkbox" <%=checkboxState%>>
A bit simplified you can think of it as arrays being a special case and not ordinary classes (a bit like primitives, but not). String and all the collections are classes, hence the methods to get size, length or similar things.
I guess the reason at the time of the design was performance. If they created it today they had probably come up with something like array-backed collection classes instead.
If anyone is interested, here is a small snippet of code to illustrate the difference between the two in generated code, first the source:
public class LengthTest {
public static void main(String[] args) {
int[] array = {12,1,4};
String string = "Hoo";
System.out.println(array.length);
System.out.println(string.length());
}
}
Cutting a way the not so important part of the byte code, running javap -c
on the class results in the following for the two last lines:
20: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
23: aload_1
24: arraylength
25: invokevirtual #4; //Method java/io/PrintStream.println:(I)V
28: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
31: aload_2
32: invokevirtual #5; //Method java/lang/String.length:()I
35: invokevirtual #4; //Method java/io/PrintStream.println:(I)V
In the first case (20-25) the code just asks the JVM for the size of the array (in JNI this would have been a call to GetArrayLength()) whereas in the String case (28-35) it needs to do a method call to get the length.
In the mid 1990s, without good JITs and stuff, it would have killed performance totally to only have the java.util.Vector (or something similar) and not a language construct which didn't really behave like a class but was fast. They could of course have masked the property as a method call and handled it in the compiler but I think it would have been even more confusing to have a method on something that isn't a real class.
You can also look into using the Collection Object. This usually works better than an array for custom objects, since it dynamically sizes and has methods for:
Plus its normally easier to loop through a collection too since you can use the for...each structure very easily with a collection.
This page is a neat summary, but is not entirely accurate:
Use
btnTest_Click( this, new EventArgs() );
Void return types / Subroutines are old news. I haven't made a Void return type (Unless I was being extremely lazy) in like 8 years (From the time of this answer, so just a bit before this question was asked).
Instead of a method like:
public void SendEmailToCustomer()
Make a method that follows Microsoft's int.TryParse() paradigm:
public bool TrySendEmailToCustomer()
Maybe there isn't any information your method needs to return for usage in the long-run, but returning the state of the method after it performs its job is a huge use to the caller.
Also, bool isn't the only state type. There are a number of times when a previously-made Subroutine could actually return three or more different states (Good, Normal, Bad, etc). In those cases, you'd just use
public StateEnum TrySendEmailToCustomer()
However, while the Try-Paradigm somewhat answers this question on how to test a void return, there are other considerations too. For example, during/after a "TDD" cycle, you would be "Refactoring" and notice you are doing two things with your method... thus breaking the "Single Responsibility Principle." So that should be taken care of first. Second, you might have idenetified a dependency... you're touching "Persistent" Data.
If you are doing the data access stuff in the method-in-question, you need to refactor into an n-tier'd or n-layer'd architecture. But we can assume that when you say "The strings are then inserted into a database", you actually mean you're calling a business logic layer or something. Ya, we'll assume that.
When your object is instantiated, you now understand that your object has dependencies. This is when you need to decide if you are going to do Dependency Injection on the Object, or on the Method. That means your Constructor or the method-in-question needs a new Parameter:
public <Constructor/MethodName> (IBusinessDataEtc otherLayerOrTierObject, string[] stuffToInsert)
Now that you can accept an interface of your business/data tier object, you can mock it out during Unit Tests and have no dependencies or fear of "Accidental" integration testing.
So in your live code, you pass in a REAL IBusinessDataEtc
object. But in your Unit Testing, you pass in a MOCK IBusinessDataEtc
object. In that Mock, you can include Non-Interface Properties like int XMethodWasCalledCount
or something whose state(s) are updated when the interface methods are called.
So your Unit Test will go through your Method(s)-In-Question, perform whatever logic they have, and call one or two, or a selected set of methods in your IBusinessDataEtc
object. When you do your Assertions at the end of your Unit Test you have a couple of things to test now.
IBusinessDataEtc
object.For more information on Dependency Injection ideas on the Construction-level... as they pertain to Unit Testing... look into Builder design patterns. It adds one more interface and class for each current interface/class you have, but they are very tiny and provide HUGE functionality increases for better Unit-Testing.
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
why not just ng-checked="true"
You need to start the SQL Server manually. Press
windows + R
type
sqlservermanager12.msc
right click ->Start
In C++, almost everything is possible! If you have no way to get private data, then you have to hack. Do it only for testing!
class A {
int iData;
};
int main ()
{
A a;
struct ATwin { int pubData; }; // define a twin class with public members
reinterpret_cast<ATwin*>( &a )->pubData = 42; // set or get value
return 0;
}
Disclaimer: I'm not a MySQL expert ... but this is my understanding of the issues.
I think TEXT is stored outside the mysql row, while I think VARCHAR is stored as part of the row. There is a maximum row length for mysql rows .. so you can limit how much other data you can store in a row by using the VARCHAR.
Also due to VARCHAR forming part of the row, I suspect that queries looking at that field will be slightly faster than those using a TEXT chunk.
Here, I am giving you a demo example. See this and customize it according to your need.
public class ShowPopUp extends Activity {
PopupWindow popUp;
boolean click = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
popUp = new PopupWindow(this);
LinearLayout layout = new LinearLayout(this);
LinearLayout mainLayout = new LinearLayout(this);
TextView tv = new TextView(this);
Button but = new Button(this);
but.setText("Click Me");
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (click) {
popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
popUp.update(50, 50, 300, 80);
click = false;
} else {
popUp.dismiss();
click = true;
}
}
});
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
tv.setText("Hi this is a sample text for popup window");
layout.addView(tv, params);
popUp.setContentView(layout);
// popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
mainLayout.addView(but, params);
setContentView(mainLayout);
}
}
Hope this will solve your issue.
grep -r -e string directory
-r
is for recursive; -e
is optional but its argument specifies the regex to search for. Interestingly, POSIX grep
is not required to support -r
(or -R
), but I'm practically certain that System V in practice they (almost) all do. Some versions of grep
did, sogrep
support -R
as well as (or conceivably instead of) -r
; AFAICT, it means the same thing.
In C, int
, char
, long
, etc. are all integers.
They typically have different memory sizes and thus different ranges as in INT_MIN
to INT_MAX
. char
and arrays of char
are often used to store characters and strings. Integers are stored in many types: int
being the most popular for a balance of speed, size and range.
ASCII is by far the most popular character encoding, but others exist. The ASCII code for an 'A' is 65, 'a' is 97, '\n' is 10, etc. ASCII data is most often stored in a char
variable. If the C environment is using ASCII encoding, the following all store the same value into the integer variable.
int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;
To convert an int
to a char
, simple assign:
int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4;
This warning comes up because int
typically has a greater range than char
and so some loss-of-information may occur. By using the cast (char)
, the potential loss of info is explicitly directed.
To print the value of an integer:
printf("<%c>\n", c3); // prints <b>
// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>
// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>
printf("<%d>\n", i3); // prints <98>
There are additional issues about printing such as using %hhu
or casting when printing an unsigned char
, but leave that for later. There is a lot to printf()
.
SELECT author FROM lyrics WHERE author LIKE 'B%';
Make sure you have an index on author
, though!
Chaining conditions creates long lines, which are discouraged by pep8. Using the .query method forces to use strings, which is powerful but unpythonic and not very dynamic.
Once each of the filters is in place, one approach is
import numpy as np
import functools
def conjunction(*conditions):
return functools.reduce(np.logical_and, conditions)
c_1 = data.col1 == True
c_2 = data.col2 < 64
c_3 = data.col3 != 4
data_filtered = data[conjunction(c1,c2,c3)]
np.logical operates on and is fast, but does not take more than two arguments, which is handled by functools.reduce.
Note that this still has some redundancies: a) shortcutting does not happen on a global level b) Each of the individual conditions runs on the whole initial data. Still, I expect this to be efficient enough for many applications and it is very readable.
You can also make a disjunction (wherein only one of the conditions needs to be true) by using np.logical_or
instead:
import numpy as np
import functools
def disjunction(*conditions):
return functools.reduce(np.logical_or, conditions)
c_1 = data.col1 == True
c_2 = data.col2 < 64
c_3 = data.col3 != 4
data_filtered = data[disjunction(c1,c2,c3)]
<button class='btn btn-danger fa fa-trash' data-toggle='modal' data-target='#deleteModal' data-backdrop='static' data-keyboard='false'></button>
simply add data-backdrop and data-keyboard attribute to your button on which model is open.
So, when you are doing some JavaScript things with an <a />
tag and if you put href="#"
as well, you can add return false at the end of the event (in case of inline event binding) like:
<a href="#" onclick="myJsFunc(); return false;">Run JavaScript Code</a>
Or you can change the href attribute with JavaScript like:
<a href="javascript://" onclick="myJsFunc();">Run JavaScript Code</a>
or
<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
But semantically, all the above ways to achieve this are wrong (it works fine though). If any element is not created to navigate the page and that have some JavaScript things associated with it, then it should not be a <a>
tag.
You can simply use a <button />
instead to do things or any other element like b, span or whatever fits there as per your need, because you are allowed to add events on all the elements.
So, there is one benefit to use <a href="#">
. You get the cursor pointer by default on that element when you do a href="#"
. For that, I think you can use CSS for this like cursor:pointer;
which solves this problem also.
And at the end, if you are binding the event from the JavaScript code itself, there you can do event.preventDefault()
to achieve this if you are using <a>
tag, but if you are not using a <a>
tag for this, there you get an advantage, you don't need to do this.
So, if you see, it's better not to use a tag for this kind of stuff.
To add on:
you can insert a time check within a loop with intensive or possible deadlock, ie.
:
section_toc_conditionalBreakOff;
:
where within this section
if (toc > timeRequiredToBreakOff) % time conditional break off
return;
% other options may be:
% 1. display intermediate values with pause;
% 2. exit; % in some cases, extreme : kill/ quit matlab
end
print
outputs each argument, followed by $,
, to $stdout
, followed by $\
. It is equivalent to args.join($,) + $\
puts
sets both $,
and $\
to "\n" and then does the same thing as print
. The key difference being that each argument is a new line with puts
.
You can require 'english'
to access those global variables with user-friendly names.
I believe a combination of reduce
with JSON.stringify
to perfectly compare Objects and selectively adding those who are not already in the accumulator is an elegant way.
Keep in mind that JSON.stringify
might become a performance issue in extreme cases where the array has many Objects and they are complex, BUT for majority of the time, this is the shortest way to go IMHO.
var collection= [{a:1},{a:2},{a:1},{a:3}]_x000D_
_x000D_
var filtered = collection.reduce((filtered, item) => {_x000D_
if( !filtered.some(filteredItem => JSON.stringify(filteredItem) == JSON.stringify(item)) )_x000D_
filtered.push(item)_x000D_
return filtered_x000D_
}, [])_x000D_
_x000D_
console.log(filtered)
_x000D_
collection.reduce((filtered, item) =>
filtered.some(filteredItem =>
JSON.stringify(filteredItem ) == JSON.stringify(item))
? filtered
: [...filtered, item]
, [])
Following script will work with table schema along with latest Types like (MAX), IMAGE, and etc. change your collation type according to your need on this line (SET @collate = 'DATABASE_DEFAULT';)
SQL SCRIPT HERE:
BEGIN
DECLARE @collate nvarchar(100);
declare @schema nvarchar(255);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length varchar(100);
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);
SET @collate = 'DATABASE_DEFAULT';
DECLARE tbl_cursor CURSOR FOR SELECT (s.[name])schemaName, (o.[name])[tableName]
FROM sysobjects sy
INNER JOIN sys.objects o on o.name = sy.name
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE OBJECTPROPERTY(sy.id, N'IsUserTable') = 1
OPEN tbl_cursor FETCH NEXT FROM tbl_cursor INTO @schema,@table
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE tbl_cursor_changed CURSOR FOR
SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
, c.name column_name
, t.Name data_type
, c.max_length
, c.column_id
FROM sys.columns c
JOIN sys.types t ON c.system_type_id = t.system_type_id
LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE c.object_id like OBJECT_ID(@schema+'.'+@table)
ORDER BY c.column_id
OPEN tbl_cursor_changed
FETCH NEXT FROM tbl_cursor_changed
INTO @row_id, @column_name, @data_type, @max_length, @column_id
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@max_length = -1) SET @max_length = 'MAX';
IF (@data_type LIKE '%char%')
BEGIN TRY
SET @sql = 'ALTER TABLE ' +@schema+'.'+ @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
print @sql
EXEC sp_executesql @sql
END TRY
BEGIN CATCH
PRINT 'ERROR:'
PRINT @sql
END CATCH
FETCH NEXT FROM tbl_cursor_changed
INTO @row_id, @column_name, @data_type, @max_length, @column_id
END
CLOSE tbl_cursor_changed
DEALLOCATE tbl_cursor_changed
FETCH NEXT FROM tbl_cursor
INTO @schema, @table
END
CLOSE tbl_cursor
DEALLOCATE tbl_cursor
PRINT 'Collation For All Tables Done!'
END
You probably want egrep. Try:
egrep '^[d-]rwx.*[0-9]$' usrLog.txt
One way is to call A's constructor and pass self
as an argument, like so:
class B(A):
def __init__(self):
A.__init__(self)
print "hello"
The advantage of this style is that it's very clear. It call A's initialiser. The downside is that it doesn't handle diamond-shaped inheritance very well, since you may end up calling the shared base class's initialiser twice.
Another way is to use super(), as others have shown. For single-inheritance, it does basically the same thing as letting you call the parent's initialiser.
However, super() is quite a bit more complicated under-the-hood and can sometimes be counter-intuitive in multiple inheritance situations. On the plus side, super() can be used to handle diamond-shaped inheritance. If you want to know the nitty-gritty of what super() does, the best explanation I've found for how super() works is here (though I'm not necessarily endorsing that article's opinions).
Here's how I do it when I need a database query's results in my batch file:
sqlplus -S schema/schema@db @query.sql> __query.tmp
set /p result=<__query.tmp
del __query.tmp
The key is in line 2: "set /p" sets the value of "result" to the value of the first line (only) in "__query.tmp" via the "<" redirection operator.
System.out.println(myList.size());
Since no elements are in the list
output => 0
myList.add("newString"); // use myList.add() to insert elements to the arraylist
System.out.println(myList.size());
Since one element is added to the list
output => 1
I got the same problem on a newly installed system, but this was a udev problem. There was no /dev/tty
node, so I had to do:
mknod -m 666 /dev/tty c 5 0
This question has already been answered, but I believe it would be good to throw some useful methods not previously discussed into the mix, and compare all methods proposed thus far in terms of performance.
Here are some useful solutions to this problem, in increasing order of performance.
DataFrame.agg
This is a simple str.format
-based approach.
df['baz'] = df.agg('{0[bar]} is {0[foo]}'.format, axis=1)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
You can also use f-string formatting here:
df['baz'] = df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
char.array
-based ConcatenationConvert the columns to concatenate as chararrays
, then add them together.
a = np.char.array(df['bar'].values)
b = np.char.array(df['foo'].values)
df['baz'] = (a + b' is ' + b).astype(str)
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
zip
I cannot overstate how underrated list comprehensions are in pandas.
df['baz'] = [str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])]
Alternatively, using str.join
to concat (will also scale better):
df['baz'] = [
' '.join([str(x), 'is', y]) for x, y in zip(df['bar'], df['foo'])]
df
foo bar baz
0 a 1 1 is a
1 b 2 2 is b
2 c 3 3 is c
List comprehensions excel in string manipulation, because string operations are inherently hard to vectorize, and most pandas "vectorised" functions are basically wrappers around loops. I have written extensively about this topic in For loops with pandas - When should I care?. In general, if you don't have to worry about index alignment, use a list comprehension when dealing with string and regex operations.
The list comp above by default does not handle NaNs. However, you could always write a function wrapping a try-except if you needed to handle it.
def try_concat(x, y):
try:
return str(x) + ' is ' + y
except (ValueError, TypeError):
return np.nan
df['baz'] = [try_concat(x, y) for x, y in zip(df['bar'], df['foo'])]
perfplot
Performance MeasurementsGraph generated using perfplot. Here's the complete code listing.
Functions
def brenbarn(df): return df.assign(baz=df.bar.map(str) + " is " + df.foo) def danielvelkov(df): return df.assign(baz=df.apply( lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)) def chrimuelle(df): return df.assign( baz=df['bar'].astype(str).str.cat(df['foo'].values, sep=' is ')) def vladimiryashin(df): return df.assign(baz=df.astype(str).apply(lambda x: ' is '.join(x), axis=1)) def erickfis(df): return df.assign( baz=df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)) def cs1_format(df): return df.assign(baz=df.agg('{0[bar]} is {0[foo]}'.format, axis=1)) def cs1_fstrings(df): return df.assign(baz=df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)) def cs2(df): a = np.char.array(df['bar'].values) b = np.char.array(df['foo'].values) return df.assign(baz=(a + b' is ' + b).astype(str)) def cs3(df): return df.assign( baz=[str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])])
You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.
declare @TableVar table
(
firstCol varchar(50) NOT NULL,
secondCol varchar(50) NOT NULL
)
BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO
INSERT INTO dbo.ExistingTable
(
firstCol,
secondCol
)
SELECT firstCol,
secondCol
FROM @TableVar
GO
See my answer to a similar question here.
It sounds like you want a background-image to keep it's own aspect ratio while expanding to 100% width and getting cropped off on the top and bottom. If that's the case, do something like this:
.chapter {
position: relative;
height: 1200px;
z-index: 1;
}
#chapter1 {
background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center top;
background-attachment: fixed;
}
jsfiddle: http://jsfiddle.net/ndKWN/3/
The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.
If you want the height to keep the image's aspect ratio, you'll have to do something like what I wrote in an edit to the answer I linked to above. Set the container's height
to 0 and set the padding-bottom
to the percentage of the width:
.chapter {
position: relative;
height: 0;
padding-bottom: 75%;
z-index: 1;
}
#chapter1 {
background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center top;
background-attachment: fixed;
}
jsfiddle: http://jsfiddle.net/ndKWN/4/
You could also put the padding-bottom
percentage into each #chapter
style if each image has a different aspect ratio. In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value.
Why don't these questions get answered with the obvious answer?
a = numpy.empty(n, dtype=object)
This creates an array of length n that can store objects. It can't be resized or appended to. In particular, it doesn't waste space by padding its length. This is the Python equivalent of Java's
Object[] a = new Object[n];
If you're really interested in performance and space and know that your array will only store certain numeric types then you can change the dtype argument to some other value like int. Then numpy will pack these elements directly into the array rather than making the array reference int objects.
One easy way to set a build as unstable, is in your "execute shell" block, run exit 13
Its very simple if you use <MediaElement>
:
<MediaElement Height="113" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="mediaElement1" VerticalAlignment="Top" Width="198" Source="C:\Users\abc.gif"
LoadedBehavior="Play" Stretch="Fill" SpeedRatio="1" IsMuted="False" />
The best way to find the path is to do via code.
Using Swift, just paste the code below inside the function application in your AppDelegate.swift
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsPath = paths.first as String
println(documentsPath)
For Obj-C code, look answer from @Ankur
The ActiveDirectory
module for powershell can be installed by adding the RSAT-AD-Powershell
feature.
In an elevated powershell window:
Add-WindowsFeature RSAT-AD-PowerShell
or
Enable-WindowsOptionalFeature -FeatureName ActiveDirectory-Powershell -Online -All
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
No need to find
. If you are just looking for a pattern within a specific directory, this should suffice:
grep -hn FOO /your/path/*.bar
Where -h
is the parameter to hide the filename, as from man grep
:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.
Note that you were using
-H, --with-filename
Print the file name for each match. This is the default when there is more than one file to search.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
And you can try this:
public static Bitmap mirrorBitmap(Bitmap bInput)
{
Bitmap bOutput;
Matrix matrix = new Matrix();
matrix.preScale(-1.0f, 1.0f);
bOutput = Bitmap.createBitmap(bInput, 0, 0, bInput.getWidth(), bInput.getHeight(), matrix, true);
return bOutput;
}
JavaType javaType = objectMapper.getTypeFactory().constructParameterizedType(Map.class, Key.class, Value.class);
Map<Key, Value> map=objectMapper.readValue(jsonStr, javaType);
i think this will solve your problem.
You do not need to make an extra view for this, the functionality is already built in.
First each page with a login link needs to know the current path, and the easiest way is to add the request context preprosessor to settings.py (the 4 first are default), then the request object will be available in each request:
settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)
Then add in the template you want the Login link:
base.html:
<a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">Login</a>
This will add a GET argument to the login page that points back to the current page.
The login template can then be as simple as this:
registration/login.html:
{% block content %}
<form method="post" action="">
{{form.as_p}}
<input type="submit" value="Login">
</form>
{% endblock %}
Try this code:
@RequestMapping(value = "/validate", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<ErrorBean> validateUser(@QueryParam("jsonInput") final String jsonInput) {
int numberHTTPDesired = 400;
ErrorBean responseBean = new ErrorBean();
responseBean.setError("ERROR");
responseBean.setMensaje("Error in validation!");
return new ResponseEntity<ErrorBean>(responseBean, HttpStatus.valueOf(numberHTTPDesired));
}
You could use String.rstrip
.
result = string.rstrip('/')
Our Server environment : SQL2008 x64 SP2 Reporting Services on Windows Server 2008 x64,
Client PC environment: Windows XP SP2 with IE6 or higher, all users are login to Active Directory, users are not members of local Administrator or power user group.
Error: When a user printing a report getting an error as "Unable to load client print control"
Solution that work for us: replace following files in sql 2008 with SQL 2008 R2
Program Files\Microsoft SQL Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer\bin RSClientPrint-x86.cab RSClientPrint-x64.cab RSClientPrint-ia64.cab
Once you replace the files one server users wont get above error and they do not required local power user or admin right to download Active X. Recommending to add report server URL as a trusted site (add to Trusted sites) via Active Directory GP.
As Shafik already wrote you need to use the right format because scanf
gets you a char.
Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/
Hint: It's faster/nicer to write x=x+1
; the shorter way: x++;
Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.
To change even less on your original query, you can turn your join into a RIGHT
join
SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM appointment
RIGHT JOIN person ON person.person_id = appointment.person_id
GROUP BY person.person_id;
This just builds on the selected answer, but as the outer join is in the RIGHT
direction, only one word needs to be added and less changes. - Just remember that it's there and can sometimes make queries more readable and require less rebuilding.
$("input").on("keydown",function search(e) {
if(e.keyCode == 13) {
alert($(this).val());
}
});
jsFiddle example : http://jsfiddle.net/NH8K2/1/
I was looking at the different answers and took time to read the documentation of secrets
The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.
In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.
Looking more into what it has to offer I found a very handy function if you want to mimic an ID like Google Drive IDs:
secrets.token_urlsafe([nbytes=None])
Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is None or not supplied, a reasonable default is used.
Use it the following way:
import secrets
import math
def id_generator():
id = secrets.token_urlsafe(math.floor(32 / 1.3))
return id
print(id_generator())
Output a 32 characters length id:
joXR8dYbBDAHpVs5ci6iD-oIgPhkeQFk
I know this is slightly different from the OP's question but I expect that it would still be helpful to many who were looking for the same use-case that I was looking for.
After hours of research this solution worked for me:
(disclaimer: results may vary due to circumstances)
the Library not found -lPods-(someCocoapod)
error was due to multiple entries in the :
Settings(Target) > Build Settings > Linking > 'Other Linker Flags'
A lot of other posts had me look there and I would see changes to the error when I messed around with the entries, but I kept getting some variation on the same error.
Too many hours lost ...
remove the -lPods-(someCocoaPod) lines in the 'Other Linker Flags' list BUT only if $(inherited) is at the top. At first I was unsure, but the reassuring sign was that I still saw references to my cocoapods when I left the edit mode(inherited). I tested in debug and release, both of which were giving me errors, and the problem was immediately resolved.
First off, I use nvm on linux machine.
When looking at the documentation for nvm at https://www.npmjs.org/package/nvm, it recommendations that you install nvm globally using the -g
switch.
npm install -g nvm
Also there is a . in the path variable that they recommend.
export PATH=./node_modules/.bin:$PATH
so maybe your path should be
C:\Program Files (x86)\nodejs\node_modules\npm\\.bin
In Window in new version you can export like this
The answer is in the documentation for bindParam
:
Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
And execute
call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers
Example:
$value = 'foo';
$s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
$s->bindParam(':baz', $value); // use bindParam to bind the variable
$value = 'foobarbaz';
$s->execute(); // executed with WHERE baz = 'foobarbaz'
or
$value = 'foo';
$s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
$s->bindValue(':baz', $value); // use bindValue to bind the variable's value
$value = 'foobarbaz';
$s->execute(); // executed with WHERE baz = 'foo'
Since ES6 filter
supports pointy arrow notation (like LINQ):
So it can be boiled down to following one-liner.
['a','b',1].filter(item => typeof item ==='string');
Last Week
SELECT UserName, InsertTime
FROM tblaccounts
WHERE WEEK(InsertTime) = WEEK(NOW()) - 1;
Last Month
SELECT UserName, InsertTime
FROM tblaccounts
WHERE MONTH(InsertTime) = MONTH(NOW()) - 1;
Last YEAR
SELECT UserName, InsertTime
FROM tblaccounts
WHERE YEAR(InsertTime) = YEAR(NOW()) - 1;