You can try this to install the 32-bit library (not all in ia32-libs):
sudo apt-get install program:i386
sudo dpkg --add-architecture i386
may be required (if you haven't ever run that).
Or if you want to install the whole ia32-lib instead, try the following order:
sudo -i
cd /etc/apt/sources.list.d
echo "deb http://old-releases.ubuntu.com/ubuntu/ raring main restricted universe multiverse" >ia32-libs-raring.list
apt-get update
apt-get install ia32-libs
PS: In this way, you can install ia32-libs
. However, we add the source of 13.04 instead, so, there may be some unknown problem. After installing ia32-libs
, I recommend you to remove the ia32-libs-raring.list
in /etc/apt/sources.list.d
, and do sudo apt-get update
.
If you want to fix the dependency of Android SDK, you can try this bellow:
sudo apt-get install -y libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5 lib32z1
Rather than silencing the warnings, gcc style is usually to use either standard C constructs or the __attribute__
extension to tell the compiler more about your intention. For instance, the warning about assignment used as a condition is suppressed by putting the assignment in parentheses, i.e. if ((p=malloc(cnt)))
instead of if (p=malloc(cnt))
. Warnings about unused function arguments can be suppressed by some odd __attribute__
I can never remember, or by self-assignment, etc. But generally I prefer just globally disabling any warning option that generates warnings for things that will occur in correct code.
You must put the expression at the beginning of the list comprehension, an if statement at the end filters elements!
[x+1 if x >= 45 else x+5 for x in l]
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
Note: This is the somewhat crude solution I posted myself, after not finding an answer here on Stack Overflow. It allows for only one array being passed, and it being the last element of the parameter list. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by called_function(), but it worked for me. Somewhat later Ken posted his solution, but I kept mine here for "historic" reference.
calling_function()
{
variable="a"
array=( "x", "y", "z" )
called_function "${variable}" "${array[@]}"
}
called_function()
{
local_variable="${1}"
shift
local_array=("${@}")
}
I just wrote this for my C programming class.
I am posting it because none of the other examples here will work with any size rectangular grid, and any number N-in-a-row consecutive marks to win.
You'll find my algorithm, such as it is, in the checkWinner()
function. It doesn't use magic numbers or anything fancy to check for a winner, it simply uses four for loops - The code is well commented so I'll let it speak for itself I guess.
// This program will work with any whole number sized rectangular gameBoard.
// It checks for N marks in straight lines (rows, columns, and diagonals).
// It is prettiest when ROWS and COLS are single digit numbers.
// Try altering the constants for ROWS, COLS, and N for great fun!
// PPDs come first
#include <stdio.h>
#define ROWS 9 // The number of rows our gameBoard array will have
#define COLS 9 // The number of columns of the same - Single digit numbers will be prettier!
#define N 3 // This is the number of contiguous marks a player must have to win
#define INITCHAR ' ' // This changes the character displayed (a ' ' here probably looks the best)
#define PLAYER1CHAR 'X' // Some marks are more aesthetically pleasing than others
#define PLAYER2CHAR 'O' // Change these lines if you care to experiment with them
// Function prototypes are next
int playGame (char gameBoard[ROWS][COLS]); // This function allows the game to be replayed easily, as desired
void initBoard (char gameBoard[ROWS][COLS]); // Fills the ROWSxCOLS character array with the INITCHAR character
void printBoard (char gameBoard[ROWS][COLS]); // Prints out the current board, now with pretty formatting and #s!
void makeMove (char gameBoard[ROWS][COLS], int player); // Prompts for (and validates!) a move and stores it into the array
int checkWinner (char gameBoard[ROWS][COLS], int player); // Checks the current state of the board to see if anyone has won
// The starting line
int main (void)
{
// Inits
char gameBoard[ROWS][COLS]; // Our gameBoard is declared as a character array, ROWS x COLS in size
int winner = 0;
char replay;
//Code
do // This loop plays through the game until the user elects not to
{
winner = playGame(gameBoard);
printf("\nWould you like to play again? Y for yes, anything else exits: ");
scanf("%c",&replay); // I have to use both a scanf() and a getchar() in
replay = getchar(); // order to clear the input buffer of a newline char
// (http://cboard.cprogramming.com/c-programming/121190-problem-do-while-loop-char.html)
} while ( replay == 'y' || replay == 'Y' );
// Housekeeping
printf("\n");
return winner;
}
int playGame(char gameBoard[ROWS][COLS])
{
int turn = 0, player = 0, winner = 0, i = 0;
initBoard(gameBoard);
do
{
turn++; // Every time this loop executes, a unique turn is about to be made
player = (turn+1)%2+1; // This mod function alternates the player variable between 1 & 2 each turn
makeMove(gameBoard,player);
printBoard(gameBoard);
winner = checkWinner(gameBoard,player);
if (winner != 0)
{
printBoard(gameBoard);
for (i=0;i<19-2*ROWS;i++) // Formatting - works with the default shell height on my machine
printf("\n"); // Hopefully I can replace these with something that clears the screen for me
printf("\n\nCongratulations Player %i, you've won with %i in a row!\n\n",winner,N);
return winner;
}
} while ( turn < ROWS*COLS ); // Once ROWS*COLS turns have elapsed
printf("\n\nGame Over!\n\nThere was no Winner :-(\n"); // The board is full and the game is over
return winner;
}
void initBoard (char gameBoard[ROWS][COLS])
{
int row = 0, col = 0;
for (row=0;row<ROWS;row++)
{
for (col=0;col<COLS;col++)
{
gameBoard[row][col] = INITCHAR; // Fill the gameBoard with INITCHAR characters
}
}
printBoard(gameBoard); // Having this here prints out the board before
return; // the playGame function asks for the first move
}
void printBoard (char gameBoard[ROWS][COLS]) // There is a ton of formatting in here
{ // That I don't feel like commenting :P
int row = 0, col = 0, i=0; // It took a while to fine tune
// But now the output is something like:
printf("\n"); //
// 1 2 3
for (row=0;row<ROWS;row++) // 1 | |
{ // -----------
if (row == 0) // 2 | |
{ // -----------
printf(" "); // 3 | |
for (i=0;i<COLS;i++)
{
printf(" %i ",i+1);
}
printf("\n\n");
}
for (col=0;col<COLS;col++)
{
if (col==0)
printf("%i ",row+1);
printf(" %c ",gameBoard[row][col]);
if (col<COLS-1)
printf("|");
}
printf("\n");
if (row < ROWS-1)
{
for(i=0;i<COLS-1;i++)
{
if(i==0)
printf(" ----");
else
printf("----");
}
printf("---\n");
}
}
return;
}
void makeMove (char gameBoard[ROWS][COLS],int player)
{
int row = 0, col = 0, i=0;
char currentChar;
if (player == 1) // This gets the correct player's mark
currentChar = PLAYER1CHAR;
else
currentChar = PLAYER2CHAR;
for (i=0;i<21-2*ROWS;i++) // Newline formatting again :-(
printf("\n");
printf("\nPlayer %i, please enter the column of your move: ",player);
scanf("%i",&col);
printf("Please enter the row of your move: ");
scanf("%i",&row);
row--; // These lines translate the user's rows and columns numbering
col--; // (starting with 1) to the computer's (starting with 0)
while(gameBoard[row][col] != INITCHAR || row > ROWS-1 || col > COLS-1) // We are not using a do... while because
{ // I wanted the prompt to change
printBoard(gameBoard);
for (i=0;i<20-2*ROWS;i++)
printf("\n");
printf("\nPlayer %i, please enter a valid move! Column first, then row.\n",player);
scanf("%i %i",&col,&row);
row--; // See above ^^^
col--;
}
gameBoard[row][col] = currentChar; // Finally, we store the correct mark into the given location
return; // And pop back out of this function
}
int checkWinner(char gameBoard[ROWS][COLS], int player) // I've commented the last (and the hardest, for me anyway)
{ // check, which checks for backwards diagonal runs below >>>
int row = 0, col = 0, i = 0;
char currentChar;
if (player == 1)
currentChar = PLAYER1CHAR;
else
currentChar = PLAYER2CHAR;
for ( row = 0; row < ROWS; row++) // This first for loop checks every row
{
for ( col = 0; col < (COLS-(N-1)); col++) // And all columns until N away from the end
{
while (gameBoard[row][col] == currentChar) // For consecutive rows of the current player's mark
{
col++;
i++;
if (i == N)
{
return player;
}
}
i = 0;
}
}
for ( col = 0; col < COLS; col++) // This one checks for columns of consecutive marks
{
for ( row = 0; row < (ROWS-(N-1)); row++)
{
while (gameBoard[row][col] == currentChar)
{
row++;
i++;
if (i == N)
{
return player;
}
}
i = 0;
}
}
for ( col = 0; col < (COLS - (N-1)); col++) // This one checks for "forwards" diagonal runs
{
for ( row = 0; row < (ROWS-(N-1)); row++)
{
while (gameBoard[row][col] == currentChar)
{
row++;
col++;
i++;
if (i == N)
{
return player;
}
}
i = 0;
}
}
// Finally, the backwards diagonals:
for ( col = COLS-1; col > 0+(N-2); col--) // Start from the last column and go until N columns from the first
{ // The math seems strange here but the numbers work out when you trace them
for ( row = 0; row < (ROWS-(N-1)); row++) // Start from the first row and go until N rows from the last
{
while (gameBoard[row][col] == currentChar) // If the current player's character is there
{
row++; // Go down a row
col--; // And back a column
i++; // The i variable tracks how many consecutive marks have been found
if (i == N) // Once i == N
{
return player; // Return the current player number to the
} // winnner variable in the playGame function
} // If it breaks out of the while loop, there weren't N consecutive marks
i = 0; // So make i = 0 again
} // And go back into the for loop, incrementing the row to check from
}
return 0; // If we got to here, no winner has been detected,
} // so we pop back up into the playGame function
// The end!
// Well, almost.
// Eventually I hope to get this thing going
// with a dynamically sized array. I'll make
// the CONSTANTS into variables in an initGame
// function and allow the user to define them.
labelname.ForeColor = Color.Colorname;
Here's another way to do it, using a LINQ lambda:
C#:
SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}"));
VB.NET:
SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}"))
I used Abdurrahim's suggestion. However, it seemed to give a weird time format and also added the abbreviation for the day as part of the build date; example: Sun 12/24/2017 13:21:05.43. I only needed just the date so I had to eliminate the rest using substring.
After adding the echo %date% %time% > "$(ProjectDir)\Resources\BuildDate.txt"
to the pre-build event, I just did the following:
string strBuildDate = YourNamespace.Properties.Resources.BuildDate;
string strTrimBuildDate = strBuildDate.Substring(4).Remove(10);
The good news here is that it worked.
With num_rows()
you first perform the query, and then you can check how many rows you got. count_all_results()
on the other hand only gives you the number of rows your query would produce, but doesn't give you the actual resultset.
// num rows example
$this->db->select('*');
$this->db->where('whatever');
$query = $this->db->get('table');
$num = $query->num_rows();
// here you can do something with $query
// count all example
$this->db->where('whatever');
$num = $this->db->count_all_results('table');
// here you only have $num, no $query
Generic solution extracting the first "n" words of refcell string into a new string of "x" number of characters
=LEFT(SUBSTITUTE(***refcell***&" "," ",REPT(" ",***x***),***n***),***x***)
Assuming A1 has text string to extract, the 1st word extracted to a 15 character result
=LEFT(SUBSTITUTE(A1&" "," ",REPT(" ",15),1),15)
This would result in "Toronto" being returned to a 15 character string. 1st 2 words extracted to a 30 character result
=LEFT(SUBSTITUTE(A1&" "," ",REPT(" ",30),2),30)
would result in "Toronto is" being returned to a 30 character string
writelines()
does not add line separators. You can alter the list of strings by using map()
to add a new \n
(line break) at the end of each string.
items = ['abc', '123', '!@#']
items = map(lambda x: x + '\n', items)
w.writelines(items)
Please see this link for more information on setting the text size in code. Basically it says:
public void setTextSize (int unit, float size)
Since: API Level 1 Set the default text size to a given unit and value. See TypedValue for the possible dimension units. Related XML Attributes
android:textSize Parameters
unit The desired dimension unit.
size The desired size in the given units.
Write the queue job information in long format to text file
qstat -f > queue.txt
Grep job names
grep 'Job_Name' queue.txt
If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):
bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
bbox = mtransforms.Bbox.union(bboxes)
bottom = bbox.y0
x, y = self.label.get_position()
self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))
You can set the label position independently of the ticks by using:
ax.xaxis.set_label_coords(x0, y0)
that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.
Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:
Delivery -> Package (One -> Many)
CREATE TABLE Delivery(
Id INT IDENTITY PRIMARY KEY,
NoteNumber NVARCHAR(255) NOT NULL
)
CREATE TABLE Package(
Id INT IDENTITY PRIMARY KEY,
Status INT NOT NULL DEFAULT 0,
Delivery_Id INT NOT NULL,
CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)
The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).
So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.
To get the full calendar name from the month number, you can use calendar.month_name. Please see the documentation for more details: https://docs.python.org/2/library/calendar.html
month_no = 1
month = calendar.month_name[month_no]
# month provides "January":
print(month)
There are indeed a lot of string similarity measures out there:
You can find explanation and java implementation of these here: https://github.com/tdebatty/java-string-similarity
I solved it doing adb reverse tcp:8081 tcp:8081
and then reload
on my phone.
Something like this...
var res = from row in myDTable.AsEnumerable()
where row.Field<int>("EmpID") == 5 &&
(row.Field<string>("EmpName") != "abc" ||
row.Field<string>("EmpName") != "xyz")
select row;
See also LINQ query on a DataTable
Accepting Optional as parameters causes unnecessary wrapping at caller level.
For example in the case of:
public int calculateSomething(Optional<String> p1, Optional<BigDecimal> p2 {}
Suppose you have two not-null strings (ie. returned from some other method):
String p1 = "p1";
String p2 = "p2";
You're forced to wrap them in Optional even if you know they are not Empty.
This get even worse when you have to compose with other "mappable" structures, ie. Eithers:
Either<Error, String> value = compute().right().map((s) -> calculateSomething(
< here you have to wrap the parameter in a Optional even if you know it's a
string >));
ref:
methods shouldn't expect Option as parameters, this is almost always a code smell that indicated a leakage of control flow from the caller to the callee, it should be responsibility of the caller to check the content of an Option
ref. https://github.com/teamdigitale/digital-citizenship-functions/pull/148#discussion_r170862749
This problem consists of two very different sub-problems:
While randomness is quite easily achieved, the uniqueness without a retry loop is not. This brings us to concentrate on the uniqueness first. Non-random uniqueness can trivially be achieved with AUTO_INCREMENT
. So using a uniqueness-preserving, pseudo-random transformation would be fine:
RAND(N)
itself!A sequence of random numbers created by the same seed is guaranteed to be
INT32
So we use @AndreyVolk's or @GordonLinoff's approach, but with a seeded RAND
:
e.g. Assumin id
is an AUTO_INCREMENT
column:
INSERT INTO vehicles VALUES (blah); -- leaving out the number plate
SELECT @lid:=LAST_INSERT_ID();
UPDATE vehicles SET numberplate=concat(
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@lid)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed)*36+1, 1)
)
WHERE id=@lid;
Try this one if this is the output you want:
<div id="main_content" >
<div id="container">
</div>
</div>
#main_content {
background-color: #2185C5;
margin: 0 auto;
}
#container {
width: 100px;
height: auto;
margin: 0 auto;
padding: 10px;
background: red;
}
All these functions and random things, I think it is best to use this, and do it like this:
this.options[this.selectedIndex].text
Jq + ec2metadata makes it a little nicer. I'm using cf and have access to the region. Otherwise you can grab it in bash.
aws ec2 describe-tags --region $REGION \
--filters "Name=resource-id,Values=`ec2metadata --instance-id`" | jq --raw-output \
'.Tags[] | select(.Key=="TAG_NAME") | .Value'
No jq.
aws ec2 describe-tags --region us-west-2 \
--filters "Name=resource-id,Values=`ec2-metadata --instance-id | cut -d " " -f 2`" \
--query 'Tags[?Key==`Name`].Value' \
--output text
Stream stream = new MemoryStream();
you can use MemoryStream
Reference: MemoryStream
One need to set NavigateItem
checked true whenever item in NavigateView
is clicked
//listen for navigation events
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
// select the correct nav menu item
navigationView.getMenu().findItem(mNavItemId).setChecked(true);
Add NavigationItemSelectedListener
on NavigationView
@Override
public boolean onNavigationItemSelected(final MenuItem menuItem) {
// update highlighted item in the navigation menu
menuItem.setChecked(true);
mNavItemId = menuItem.getItemId();
// allow some time after closing the drawer before performing real navigation
// so the user can see what is happening
mDrawerLayout.closeDrawer(GravityCompat.START);
mDrawerActionHandler.postDelayed(new Runnable() {
@Override
public void run() {
navigate(menuItem.getItemId());
}
}, DRAWER_CLOSE_DELAY_MS);
return true;
}
The easiest way to differentiate O(1) and O(n) is comparing array and list.
For array, if you have the right index value, you can access the data instantly. (If you don't know the index and have to loop through the array, then it won't be O(1) anymore)
For list, you always need to loop through it whether you know the index or not.
First of all, you're not leveraging the advantage of using a PreparedStatement
. I would first suggest that you modify your PreparedStatement
as follows:
PreparedStatement statement = con.prepareStatement("select * from orders where status=? AND date=?")
You can then use statement.setXX(param_index, param_value)
to set the respective values. For conversion to timestamp
, have a look at the following javadocs:
PreparedStatement.setTimeStamp()
Timestamp
Hope this helps!
Just remove the .val(). Like:
if ( $('html').attr('lang') == 'fr-FR' ) {
// do this
} else {
// do that
}
The solution that worked for me with default value 0 is the following
ALTER TABLE reservations ADD COLUMN isGuest BIT DEFAULT 0
Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.
Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.
Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.
To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.
1. SELECT MAX(Id) FROM Table
ISOC++11 (officially ISO/IEC 14882:2011) is the most recent version of the standard of the C++ programming language. It contains some new features, and concepts, for example:
If we would like to understand the concepts of the new expression value categories we have to be aware of that there are rvalue and lvalue references. It is better to know rvalues can be passed to non-const rvalue references.
int& r_i=7; // compile error
int&& rr_i=7; // OK
We can gain some intuition of the concepts of value categories if we quote the subsection titled Lvalues and rvalues from the working draft N3337 (the most similar draft to the published ISOC++11 standard).
3.10 Lvalues and rvalues [basic.lval]
1 Expressions are categorized according to the taxonomy in Figure 1.
- An lvalue (so called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object. [ Example: If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue. —end example ]
- An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references (8.3.2). [ Example: The result of calling a function whose return type is an rvalue reference is an xvalue. —end example ]
- A glvalue (“generalized” lvalue) is an lvalue or an xvalue.
- An rvalue (so called, historically, because rvalues could appear on the right-hand side of an assignment expression) is an xvalue, a
temporary object (12.2) or subobject thereof, or a value that is not
associated with an object.- A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [ Example: The result of calling a function whose return type is not a
reference is a prvalue. The value of a literal such as 12, 7.3e5, or
true is also a prvalue. —end example ]Every expression belongs to exactly one of the fundamental classifications in this taxonomy: lvalue, xvalue, or prvalue. This property of an expression is called its value category.
But I am not quite sure about that this subsection is enough to understand the concepts clearly, because "usually" is not really general, "near the end of its lifetime" is not really concrete, "involving rvalue references" is not really clear, and "Example: The result of calling a function whose return type is an rvalue reference is an xvalue." sounds like a snake is biting its tail.
Every expression belongs to exactly one primary value category. These value categories are lvalue, xvalue and prvalue categories.
The expression E belongs to the lvalue category if and only if E refers to an entity that ALREADY has had an identity (address, name or alias) that makes it accessible outside of E.
#include <iostream>
int i=7;
const int& f(){
return i;
}
int main()
{
std::cout<<&"www"<<std::endl; // The expression "www" in this row is an lvalue expression, because string literals are arrays and every array has an address.
i; // The expression i in this row is an lvalue expression, because it refers to the same entity ...
i; // ... as the entity the expression i in this row refers to.
int* p_i=new int(7);
*p_i; // The expression *p_i in this row is an lvalue expression, because it refers to the same entity ...
*p_i; // ... as the entity the expression *p_i in this row refers to.
const int& r_I=7;
r_I; // The expression r_I in this row is an lvalue expression, because it refers to the same entity ...
r_I; // ... as the entity the expression r_I in this row refers to.
f(); // The expression f() in this row is an lvalue expression, because it refers to the same entity ...
i; // ... as the entity the expression f() in this row refers to.
return 0;
}
The expression E belongs to the xvalue category if and only if it is
— the result of calling a function, whether implicitly or explicitly, whose return type is an rvalue reference to the type of object being returned, or
int&& f(){
return 3;
}
int main()
{
f(); // The expression f() belongs to the xvalue category, because f() return type is an rvalue reference to object type.
return 0;
}
— a cast to an rvalue reference to object type, or
int main()
{
static_cast<int&&>(7); // The expression static_cast<int&&>(7) belongs to the xvalue category, because it is a cast to an rvalue reference to object type.
std::move(7); // std::move(7) is equivalent to static_cast<int&&>(7).
return 0;
}
— a class member access expression designating a non-static data member of non-reference type in which the object expression is an xvalue, or
struct As
{
int i;
};
As&& f(){
return As();
}
int main()
{
f().i; // The expression f().i belongs to the xvalue category, because As::i is a non-static data member of non-reference type, and the subexpression f() belongs to the xvlaue category.
return 0;
}
— a pointer-to-member expression in which the first operand is an xvalue and the second operand is a pointer to data member.
Note that the effect of the rules above is that named rvalue references to objects are treated as lvalues and unnamed rvalue references to objects are treated as xvalues; rvalue references to functions are treated as lvalues whether named or not.
#include <functional>
struct As
{
int i;
};
As&& f(){
return As();
}
int main()
{
f(); // The expression f() belongs to the xvalue category, because it refers to an unnamed rvalue reference to object.
As&& rr_a=As();
rr_a; // The expression rr_a belongs to the lvalue category, because it refers to a named rvalue reference to object.
std::ref(f); // The expression std::ref(f) belongs to the lvalue category, because it refers to an rvalue reference to function.
return 0;
}
The expression E belongs to the prvalue category if and only if E belongs neither to the lvalue nor to the xvalue category.
struct As
{
void f(){
this; // The expression this is a prvalue expression. Note, that the expression this is not a variable.
}
};
As f(){
return As();
}
int main()
{
f(); // The expression f() belongs to the prvalue category, because it belongs neither to the lvalue nor to the xvalue category.
return 0;
}
There are two further important mixed value categories. These value categories are rvalue and glvalue categories.
The expression E belongs to the rvalue category if and only if E belongs to the xvalue category, or to the prvalue category.
Note that this definition means that the expression E belongs to the rvalue category if and only if E refers to an entity that has not had any identity that makes it accessible outside of E YET.
The expression E belongs to the glvalue category if and only if E belongs to the lvalue category, or to the xvalue category.
Scott Meyer has published a very useful rule of thumb to distinguish rvalues from lvalues.
- If you can take the address of an expression, the expression is an lvalue.
- If the type of an expression is an lvalue reference (e.g., T& or const T&, etc.), that expression is an lvalue.
- Otherwise, the expression is an rvalue. Conceptually (and typically also in fact), rvalues correspond to temporary objects, such as those returned from functions or created through implicit type conversions. Most literal values (e.g., 10 and 5.3) are also rvalues.
Through the Computer management console, navigate through Event Viewer > Windows Logs > System. Every services that change state will be logged here.
You'll see info like: The XXXX service entered the running state or The XXXX service entered the stopped state, etc.
As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.
If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS
Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");
, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.
.iOS-device {
style-you-want-to-set: yada;
}
Actually I work on project compatible python 2.6, 2.7 and 3.4 and I have to create IDs from free user entries.
Thanks to you, I have created this function that works wonders.
import re
import unicodedata
def strip_accents(text):
"""
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
try:
text = unicode(text, 'utf-8')
except (TypeError, NameError): # unicode is a default on python 3
pass
text = unicodedata.normalize('NFD', text)
text = text.encode('ascii', 'ignore')
text = text.decode("utf-8")
return str(text)
def text_to_id(text):
"""
Convert input text to id.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
text = strip_accents(text.lower())
text = re.sub('[ ]+', '_', text)
text = re.sub('[^0-9a-zA-Z_-]', '', text)
return text
result:
text_to_id("Montréal, über, 12.89, Mère, Françoise, noël, 889")
>>> 'montreal_uber_1289_mere_francoise_noel_889'
var language = "Swift"
var resultStr = "\(language) is a new programming language"
No siblings solution:
var x = $('#xxx').parent().html();
alert(x);
Universal solution:
// no cloning necessary
var x = $('#xxx').wrapAll('<div>').parent().html();
alert(x);
Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
Try to rebase your local master branch onto your remote/origin master branch and resolve any conflicts in the process.
To implement that, it seems that you have to:
org.springframework.security.authentication.ProviderManager
and configure it (set its providers) to a custom org.springframework.security.authentication.AuthenticationProvider
.
This last one should return on its authenticate method a Authentication, which should be setted with the org.springframework.security.core.GrantedAuthority
, in your case, all the permissions for the given user.The trick in that article is to have roles assigned to users, but, to set the permissions for those roles in the Authentication.authorities
object.
For that I advise you to read the API, and see if you can extend some basic ProviderManager and AuthenticationProvider instead of implementing everything. I've done that with org.springframework.security.ldap.authentication.LdapAuthenticationProvider
setting a custom LdapAuthoritiesPopulator, that would retrieve the correct roles for the user.
Hope this time I got what you are looking for. Good luck.
If you have BS4 another option could be:
.dropdown-item {
width: max-content !important;
}
.dropdown-menu {
max-height: max-content;
max-width: max-content;
}
Well I did a bit of searching around the internet for you and I found this handy link.
Easiest way to find duplicate values in a JavaScript array
You can adapt the sample code that is provided in the above link, courtesy of "swilliams" to your solution.
I'd use either String.split
or a regex:
Using String.split
String[] numberSplit = yourString.split(":") ;
String numbers = numberSplit[ (numberSplit.length-1) ] ; //!! last array element
Using RegEx (requires import java.util.regex.*
)
String numbers = "" ;
Matcher numberMatcher = Pattern.compile("[0-9]{7}").matcher(yourString) ;
if( matcher.find() ) {
numbers = matcher.group(0) ;
}
Validation (HTML5): Attribute 'name' is not a valid attribute of element 'label'.
If i understand correctly, can't you simply use:
foreach($arr as $key=>$value)
{
echo $key;
}
See PHP manual
BUILD_NUMBER
is the current build number. You can use it in the command you execute for the job, or just use it in the script your job executes.
See the Jenkins documentation for the full list of available environment variables. The list is also available from within your Jenkins instance at http://hostname/jenkins/env-vars.html.
The slice() method returns a copy of a portion of an array into a new array object.
$scope.participantForms.slice(index, 1);
This does NOT change the participantForms
array but returns a new array containing the single element found at the index
position in the original array.
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
$scope.participantForms.splice(index, 1);
This will remove one element from the participantForms
array at the index
position.
These are the Javascript native functions, AngularJS has nothing to do with them.
I got rid of this problem by deleting the Bin
and Gen
folder from project(which automatically come back when the project will build) and then cleaning the project from ->Menu -> Project -> clean.
Thanks.
Replace this line:
count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments
With this one:
coalesce(sum(ccc_news_comments.id = 'approved'), 0) comments
In my case this helped:
$ export LDFLAGS="-L/usr/local/opt/openssl/lib"
$ export CPPFLAGS="-I/usr/local/opt/openssl/include"
Then:
gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/' -- --with-cppflags=-I/usr/local/opt/openssl/include --with-ldflags=-L/usr/local/opt/openssl/lib
Result:
Building native extensions with: '--with-cppflags=-I/usr/local/opt/openssl/include --with-ldflags=-L/usr/local/opt/openssl/lib'
This could take a while...
Successfully installed mysql2-0.5.2
Parsing documentation for mysql2-0.5.2
Installing ri documentation for mysql2-0.5.2
Done installing documentation for mysql2 after 0 seconds
1 gem installed
See this post (WARNING: Japanese language inside).
You can use this but there remains a security issue
<script type="text/javascript">
function fnc1()
{
var a=window.location.href;
username="p";
password=1234;
window.open(a+'?username='+username+'&password='+password,"");
}
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext" />
INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)
It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1
is null or ConfigurationManager.AppSettings.Get("Url")
is returning null.
As error message said your application has no permissions to read from the directory. It can be the case when you created the directory as one user and run script as another user.
This is the default working setup https://www.youtube.com/watch?v=XiD7JTCBdpI
Use Connection Method: standard TCP/IP over ssh
Then ssh hostname: 127.0.0.1:2222
SSH Username: vagrant password vagrant
MySQL Hostname: localhost
Username: homestead password:secret
GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH
. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:
export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).
My npm install
worked fine, but I had this problem with npm update
. To fix it, I had to run npm cache clean
and then npm cache clear
.
The simplest solution is to use option -B or --databases.Then CREATE database command appears in the output file. For example:
mysqldump -uuser -ppassword -d -B --events --routines --triggers database_example > database_example.sql
Here is a dumpfile's header:
-- MySQL dump 10.13 Distrib 5.5.36-34.2, for Linux (x86_64)
--
-- Host: localhost Database: database_example
-- ------------------------------------------------------
-- Server version 5.5.36-34.2-log
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Current Database: `database_example`
--
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_example` /*!40100 DEFAULT CHARACTER SET utf8 */;
If you only want to read the first 999,999 (non-header) rows:
read_csv(..., nrows=999999)
If you only want to read rows 1,000,000 ... 1,999,999
read_csv(..., skiprows=1000000, nrows=999999)
nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*
skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file
and for large files, you'll probably also want to use chunksize:
chunksize : int, default None Return TextFileReader object for iteration
Given the, most than probable similarities in performance, use whatever feel more correct and readable to the piece of code you're using.
I feel an operation that describes an addition, being the presence of the key already a really rare exception is best represented with the add. Semantically it makes more sense.
The dict[key] = value
represents better a substitution. If I see that code I half expect the key to already be in the dictionary anyway.
To extend the given answer with few useful tricks:
var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
bounds.extend(markers[i].getPosition());
}
//center the map to a specific spot (city)
map.setCenter(center);
//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
map.setZoom(15);
}
//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
map.setMaxZoom(15);
map.fitBounds(bounds);
map.setMaxZoom(Null)
}
UPDATE:
Further research in the topic show that fitBounds() is a asynchronic
and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
this.setZoom(map.getZoom()-1);
if (this.getZoom() > 15) {
this.setZoom(15);
}
});
map.fitBounds(bounds);
assuming both elements have 50% width, here is what i used:
css:
.parent {
width: 100%;
display: flex;
}
.child-1 {
width: 50%;
margin-right: -50%;
margin-left: 50%;
background: #ff0;
}
.child-2 {
width: 50%;
margin-right: 50%;
margin-left: -50%;
background: #0f0;
}
html:
<div class="parent">
<div class="child-1">child1</div>
<div class="child-2">child2</div>
</div>
example: https://jsfiddle.net/gzveri/o6umhj53/
btw, this approach works for any 2 nearby elements in a long list of elements. For example I have a long list of elements with 2 items per row and I want each 3-rd and 4-th element in the list to be swapped, so that it renders elements in a chess style, then I use these rules:
.parent > div:nth-child(4n+3) {
margin-right: -50%;
margin-left: 50%;
}
.parent > div:nth-child(4n+4) {
margin-right: 50%;
margin-left: -50%;
}
In case anyone wanted more of a visual reference:
Decimal approximations reference table:
+----------------------------------------------------------------------------+
¦ aspect ratio ¦ decimal approx. ¦ decimal approx. ¦
¦ [long edge x short edge] ¦ [short edge/long edge] ¦ [long edge/short edge] ¦
¦--------------------------+------------------------+------------------------¦
¦ 19.5 x 9 ¦ 0.462... ¦ 2.167... ¦
¦--------------------------+------------------------+------------------------¦
¦ 19 x 9 ¦ 0.474... ¦ 2.11... ¦
¦--------------------------+------------------------+------------------------¦
¦ ~18.7 x 9 ¦ 0.482... ¦ 2.074... ¦
¦--------------------------+------------------------+------------------------¦
¦ 18.5 x 9 ¦ 0.486... ¦ 2.056... ¦
¦--------------------------+------------------------+------------------------¦
¦ 18 x 9 ¦ 0.5 ¦ 2 ¦
¦--------------------------+------------------------+------------------------¦
¦ 19 x 10 ¦ 0.526... ¦ 1.9 ¦
¦--------------------------+------------------------+------------------------¦
¦ 16 x 9 ¦ 0.5625 ¦ 1.778... ¦
¦--------------------------+------------------------+------------------------¦
¦ 5 x 3 ¦ 0.6 ¦ 1.667... ¦
¦--------------------------+------------------------+------------------------¦
¦ 16 x 10 ¦ 0.625 ¦ 1.6 ¦
¦--------------------------+------------------------+------------------------¦
¦ 3 x 2 ¦ 0.667... ¦ 1.5 ¦
¦--------------------------+------------------------+------------------------¦
¦ 4 x 3 ¦ 0.75 ¦ 1.333... ¦
+----------------------------------------------------------------------------+
Changelog:
56x27 === ~18.7x9
(Huawei P20), 19x9
(Nokia X6 2018) and 19.5x9
(LG G7 ThinQ)19x10
(Essential Phone)18.5x9
(Samsung Galaxy S8) and 18x9
(LG G6)For those looking for a version of Roman Pekar's answer that avoids manual column naming:
column_to_explode = 'samples'
res = (df
.set_index([x for x in df.columns if x != column_to_explode])[column_to_explode]
.apply(pd.Series)
.stack()
.reset_index())
res = res.rename(columns={
res.columns[-2]:'exploded_{}_index'.format(column_to_explode),
res.columns[-1]: '{}_exploded'.format(column_to_explode)})
Yes, add the -Force
parameter.
copy-item $from $to -Recurse -Force
Here's a simple example:
public class ObservableClass
{
private Int32 _Value;
public Int32 Value
{
get { return _Value; }
set
{
if (_Value != value)
{
_Value = value;
OnValueChanged();
}
}
}
public event EventHandler ValueChanged;
protected void OnValueChanged()
{
if (ValueChanged != null)
ValueChanged(this, EventArgs.Empty);
}
}
public class ObserverClass
{
public ObserverClass(ObservableClass observable)
{
observable.ValueChanged += TheValueChanged;
}
private void TheValueChanged(Object sender, EventArgs e)
{
Console.Out.WriteLine("Value changed to " +
((ObservableClass)sender).Value);
}
}
public class Program
{
public static void Main()
{
ObservableClass observable = new ObservableClass();
ObserverClass observer = new ObserverClass(observable);
observable.Value = 10;
}
}
Note:
ALTER TABLE `tablename` DROP `columnname`;
Or,
ALTER TABLE `tablename` DROP COLUMN `columnname`;
Try this:
if( $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
// authenticated (NON anonymous)
}
Further information:
"Anonymous users are technically authenticated, meaning that the isAuthenticated() method of an anonymous user object will return true. To check if your user is actually authenticated, check for the IS_AUTHENTICATED_FULLY role."
Usually, you would do something like this:
$post_data = json_encode(array('item' => $post_data));
But, as it seems you want the output to be with "{}
", you better make sure to force json_encode()
to encode as object, by passing the JSON_FORCE_OBJECT
constant.
$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);
"{}
" brackets specify an object and "[]
" are used for arrays according to JSON specification.
You can also use
ExpectedConditions.ElementExists
So you will search for an element availability like that
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementExists((By.Id(login))));
You want to use a FrameLayout or a Merge layout to achieve this. Android dev guide has a great example of this here: Android Layout Tricks #3: Optimize by merging.
The error you are getting is either because you are doing TO_DATE
on a column that's already a date, and you're using a format mask that is different to your nls_date_format
parameter[1] or because the event_occurrence column contains data that isn't a number.
You need to a) correct your query so that it's not using TO_DATE on the date column, and b) correct your data, if event_occurrence is supposed to be just numbers.
And fix the datatype of that column to make sure you can only store numbers.
[1] What Oracle does when you do: TO_DATE(date_column, non_default_format_mask)
is:
TO_DATE(TO_CHAR(date_column, nls_date_format), non_default_format_mask)
Generally, the default nls_date_format
parameter is set to dd-MON-yy
, so in your query, what is likely to be happening is your date column is converted to a string in the format dd-MON-yy, and you're then turning it back to a date using the format MMDD. The string is not in this format, so you get an error.
I've found a solution for this
Create a custom transparent dialog and inside that dialog open the popup window:
dialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar);
emptyDialog = LayoutInflater.from(context).inflate(R.layout.empty, null);
/* blur background*/
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.dimAmount=0.0f;
dialog.getWindow().setAttributes(lp);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
dialog.setContentView(emptyDialog);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnShowListener(new OnShowListener()
{
@Override
public void onShow(DialogInterface dialogIx)
{
mQuickAction.show(emptyDialog); //open the PopupWindow here
}
});
dialog.show();
xml for the dialog(R.layout.empty):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent" android:layout_width="match_parent"
style="@android:style/Theme.Translucent.NoTitleBar" />
now you want to dismiss the dialog when Popup window dismisses. so
mQuickAction.setOnDismissListener(new OnDismissListener()
{
@Override
public void onDismiss()
{
if(dialog!=null)
{
dialog.dismiss(); // dismiss the empty dialog when the PopupWindow closes
dialog = null;
}
}
});
Note: I've used NewQuickAction
plugin for creating PopupWindow here. It can also be done on native Popup Windows
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if(segue!.identifier){
var name = segue!.identifier;
if (name.compare("Load View") == 0){
}
}
}
You can't compare the the identifier with == you have to use the compare() method
view.subviews.forEach { $0.removeFromSuperview() }
You can also use CURRENT_TIMESTAMP
, if you feel like being more ANSI compliant (though if you're porting code between database vendors, that'll be the least of your worries). It's exactly the same as GetDate()
under the covers (see this question for more on that).
There's no ANSI equivalent for GetUTCDate()
, however, which is probably the one you should be using if your app operates in more than a single time zone ...
Also you can use this
private static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);
it's the most simple method
3D case
Modifying Mohsen's answer for 3D array:
[M,I] = max (A(:));
[ind1, ind2, ind3] = ind2sub(size(A),I)
If your entity is mapped through annotations, add the following code to your configuration;
configuration.addAnnotatedClass(theEntityPackage.EntityClassName.class);
For example;
configuration.addAnnotatedClass(com.foo.foo1.Products.class);
if your entity is mapped with xml file, use addClass instead of addAnnotatedClass.
As an example;
configuration.addClass(com.foo.foo1.Products.class);
Ping me if you need more help.
this does not refresh your component I solved the problem by using Vux create a module for vuex "page"
export const state = {
currentScrollY: 0,
};
export const getters = {
currentScrollY: s => s.currentScrollY
};
export const actions = {
setCurrentScrollY ({ commit }, y) {
commit('setCurrentScrollY', {y});
},
};
export const mutations = {
setCurrentScrollY (s, {y}) {
s.currentScrollY = y;
},
};
export default {
state,
getters,
actions,
mutations,
};
in App.vue :
created() {
window.addEventListener("scroll", this.handleScroll);
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll () {
this.$store.dispatch("page/setCurrentScrollY", window.scrollY);
}
},
in your component :
computed: {
currentScrollY() {
return this.$store.getters["page/currentScrollY"];
}
},
watch: {
currentScrollY(val) {
if (val > 100) {
this.isVisibleStickyMenu = true;
} else {
this.isVisibleStickyMenu = false;
}
}
},
and it works great.
I realize this is an old post, but it ranks high in Google, so I'm adding what I figured out for MY problem. If you have a mix of table types (e.g. MyISAM and InnoDB), you will get this error as well. In this case, InnoDB is the default table type, but one table needed fulltext searching so it was migrated to MyISAM. In this situation, you cannot create a foreign key in the InnoDB table that references the MyISAM table.
You're trying to pass file objects as filenames. Try using
infile = '110331_HS1A_1_rtTA.result'
outfile = '2.txt'
at the top of your code.
(Not only does the doubled usage of open()
cause that problem with trying to open the file again, it also means that infile
and outfile
are never closed during the course of execution, though they'll probably get closed once the program ends.)
Without using regular expressions:
while (myString.IndexOf(" ", StringComparison.CurrentCulture) != -1)
{
myString = myString.Replace(" ", " ");
}
OK to use on short strings, but will perform badly on long strings with lots of spaces.
I got rid of this warning by changing the "Swift 3 @objc Inference" build setting of my targets to "Default".
From this article:
Before Swift 4, the compiler made some Swift declarations automatically available to Objective-C. For example, if one subclassed from NSObject, the compiler created Objective-C entry points for all methods in such classes. The mechanism is called @objc inference.
In Swift 4, such automatic @objc inference is deprecated because it is costly to generate all those Objective-C entry points. When "Swift 3 @objc Inference" setting is set to "On", it allows the old code to work. However, it will show deprecation warnings that need to be addressed. It is recommended to "fix" these warnings and switch the setting to "Default", which is the default for new Swift projects.
Please also refer to this Swift proposal for more information.
If you are using Bootstrap, look at padding
of your td
s.
To simple clear everything do:
$ docker system prune --all
Everything means:
- all stopped containers
- all networks not used by at least one container
- all images without at least one container associated to them
- all build cache
The default value of "spark.master" is spark://HOST:PORT, and the following code tries to get a session from the standalone cluster that is running at HOST:PORT, and expects the HOST:PORT value to be in the spark config file.
SparkSession spark = SparkSession
.builder()
.appName("SomeAppName")
.getOrCreate();
"org.apache.spark.SparkException: A master URL must be set in your configuration" states that HOST:PORT is not set in the spark configuration file.
To not bother about value of "HOST:PORT", set spark.master as local
SparkSession spark = SparkSession
.builder()
.appName("SomeAppName")
.config("spark.master", "local")
.getOrCreate();
Here is the link for list of formats in which master URL can be passed to spark.master
Reference : Spark Tutorial - Setup Spark Ecosystem
element.style
has a setProperty
method that can take the priority as a third parameter:
element.style.setProperty("display", "inline", "important")
It didn't work in old IEs but it should be fine in current browsers.
Basically, all Maven is telling you is that certain dependencies in your project are not available in the central maven repository. The default is to look in your local .m2 folder (local repository), and then any configured repositories in your POM, and then the central maven repository. Look at the repositories section of the Maven reference.
The problem is that the project that was checked in didn't configure the POM in such a way that all the dependencies could be found and the project could be built from scratch.
Right click on the table and click on Design,then click on column that you want to set default value.
Then in bottom of page in column properties set Default value or binding to : 'getdate()'
This can be done easily by first using tr
to replace the newlines with some other character:
tr '\n' '\a' | grep -o 'abc.*def' | tr '\a' '\n'
Here, I am using the alarm character, \a
(ASCII 7) in place of a newline.
This is almost never found in your text, and grep
can match it with a .
, or match it specifically with \a
.
if ( $("#anid").length ) {
alert("element(s) found")
}
else {
alert("nothing found")
}
This is a one line solution involving LINQ.
var elements = new String[] { "1", "2", "3" };
Foo(elements.Cast<object>().ToArray())
Indeed, window.location.origin works fine in browsers following standards, but guess what. IE isn't following standards.
So because of that, this is what worked for me in IE, FireFox and Chrome:
var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
but for possible future enhancements which could cause conflicts, I specified the "window" reference before the "location" object.
var full = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: '');
Asp:Hyperlink http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlink.aspx
Works on UBUNTU 18.04
Edit file: '/usr/share/phpmyadmin/libraries/sql.lib.php'
Replace: (count($analyzed_sql_results['select_expr'] == 1)
With: ((count($analyzed_sql_results['select_expr']) == 1)
Restart the server
sudo service apache2 restart
Try:
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
1.->
for accessing object member variables and methods via pointer
to object
Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();
2..
for accessing object member variables and methods via object instance
Foo foo;
foo.member_var = 10;
foo.member_func();
3.::
for accessing static variables and methods of a class/struct
or namespace
. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)
int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();
for swift 3 and Xcode 8.2 (nice to have blocks, but if You compile for iOS9 AND want userInfo):
...
self.timer = Timer(fireAt: fire,
interval: deltaT,
target: self,
selector: #selector(timerCallBack(timer:)),
userInfo: ["custom":"data"],
repeats: true)
RunLoop.main.add(self.timer!, forMode: RunLoopMode.commonModes)
self.timer!.fire()
}
func timerCallBack(timer: Timer!){
let info = timer.userInfo
print(info)
}
Try the CURRENT_USER()
function. This returns the username that MySQL used to authenticate your client connection. It is this username that determines your privileges.
This may be different from the username that was sent to MySQL by the client (for example, MySQL might use an anonymous account to authenticate your client, even though you sent a username). If you want the username the client sent to MySQL when connecting use the USER()
function instead.
The value indicates the user name you specified when connecting to the server, and the client host from which you connected. The value can be different from that of CURRENT_USER().
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_current-user
The menu location seems to have changed to:
Query Designer --> Pane --> SQL
and you can do that by simple code:
filter:alpha(opacity=30);
-moz-opacity:0.3;
-khtml-opacity: 0.3;
opacity: 0.3;
You can avoid any focus on your elements by setting the attribute android:descendantFocusability of the parent element.
Here is an example:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/search__scroller"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ScrollView>
Here, the attribute android:descendantFocusability set to "blocksDescendants" is blocking the focus on the child elements.
You can find more info here.
As far as I know, the most pythonic/efficient method would be:
import string
filtered_string = filter(lambda x: x in string.printable, myStr)
In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj)
in your ModelForm.save
override, as ModelForm.save
later populates your m2m from self.cleaned_data['my_m2m']
which overwrites your changes. Instead call:
my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms
(It is fine to convert the incoming QuerySet to a list - the ManyToManyField
does that anyway.)
EDIT 7/1/15:
I wrote this answer a pretty long time ago and haven't been keeping up a lot with angular for a while, but it seems as though this answer is still relatively popular, so I wanted to point out that a couple of the point @nicolas makes below are good. For one, injecting $rootScope and attaching the helpers there will keep you from having to add them for every controller. Also - I agree that if what you're adding should be thought of as Angular services OR filters, they should be adopted into the code in that manner.
Also, as of the current version 1.4.2, Angular exposes a "Provider" API, which is allowed to be injected into config blocks. See these resources for more:
https://docs.angularjs.org/guide/module#module-loading-dependencies
AngularJS dependency injection of value inside of module.config
I don't think I'm going to update the actual code blocks below, because I'm not really actively using Angular these days and I don't really want to hazard a new answer without feeling comfortable that it's actually conforming to new best practices. If someone else feels up to it, by all means go for it.
EDIT 2/3/14:
After thinking about this and reading some of the other answers, I actually think I prefer a variation of the method brought up by @Brent Washburne and @Amogh Talpallikar. Especially if you're looking for utilities like isNotString() or similar. One of the clear advantages here is that you can re-use them outside of your angular code and you can use them inside of your config function (which you can't do with services).
That being said, if you're looking for a generic way to re-use what should properly be services, the old answer I think is still a good one.
What I would do now is:
app.js:
var MyNamespace = MyNamespace || {};
MyNamespace.helpers = {
isNotString: function(str) {
return (typeof str !== "string");
}
};
angular.module('app', ['app.controllers', 'app.services']).
config(['$routeProvider', function($routeProvider) {
// Routing stuff here...
}]);
controller.js:
angular.module('app.controllers', []).
controller('firstCtrl', ['$scope', function($scope) {
$scope.helpers = MyNamespace.helpers;
});
Then in your partial you can use:
<button data-ng-click="console.log(helpers.isNotString('this is a string'))">Log String Test</button>
Old answer below:
It might be best to include them as a service. If you're going to re-use them across multiple controllers, including them as a service will keep you from having to repeat code.
If you'd like to use the service functions in your html partial, then you should add them to that controller's scope:
$scope.doSomething = ServiceName.functionName;
Then in your partial you can use:
<button data-ng-click="doSomething()">Do Something</button>
Here's a way you might keep this all organized and free from too much hassle:
Separate your controller, service and routing code/config into three files: controllers.js, services.js, and app.js. The top layer module is "app", which has app.controllers and app.services as dependencies. Then app.controllers and app.services can be declared as modules in their own files. This organizational structure is just taken from Angular Seed:
app.js:
angular.module('app', ['app.controllers', 'app.services']).
config(['$routeProvider', function($routeProvider) {
// Routing stuff here...
}]);
services.js:
/* Generic Services */
angular.module('app.services', [])
.factory("genericServices", function() {
return {
doSomething: function() {
//Do something here
},
doSomethingElse: function() {
//Do something else here
}
});
controller.js:
angular.module('app.controllers', []).
controller('firstCtrl', ['$scope', 'genericServices', function($scope, genericServices) {
$scope.genericServices = genericServices;
});
Then in your partial you can use:
<button data-ng-click="genericServices.doSomething()">Do Something</button>
<button data-ng-click="genericServices.doSomethingElse()">Do Something Else</button>
That way you only add one line of code to each controller and are able to access any of the services functions wherever that scope is accessible.
var table=document.getElementById("mytab1");_x000D_
var r=0; //start counting rows in table_x000D_
while(row=table.rows[r++])_x000D_
{_x000D_
var c=0; //start counting columns in row_x000D_
while(cell=row.cells[c++])_x000D_
{_x000D_
cell.innerHTML='[R'+r+'C'+c+']'; // do sth with cell_x000D_
}_x000D_
}
_x000D_
<table id="mytab1">_x000D_
<tr>_x000D_
<td>A1</td><td>A2</td><td>A3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>B1</td><td>B2</td><td>B3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>C1</td><td>C2</td><td>C3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
In each pass through while loop r/c iterator increases and new row/cell object from collection is assigned to row/cell variables. When there's no more rows/cells in collection, false is assigned to row/cell variable and iteration through while loop stops (exits).
I know that this is rather old also. I recently had a need to create a context menu that I inject into other sites that have different properties based n the element clicked.
It's rather rough, and there are probable better ways to achieve this. It uses the jQuery Context menu Library Located Here
I enjoyed creating it and though that you guys might have some use out of it.
Here is the fiddle. I hope that it can hopefully help someone out there.
$(function() {
function createSomeMenu() {
var all_array = '{';
var x = event.clientX,
y = event.clientY,
elementMouseIsOver = document.elementFromPoint(x, y);
if (elementMouseIsOver.closest('a')) {
all_array += '"Link-Fold": {"name": "Link", "icon": "fa-external-link", "items": {"fold2-key1": {"name": "Open Site in New Tab"}, "fold2-key2": {"name": "Open Site in Split Tab"}, "fold2-key3": {"name": "Copy URL"}}},';
}
if (elementMouseIsOver.closest('img')) {
all_array += '"Image-Fold": {"name": "Image","icon": "fa-picture-o","items": {"fold1-key1": {"name":"Download Image"},"fold1-key2": {"name": "Copy Image Location"},"fold1-key3": {"name": "Go To Image"}}},';
}
all_array += '"copy": {"name": "Copy","icon": "copy"},"paste": {"name": "Paste","icon": "paste"},"edit": {"name": "Edit HTML","icon": "fa-code"}}';
return JSON.parse(all_array);
}
// setup context menu
$.contextMenu({
selector: 'body',
build: function($trigger, e) {
return {
callback: function(key, options) {
var m = "clicked: " + key;
console.log(m);
},
items: createSomeMenu()
};
}
});
});
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
If you add file ipython_config.py into the ~/.ipython/profile_default directory with lines like below, then the autoreload functionality will be loaded on IPython startup (tested on 2.0.0):
print "--------->>>>>>>> ENABLE AUTORELOAD <<<<<<<<<------------"
c = get_config()
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
Just add "D".
int i = 6;
double d = i / 2D; // This will divide bei double.
System.out.println(d); // This will print a double. = 3D
If usb is not working you should checkout debugging over bluetooth (Without Rooting)
http://zcourts.com/2013/07/19/android-debugging-over-bluetooth-without-root/#sthash.hVCLtWSk.dpbs
Cast them to a Number
$('#total_price').val(Number(a)+Number(b));
But before you do that
if (!isNaN($('input[name=service_price]').val()) {...
How about print (x, y)
at once.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
for xy in zip(A, B): # <--
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--
plt.grid()
plt.show()
Really the trade off you are making (in a large project) is in initial load time, the libraries are going to get linked at one time or another, the decision that has to be made is will the link take long enough that the compiler needs to bite the bullet and do it up front, or can the dynamic linker do it at load time.
For Java 8 it's very easy:
List < UserEntity > vList= new ArrayList<>();
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());
In Terminal type gradlew clean. it will automatically download and install gradle version 2.10(ie latest gradle verson available)
Eg : C:\android\workspace\projectname>gradlew clean
At some point, isn't it easier(or just as easy) to use a forEach
var options = [_x000D_
{ name: 'One', assigned: true }, _x000D_
{ name: 'Two', assigned: false }, _x000D_
{ name: 'Three', assigned: true }, _x000D_
];_x000D_
_x000D_
var reduced = []_x000D_
options.forEach(function(option) {_x000D_
if (option.assigned) {_x000D_
var someNewValue = { name: option.name, newProperty: 'Foo' }_x000D_
reduced.push(someNewValue);_x000D_
}_x000D_
});_x000D_
_x000D_
document.getElementById('output').innerHTML = JSON.stringify(reduced);
_x000D_
<h1>Only assigned options</h1>_x000D_
<pre id="output"> </pre>
_x000D_
However it would be nice if there was a malter()
or fap()
function that combines the map
and filter
functions. It would work like a filter, except instead of returning true or false, it would return any object or a null/undefined.
As with all good examples, you've simplified what you're actually trying to do. This is good, but it is worth noting that python has a lot of flexibility when it comes to class versus instance variables. The same can be said of methods. For a good list of possibilities, I recommend reading Michael Fötsch' new-style classes introduction, especially sections 2 through 6.
One thing that takes a lot of work to remember when getting started is that python is not java. More than just a cliche. In java, an entire class is compiled, making the namespace resolution real simple: any variables declared outside a method (anywhere) are instance (or, if static, class) variables and are implicitly accessible within methods.
With python, the grand rule of thumb is that there are three namespaces that are searched, in order, for variables:
{begin pedagogy}
There are limited exceptions to this. The main one that occurs to me is that, when a class definition is being loaded, the class definition is its own implicit namespace. But this lasts only as long as the module is being loaded, and is entirely bypassed when within a method. Thus:
>>> class A(object):
foo = 'foo'
bar = foo
>>> A.foo
'foo'
>>> A.bar
'foo'
but:
>>> class B(object):
foo = 'foo'
def get_foo():
return foo
bar = get_foo()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
class B(object):
File "<pyshell#11>", line 5, in B
bar = get_foo()
File "<pyshell#11>", line 4, in get_foo
return foo
NameError: global name 'foo' is not defined
{end pedagogy}
In the end, the thing to remember is that you do have access to any of the variables you want to access, but probably not implicitly. If your goals are simple and straightforward, then going for Foo.bar or self.bar will probably be sufficient. If your example is getting more complicated, or you want to do fancy things like inheritance (you can inherit static/class methods!), or the idea of referring to the name of your class within the class itself seems wrong to you, check out the intro I linked.
This information is outdated as of now, but cannot be deleted.
You can create File
instances just by specifying a path when your code is chrome-privileged:
new File("/path/to/file");
File
is a sub-class of Blob
, so all File
instances are also valid Blob
s.
Please note that this requires a platform path, and not a file URL.
Yes, FileReader
is available to addons.
File
and FileReader
are available in all window
s. If you want to use them in a non-window scope (like bootstrap.js
or a code module), you may use nsIDOMFile
/nsIDOMFileReader
.
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
Here it is:
[chr(i) for i in xrange(127)]
Try something like:
$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
SQLite has hooks built-in for encryption which are not used in the normal distribution, but here are a few implementations I know of:
The SEE and SQLiteCrypt require the purchase of a license.
Disclosure: I created botansqlite3.
To add second message you need to -
IEnumerable<T> items = new T[]{new T("msg")};
items = items.Concat(new[] {new T("msg2")})
If for some reason you don't like interactive editors, you can use git rebase --onto
.
Say you want to modify Commit1
. First, branch from before Commit1
:
git checkout -b amending [commit before Commit1]
Second, grab Commit1
with cherry-pick
:
git cherry-pick Commit1
Now, amend your changes, creating Commit1'
:
git add ...
git commit --amend -m "new message for Commit1"
And finally, after having stashed any other changes, transplant the rest of your commits up to master
on top of your
new commit:
git rebase --onto amending Commit1 master
Read: "rebase, onto the branch amending
, all commits between Commit1
(non-inclusive) and master
(inclusive)". That is, Commit2 and Commit3, cutting the old Commit1 out entirely. You could just cherry-pick them, but this way is easier.
Remember to clean up your branches!
git branch -d amending
Code updated for Swift 3
Swift code
import UIKit
class ViewController: UIViewController {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
@IBOutlet weak var myBlueSubview: UIView!
@IBAction func showButtonTapped(sender: UIButton) {
activityIndicator.startAnimating()
}
@IBAction func hideButtonTapped(sender: UIButton) {
activityIndicator.stopAnimating()
}
override func viewDidLoad() {
super.viewDidLoad()
// set up activity indicator
activityIndicator.center = CGPoint(x: myBlueSubview.bounds.size.width/2, y: myBlueSubview.bounds.size.height/2)
activityIndicator.color = UIColor.yellow
myBlueSubview.addSubview(activityIndicator)
}
}
Notes
You can center the activity indicator in middle of the screen by adding it as a subview to the root view
rather than myBlueSubview
.
activityIndicator.center = CGPoint(x: self.view.bounds.size.width/2, y: self.view.bounds.size.height/2)
self.view.addSubview(activityIndicator)
You can also create the UIActivityIndicatorView
in the Interface Builder. Just drag an Activity Indicator View onto the storyboard and set the properties. Be sure to check Hides When Stopped. Use an outlet to call startAnimating()
and stopAnimating()
. See this tutorial.
Remember that the default color of the LargeWhite
style is white. So if you have a white background you can't see it, just change the color to black or whatever other color you want.
activityIndicator.color = UIColor.black
A common use case would be while a background task runs. Here is an example:
// start animating before the background task starts
activityIndicator.startAnimating()
// background task
DispatchQueue.global(qos: .userInitiated).async {
doSomethingThatTakesALongTime()
// return to the main thread
DispatchQueue.main.async {
// stop animating now that background task is finished
self.activityIndicator.stopAnimating()
}
}
adb -d shell
run-as com.your.packagename cat databases/database.db > /sdcard/database.db
cd /sdcard
to make sure database.db
is there.adb pull /sdcard/database.db
or simply you can copy database.db from device .I dont know about SmallSQL, but this works for MSSQL:
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
Based on the where-condition, this updates the row if it exists, else it will insert a new one.
I hope that's what you were looking for.
It's working for me:
<%= image_tag( root_url + "images/rss.jpg", size: "50x50", :alt => "rss feed") -%>
Have you tried using the replaceAll method to replace any occurence of \n or \r with the empty String?
Computed could be consider has a function. So for an exemple on valdiation you could clearly do something like :
methods: {
validation(attr){
switch(attr) {
case 'email':
const re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
return re.test(this.form.email);
case 'password':
return this.form.password.length > 4
}
},
...
}
Which you'll be using like :
<b-form-input
id="email"
v-model="form.email"
type="email"
:state="validation('email')"
required
placeholder="Enter email"
></b-form-input>
Just keep in mind that you will still miss the caching specific to computed.
Google Sheets now have a duration formatting option. Select: Format -> Number -> Duration.
get radio value by name
$('input').on('className', function(event){
console.log($(this).attr('name'));
if($(this).attr('name') == "worker")
{
resetAll();
}
});
No floating point operations are done below. This is faster and will tolerate higher arguments. The reason you must go only to the square-root is that if a number has a factor larger than its square root, it also has a factor smaller than it.
def is_prime(n):
""""pre-condition: n is a nonnegative integer
post-condition: return True if n is prime and False otherwise."""
if n < 2:
return False;
if n % 2 == 0:
return n == 2 # return False
k = 3
while k*k <= n:
if n % k == 0:
return False
k += 2
return True
First you need to remember that in Unix and Linux, everything is a file, even directories. For a file to have the rights to be executed as a command, it needs to satisfy 3 conditions:
So this can be done simply with:
[ -f "${file}" ] && [ -r "${file}" ] && [ -x "${file}" ]
If your file is a symbolic link to a regular file, the test command will operate on the target and not the link-name. So the above command distinguishes if a file can be used as a command or not. So there is no need to pass the file first to realpath
or readlink
or any of those variants.
If the file can be executed on the current OS, that is a different question. Some answers above already pointed to some possibilities for that, so there is no need to repeat it here.
position: fixed;
bottom: 0;
(if needs element in whole display and left align)
left:0;
width: 100%;
You could basically use html tags in your string resource like:
<resource>
<string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string>
</resources>
And use Html.fromHtml or use spannable, check the link I posted.
Old similar question: Is it possible to have multiple styles inside a TextView?
problem is, it is not converted to proper format. Use function "printPreview(binaryPDFData)" to get print preview dialog of binary pdf data. you can comment script part if you don't want print dialog open.
printPreview = (data, type = 'application/pdf') => {
let blob = null;
blob = this.b64toBlob(data, type);
const blobURL = URL.createObjectURL(blob);
const theWindow = window.open(blobURL);
const theDoc = theWindow.document;
const theScript = document.createElement('script');
function injectThis() {
window.print();
}
theScript.innerHTML = `window.onload = ${injectThis.toString()};`;
theDoc.body.appendChild(theScript);
};
b64toBlob = (content, contentType) => {
contentType = contentType || '';
const sliceSize = 512;
// method which converts base64 to binary
const byteCharacters = window.atob(content);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {
type: contentType
}); // statement which creates the blob
return blob;
};
try this. There are in general three ways to use mysqldump—
in order to dump a set of one or more tables,
shell> mysqldump [options] db_name [tbl_name ...]
a set of one or more complete databases
shell> mysqldump [options] --databases db_name ...
or an entire MySQL server—as shown here:
shell> mysqldump [options] --all-databases
While the above answers are probably best for this situation, if you just want to do a one-off and don't want to bother with modifying other files, you can in-line the CSS.
<p style="margin-bottom:3cm;">This is the first question?</p>
'data' should be a stringified JavaScript object:
data: JSON.stringify({ "userName": userName, "password" : password })
To send your formData
, pass it to stringify
:
data: JSON.stringify(formData)
Some servers also require the application/json
content type:
contentType: 'application/json'
There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice
I had the same issue in cPanel 92.0.3
and it was solved through this solution:
In cPanel
go to the below directory
software --> select PHP version--> option--> upload_max_filesize
Then choose the optional size
to upload your files.
I used requests-mock for writing tests for separate module:
# module.py
import requests
class A():
def get_response(self, url):
response = requests.get(url)
return response.text
And the tests:
# tests.py
import requests_mock
import unittest
from module import A
class TestAPI(unittest.TestCase):
@requests_mock.mock()
def test_get_response(self, m):
a = A()
m.get('http://aurl.com', text='a response')
self.assertEqual(a.get_response('http://aurl.com'), 'a response')
m.get('http://burl.com', text='b response')
self.assertEqual(a.get_response('http://burl.com'), 'b response')
m.get('http://curl.com', text='c response')
self.assertEqual(a.get_response('http://curl.com'), 'c response')
if __name__ == '__main__':
unittest.main()
i've had the same issue on Spring Tool Suite (STS) and turns out, all i had to do was update my proxy settings in STS network config.
window > preferences > General > Network Connections and on the dropdown select "Manual" from "Native".
Here, just add your proxy url, port and your credentials for http and https by clicking on edit. Apply and close.
Hope it works for you.
This worked for me:
& 'D:\Server\PSTools\PsExec.exe' @('\\1.1.1.1', '-accepteula', '-d', '-i', $id, '-h', '-u', 'domain\user', '-p', 'password', '-w', 'C:\path\to\the\app', 'java', '-jar', 'app.jar')
Just put paths or connection strings in one array item and split the other things in one array item each.
There are a lot of other options here: https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx
Microsoft should make this way simpler and compatible with command prompt syntax.
In the HTML which you have shared:
<div id="a">This is some
<div id="b">text</div>
</div>
The text This is some
is within a text node. To depict the text node in a structured way:
<div id="a">
This is some
<div id="b">text</div>
</div>
To extract and print the text This is some
from the text node using Selenium's python client you have 2 ways as follows:
Using splitlines()
: You can identify the parent element i.e. <div id="a">
, extract the innerHTML
and then use splitlines()
as follows:
using xpath:
print(driver.find_element_by_xpath("//div[@id='a']").get_attribute("innerHTML").splitlines()[0])
using xpath:
print(driver.find_element_by_css_selector("div#a").get_attribute("innerHTML").splitlines()[0])
Using execute_script()
: You can also use the execute_script()
method which can synchronously execute JavaScript in the current window/frame as follows:
using xpath and firstChild:
parent_element = driver.find_element_by_xpath("//div[@id='a']")
print(driver.execute_script('return arguments[0].firstChild.textContent;', parent_element).strip())
using xpath and childNodes[n]:
parent_element = driver.find_element_by_xpath("//div[@id='a']")
print(driver.execute_script('return arguments[0].childNodes[1].textContent;', parent_element).strip())
First, regarding this solution:
# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')
It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.
A better solution is to change sys.stdout
at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by "toka":
import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
This answer shows the python perspective. Jupyter supports various languages besides python.
Both Jupyter Notebook and Jupyterlab are browser compatible interactive python (i.e. python ".ipynb" files) environments, where you can divide the various portions of the code into various individually executable cells for the sake of better readability. Both of these are popular in Data Science/Scientific Computing domain.
I'd suggest you to go with Jupyterlab for the advantages over Jupyter notebooks:
I'd recommend using PIP to install Jupyterlab.
If you can't open a ".ipynb" file using Jupyterlab on Windows system, here are the steps:
I think the usual use case is to call it when no exception was thrown in a negative test.
Something like the following pseudo-code:
test_addNilThrowsNullPointerException()
{
try {
foo.add(NIL); // we expect a NullPointerException here
fail("No NullPointerException"); // cause the test to fail if we reach this
} catch (NullNullPointerException e) {
// OK got the expected exception
}
}
This piece of snippet is from c++ primer book. Although I am sure this is wrong.
Each type parameter must be preceded by the keyword class or typename:
// error: must precede U with either typename or class
template <typename T, U> T calc(const T&, const U&);
These keywords have the same meaning and can be used interchangeably inside a template parameter list. A template parameter list can use both keywords:
// ok: no distinction between typename and class in a template parameter list
template <typename T, class U> calc (const T&, const U&);
It may seem more intuitive to use the keyword typename rather than class to designate a template type parameter. After all, we can use built-in (nonclass) types as a template type argument. Moreover, typename more clearly indicates that the name that follows is a type name. However, typename was added to C++ after templates were already in widespread use; some programmers continue to use class exclusively
Button inputs don't have a submit event. Try attaching the event handler to the form instead:
<script type="text/javascript">
$('#login_form').submit(function() {
$('#gif').show();
return true;
});
</script>
You can try Wolfram Alpha as in this example based on your input:
you can use the views *_DEPENDENCIES
, for example:
SELECT owner, NAME
FROM dba_dependencies
WHERE referenced_owner = :table_owner
AND referenced_name = :table_name
AND TYPE IN ('PACKAGE', 'PACKAGE BODY')
When compiling for x64, the difference between int and long is somewhere between 0 and 4 bytes, depending on what compiler you use.
GCC uses the LP64 model, which means that ints are 32-bits but longs are 64-bits under 64-bit mode.
MSVC for example uses the LLP64 model, which means both ints and longs are 32-bits even in 64-bit mode.
$(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded like CSS, images and frames. One best example is if we want to get the actual image size or to get the details of anything we use it.
$(document).ready() indicates that code in it need to be executed once the DOM got loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.
<script type = "text/javascript">
//$(window).load was deprecated in 1.8, and removed in jquery 3.0
// $(window).load(function() {
// alert("$(window).load fired");
// });
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>
$(window).load fired after the $(document).ready().
$(window).load was deprecated in 1.8, and removed in jquery 3.0
Here is my solution to a modal that can be rendered on any screen and initialized in App.tsx
ModalComponent.tsx
import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet, Platform } from 'react-native';
import EventEmitter from 'events';
// I keep localization files for strings and device metrics like height and width which are used for styling
import strings from '../../config/strings';
import metrics from '../../config/metrics';
const emitter = new EventEmitter();
export const _modalEmitter = emitter
export class ModalView extends Component {
state: {
modalVisible: boolean,
text: string,
callbackSubmit: any,
callbackCancel: any,
animation: any
}
constructor(props) {
super(props)
this.state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {}),
animation: new Animated.Value(0)
}
}
componentDidMount() {
_modalEmitter.addListener(strings.modalOpen, (event) => {
var state = {
modalVisible: true,
text: event.text,
callbackSubmit: event.onSubmit,
callbackCancel: event.onClose,
animation: new Animated.Value(0)
}
this.setState(state)
})
_modalEmitter.addListener(strings.modalClose, (event) => {
var state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {}),
animation: new Animated.Value(0)
}
this.setState(state)
})
}
componentWillUnmount() {
var state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {})
}
this.setState(state)
}
closeModal = () => {
_modalEmitter.emit(strings.modalClose)
}
startAnimation=()=>{
Animated.timing(this.state.animation, {
toValue : 0.5,
duration : 500
}).start()
}
body = () => {
const animatedOpacity ={
opacity : this.state.animation
}
this.startAnimation()
return (
<View style={{ height: 0 }}>
<Modal
animationType="fade"
transparent={true}
visible={this.state.modalVisible}>
// render a transparent gray background over the whole screen and animate it to fade in, touchable opacity to close modal on click out
<Animated.View style={[styles.modalBackground, animatedOpacity]} >
<TouchableOpacity onPress={() => this.closeModal()} activeOpacity={1} style={[styles.modalBackground, {opacity: 1} ]} >
</TouchableOpacity>
</Animated.View>
// render an absolutely positioned modal component over that background
<View style={styles.modalContent}>
<View key="text_container">
<Text>{this.state.text}?</Text>
</View>
<View key="options_container">
// keep in mind the content styling is very minimal for this example, you can put in your own component here or style and make it behave as you wish
<TouchableOpacity
onPress={() => {
this.state.callbackSubmit();
}}>
<Text>Confirm</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.state.callbackCancel();
}}>
<Text>Cancel</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</View>
);
}
render() {
return this.body()
}
}
// to center the modal on your screen
// top: metrics.DEVICE_HEIGHT/2 positions the top of the modal at the center of your screen
// however you wanna consider your modal's height and subtract half of that so that the
// center of the modal is centered not the top, additionally for 'ios' taking into consideration
// the 20px top bunny ears offset hence - (Platform.OS == 'ios'? 120 : 100)
// where 100 is half of the modal's height of 200
const styles = StyleSheet.create({
modalBackground: {
height: '100%',
width: '100%',
backgroundColor: 'gray',
zIndex: -1
},
modalContent: {
position: 'absolute',
alignSelf: 'center',
zIndex: 1,
top: metrics.DEVICE_HEIGHT/2 - (Platform.OS == 'ios'? 120 : 100),
justifyContent: 'center',
alignItems: 'center',
display: 'flex',
height: 200,
width: '80%',
borderRadius: 27,
backgroundColor: 'white',
opacity: 1
},
})
App.tsx render and import
import { ModalView } from './{your_path}/ModalComponent';
render() {
return (
<React.Fragment>
<StatusBar barStyle={'dark-content'} />
<AppRouter />
<ModalView />
</React.Fragment>
)
}
and to use it from any component
SomeComponent.tsx
import { _modalEmitter } from './{your_path}/ModalComponent'
// Some functions within your component
showModal(modalText, callbackOnSubmit, callbackOnClose) {
_modalEmitter.emit(strings.modalOpen, { text: modalText, onSubmit: callbackOnSubmit.bind(this), onClose: callbackOnClose.bind(this) })
}
closeModal() {
_modalEmitter.emit(strings.modalClose)
}
Hope I was able to help some of you, I used a very similar structure for in-app notifications
Happy coding
Add to your .gitconfig
under [alias]
:
aliases = !git config --list | grep ^alias\\. | cut -c 7- | grep -Ei --color \"$1\" "#"
Then you can do
git aliases
- show ALL aliasesgit aliases commit
- only aliases containing "commit"I have a more complicated situation, the dataset has a nested structure:
import json
data = '{"TextID":{"0":"0038f0569e","1":"003eb6998d","2":"006da49ea0"},"Summary":{"0":{"Crisis_Level":["c"],"Type":["d"],"Special_Date":["a"]},"1":{"Crisis_Level":["d"],"Type":["a","d"],"Special_Date":["a"]},"2":{"Crisis_Level":["d"],"Type":["a"],"Special_Date":["a"]}}}'
df = pd.DataFrame.from_dict(json.loads(data))
print(df)
output:
TextID Summary
0 0038f0569e {'Crisis_Level': ['c'], 'Type': ['d'], 'Specia...
1 003eb6998d {'Crisis_Level': ['d'], 'Type': ['a', 'd'], 'S...
2 006da49ea0 {'Crisis_Level': ['d'], 'Type': ['a'], 'Specia...
The Summary
column contains dict objects, so I use apply
with from_dict
and stack
to extract each row of dict:
df2 = df.apply(
lambda x: pd.DataFrame.from_dict(x[1], orient='index').stack(), axis=1)
print(df2)
output:
Crisis_Level Special_Date Type
0 0 0 1
0 c a d NaN
1 d a a d
2 d a a NaN
Looks good, but missing the TextID
column. To get TextID
column back, I've tried three approach:
Modify apply
to return multiple columns:
df_tmp = df.copy()
df_tmp[['TextID', 'Summary']] = df.apply(
lambda x: pd.Series([x[0], pd.DataFrame.from_dict(x[1], orient='index').stack()]), axis=1)
print(df_tmp)
output:
TextID Summary
0 0038f0569e Crisis_Level 0 c
Type 0 d
Spec...
1 003eb6998d Crisis_Level 0 d
Type 0 a
...
2 006da49ea0 Crisis_Level 0 d
Type 0 a
Spec...
But this is not what I want, the Summary
structure are flatten.
Use pd.concat
:
df_tmp2 = pd.concat([df['TextID'], df2], axis=1)
print(df_tmp2)
output:
TextID (Crisis_Level, 0) (Special_Date, 0) (Type, 0) (Type, 1)
0 0038f0569e c a d NaN
1 003eb6998d d a a d
2 006da49ea0 d a a NaN
Looks fine, the MultiIndex
column structure are preserved as tuple. But check columns type:
df_tmp2.columns
output:
Index(['TextID', ('Crisis_Level', 0), ('Special_Date', 0), ('Type', 0),
('Type', 1)],
dtype='object')
Just as a regular Index
class, not MultiIndex
class.
use set_index
:
Turn all columns you want to preserve into row index, after some complicated apply
function and then reset_index
to get columns back:
df_tmp3 = df.set_index('TextID')
df_tmp3 = df_tmp3.apply(
lambda x: pd.DataFrame.from_dict(x[0], orient='index').stack(), axis=1)
df_tmp3 = df_tmp3.reset_index(level=0)
print(df_tmp3)
output:
TextID Crisis_Level Special_Date Type
0 0 0 1
0 0038f0569e c a d NaN
1 003eb6998d d a a d
2 006da49ea0 d a a NaN
Check the type of columns
df_tmp3.columns
output:
MultiIndex(levels=[['Crisis_Level', 'Special_Date', 'Type', 'TextID'], [0, 1, '']],
codes=[[3, 0, 1, 2, 2], [2, 0, 0, 0, 1]])
So, If your apply
function will return MultiIndex
columns, and you want to preserve it, you may want to try the third method.
Being that the transform solution doesn't work in iOS 11 I decided to write a new approach.
Adjusting the buttons semanticContentAttribute
gives us the image nicely to the right without having to relayout if the text changes. Because of this it's the ideal solution. However I still need RTL support. The fact that an app can not change it's layout direction in the same session resolves this issue easily.
With that said, it's pretty straight forward.
extension UIButton {
func alignImageRight() {
if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
semanticContentAttribute = .forceRightToLeft
}
else {
semanticContentAttribute = .forceLeftToRight
}
}
}
This
var verificaHorario = $("#tbIntervalos").find("#" + horaInicial);
will find you the td that needs to be blocked.
Actually this will also do:
var verificaHorario = $("#" + horaInicial);
Testing for the size() of the wrapped set will answer your question regarding the existence of the id.
You need to name the entity that holds the association to User. For example,
... INNER JOIN ug.user u ...
That's the "path" the error message is complaining about -- path from UserGroup to User entity.
Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.
I had to install the dependency
oracle-instantclient12.2-basic-12.2.0.1.0-1.x86_64
This annotation is commonly used to eliminate NullPointerExceptions
. @Nullable
says that this parameter might be null
. A good example of such behaviour can be found in Google Guice. In this lightweight dependency injection framework you can tell that this dependency might be null
. If you would try to pass null
without an annotation the framework would refuse to do it's job.
What is more @Nullable
might be used with @NotNull
annotation. Here you can find some tips on how to use them properly. Code inspection in IntelliJ checks the annotations and helps to debug the code.
GitHub
git config --global url.ssh://[email protected]/.insteadOf https://github.com/
BitBucket
git config --global url.ssh://[email protected]/.insteadOf https://bitbucket.org/
That tells git to always use SSH instead of HTTPS when connecting to GitHub/BitBucket, so you'll authenticate by certificate by default, instead of being prompted for a password.
Encountered this issue quite a few times, note that I'm running laravel via Vagrant. So here are the fixes that work for me:
You may try reloading your server instead of vagrant (ie MAMP)
If you are using large table and want to access of 10 percent of the data then run this following command: SELECT TOP 10 PERCENT * FROM Table1 ORDER BY NEWID();
Make sure all of your IIS features are properly enabled.
Scroll down to Internet Information Services
Open the World Wide Web plus box drop down
Use localStorage to store the fact that you opened the page :
$(document).ready(function() {
var yetVisited = localStorage['visited'];
if (!yetVisited) {
// open popup
localStorage['visited'] = "yes";
}
});
Use the following in the function you will call and it will work just fine.
[a b c] = yourfunction(optional)
%your code
a = 5;
b = 7;
c = 10;
return
end
This is a way to call the function both from another function and from the command terminal
[aa bb cc] = yourfunction(optional);
The variables aa, bb and cc now hold the return variables.
I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands
which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.
You put the if
at the end:
[y for y in a if y not in b]
List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:
outputlist = []
for y in a:
if y not in b:
outputlist.append(y)
Your version tried to do this instead:
outputlist = []
if y not in b:
for y in a:
outputlist.append(y)
but a list comprehension must start with at least one outer loop.
Use the PropertyConfigurator: PropertyConfigurator.configure(configFileUrl);
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
The fact that angular is injecting an empty option element to the select is that the model object binded to it by default comes with an empty value in when initialized.
If you want to select a default option then you can probably can set it on the scope in the controller
$scope.filterCondition.operator = "your value here";
If you want to an empty option placeholder, this works for me
<select ng-model="filterCondition.operator" ng-options="operator.id as operator.name for operator in operators">
<option value="">Choose Operator</option>
</select>
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
Easy & configurable solution is create one jndi.properties file and put this file in classpath. jndi.properties can be created as
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
# use the following property to configure the default connector
java.naming.provider.url = vm://localhost
# use the following property to specify the JNDI name the connection factory
# should appear as.
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue = example.MyQueue
# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic = example.MyTopic
Just specify your naming factory & url and put this file in your classpath. JMS will fetch required info by itself and it's easily configurable in future also.
Hey how about to copy all fields, change one of them to the same value + something else.
INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, Event_ID+"155"
FROM Table
WHERE Event_ID = "120"
??????????
try this
open the build.gradle
file
android {
dexOptions {
javaMaxHeapSize = "4g"
}
}
If you have your MySQL server up and running, then you just need a client to connect to it and start practicing. One is the mysql-client
, which is a command-line tool, or you can use phpMyAdmin
, which is a web-based tool.
If you use Grunt to build your project, there is a plugin that will automatically assemble your partials into an Angular module that primes $templateCache. You can concatenate this module with the rest of your code and load everything from one file on startup.
Alternate way is to use a "container view". Just make alpha below 1 and embed with seque. XCode 5, target iOS7. Tested on iPhone.
Container view available from iOS6. Link to blog post about that.
There is no "Numeric Keypad" for iPads out of the box. When you specify one iPads display the normal keypad with the numeric part displayed. You can switch over to alpha characters, etc. If you want to display a numbers only keyboard for iPad you must implement it yourself.
See here: Number keyboard in iPad?
Have you tried using ASP.NET MVC TempData ?
ASP.NET MVC TempData dictionary is used to share data between controller actions. The value of TempData persists until it is read or until the current user’s session times out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request.
The code would be something like this:
[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
XDocument updatedResultsDocument = myService.UpdateApplicationPools();
TempData["doc"] = updatedResultsDocument;
return RedirectToAction("UpdateConfirmation");
}
And in the ApplicationPoolController:
public ActionResult UpdateConfirmation()
{
if (TempData["doc"] != null)
{
XDocument updatedResultsDocument = (XDocument) TempData["doc"];
...
return View();
}
}
there's a library called DropKick.js that replaces the normal select dropdowns with HTML/CSS so you can fully style and control them with javascript. http://dropkickjs.com/
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
In this very basic example, we send a request to myAjax.php
when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output
.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
XMLHttpRequest
on MDN - https://developer.mozilla.org/en/XMLHttpRequestXMLHttpRequest
on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspxjQuery.ajax
- http://api.jquery.com/jQuery.ajax/Use
$(window).scrollTop()
It'll scroll the window to the item.
var scrollPos = $("#branch1").offset().top;
$(window).scrollTop(scrollPos);
This example will help you:
<form>
<input type="button" value="Open Window" onclick="window.open('http://www.google.com')">
</form>
You can open next page on same page by:
<input type="button" value="Open Window" onclick="window.open('http://www.google.com','_self')">
Make sure you aren't trying to use the same User object more than once while changing the ID. In other words, if you were doing something in a batch type operation:
User user = new User(); // Using the same one over and over, won't work
List<Customer> customers = fetchCustomersFromSomeService();
for(Customer customer : customers) {
// User user = new User(); <-- This would work, you get a new one each time
user.setId(customer.getId());
user.setName(customer.getName());
saveUserToDB(user);
}
You need to import time and then use time.time() method to know current time.
import time
start_time=time.time() #taking current time as starting time
#here your code
elapsed_time=time.time()-start_time #again taking current time - starting time
I suspect you are having a problem with factors. For example,
> x = factor(4:8)
> x
[1] 4 5 6 7 8
Levels: 4 5 6 7 8
> as.numeric(x)
[1] 1 2 3 4 5
> as.numeric(as.character(x))
[1] 4 5 6 7 8
Some comments:
as.numeric
to do with these values?read.csv
, try using the argument stringsAsFactors=FALSE
sep="/t
and not sep="\t"
head(pitchman)
to check the first fews rows of your datapichman <- read.csv(file="picman.txt", header=TRUE, sep="/t")
since I don't have access to the data set.UDP: Anything where you don't care too much if you get all data always
TCP: Almost anything where you have to get all transmitted data
EDIT: I'm not going to bother explaining the differences, since you state that you already know and every other answer explains it anyway :)
To get screen resolution in JS use screen
object
screen.height;
screen.width;
Based on that values you can calculate your margin to whatever suits you.
To DELETE, without changing the references, you should first delete or otherwise alter (in a manner suitable for your purposes) all relevant rows in other tables.
To TRUNCATE you must remove the references. TRUNCATE is a DDL statement (comparable to CREATE and DROP) not a DML statement (like INSERT and DELETE) and doesn't cause triggers, whether explicit or those associated with references and other constraints, to be fired. Because of this, the database could be put into an inconsistent state if TRUNCATE was allowed on tables with references. This was a rule when TRUNCATE was an extension to the standard used by some systems, and is mandated by the the standard, now that it has been added.