As said before, @Column(unique = true)
is a shortcut to UniqueConstraint
when it is only a single field.
From the example you gave, there is a huge difference between both.
@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private ProductSerialMask mask;
@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Group group;
This code implies that both mask
and group
have to be unique, but separately. That means that if, for example, you have a record with a mask.id = 1 and tries to insert another record with mask.id = 1, you'll get an error, because that column should have unique values. The same aplies for group.
On the other hand,
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {@UniqueConstraint(columnNames = {"mask", "group"})}
)
Implies that the values of mask + group combined should be unique. That means you can have, for example, a record with mask.id = 1 and group.id = 1, and if you try to insert another record with mask.id = 1 and group.id = 2, it'll be inserted successfully, whereas in the first case it wouldn't.
If you'd like to have both mask and group to be unique separately and to that at class level, you'd have to write the code as following:
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {
@UniqueConstraint(columnNames = "mask"),
@UniqueConstraint(columnNames = "group")
}
)
This has the same effect as the first code block.
I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.
If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany
annotation with the 'mappedBy
' property, it also means that the other side holding the @ManyToOne
annotation with the @JoinColumn
is the 'owner' of this bi-directional relationship.
Also, mappedBy
takes in the instance name (mCustomer
in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).
BONUS :
Also, look into the orphanRemoval
property of @OneToMany
annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.
I know sounds crazy but I received such error because I forget to remove
private static final long serialVersionUID = 1L;
automatically generated by Eclipse JPA tool when a table to entities transformation I've done.
Removing the line above that solved the issue
There are many answers and all are correct as well. But unfortunately none of them have a clear explanation.
The following works for a non-primary key mapping as well.
Let's say we have parent table A with column 1 and another table, B, with column 2 which references column 1:
@ManyToOne
@JoinColumn(name = "TableBColumn", referencedColumnName = "TableAColumn")
private TableA session_UserName;
@ManyToOne
@JoinColumn(name = "bok_aut_id", referencedColumnName = "aut_id")
private Author bok_aut_id;
@NotNull
is a JSR 303 Bean Validation annotation. It has nothing to do with database constraints itself. As Hibernate is the reference implementation of JSR 303, however, it intelligently picks up on these constraints and translates them into database constraints for you, so you get two for the price of one. @Column(nullable = false)
is the JPA way of declaring a column to be not-null. I.e. the former is intended for validation and the latter for indicating database schema details. You're just getting some extra (and welcome!) help from Hibernate on the validation annotations.
For completeness, also look into the local storage capabilities & sessionStorage of HTML5. These are supported in the latest versions of all modern browsers, and are much easier to use and less fiddly than cookies.
http://www.w3.org/TR/2009/WD-webstorage-20091222/
https://www.w3.org/TR/webstorage/. (second edition)
Here are some sample code for setting and getting the values using sessionStorage and localStorage :
// HTML5 session Storage
sessionStorage.setItem("variableName","test");
sessionStorage.getItem("variableName");
//HTML5 local storage
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");
I believe, this arrow exists because of your IDE. IntelliJ IDEA does such thing with some code. This is called code folding. You can click at the arrow to expand it.
You can have multiple CTE
s in one query, as well as reuse a CTE
:
WITH cte1 AS
(
SELECT 1 AS id
),
cte2 AS
(
SELECT 2 AS id
)
SELECT *
FROM cte1
UNION ALL
SELECT *
FROM cte2
UNION ALL
SELECT *
FROM cte1
Note, however, that SQL Server
may reevaluate the CTE
each time it is accessed, so if you are using values like RAND()
, NEWID()
etc., they may change between the CTE
calls.
JSX will evaluate JavaScript expressions in curly braces
In this case, this.props.removeTaskFunction(todo)
is invoked and the return value is assigned to onClick
What you have to provide for onClick
is a function. To do this, you can wrap the value in an anonymous function.
export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
const taskNodes = todoTasks.map(todo => (
<div>
{todo.task}
<button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
</div>
);
return (
<div className="todo-task-list">
{taskNodes}
</div>
);
}
});
In a nutshell, Forking is perhaps the same as "cloning under your GitHub ID/profile". A fork is anytime better than a clone, with a few exceptions, obviously. The forked repository is always being monitored/compared with the original repository unlike a cloned repository. That enables you to track the changes, initiate pull requests and also manually sync the changes made in the original repository with your forked one.
suppose
alias command1='grep a <<<abc'
alias command2='grep x <<<abc'
alias command3='grep c <<<abc'
either
{ command1 1>/dev/null || { echo "cmd1 fail"; /bin/false; } } && echo "cmd1 succeed" &&
{ command2 1>/dev/null || { echo "cmd2 fail"; /bin/false; } } && echo "cmd2 succeed" &&
{ command3 1>/dev/null || { echo "cmd3 fail"; /bin/false; } } && echo "cmd3 succeed"
or
{ { command1 1>/dev/null && echo "cmd1 succeed"; } || { echo "cmd1 fail"; /bin/false; } } &&
{ { command2 1>/dev/null && echo "cmd2 succeed"; } || { echo "cmd2 fail"; /bin/false; } } &&
{ { command3 1>/dev/null && echo "cmd3 succeed"; } || { echo "cmd3 fail"; /bin/false; } }
yields
cmd1 succeed
cmd2 fail
Tedious it is. But the readability isn't bad.
function addDays(n){
var t = new Date();
t.setDate(t.getDate() + n);
var month = "0"+(t.getMonth()+1);
var date = "0"+t.getDate();
month = month.slice(-2);
date = date.slice(-2);
var date = date +"/"+month +"/"+t.getFullYear();
alert(date);
}
addDays(5);
You need to explicitly tell TypeScript the type of the HTMLElement which is your target.
The way to do it is using a generic type to cast it to a proper type:
this.countUpdate.emit((<HTMLTextAreaElement>e.target).value./*...*/)
or (as you like)
this.countUpdate.emit((e.target as HTMLTextAreaElement).value./*...*/)
or (again, matter of preference)
const target = e.target as HTMLTextAreaElement;
this.countUpdate.emit(target.value./*...*/)
This will let TypeScript know that the element is a textarea
and it will know of the value property.
The same could be done with any kind of HTML element, whenever you give TypeScript a bit more information about their types it pays you back with proper hints and of course less errors.
To make it easier for the future you might want to directly define an event with the type of its target:
// create a new type HTMLElementEvent that has a target of type you pass
// type T must be a HTMLElement (e.g. HTMLTextAreaElement extends HTMLElement)
type HTMLElementEvent<T extends HTMLElement> = Event & {
target: T;
// probably you might want to add the currentTarget as well
// currentTarget: T;
}
// use it instead of Event
let e: HTMLElementEvent<HTMLTextAreaElement>;
console.log(e.target.value);
// or in the context of the given example
emitWordCount(e: HTMLElementEvent<HTMLTextAreaElement>) {
this.countUpdate.emit(e.target.value);
}
See this thread for an explanation: VIM for Windows - What do I type to save and exit from a file?
As I wrote there: to learn Vimming, you could use one of the quick reference cards:
Also note How can I set up an editor to work with Git on Windows? if you're not comfortable in using Vim but want to use another editor for your commit messages.
If your commit message is not too long, you could also type
git commit -a -m "your message here"
If you are trying to install a module that is listed on the central repository for PS content called PowerShell Gallery, you need to install PowerShellGet. Then the command will be available. I'm currently using PS 4.0. Installing PowerShellGet did the trick for me.
With the latest PowerShellGet module, you can:
Try to type in cmd: php artisan key:generate the problems will be solved
is you want fix XSS on input element? you can encode string before output to input field
PHP:
$str = htmlentities($str);
C#:
str = WebUtility.HtmlEncode(str);
after that output value direct to input field:
<input type="text" value="<?php echo $str" />
Use the static methods in the Math
class for both - there are no operators for this in the language:
double root = Math.sqrt(value);
double absolute = Math.abs(value);
(Likewise there's no operator for raising a value to a particular power - use Math.pow
for that.)
If you use these a lot, you might want to use static imports to make your code more readable:
import static java.lang.Math.sqrt;
import static java.lang.Math.abs;
...
double x = sqrt(abs(x) + abs(y));
instead of
double x = Math.sqrt(Math.abs(x) + Math.abs(y));
In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file. Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).
Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.
Code offset dynamic for dynamic page
var pos=$('#send').offset().top;
$('#loading').offset({ top : pos-220});
You can get this using Emulation (Ctrl + 8) Document mode (10,9,8,7,5), Browser Profile (Desktop, Windows Phone)
How to deal with
SettingWithCopyWarning
in Pandas?
This post is meant for readers who,
Setup
np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (3, 5)), columns=list('ABCDE'))
df
A B C D E
0 5 0 3 3 7
1 9 3 5 2 4
2 7 6 8 8 1
SettingWithCopyWarning
?To know how to deal with this warning, it is important to understand what it means and why it is raised in the first place.
When filtering DataFrames, it is possible slice/index a frame to return either a view, or a copy, depending on the internal layout and various implementation details. A "view" is, as the term suggests, a view into the original data, so modifying the view may modify the original object. On the other hand, a "copy" is a replication of data from the original, and modifying the copy has no effect on the original.
As mentioned by other answers, the SettingWithCopyWarning
was created to flag "chained assignment" operations. Consider df
in the setup above. Suppose you would like to select all values in column "B" where values in column "A" is > 5. Pandas allows you to do this in different ways, some more correct than others. For example,
df[df.A > 5]['B']
1 3
2 6
Name: B, dtype: int64
And,
df.loc[df.A > 5, 'B']
1 3
2 6
Name: B, dtype: int64
These return the same result, so if you are only reading these values, it makes no difference. So, what is the issue? The problem with chained assignment, is that it is generally difficult to predict whether a view or a copy is returned, so this largely becomes an issue when you are attempting to assign values back. To build on the earlier example, consider how this code is executed by the interpreter:
df.loc[df.A > 5, 'B'] = 4
# becomes
df.__setitem__((df.A > 5, 'B'), 4)
With a single __setitem__
call to df
. OTOH, consider this code:
df[df.A > 5]['B'] = 4
# becomes
df.__getitem__(df.A > 5).__setitem__('B", 4)
Now, depending on whether __getitem__
returned a view or a copy, the __setitem__
operation may not work.
In general, you should use loc
for label-based assignment, and iloc
for integer/positional based assignment, as the spec guarantees that they always operate on the original. Additionally, for setting a single cell, you should use at
and iat
.
More can be found in the documentation.
Note
All boolean indexing operations done withloc
can also be done withiloc
. The only difference is thatiloc
expects either integers/positions for index or a numpy array of boolean values, and integer/position indexes for the columns.For example,
df.loc[df.A > 5, 'B'] = 4
Can be written nas
df.iloc[(df.A > 5).values, 1] = 4
And,
df.loc[1, 'A'] = 100
Can be written as
df.iloc[1, 0] = 100
And so on.
Consider a simple operation on the "A" column of df
. Selecting "A" and dividing by 2 will raise the warning, but the operation will work.
df2 = df[['A']]
df2['A'] /= 2
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/__main__.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
df2
A
0 2.5
1 4.5
2 3.5
There are a couple ways of directly silencing this warning:
(recommended) Use loc
to slice subsets:
df2 = df.loc[:, ['A']]
df2['A'] /= 2 # Does not raise
Change pd.options.mode.chained_assignment
Can be set to None
, "warn"
, or "raise"
. "warn"
is the default. None
will suppress the warning entirely, and "raise"
will throw a SettingWithCopyError
, preventing the operation from going through.
pd.options.mode.chained_assignment = None
df2['A'] /= 2
Make a deepcopy
df2 = df[['A']].copy(deep=True)
df2['A'] /= 2
@Peter Cotton in the comments, came up with a nice way of non-intrusively changing the mode (modified from this gist) using a context manager, to set the mode only as long as it is required, and the reset it back to the original state when finished.
class ChainedAssignent: def __init__(self, chained=None): acceptable = [None, 'warn', 'raise'] assert chained in acceptable, "chained must be in " + str(acceptable) self.swcw = chained def __enter__(self): self.saved_swcw = pd.options.mode.chained_assignment pd.options.mode.chained_assignment = self.swcw return self def __exit__(self, *args): pd.options.mode.chained_assignment = self.saved_swcw
The usage is as follows:
# some code here
with ChainedAssignent():
df2['A'] /= 2
# more code follows
Or, to raise the exception
with ChainedAssignent(chained='raise'):
df2['A'] /= 2
SettingWithCopyError:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
A lot of the time, users attempt to look for ways of suppressing this exception without fully understanding why it was raised in the first place. This is a good example of an XY problem, where users attempt to solve a problem "Y" that is actually a symptom of a deeper rooted problem "X". Questions will be raised based on common problems that encounter this warning, and solutions will then be presented.
Question 1
I have a DataFramedf A B C D E 0 5 0 3 3 7 1 9 3 5 2 4 2 7 6 8 8 1
I want to assign values in col "A" > 5 to 1000. My expected output is
A B C D E 0 5 0 3 3 7 1 1000 3 5 2 4 2 1000 6 8 8 1
Wrong way to do this:
df.A[df.A > 5] = 1000 # works, because df.A returns a view
df[df.A > 5]['A'] = 1000 # does not work
df.loc[df.A 5]['A'] = 1000 # does not work
Right way using loc
:
df.loc[df.A > 5, 'A'] = 1000
Question 21
I am trying to set the value in cell (1, 'D') to 12345. My expected output isA B C D E 0 5 0 3 3 7 1 9 3 5 12345 4 2 7 6 8 8 1
I have tried different ways of accessing this cell, such as
df['D'][1]
. What is the best way to do this?1. This question isn't specifically related to the warning, but it is good to understand how to do this particular operation correctly so as to avoid situations where the warning could potentially arise in future.
You can use any of the following methods to do this.
df.loc[1, 'D'] = 12345
df.iloc[1, 3] = 12345
df.at[1, 'D'] = 12345
df.iat[1, 3] = 12345
Question 3
I am trying to subset values based on some condition. I have a DataFrameA B C D E 1 9 3 5 2 4 2 7 6 8 8 1
I would like to assign values in "D" to 123 such that "C" == 5. I tried
df2.loc[df2.C == 5, 'D'] = 123
Which seems fine but I am still getting the
SettingWithCopyWarning
! How do I fix this?
This is actually probably because of code higher up in your pipeline. Did you create df2
from something larger, like
df2 = df[df.A > 5]
? In this case, boolean indexing will return a view, so df2
will reference the original. What you'd need to do is assign df2
to a copy:
df2 = df[df.A > 5].copy()
# Or,
# df2 = df.loc[df.A > 5, :]
Question 4
I'm trying to drop column "C" in-place from
A B C D E 1 9 3 5 2 4 2 7 6 8 8 1
But using
df2.drop('C', axis=1, inplace=True)
Throws
SettingWithCopyWarning
. Why is this happening?
This is because df2
must have been created as a view from some other slicing operation, such as
df2 = df[df.A > 5]
The solution here is to either make a copy()
of df
, or use loc
, as before.
shutdown you pc and open bios settings, and enable Virtual Technology-x option and restart your pc.
done.
Here is the full HTML that I use to center by button in Bootsrap form after closing form-group:
<div class="form-row text-center">
<div class="col-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
win32com.client
is a part of pywin32
So, download pywin32 from here
and the implicit comment by many posters => Dont use arrays, use vectors. All of the benefits of arrays with none of the downsides. PLus you get lots of other goodies
If you dont know STL, read Josuttis The C++ standard library and meyers effective STL
import UIKit
class TabbarViewController: UITabBarController,UITabBarControllerDelegate {
//MARK:- View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//Tabbar delegate method
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
yourView.popToRootViewController(animated:false)
}
}
As you add more modules to Android, there is an incredible demand placed on the Android build system, and the default memory settings will not work. To avoid OutOfMemory
errors during Android builds, you should uncomment the alternate Gradle memory setting present in /android/gradle.properties
:
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
There are also the following options:
docker container ls
docker container ls -a
# --all, -a
# Show all containers (default shows just running)
since: 1.13.0 (2017-01-18):
Restructure CLI commands by adding
docker image
anddocker container
commands for more consistency #26025
and as stated here: Introducing Docker 1.13, users are encouraged to adopt the new syntax:
CLI restructured
In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with. For example
list
andstart
of containers are now subcommands ofdocker container
andhistory
is a subcommand ofdocker image
.These changes let us clean up the Docker CLI syntax, improve help text and make Docker simpler to use. The old command syntax is still supported, but we encourage everybody to adopt the new syntax.
You should bind a function to keyup event
textarea.keyup = function(){
textarea.value.length....
}
with jquery
$('textarea').keyup(function(){
var length = $(this).val().length;
});
Just as an update this can be done by using Toad 9 also.Goto Database>Export>Data Pump Export wizard.At the desitination directory window if you dont find any directory in the dropdown,then you probably have to create a directory object.
CREATE OR REPLACE DIRECTORY data_pmp_dir_test AS '/u01/app/oracle/oradata/pmp_dir_test';
See this for an example.
You should check if the POST['username']
is defined. Use this above:
$username = "";
if(isset($_POST['username'])){
$username = $_POST['username'];
}
"SELECT password FROM users WHERE username='".$username."'"
MySQL 5.5 Reference Manual: "InnoDB and FOREIGN KEY Constraints"
SELECT
ke.REFERENCED_TABLE_SCHEMA parentSchema,
ke.referenced_table_name parentTable,
ke.REFERENCED_COLUMN_NAME parentColumnName,
ke.TABLE_SCHEMA ChildSchema,
ke.table_name childTable,
ke.COLUMN_NAME ChildColumnName
FROM
information_schema.KEY_COLUMN_USAGE ke
WHERE
ke.referenced_table_name IS NOT NULL
AND ke.REFERENCED_COLUMN_NAME = 'ci_id' ## Find Foreign Keys linked to this Primary Key
ORDER BY
ke.referenced_table_name;
Short and easy-to-understand one-liners without regular expressions.
startsWith() is straight forward.
function startsWith($haystack, $needle) {
return (strpos($haystack, $needle) === 0);
}
endsWith() uses the slightly fancy and slow strrev():
function endsWith($haystack, $needle) {
return (strpos(strrev($haystack), strrev($needle)) === 0);
}
alter table User
add constraint userProperties
foreign key (properties)
references Properties(ID)
I have scopes for this, hope it help somebody. https://laravel.com/docs/master/eloquent#local-scopes
public function scopeWhereLike($query, $column, $value)
{
return $query->where($column, 'like', '%'.$value.'%');
}
public function scopeOrWhereLike($query, $column, $value)
{
return $query->orWhere($column, 'like', '%'.$value.'%');
}
Usage:
$result = BookingDates::whereLike('email', $email)->orWhereLike('name', $name)->get();
$(document).ready(function(){
$("#form_id").submit(function(){
return condition;
});
});
You can use like below -
this.setState(() => ({ subChartType1: value }), () => this.props.dispatch(setChartData(null)));
I call it my billion-dollar mistake…At that time, I was designing the first comprehensive type system for references in an object-oriented language. My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. – Tony Hoare, inventor of ALGOL W.
See here for an elaborate shit storm about null
in general. I do not agree with the statement that undefined
is another null
, but it is still worth reading. And it explains, why you should avoid null
at all and not just in the case you have asked. The essence is, that null
is in any language a special case. You have to think about null
as an exception. undefined
is different in that way, that code dealing with undefined behavior is in most cases just a bug. C and most other languages have also undefined behavior but most of them have no identifier for that in the language.
MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw
and cygwin fork
package.
To install the MinGW-w64 toolchain (Reference):
pacman -Sy pacman
to update the package databasepacman -Syu
to update the package database and core system packagespacman -Su
to update the restpacman -S mingw-w64-i686-toolchain
pacman -S mingw-w64-x86_64-toolchain
make
, run pacman -S make
For Python 3 that would be:
# Filename e.g. cat.py
import sys
for line in sys.stdin:
print(line, end="")
This is basically a simple form of cat(1), since it doesn't add a newline after each line. You can use this (after You marked the file executable using chmod +x cat.py
such as:
echo Hello | ./cat.py
As everyone pointed out even though having multiple template directives in a single element works in angular 1.x it is not allowed in Angular 2. you can find more info from here : https://github.com/angular/angular/issues/7315
solution is to use the <template>
as a placeholder, so the code goes like this
<template *ngFor="let nav_link of defaultLinks" >
<li *ngIf="nav_link.visible">
.....
</li>
</template>
but for some reason above does not work in 2.0.0-rc.4
in that case you can use this
<template ngFor let-nav_link [ngForOf]="defaultLinks" >
<li *ngIf="nav_link.visible">
.....
</li>
</template>
With updates, right now in 2018 angular v6 recommend to use <ng-container>
instead of <template>
so here is the updated answer.
<ng-container *ngFor="let nav_link of defaultLinks" >
<li *ngIf="nav_link.visible">
.....
</li>
</ng-container>
Have you tried this?
git log --pretty=oneline --abbrev-commit
The problem is probably that you are missing an empty line after the first line. The command above usually works for me, but I just tested on a commit without empty second line. I got the same result as you: the whole message on one line.
Empty second line is a standard in git commit messages. The behaviour you see was probably implemented on purpose.
The first line of a commit message is meant to be a short description. If you cannot make it in a single line you can use several, but git considers everything before the first empty line to be the "short description". oneline
prints the whole short description, so all your 3 rows.
I used the [[NSMutableArray new] addObject:nil] approach mentioned above to force-quit (crash) the app without making a tell-tale exit(0) function call.
Why? Because my app uses certificate pinning on all network API calls to prevent man-in-the-middle attacks. These include the initialization calls my financial app makes on startup.
If certificate authentication fails, all of my initialization calls error out and leave my app in an indeterminate state. Letting the user go home and then back into the app doesn't help, as unless the app has been purged by the OS it's still uninitialized and untrustworthy.
So, in this one case, we deemed it best to pop an alert informing the user that the app is operating in an insecure environment and then, when they hit "Close", force quit the app using the aforementioned method.
If you want to set a custom drawable file use this code snippet
fun setCustomStatusBar(){
if (Build.VERSION.SDK_INT >= 21) {
val decor = window.decorView
decor.viewTreeObserver.addOnPreDrawListener(object :
ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
decor.viewTreeObserver.removeOnPreDrawListener(this)
val statusBar = decor.findViewById<View>
(android.R.id.statusBarBackground)
statusBar.setBackgroundResource(R.drawable.bg_statusbar)
return true
}
})
}
}
Go to the download page and download the Windows x86
version with filename jdk-7-windows-i586.exe
.
Use This:-
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
What is, and is not a float may surprise you:
Command to parse Is it a float? Comment
-------------------------------------- --------------- ------------
print(isfloat("")) False
print(isfloat("1234567")) True
print(isfloat("NaN")) True nan is also float
print(isfloat("NaNananana BATMAN")) False
print(isfloat("123.456")) True
print(isfloat("123.E4")) True
print(isfloat(".1")) True
print(isfloat("1,234")) False
print(isfloat("NULL")) False case insensitive
print(isfloat(",1")) False
print(isfloat("123.EE4")) False
print(isfloat("6.523537535629999e-07")) True
print(isfloat("6e777777")) True This is same as Inf
print(isfloat("-iNF")) True
print(isfloat("1.797693e+308")) True
print(isfloat("infinity")) True
print(isfloat("infinity and BEYOND")) False
print(isfloat("12.34.56")) False Two dots not allowed.
print(isfloat("#56")) False
print(isfloat("56%")) False
print(isfloat("0E0")) True
print(isfloat("x86E0")) False
print(isfloat("86-5")) False
print(isfloat("True")) False Boolean is not a float.
print(isfloat(True)) True Boolean is a float
print(isfloat("+1e1^5")) False
print(isfloat("+1e1")) True
print(isfloat("+1e1.3")) False
print(isfloat("+1.3P1")) False
print(isfloat("-+1")) False
print(isfloat("(1)")) False brackets not interpreted
Instead of using intent Settings.ACTION_LOCATION_SOURCE_SETTINGS you can directly able to show pop up in your app like Google Map & on Gps on click of ok button their is no need to redirect to setting simply you need to use my code as
Note : This line of code automatic open the dialog box if Location is not on. This piece of line is used in Google Map also
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
PendingResult<LocationSettingsResult> result;
final static int REQUEST_LOCATION = 199;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
//final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
//...
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
MainActivity.this,
REQUEST_LOCATION);
} catch (SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
//...
break;
}
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d("onActivityResult()", Integer.toString(resultCode));
//final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode)
{
case REQUEST_LOCATION:
switch (resultCode)
{
case Activity.RESULT_OK:
{
// All required changes were successfully made
Toast.makeText(MainActivity.this, "Location enabled by user!", Toast.LENGTH_LONG).show();
break;
}
case Activity.RESULT_CANCELED:
{
// The user was asked to change settings, but chose not to
Toast.makeText(MainActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
break;
}
default:
{
break;
}
}
break;
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
Note : This line of code automatic open the dialog box if Location is not on. This piece of line is used in Google Map also
For those who came here looking for a command-line solution, like me, cURL's --data-urlencode works fine:
curl -G -v -s --data-urlencode 'query={"type" : "/music/artist"}' 'https://www.googleapis.com/freebase/v1/mqlread'
sends
GET /freebase/v1/mqlread?query=%7B%22type%22%20%3A%20%22%2Fmusic%2Fartist%22%7D HTTP/1.1
, for example. Larger JSON data can be put in a file and you'd use the @ syntax to specify a file to slurp in the to-be-escaped data from. For example, if
$ cat 1.json
{
"type": "/music/artist",
"name": "The Police",
"album": []
}
you'd use
curl -G -v -s --data-urlencode [email protected] 'https://www.googleapis.com/freebase/v1/mqlread'
And now, this is also a tutorial on how to query Freebase from the command line :-)
I don't know if YUI DT has this feature but I won't be surprised if it does.
Singletons aren't evil, if you use it properly & minimally. There are lot of other good design patterns which replaces the needs of singleton at some point (& also gives best results). But some programmers are unaware of those good patterns & uses the singleton for all the cases which makes the singleton evil for them.
<input type="button" value="Clear" onclick="javascript: functionName();" >
you just need to set the onclick event, call your desired function on this onclick event.
function functionName()
{
$("#output").val("");
}
Above function will set the value of text area to empty string.
For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);
If you want it to download and install from your own server then use the following code
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
startActivity(intent);
I found I was missing the WebApplications folder on my local PC, did not install with Visual Studio 2017 like it had when I was using 2012.
GISTS The Gist is an outstanding service provided by GitHub. Using this service, you can share your work publically or privately. You can share a single file, articles, full applications or source code etc.
The GitHub is much more than just Gists. It provides immense services to group together a project or programs digital resources in a centralized location called repository and share among stakeholder. The GitHub repository will hold or maintain the multiple version of the files or history of changes and you can retrieve a specific version of a file when you want. Whereas gist will create each post as a new repository and will maintain the history of the file.
Alternative approach using npm-upgrade:
npm i -g npm-upgrade
Go to your project folder
npm-upgrade check
It will ask you if you wish to upgrade the package, select Yes
That's simple
Just use:
<?php
include("/path/to/file.html");
?>
That will echo it as well. This also has the benefit of executing any PHP in the file.
If you need to do anything with the contents, use file_get_contents(),
For example,
<?php
$pagecontents = file_get_contents("/path/to/file.html");
echo str_replace("Banana", "Pineapple", $pagecontents);
?>
This doesn't execute code in that file, so be careful if you expect that to work.
I usually use:
include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");
as then I can move files without breaking the includes.
It wouldn't be wrong to mention that Pexpect
does throw a similar error
#python -c "import pexpect; p=pexpect.spawn('/usr/local/ssl/bin/openssl_1.1.0f version'); p.interact()"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pexpect.py", line 430, in __init__
self._spawn (command, args)
File "/usr/lib/python2.7/site-packages/pexpect.py", line 560, in _spawn
os.execv(self.command, self.args)
OSError: [Errno 8] Exec format error
Over here, the openssl_1.1.0f
file at the specified path has exec
command specified in it and is running the actual openssl binary when called.
Usually, I wouldn't mention this unless I have the root cause, but this problem was not there earlier. Unable to find the similar problem, the closest explanation to make it work is the same as the one provided by @jfs above.
what worked for me is both
/bin/bash
at the beginning of the command or file you are#!/bin/sh
as the first line.for ex.
#python -c "import pexpect; p=pexpect.spawn('/bin/bash /usr/local/ssl/bin/openssl_1.1.0f version'); p.interact()"
OpenSSL 1.1.0f 25 May 2017
Here is the method by using explode
:
$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string
or:
$text = @end((explode('_', '233718_This_is_a_string', 2)));
By specifying 2
for the limit
parameter in explode()
, it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]
), will give the rest of string.
Here is another one-liner by using strpos
(as suggested by @flu):
$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string
Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.
Here are some providers which have a "free-tier" (may change in future):
Open source solutions:
It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have ==
in there. You can make the warning go away by adding another set of parentheses:
while ((list = list->next))
$('.btnMedio').click(function(event) {
// Preventing default action of the event
event.preventDefault();
// Getting the height of the document
var n = $(document).height();
$('html, body').animate({ scrollTop: n }, 50);
// | |
// | --- duration (milliseconds)
// ---- distance from the top
});
private DataTable CreateDataTable(IList<T> item)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in item)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
Firstly, the PHP documentation has some excellent information on sessions.
Secondly, you will need some way to store the credentials for each user of your website (e.g. a database). It is a good idea not to store passwords as human-readable, unencrypted plain text. When storing passwords, you should use PHP's crypt()
hashing function. This means that if any credentials are compromised, the passwords are not readily available.
Most log-in systems will hash/crypt the password a user enters then compare the result to the hash in the storage system (e.g. database) for the corresponding username. If the hash of the entered password matches the stored hash, the user has entered the correct password.
You can use session variables to store information about the current state of the user - i.e. are they logged in or not, and if they are you can also store their unique user ID or any other information you need readily available.
To start a PHP session, you need to call session_start()
. Similarly, to destroy a session and its data, you need to call session_destroy()
(for example, when the user logs out):
// Begin the session
session_start();
// Use session variables
$_SESSION['userid'] = $userid;
// E.g. find if the user is logged in
if($_SESSION['userid']) {
// Logged in
}
else {
// Not logged in
}
// Destroy the session
if($log_out)
session_destroy();
I would also recommend that you take a look at this. There's some good, easy to follow information on creating a simple log-in system there.
I know this is a couple of years late, but I'm putting it out there for the next person on this journey.
GraphQL has been helpful and way easier compared to DjangoRESTFramework. It is also more flexible in terms of the responses you get. You get what you ask for and don't have to filter through the response to get what you want.
You can use Graphene Django on the server side and React+Apollo/Relay... You can look into it as that is not your question.
Right now you're setting the innerHTML to an entire div element; you want to set it to just the innerHTML. Also, I think you want MyDiv2.innerHTML = MyDiv 1 .innerHTML. Also, I think the argument to document.getElementById
is case sensitive. You were passing Div2
when you wanted DIV2
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
Also, this code will run before your DOM is ready. You can either put this script at the bottom of your body like paislee said, or put it in your body's onload function
<body onload="loadFunction()">
and then
function loadFunction(){
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
}
Your user don't have the right permissions to read
the file, since you used open()
without specifying a mode.
Since you're using Windows, you should read a little more about File and Folder Permissions.
Also, if you want to play with your file permissions, you should right-click
it, choose Properties
and select Security
tab.
Or if you want to be a little more hardcore, you can run your script as admin.
SO Related Questions:
Problem 1
You mentioned it was your private docker registry, so you probably need to check Registry API instead of Hub registry API doc, which is the link you provided.
Problem 2
docker registry API is a client/server protocol, it is up to the server's implementation on whether to remove the images in the back-end. (I guess)
DELETE /v1/repositories/(namespace)/(repository)/tags/(tag*)
Detailed explanation
Below I demo how it works now from your description as my understanding for your questions.
I run a private docker registry.
I use the default one, and listen on port 5000
.
docker run -d -p 5000:5000 registry
Then I tag the local image and push into it.
$ docker tag ubuntu localhost:5000/ubuntu
$ docker push localhost:5000/ubuntu
The push refers to a repository [localhost:5000/ubuntu] (len: 1)
Sending image list
Pushing repository localhost:5000/ubuntu (1 tags)
511136ea3c5a: Image successfully pushed
d7ac5e4f1812: Image successfully pushed
2f4b4d6a4a06: Image successfully pushed
83ff768040a0: Image successfully pushed
6c37f792ddac: Image successfully pushed
e54ca5efa2e9: Image successfully pushed
Pushing tag for rev [e54ca5efa2e9] on {http://localhost:5000/v1/repositories/ubuntu/tags/latest}
After that I can use Registry API to check it exists in your private docker registry
$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags
{"latest": "e54ca5efa2e962582a223ca9810f7f1b62ea9b5c3975d14a5da79d3bf6020f37"}
Now I can delete the tag using that API !!
$ curl -X DELETE localhost:5000/v1/repositories/ubuntu/tags/latest
true
Check again, the tag doesn't exist in my private registry server
$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags/latest
{"error": "Tag not found"}
The ISO C++ standard way to do it is to #include <iomanip>
and use io manipulators like std::setw
. However, that said, those io manipulators are a real pain to use even for text, and are just about unusable for formatting numbers (I assume you want your dollar amounts to line up on the decimal, have the correct number of significant digits, etc.). Even for just plain text labels, the code will look something like this for the first part of your first line:
// using standard iomanip facilities
cout << setw(20) << "Artist"
<< setw(20) << "Title"
<< setw(8) << "Price";
// ... not going to try to write the numeric formatting...
If you are able to use the Boost libraries, run (don't walk) and use the Boost.Format library instead. It is fully compatible with the standard iostreams, and it gives you all the goodness for easy formatting with printf/Posix formatting string, but without losing any of the power and convenience of iostreams themselves. For example, the first parts of your first two lines would look something like:
// using Boost.Format
cout << format("%-20s %-20s %-8s\n") % "Artist" % "Title" % "Price";
cout << format("%-20s %-20s %8.2f\n") % "Merle" % "Blue" % 12.99;
you the have to corp your image from sides to hide it try this
3 Easy and Fast CSS Techniques for Faux Image Cropping | Css ...
one of the demo for the first way on the site above
i will do some reading on it too
You can create your own dictionary wrapper, something like this one, as a bonus it supports null value as a key:
/// <summary>
/// Dictionary which supports duplicates and null entries
/// </summary>
/// <typeparam name="TKey">Type of key</typeparam>
/// <typeparam name="TValue">Type of items</typeparam>
public class OpenDictionary<TKey, TValue>
{
private readonly Lazy<List<TValue>> _nullStorage = new Lazy<List<TValue>>(
() => new List<TValue>());
private readonly Dictionary<TKey, List<TValue>> _innerDictionary =
new Dictionary<TKey, List<TValue>>();
/// <summary>
/// Get all entries
/// </summary>
public IEnumerable<TValue> Values =>
_innerDictionary.Values
.SelectMany(x => x)
.Concat(_nullStorage.Value);
/// <summary>
/// Add an item
/// </summary>
public OpenDictionary<TKey, TValue> Add(TKey key, TValue item)
{
if (ReferenceEquals(key, null))
_nullStorage.Value.Add(item);
else
{
if (!_innerDictionary.ContainsKey(key))
_innerDictionary.Add(key, new List<TValue>());
_innerDictionary[key].Add(item);
}
return this;
}
/// <summary>
/// Remove an entry by key
/// </summary>
public OpenDictionary<TKey, TValue> RemoveEntryByKey(TKey key, TValue entry)
{
if (ReferenceEquals(key, null))
{
int targetIdx = _nullStorage.Value.FindIndex(x => x.Equals(entry));
if (targetIdx < 0)
return this;
_nullStorage.Value.RemoveAt(targetIdx);
}
else
{
if (!_innerDictionary.ContainsKey(key))
return this;
List<TValue> targetChain = _innerDictionary[key];
if (targetChain.Count == 0)
return this;
int targetIdx = targetChain.FindIndex(x => x.Equals(entry));
if (targetIdx < 0)
return this;
targetChain.RemoveAt(targetIdx);
}
return this;
}
/// <summary>
/// Remove all entries by key
/// </summary>
public OpenDictionary<TKey, TValue> RemoveAllEntriesByKey(TKey key)
{
if (ReferenceEquals(key, null))
{
if (_nullStorage.IsValueCreated)
_nullStorage.Value.Clear();
}
else
{
if (_innerDictionary.ContainsKey(key))
_innerDictionary[key].Clear();
}
return this;
}
/// <summary>
/// Try get entries by key
/// </summary>
public bool TryGetEntries(TKey key, out IReadOnlyList<TValue> entries)
{
entries = null;
if (ReferenceEquals(key, null))
{
if (_nullStorage.IsValueCreated)
{
entries = _nullStorage.Value;
return true;
}
else return false;
}
else
{
if (_innerDictionary.ContainsKey(key))
{
entries = _innerDictionary[key];
return true;
}
else return false;
}
}
}
The sample of usage:
var dictionary = new OpenDictionary<string, int>();
dictionary.Add("1", 1);
// The next line won't throw an exception;
dictionary.Add("1", 2);
dictionary.TryGetEntries("1", out List<int> result);
// result is { 1, 2 }
dictionary.Add(null, 42);
dictionary.Add(null, 24);
dictionary.TryGetEntries(null, out List<int> result);
// result is { 42, 24 }
It's possible that the error didn't occur in the dot product, but after. For example try this
a = np.random.randn(12,1)
b = np.random.randn(1,5)
c = np.random.randn(5,12)
d = np.dot(a,b) * c
np.dot(a,b) will be fine; however np.dot(a, b) * c is clearly wrong (12x1 X 1x5 = 12x5 which cannot element-wise multiply 5x12) but numpy will give you
ValueError: operands could not be broadcast together with shapes (12,1) (1,5)
The error is misleading; however there is an issue on that line.
Have you tried the Arrays.fill function?
Had the same issue but half of your approach didn't work for me . i took the path the way you did :from the output of react-native-cli instal but then manually wrote in ect/pathes with:
sudo nano /etc/paths
at the end i've added the path from output then ctrl x and y to save . Only this way worked but big thanks for the clue!
To clarify what Gillian said about 4 string, if you have something like this:
string a,b,c,d;
a = b + c + d;
then it would be faster using strings and the plus operator. This is because (like Java, as Eric points out), it internally uses StringBuilder automatically (Actually, it uses a primitive that StringBuilder also uses)
However, if what you are doing is closer to:
string a,b,c,d;
a = a + b;
a = a + c;
a = a + d;
Then you need to explicitly use a StringBuilder. .Net doesn't automatically create a StringBuilder here, because it would be pointless. At the end of each line, "a" has to be an (immutable) string, so it would have to create and dispose a StringBuilder on each line. For speed, you'd need to use the same StringBuilder until you're done building:
string a,b,c,d;
StringBuilder e = new StringBuilder();
e.Append(b);
e.Append(c);
e.Append(d);
a = e.ToString();
SimpleDateFormat
sdf=new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");
String dateString=sdf.format(date);
It will give the output 28/09/2013 09:57:19
as you expected.
The problem is not in Django settings, but in the date passed to the model. Here's how a timezone-aware object looks like:
>>> from django.utils import timezone
>>> import pytz
>>> timezone.now()
datetime.datetime(2013, 11, 20, 20, 8, 7, 127325, tzinfo=pytz.UTC)
And here's a naive object:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2013, 11, 20, 20, 9, 26, 423063)
So if you are passing email date anywhere (and it eventually gets to some model), just use Django's now()
. If not, then it's probably an issue with an existing package that fetches date without timezone and you can patch the package, ignore the warning or set USE_TZ to False.
attr_accessor
is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname
and you can use this field in your View, or model, if you wanted, but mostly in your View.
Let's consider the following example
class Address
attr_reader :street
attr_writer :street
def initialize
@street = ""
end
end
Here we have used attr_reader
(readable attribute) and attr_writer
(writable attribute) for accessing purpose. But we can achieve the same functionality using attr_accessor
. In short, attr_accessor provides access to both getter and setter methods.
So modified code is as below
class Address
attr_accessor :street
def initialize
@street = ""
end
end
attr_accessible
allows you to list all the columns you want to allow Mass Assignment. The opposite of this is attr_protected
which means this field I do NOT want anyone to be allowed to Mass Assign to. More than likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.
Considering a part of a Comment made by @SSilk my end goal has really been to get everything to the right of that last occurence an alternative approach with a very simple formula is to copy a column (say A
) of strings and on the copy (say ColumnB) apply Find and Replace. For instance taking the example: Drive:\Folder\SubFolder\Filename.ext
This returns what remains (here Filename.ext
) after the last instance of whatever character is chosen (here \
) which is sometimes the objective anyway and facilitates finding the position of the last such character with a short formula such as:
=FIND(B1,A1)-1
This has changed, it's now fb://profile/(profileID)
There are many problems in your query.
This is a modified version of your code
string connetionString = null;
string sql = null;
// All the info required to reach your db. See connectionstrings.com
connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
// Prepare a proper parameterized query
sql = "insert into Main ([Firt Name], [Last Name]) values(@first,@last)";
// Create the connection (and be sure to dispose it at the end)
using(SqlConnection cnn = new SqlConnection(connetionString))
{
try
{
// Open the connection to the database.
// This is the first critical step in the process.
// If we cannot reach the db then we have connectivity problems
cnn.Open();
// Prepare the command to be executed on the db
using(SqlCommand cmd = new SqlCommand(sql, cnn))
{
// Create and set the parameters values
cmd.Parameters.Add("@first", SqlDbType.NVarChar).Value = textbox2.text;
cmd.Parameters.Add("@last", SqlDbType.NVarChar).Value = textbox3.text;
// Let's ask the db to execute the query
int rowsAdded = cmd.ExecuteNonQuery();
if(rowsAdded > 0)
MessageBox.Show ("Row inserted!!" + );
else
// Well this should never really happen
MessageBox.Show ("No row inserted");
}
}
catch(Exception ex)
{
// We should log the error somewhere,
// for this example let's just show a message
MessageBox.Show("ERROR:" + ex.Message);
}
}
using
statement to be sure that the connection
will be closed and resources released Apart from this, there are other potential problems. What if the user doesn't input anything in the textbox controls? Do you have done any checking on this before trying to insert? As I have said the fields names contain spaces and this will cause inconveniences in your code. Try to change those field names.
This code assumes that your database columns are of type NVARCHAR, if not, then use the appropriate SqlDbType enum value.
Please plan to switch to a more recent version of NET Framework as soon as possible. The 1.1 is really obsolete now.
And, about AddWithValue problems, this article explain why we should avoid it. Can we stop using AddWithValue() already?
if(!empty($_POST['filename'])){
$filename = $_POST['filename'];
echo $filename;
}
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
I'm using this, and it works well for me:
textBox1.Text = ConfigurationManager.AppSettings["Name"];
This is a simple copy, just like you would do with memcpy()
(indeed, some compilers actually produce a call to memcpy()
for that code). There is no "string" in C, only pointers to a bunch a chars. If your source structure contains such a pointer, then the pointer gets copied, not the chars themselves.
The solution of @Ashivad mostly fixed my problem, but I needed to make this one-line addition to prevent the input to be erased after the results dropdown is displayed:
in success
callback of the autocomplete added this line after triggering chosen:updated
:
$combosearchChosen.find('input').val(request.term);
Complete listing:
var $combosearch = $('[data-combosearch]');
if (!$combosearch.length) {
return;
}
var options = $combosearch.data('options');
console.log('combosearch', $combosearch, options);
$combosearch.chosen({
no_results_text: "Oops, nothing found!",
width: "60%"
});
// actual chosen container
var $combosearchChosen = $combosearch.next();
$combosearchChosen.find('input').autocomplete({
source: function( request, response ) {
$.ajax({
url: options.remote_source + "&query=" + request.term,
dataType: "json",
beforeSend: function(){
$('ul.chosen-results').empty();
},
success: function( data ) {
response( $.map( data, function( item, index ) {
$combosearch.append('<option value="' + item.id + '">' + item.label + '</option>');
}));
$combosearch.trigger('chosen:updated');
$combosearchChosen.find('input').val(request.term);
}
});
}
});
If you just need to test some of the concrete methods without touching any of the abstracts, you can use CALLS_REAL_METHODS
(see Morten's answer), but if the concrete method under test calls some of the abstracts, or unimplemented interface methods, this won't work -- Mockito will complain "Cannot call real method on java interface."
(Yes, it's a lousy design, but some frameworks, e.g. Tapestry 4, kind of force it on you.)
The workaround is to reverse this approach -- use the ordinary mock behavior (i.e., everything's mocked/stubbed) and use doCallRealMethod()
to explicitly call out the concrete method under test. E.g.
public abstract class MyClass {
@SomeDependencyInjectionOrSomething
public abstract MyDependency getDependency();
public void myMethod() {
MyDependency dep = getDependency();
dep.doSomething();
}
}
public class MyClassTest {
@Test
public void myMethodDoesSomethingWithDependency() {
MyDependency theDependency = mock(MyDependency.class);
MyClass myInstance = mock(MyClass.class);
// can't do this with CALLS_REAL_METHODS
when(myInstance.getDependency()).thenReturn(theDependency);
doCallRealMethod().when(myInstance).myMethod();
myInstance.myMethod();
verify(theDependency, times(1)).doSomething();
}
}
Updated to add:
For non-void methods, you'll need to use thenCallRealMethod()
instead, e.g.:
when(myInstance.myNonVoidMethod(someArgument)).thenCallRealMethod();
Otherwise Mockito will complain "Unfinished stubbing detected."
Since the values are actually inside of an HTML attribute, you should use '
"<img src='something' onmouseover='change('ex1')' />";
That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).
The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:
[data getBytes:&byteData length:len];
Which fills the array you have allocated with data from the NSData object.
Actually, you don't need all that stuff with opacity, visibility, <input>
styling, etc. Just take a look:
<a href="#">Just click me.</a>
<script type="text/javascript">
$("a").click(function() {
// creating input on-the-fly
var input = $(document.createElement("input"));
input.attr("type", "file");
// add onchange handler if you wish to get the file :)
input.trigger("click"); // opening dialog
return false; // avoiding navigation
});
</script>
Demo on jsFiddle. Tested in Chrome 30.0 and Firefox 24.0. Didn't work in Opera 12.16, however.
Specify the name of columns in the CSV in the load data infile statement.
The code is like this:
LOAD DATA INFILE '/path/filename.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(column_name3, column_name5);
Here you go with adding data to only two columns(you can choose them with the name of the column) to the table.
The only thing you have to take care is that you have a CSV file(filename.csv) with two values per line(row). Otherwise please mention. I have a different solution.
Thank you.
As @Ninefingers mentioned, pthreads are unix-only. Posix only, really.
That said, Microsoft does have a library that duplicates pthreads:
Here's some sample code I used recently to do just that.
It opens a workbook, goes down the rows, if a condition is met it writes some data in the row. Finally it saves the modified file.
from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
START_ROW = 297 # 0 based (subtract 1 from excel row number)
col_age_november = 1
col_summer1 = 2
col_fall1 = 3
rb = open_workbook(file_path,formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy
for row_index in range(START_ROW, r_sheet.nrows):
age_nov = r_sheet.cell(row_index, col_age_november).value
if age_nov == 3:
#If 3, then Combo I 3-4 year old for both summer1 and fall1
w_sheet.write(row_index, col_summer1, 'Combo I 3-4 year old')
w_sheet.write(row_index, col_fall1, 'Combo I 3-4 year old')
wb.save(file_path + '.out' + os.path.splitext(file_path)[-1])
first you have to create data directory where MongoDB stores data. MongoDB’s default data directory path is the absolute path \data\db on the drive from which you start MongoDB.
if you have install in C:/ drive then you have to create data\db directory. for doing this run command in cmd
C:\>mkdir data\db
To start MongoDB, run mongod.exe.
"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --dbpath="c:\data\db"
The --dbpath option points to your database directory.
Connect to MongoDB.
"C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe"
to check all work good :
show dbs
I'm trying to learn how to do this myself, and it seems you can install the library like this:
cmake_minimum_required(VERSION 2.4.0)
project(mycustomlib)
# Find source files
file(GLOB SOURCES src/*.cpp)
# Include header files
include_directories(include)
# Create shared library
add_library(${PROJECT_NAME} SHARED ${SOURCES})
# Install library
install(TARGETS ${PROJECT_NAME} DESTINATION lib/${PROJECT_NAME})
# Install library headers
file(GLOB HEADERS include/*.h)
install(FILES ${HEADERS} DESTINATION include/${PROJECT_NAME})
Another alternative, assuming your elements are stored as variables (which is often a good idea if you're accessing them multiple times in a function body):
function disableMinHeight() {
var $html = $("html");
var $body = $("body");
var $slideout = $("#slideout");
$html.add($body).add($slideout).css("min-height", 0);
};
Takes advantage of jQuery chaining and allows you to use references.
Simpler nio usage:
URL website = new URL("http://www.website.com/information.asp");
try (InputStream in = website.openStream()) {
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
}
I was also developing a similar application. I was also getting not found error even though the file was there. This solve my problem. I mention my download folder in 'static_folder':
app = Flask(__name__,static_folder='pdf')
My code for the download is as follows:
@app.route('/pdf/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(directory='pdf', filename=filename)
This is how I am calling my file from html.
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.pdf target="_blank" style="margin-right: 5px;">Download pdf </a>
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.png target="_blank" style="margin-right: 5px;">Download png </a>
Let's say you have already set up your origin
as the remote repository. Then,
git diff <local branch> <origin>/<remote branch name>
See Converting unix timestamp to excel date-time forum thread.
You Can try this script
<!DOCTYPE html>
<html>
<script>
function getMultipleSelectedValue()
{
var x=document.getElementById("alpha");
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
alert(x.options[i].value);
}
}
}
</script>
</head>
<body>
<select multiple="multiple" id="alpha">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
<input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
</body>
</html>
compile
is a configuration
that is usually introduced by a plugin (most likely the java plugin) Have a look at the gradle userguide for details about configurations. For now adding the java plugin on top of your build script should do the trick:
apply plugin:'java'
Just to show an example of how to dynamically add the "Content-type" header to every POST request. In may case I'm passing POST params as query string, that is done using the transformRequest. In this case its value is application/x-www-form-urlencoded.
// set Content-Type for POST requests
angular.module('myApp').run(basicAuth);
function basicAuth($http) {
$http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
}
Then from the interceptor in the request method before return the config object
// if header['Content-type'] is a POST then add data
'request': function (config) {
if (
angular.isDefined(config.headers['Content-Type'])
&& !angular.isDefined(config.data)
) {
config.data = '';
}
return config;
}
How about this:
< jQuery 1.7
$("#input").bind("propertychange change keyup paste input", function(){
// do stuff;
});
> jQuery 1.7
$("#input").on("propertychange change keyup paste input", function(){
// do stuff;
});
This works in IE8/IE9, FF, Chrome
When I'm in a C mood, I usually use zip and list comprehensions for scanf-like behavior. Like this:
input = '1 3.0 false hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,strtobool,str),input.split())]
print (a, b, c, d)
Note that for more complex format strings, you do need to use regular expressions:
import re
input = '1:3.0 false,hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,strtobool,str),re.search('^(\d+):([\d.]+) (\w+),(\w+)$',input).groups())]
print (a, b, c, d)
Note also that you need conversion functions for all types you want to convert. For example, above I used something like:
strtobool = lambda s: {'true': True, 'false': False}[s]
The following should work, but you may need to change the format:
echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));
One thing we should note: the jdk
should be installed on C:
drive.
I had JDK installed on my D:
drive like this:
D:\Program Files\Java\jdk1.8.0_101
And it would still give me the same error. For some reason Java should be installed on C: drive.
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-Type: application/xml; charset=utf-8");
To parse a Date from a String you can choose which format you would like it to have. For example:
public Date StringToDate(String s){
Date result = null;
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result = dateFormat.parse(s);
}
catch(ParseException e){
e.printStackTrace();
}
return result ;
}
If you would like to use this method now, you will have to use something like this
Date date = StringToDate("2015-12-06 17:03:00");
For more explanation you should check out http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.
HTML
<div class="shadow-block">
<div class="shadow"></div>
<div class="overlay">
<div class="overlay-inner">
content here
</div>
</div>
</div>
CSS
.overlay {
background: #f7f7f4;
height: 185px;
overflow: hidden;
position: relative;
width: 100%;
}
.overlay:before {
border-radius: 50% 50% 50% 50%;
box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
content: " ";
display: block;
margin: 0 auto;
width: 80%;
}
.overlay:after {
border-radius: 50% 50% 50% 50%;
box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
content: "-";
display: block;
margin: 0 auto;
position: absolute;
bottom: -65px;
left: -50%;
right: -50%;
width: 80%;
}
.shadow {
position: relative;
width:100%;
height:8px;
margin: 0 0 -22px 0;
-webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
border-radius: 50%;
}
In order to resolve java.lang.OutOfMemoryError: Java heap space in Maven, try to configure below configuration in pom
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<verbose>true</verbose>
<fork>true</fork>
<argLine>-XX:MaxPermSize=500M</argLine>
</configuration>
</plugin>
Compiled some answers from here into re-usable ClaimsManager class with my additions.
Claims got persisted, user cookie updated, sign in refreshed.
Please note that ApplicationUser can be substituted with IdentityUser if you didn't customize former. Also in my case it needs to have slightly different logic in Development environment, so you might want to remove IWebHostEnvironment dependency.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using YourMvcCoreProject.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Hosting;
namespace YourMvcCoreProject.Identity
{
public class ClaimsManager
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IWebHostEnvironment _env;
private readonly ClaimsPrincipalAccessor _currentPrincipalAccessor;
public ClaimsManager(
ClaimsPrincipalAccessor currentPrincipalAccessor,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IWebHostEnvironment env)
{
_currentPrincipalAccessor = currentPrincipalAccessor;
_userManager = userManager;
_signInManager = signInManager;
_env = env;
}
/// <param name="refreshSignin">Sometimes (e.g. when adding multiple claims at once) it is desirable to refresh cookie only once, for the last one </param>
public async Task AddUpdateClaim(string claimType, string claimValue, bool refreshSignin = true)
{
await AddClaim(
_currentPrincipalAccessor.ClaimsPrincipal,
claimType,
claimValue,
async user =>
{
await RemoveClaim(_currentPrincipalAccessor.ClaimsPrincipal, user, claimType);
},
refreshSignin);
}
public async Task AddClaim(string claimType, string claimValue, bool refreshSignin = true)
{
await AddClaim(_currentPrincipalAccessor.ClaimsPrincipal, claimType, claimValue, refreshSignin);
}
/// <summary>
/// At certain stages of user auth there is no user yet in context but there is one to work with in client code (e.g. calling from ClaimsTransformer)
/// that's why we have principal as param
/// </summary>
public async Task AddClaim(ClaimsPrincipal principal, string claimType, string claimValue, bool refreshSignin = true)
{
await AddClaim(
principal,
claimType,
claimValue,
async user =>
{
// allow reassignment in dev
if (_env.IsDevelopment())
await RemoveClaim(principal, user, claimType);
if (GetClaim(principal, claimType) != null)
throw new ClaimCantBeReassignedException(claimType);
},
refreshSignin);
}
public async Task RemoveClaims(IEnumerable<string> claimTypes, bool refreshSignin = true)
{
await RemoveClaims(_currentPrincipalAccessor.ClaimsPrincipal, claimTypes, refreshSignin);
}
public async Task RemoveClaims(ClaimsPrincipal principal, IEnumerable<string> claimTypes, bool refreshSignin = true)
{
AssertAuthenticated(principal);
foreach (var claimType in claimTypes)
{
await RemoveClaim(principal, claimType);
}
// reflect the change in the Identity cookie
if (refreshSignin)
await _signInManager.RefreshSignInAsync(await _userManager.GetUserAsync(principal));
}
public async Task RemoveClaim(string claimType, bool refreshSignin = true)
{
await RemoveClaim(_currentPrincipalAccessor.ClaimsPrincipal, claimType, refreshSignin);
}
public async Task RemoveClaim(ClaimsPrincipal principal, string claimType, bool refreshSignin = true)
{
AssertAuthenticated(principal);
var user = await _userManager.GetUserAsync(principal);
await RemoveClaim(principal, user, claimType);
// reflect the change in the Identity cookie
if (refreshSignin)
await _signInManager.RefreshSignInAsync(user);
}
private async Task AddClaim(ClaimsPrincipal principal, string claimType, string claimValue, Func<ApplicationUser, Task> processExistingClaims, bool refreshSignin)
{
AssertAuthenticated(principal);
var user = await _userManager.GetUserAsync(principal);
await processExistingClaims(user);
var claim = new Claim(claimType, claimValue);
ClaimsIdentity(principal).AddClaim(claim);
await _userManager.AddClaimAsync(user, claim);
// reflect the change in the Identity cookie
if (refreshSignin)
await _signInManager.RefreshSignInAsync(user);
}
/// <summary>
/// Due to bugs or as result of debug it can be more than one identity of the same type.
/// The method removes all the claims of a given type.
/// </summary>
private async Task RemoveClaim(ClaimsPrincipal principal, ApplicationUser user, string claimType)
{
AssertAuthenticated(principal);
var identity = ClaimsIdentity(principal);
var claims = identity.FindAll(claimType).ToArray();
if (claims.Length > 0)
{
await _userManager.RemoveClaimsAsync(user, claims);
foreach (var c in claims)
{
identity.RemoveClaim(c);
}
}
}
private static Claim GetClaim(ClaimsPrincipal principal, string claimType)
{
return ClaimsIdentity(principal).FindFirst(claimType);
}
/// <summary>
/// This kind of bugs has to be found during testing phase
/// </summary>
private static void AssertAuthenticated(ClaimsPrincipal principal)
{
if (!principal.Identity.IsAuthenticated)
throw new InvalidOperationException("User should be authenticated in order to update claims");
}
private static ClaimsIdentity ClaimsIdentity(ClaimsPrincipal principal)
{
return (ClaimsIdentity) principal.Identity;
}
}
public class ClaimCantBeReassignedException : Exception
{
public ClaimCantBeReassignedException(string claimType) : base($"{claimType} can not be reassigned")
{
}
}
public class ClaimsPrincipalAccessor
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ClaimsPrincipalAccessor(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public ClaimsPrincipal ClaimsPrincipal => _httpContextAccessor.HttpContext.User;
}
// to register dependency put this into your Startup.cs and inject ClaimsManager into Controller constructor (or other class) the in same way as you do for other dependencies
public class Startup
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddTransient<ClaimsPrincipalAccessor>();
services.AddTransient<ClaimsManager>();
}
}
}
unset
is the command you're looking for.
unset GNUPLOT_DRIVER_DIR
The default console handler is attached to the root logger, which is a parent of all other loggers including yours. So I see two ways to solve your problem:
If this is only affects this particular class of yours, the simplest solution would be to disable passing the logs up to the parent logger:
logger.setUseParentHandlers(false);
If you want to change this behaviour for your whole app, you could remove the default console handler from the root logger altogether before adding your own handlers:
Logger globalLogger = Logger.getLogger("global");
Handler[] handlers = globalLogger.getHandlers();
for(Handler handler : handlers) {
globalLogger.removeHandler(handler);
}
Note: if you want to use the same log handlers in other classes too, the best way is to move the log configuration into a config file in the long run.
final ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
}
});
I hope this fixes your problem.
Those are caused most likely by 2 issues:
If some of those are omitted - maven could fail with random error messages.
Just hope I've saved somebody from googling around this issue for 6 hours, like I did.
An auto-updated column is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. An auto-updated column remains unchanged if all other columns are set to their current values.
To explain it let's imagine you have only one row:
-------------------------------
| price | updated_at |
-------------------------------
| 2 | 2018-02-26 16:16:17 |
-------------------------------
Now, if you run the following update column:
update my_table
set price = 2
it will not change the value of updated_at, since price value wasn't actually changed (it was already 2).
But if you have another row with price value other than 2, then the updated_at value of that row (with price <> 3) will be updated to CURRENT_TIMESTAMP.
If you are looking for Hash modification, your solution works ok. However, if you want to change the query, you can use the pushState, as you said. Here it is an example that might help you to implement it properly. I tested and it worked fine:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values. And of course that it requires modern browsers that can process HTML5 History API.
For more information:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
You can use PSCP to copy files from Windows to Linux.
Type command pscp source_file user@host:destination_file
pscp sample.txt [email protected]:/mydata/sample.txt
Here is my updated code. It works fine and it can help you.
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
function go(loc) {
document.getElementById('calendar').src = loc;
}
</script>
</head>
<body>
<iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>
<form method="post">
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month
</form>
</body>
</html>
It is true that the same-origin policy prevents JavaScript from making requests across domains, but the CORS specification allows just the sort of API access you are looking for, and is supported by the current batch of major browsers.
See how to enable cross-origin resource sharing for client and server:
"Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries. If you serve public content, please consider using CORS to open it up for universal JavaScript/browser access."
This answer may be late reply but it will be useful for seeing this topic in future.
The features of .NET framework 4.5 can be seen in the following link.
To summarize:
Installation
.NET Framework 4.5 does not support Windows XP or Windows Server 2003, and therefore, if you have to create applications that target these operating systems, you will need to stay with .NET Framework 4.0. In contrast, Windows 8 and Windows Server 2012 in all of their editions include .NET Framework 4.5.
- Support for Arrays Larger than 2 GB on 64-bit Platforms
- Enhanced Background Server Garbage Collection
- Support for Timeouts in Regular Expression Evaluations
- Support for Unicode 6.0.0 in Culture-Sensitive Sorting and Casing Rules on Windows 8
- Simple Default Culture Definition for an Application Domain
- Internationalized Domain Names in Windows 8 Apps
For those still wanting a way to get the thumbnail via URL only, just like Youtube, I built a small application that fetches it with just the Vimeo ID.
https://vumbnail.com/358629078.jpg
Just plug in your video ID and it will pull it and cache it for 28 days so it serves fast.
Here are a couple of examples in HTML:
Simple Image Example
<img src="https://vumbnail.com/358629078.jpg" />
<br>
<br>
Modern Responsive Image Example
<img srcset="https://vumbnail.com/358629078.jpg 640w, https://vumbnail.com/358629078_large.jpg 640w, https://vumbnail.com/358629078_medium.jpg 200w, https://vumbnail.com/358629078_small.jpg 100w" sizes="(max-width: 640px) 100vw, 640px" src="https://vumbnail.com/358629078.jpg" />
_x000D_
If you want to spin up your own you can do so here.
You need to Tomcat Dependency and also extend your Application Class from extends SpringBootServletInitializer
@SpringBootApplication
public class App extend SpringBootServletInitializer
{
public static void main( String[] args )
{
SpringApplication.run(App.class, "hello");
}
}
I like to use a NOT EXIST
-based solution for this problem:
SELECT
id,
rev
-- you can select other columns here
FROM YourTable t
WHERE NOT EXISTS (
SELECT * FROM YourTable t WHERE t.id = id AND rev > t.rev
)
This will select all records with max value within the group and allows you to select other columns.
It's in https://console.firebase.google.com/project/(your-project-id)/settings/cloudmessaging
You can find the API KEY in:
(gear-next-to-project-name) > Project Settings > Cloud Messaging
Server Key is the API key.
Just a supplement of the answers:
There may be a time you set all things right, but you may accidentally add some other UIs in you .xib
, like a UIButton
:
Just delete the extra UI, it works.
have u tried this :
>>> from datetime import datetime as DT
>>> l =[]
>>> l.append(DT(1988,12,12))
>>> l.append(DT(1979,12,12))
>>> l.append(DT(1979,12,11))
>>> l.append(DT(2011,12,11))
>>> l.append(DT(2022,12,11))
>>> min(l)
datetime.datetime(1979, 12, 11, 0, 0)
>>> max(l)
datetime.datetime(2022, 12, 11, 0, 0)
I know that this is a pretty old question but I've just met same issue. I don't know exactly why but it seems that tableFooterView can be only an instance of UIView (not "kind of" but "is member")... So in my case I've created new UIView object (for example wrapperView) and add my custom subview to it... In your case, chamge your code from:
CGRect footerRect = CGRectMake(0, 0, 320, 40);
UILabel *tableFooter = [[UILabel alloc] initWithFrame:footerRect];
tableFooter.textColor = [UIColor blueColor];
tableFooter.backgroundColor = [self.theTable backgroundColor];
tableFooter.opaque = YES;
tableFooter.font = [UIFont boldSystemFontOfSize:15];
tableFooter.text = @"test";
self.theTable.tableFooterView = tableFooter;
[tableFooter release];
to:
CGRect footerRect = CGRectMake(0, 0, 320, 40);
UIView *wrapperView = [[UIView alloc] initWithFrame:footerRect];
UILabel *tableFooter = [[UILabel alloc] initWithFrame:footerRect];
tableFooter.textColor = [UIColor blueColor];
tableFooter.backgroundColor = [self.theTable backgroundColor];
tableFooter.opaque = YES;
tableFooter.font = [UIFont boldSystemFontOfSize:15];
tableFooter.text = @"test";
[wrapperView addSubview:tableFooter];
self.theTable.tableFooterView = wrapperView;
[wrapperView release];
[tableFooter release];
Hope it helps. It works for me.
if you know the id of the inputs you only need to use this:
var value = $("#inputID").val();
Working code :
{
DataBaseEntity db = new DataBaseEntity (); //This is EF entity
string dateCheck="5/21/2018";
var list= db.tbl
.where(x=>(x.DOE.Value.Month
+"/"+x.DOE.Value.Day
+"/"+x.DOE.Value.Year)
.ToString()
.Contains(dateCheck))
}
I tried Apache Commons StringEscapeUtils.unescapeHtml3() in my project, but wasn't satisfied with its performance. Turns out, it does a lot of unnecessary operations. For one, it allocates a StringWriter for every call, even if there's nothing to unescape in the string. I've rewritten that code differently, now it works much faster. Whoever finds this in google is welcome to use it.
Following code unescapes all HTML 3 symbols and numeric escapes (equivalent to Apache unescapeHtml3). You can just add more entries to the map if you need HTML 4.
package com.example;
import java.io.StringWriter;
import java.util.HashMap;
public class StringUtils {
public static final String unescapeHtml3(final String input) {
StringWriter writer = null;
int len = input.length();
int i = 1;
int st = 0;
while (true) {
// look for '&'
while (i < len && input.charAt(i-1) != '&')
i++;
if (i >= len)
break;
// found '&', look for ';'
int j = i;
while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';')
j++;
if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) {
i++;
continue;
}
// found escape
if (input.charAt(i) == '#') {
// numeric escape
int k = i + 1;
int radix = 10;
final char firstChar = input.charAt(k);
if (firstChar == 'x' || firstChar == 'X') {
k++;
radix = 16;
}
try {
int entityValue = Integer.parseInt(input.substring(k, j), radix);
if (writer == null)
writer = new StringWriter(input.length());
writer.append(input.substring(st, i - 1));
if (entityValue > 0xFFFF) {
final char[] chrs = Character.toChars(entityValue);
writer.write(chrs[0]);
writer.write(chrs[1]);
} else {
writer.write(entityValue);
}
} catch (NumberFormatException ex) {
i++;
continue;
}
}
else {
// named escape
CharSequence value = lookupMap.get(input.substring(i, j));
if (value == null) {
i++;
continue;
}
if (writer == null)
writer = new StringWriter(input.length());
writer.append(input.substring(st, i - 1));
writer.append(value);
}
// skip escape
st = j + 1;
i = st;
}
if (writer != null) {
writer.append(input.substring(st, len));
return writer.toString();
}
return input;
}
private static final String[][] ESCAPES = {
{"\"", "quot"}, // " - double-quote
{"&", "amp"}, // & - ampersand
{"<", "lt"}, // < - less-than
{">", "gt"}, // > - greater-than
// Mapping to escape ISO-8859-1 characters to their named HTML 3.x equivalents.
{"\u00A0", "nbsp"}, // non-breaking space
{"\u00A1", "iexcl"}, // inverted exclamation mark
{"\u00A2", "cent"}, // cent sign
{"\u00A3", "pound"}, // pound sign
{"\u00A4", "curren"}, // currency sign
{"\u00A5", "yen"}, // yen sign = yuan sign
{"\u00A6", "brvbar"}, // broken bar = broken vertical bar
{"\u00A7", "sect"}, // section sign
{"\u00A8", "uml"}, // diaeresis = spacing diaeresis
{"\u00A9", "copy"}, // © - copyright sign
{"\u00AA", "ordf"}, // feminine ordinal indicator
{"\u00AB", "laquo"}, // left-pointing double angle quotation mark = left pointing guillemet
{"\u00AC", "not"}, // not sign
{"\u00AD", "shy"}, // soft hyphen = discretionary hyphen
{"\u00AE", "reg"}, // ® - registered trademark sign
{"\u00AF", "macr"}, // macron = spacing macron = overline = APL overbar
{"\u00B0", "deg"}, // degree sign
{"\u00B1", "plusmn"}, // plus-minus sign = plus-or-minus sign
{"\u00B2", "sup2"}, // superscript two = superscript digit two = squared
{"\u00B3", "sup3"}, // superscript three = superscript digit three = cubed
{"\u00B4", "acute"}, // acute accent = spacing acute
{"\u00B5", "micro"}, // micro sign
{"\u00B6", "para"}, // pilcrow sign = paragraph sign
{"\u00B7", "middot"}, // middle dot = Georgian comma = Greek middle dot
{"\u00B8", "cedil"}, // cedilla = spacing cedilla
{"\u00B9", "sup1"}, // superscript one = superscript digit one
{"\u00BA", "ordm"}, // masculine ordinal indicator
{"\u00BB", "raquo"}, // right-pointing double angle quotation mark = right pointing guillemet
{"\u00BC", "frac14"}, // vulgar fraction one quarter = fraction one quarter
{"\u00BD", "frac12"}, // vulgar fraction one half = fraction one half
{"\u00BE", "frac34"}, // vulgar fraction three quarters = fraction three quarters
{"\u00BF", "iquest"}, // inverted question mark = turned question mark
{"\u00C0", "Agrave"}, // ? - uppercase A, grave accent
{"\u00C1", "Aacute"}, // ? - uppercase A, acute accent
{"\u00C2", "Acirc"}, // ? - uppercase A, circumflex accent
{"\u00C3", "Atilde"}, // ? - uppercase A, tilde
{"\u00C4", "Auml"}, // ? - uppercase A, umlaut
{"\u00C5", "Aring"}, // ? - uppercase A, ring
{"\u00C6", "AElig"}, // ? - uppercase AE
{"\u00C7", "Ccedil"}, // ? - uppercase C, cedilla
{"\u00C8", "Egrave"}, // ? - uppercase E, grave accent
{"\u00C9", "Eacute"}, // ? - uppercase E, acute accent
{"\u00CA", "Ecirc"}, // ? - uppercase E, circumflex accent
{"\u00CB", "Euml"}, // ? - uppercase E, umlaut
{"\u00CC", "Igrave"}, // ? - uppercase I, grave accent
{"\u00CD", "Iacute"}, // ? - uppercase I, acute accent
{"\u00CE", "Icirc"}, // ? - uppercase I, circumflex accent
{"\u00CF", "Iuml"}, // ? - uppercase I, umlaut
{"\u00D0", "ETH"}, // ? - uppercase Eth, Icelandic
{"\u00D1", "Ntilde"}, // ? - uppercase N, tilde
{"\u00D2", "Ograve"}, // ? - uppercase O, grave accent
{"\u00D3", "Oacute"}, // ? - uppercase O, acute accent
{"\u00D4", "Ocirc"}, // ? - uppercase O, circumflex accent
{"\u00D5", "Otilde"}, // ? - uppercase O, tilde
{"\u00D6", "Ouml"}, // ? - uppercase O, umlaut
{"\u00D7", "times"}, // multiplication sign
{"\u00D8", "Oslash"}, // ? - uppercase O, slash
{"\u00D9", "Ugrave"}, // ? - uppercase U, grave accent
{"\u00DA", "Uacute"}, // ? - uppercase U, acute accent
{"\u00DB", "Ucirc"}, // ? - uppercase U, circumflex accent
{"\u00DC", "Uuml"}, // ? - uppercase U, umlaut
{"\u00DD", "Yacute"}, // ? - uppercase Y, acute accent
{"\u00DE", "THORN"}, // ? - uppercase THORN, Icelandic
{"\u00DF", "szlig"}, // ? - lowercase sharps, German
{"\u00E0", "agrave"}, // ? - lowercase a, grave accent
{"\u00E1", "aacute"}, // ? - lowercase a, acute accent
{"\u00E2", "acirc"}, // ? - lowercase a, circumflex accent
{"\u00E3", "atilde"}, // ? - lowercase a, tilde
{"\u00E4", "auml"}, // ? - lowercase a, umlaut
{"\u00E5", "aring"}, // ? - lowercase a, ring
{"\u00E6", "aelig"}, // ? - lowercase ae
{"\u00E7", "ccedil"}, // ? - lowercase c, cedilla
{"\u00E8", "egrave"}, // ? - lowercase e, grave accent
{"\u00E9", "eacute"}, // ? - lowercase e, acute accent
{"\u00EA", "ecirc"}, // ? - lowercase e, circumflex accent
{"\u00EB", "euml"}, // ? - lowercase e, umlaut
{"\u00EC", "igrave"}, // ? - lowercase i, grave accent
{"\u00ED", "iacute"}, // ? - lowercase i, acute accent
{"\u00EE", "icirc"}, // ? - lowercase i, circumflex accent
{"\u00EF", "iuml"}, // ? - lowercase i, umlaut
{"\u00F0", "eth"}, // ? - lowercase eth, Icelandic
{"\u00F1", "ntilde"}, // ? - lowercase n, tilde
{"\u00F2", "ograve"}, // ? - lowercase o, grave accent
{"\u00F3", "oacute"}, // ? - lowercase o, acute accent
{"\u00F4", "ocirc"}, // ? - lowercase o, circumflex accent
{"\u00F5", "otilde"}, // ? - lowercase o, tilde
{"\u00F6", "ouml"}, // ? - lowercase o, umlaut
{"\u00F7", "divide"}, // division sign
{"\u00F8", "oslash"}, // ? - lowercase o, slash
{"\u00F9", "ugrave"}, // ? - lowercase u, grave accent
{"\u00FA", "uacute"}, // ? - lowercase u, acute accent
{"\u00FB", "ucirc"}, // ? - lowercase u, circumflex accent
{"\u00FC", "uuml"}, // ? - lowercase u, umlaut
{"\u00FD", "yacute"}, // ? - lowercase y, acute accent
{"\u00FE", "thorn"}, // ? - lowercase thorn, Icelandic
{"\u00FF", "yuml"}, // ? - lowercase y, umlaut
};
private static final int MIN_ESCAPE = 2;
private static final int MAX_ESCAPE = 6;
private static final HashMap<String, CharSequence> lookupMap;
static {
lookupMap = new HashMap<String, CharSequence>();
for (final CharSequence[] seq : ESCAPES)
lookupMap.put(seq[1].toString(), seq[0]);
}
}
in case if your table has tbody
let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)
<ul>
<li ng-repeat=interface in interfaces>
<img src='green-checkmark.png' ng-show="interface=='UP'" />
<img src='big-black-X.png' ng-show="interface=='DOWN'" />
</li>
</ul>
Make sure you have closed your MSAccess file before running the java program.
By using pandas we can read excel easily.
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
DataF=pd.read_excel("Test.xlsx",sheet_name='Sheet1')
print("Column headings:")
print(DataF.columns)
Test at :https://repl.it Reference: https://pythonspot.com/read-excel-with-pandas/
function countWords(str) {
var regEx = /([^\u0000-\u007F]|\w)+/g;
return str.match(regEx).length;
}
Explanation:
/([^\u0000-\u007F]|\w)
matches word characters - which is great -> regex does the heavy lifting for us. (This pattern is based on the following SO answer: https://stackoverflow.com/a/35743562/1806956 by @Landeeyo)
+
matches the whole string of the previously specified word characters - so we basically group word characters.
/g
means it keeps looking till the end.
str.match(regEx)
returns an array of the found words - so we count its length.
Wordpress dont have a php.ini file.
It just a cms, look into your server.
for example if you use XAMPP in windows xampp\php\php.ini
is the location.
savefig
specifies the DPI for the saved figure (The default is 100 if it's not specified in your .matplotlibrc, have a look at the dpi
kwarg to savefig
). It doesn't inheret it from the DPI of the original figure.
The DPI affects the relative size of the text and width of the stroke on lines, etc. If you want things to look identical, then pass fig.dpi
to fig.savefig
.
E.g.
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', dpi=fig.dpi)
This question is 2 years old but it's still a good question and it was the first Google result ... but all of the existing answers recommend setting and removing the HTML attribute (removeAttr("disabled")) "disabled", which is not the right approach. There is a lot of confusion regarding attribute vs. property.
The "disabled" in <input type="button" disabled>
in the markup is called a boolean attribute by the W3C.
Quote:
A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.
https://stackoverflow.com/a/7572855/664132
Related:
Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property...
Relevant:
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.
$( "input" ).prop( "disabled", false );
To [...] change DOM properties such as the [...] disabled state of form elements, use the .prop() method.
As for the disable on change part of the question: There is an event called "input", but browser support is limited and it's not a jQuery event, so jQuery won't make it work. The change event works reliably, but is fired when the element loses focus. So one might combine the two (some people also listen for keyup and paste).
Here's an untested piece of code to show what I mean:
$(document).ready(function() {
var $submit = $('input[type="submit"]');
$submit.prop('disabled', true);
$('input[type="text"]').on('input change', function() { //'input change keyup paste'
$submit.prop('disabled', !$(this).val().length);
});
});
In my case I was adding javascript dynamicly and using double quotes 2 times in string templates so i changed the second to single quotes and the error was gone. I hope it will help some of the people coming here for the same reason.
you can use Info-unzip command line cod.you only need to download unzip.exe from Info-unzip official website.
internal static void Unzip(string sorcefile)
{
try
{
AFolderFiles.AFolderFilesDelete.DeleteFolder(TempBackupFolder); // delete old folder
AFolderFiles.AFolderFilesCreate.CreateIfNotExist(TempBackupFolder); // delete old folder
//need to Command command also to export attributes to a excel file
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; // window type
startInfo.FileName = UnzipExe;
startInfo.Arguments = sorcefile + " -d " + TempBackupFolder;
process.StartInfo = startInfo;
process.Start();
//string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Dispose();
process.Close();
}
catch (Exception ex){ throw ex; }
}
other option In Load Url in Same Application using Webview
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
This works and is even simpler. If you remove ECHO-s, it will be even smaller:
REM
REM DEMO - how to launch several processes in parallel, and wait until all of them finish.
REM
@ECHO OFF
start "!The Title!" Echo Close me manually!
start "!The Title!" Echo Close me manually!
:waittofinish
echo At least one process is still running...
timeout /T 2 /nobreak >nul
tasklist.exe /fi "WINDOWTITLE eq !The Title!" | find ":" >nul
if errorlevel 1 goto waittofinish
echo Finished!
PAUSE
I personally use a more generic function that works for any property of any array:
function lookup(array, prop, value) {
for (var i = 0, len = array.length; i < len; i++)
if (array[i] && array[i][prop] === value) return array[i];
}
You just call it like this:
lookup(purposeObjects, "purpose", "daily");
In my case I didn't see any tables under my database on phpMyAdmin
I am using Wamp server
but when I checked the directory under C:\wamp\bin\mysql\mysql5.6.12\data
I found this employed.ibd
when I deleted this file manually I was able to drop
the database from phpMyAdmin
smoothly without any problems.
If array is static allocated:
size_t size = sizeof(arr) / sizeof(int);
if array is dynamic allocated(heap):
int *arr = malloc(sizeof(int) * size);
where variable size is a dimension of the arr.
# Close STDOUT file descriptor
exec 1<&-
# Close STDERR FD
exec 2<&-
# Open STDOUT as $LOG_FILE file for read and write.
exec 1<>$LOG_FILE
# Redirect STDERR to STDOUT
exec 2>&1
echo "This line will appear in $LOG_FILE, not 'on screen'"
Now, simple echo will write to $LOG_FILE. Useful for daemonizing.
To the author of the original post,
It depends what you need to achieve. If you just need to redirect in/out of a command you call from your script, the answers are already given. Mine is about redirecting within current script which affects all commands/built-ins(includes forks) after the mentioned code snippet.
Another cool solution is about redirecting to both std-err/out AND to logger or log file at once which involves splitting "a stream" into two. This functionality is provided by 'tee' command which can write/append to several file descriptors(files, sockets, pipes, etc) at once: tee FILE1 FILE2 ... >(cmd1) >(cmd2) ...
exec 3>&1 4>&2 1> >(tee >(logger -i -t 'my_script_tag') >&3) 2> >(tee >(logger -i -t 'my_script_tag') >&4)
trap 'cleanup' INT QUIT TERM EXIT
get_pids_of_ppid() {
local ppid="$1"
RETVAL=''
local pids=`ps x -o pid,ppid | awk "\\$2 == \\"$ppid\\" { print \\$1 }"`
RETVAL="$pids"
}
# Needed to kill processes running in background
cleanup() {
local current_pid element
local pids=( "$$" )
running_pids=("${pids[@]}")
while :; do
current_pid="${running_pids[0]}"
[ -z "$current_pid" ] && break
running_pids=("${running_pids[@]:1}")
get_pids_of_ppid $current_pid
local new_pids="$RETVAL"
[ -z "$new_pids" ] && continue
for element in $new_pids; do
running_pids+=("$element")
pids=("$element" "${pids[@]}")
done
done
kill ${pids[@]} 2>/dev/null
}
So, from the beginning. Let's assume we have terminal connected to /dev/stdout(FD #1) and /dev/stderr(FD #2). In practice, it could be a pipe, socket or whatever.
The result of running a script having the above line and additionally this one:
echo "Will end up in STDOUT(terminal) and /var/log/messages"
...is as follows:
$ ./my_script
Will end up in STDOUT(terminal) and /var/log/messages
$ tail -n1 /var/log/messages
Sep 23 15:54:03 wks056 my_script_tag[11644]: Will end up in STDOUT(terminal) and /var/log/messages
If you want to see clearer picture, add these 2 lines to the script:
ls -l /proc/self/fd/
ps xf
sudo apt-get -y install python-software-properties && \
sudo apt-get -y install software-properties-common && \
sudo apt-get -y install gcc make build-essential libssl-dev libffi-dev python-dev
You need the libssl-dev and libffi-dev if especially you are trying to install python's cryptography libraries or python libs that depend on it(eg ansible)
A little tip on sysout -- I like to renamed it to "sop". Nothing else in the java libs starts with "sop" so you can quickly type "sop" and boom, it inserts.
Try this :
<?php
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = wc_get_product( $values['data']->get_id());
echo "<b>".$_product->get_title().'</b> <br> Quantity: '.$values['quantity'].'<br>';
$price = get_post_meta($values['product_id'] , '_price', true);
echo " Price: ".$price."<br>";
}
?>
To get Product Image and Regular & Sale Price:
<?php
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = wc_get_product( $values['data']->get_id() );
//product image
$getProductDetail = wc_get_product( $values['product_id'] );
echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )
echo "<b>".$_product->get_title() .'</b> <br> Quantity: '.$values['quantity'].'<br>';
$price = get_post_meta($values['product_id'] , '_price', true);
echo " Price: ".$price."<br>";
/*Regular Price and Sale Price*/
echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."<br>";
echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."<br>";
}
?>
Sticky notes in Windows 10 are stored here:
C:\Users\"Username"\Appdata\Roaming\Microsoft\Sticky Notes
If you want to restore your sticky notes from earlier versions of windwos, just copy the .snt file and place it in the above location.
N.B: Replace only if you don't have any new notes in Windows 10!
You are looking for continue.
Use HTML textarea with runat="server"
to access it in server side.
This solution has less pain than using javascript or regex.
<textarea runat="server" id="txt1" maxlength="100" />
Note: To access Text
Property in server side, you should use txt1.Value
instead of txt1.Text
Since 2009, a lot happened. Rust delivered many CLI utilities, among them ripgrep. It is advertised as a recursively searches directories for a regex pattern, supports Windows, MacOSX and Linux.
It is fast. Look at this performance comparison with similar tools. It also has many explanations on the design of the tool. Quite informative and geeky. =)
Supports a wide range of features that the POSIX grep tools support. Look at the comparison by ack author here.
If you have Scoop, you can install it with scoop install ripgrep
. Else head over to the installation section of the doc.
One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
I think this answer needs an update, check the edit history for the old answer.
Basically, you have three deferent cases null, undefined, and undeclared, see the snippet below.
// bad-file.ts
console.log(message)
You'll get an error says that variable message
is undefined (aka undeclared), of course, the Typescript compiler shouldn't let you do that but REALLY nothing can prevent you.
// evil-file.ts
// @ts-gnore
console.log(message)
The compiler will be happy to just compile the code above. So, if you're sure that all variables are declared you can simply do that
if ( message != null ) {
// do something with the message
}
the code above will check for null
and undefined
, BUT in case the message
variable may be undeclared (for safety), you may consider the following code
if ( typeof(message) !== 'undefined' && message !== null ) {
// message variable is more than safe to be used.
}
Note: the order here typeof(message) !== 'undefined' && message !== null
is very important you have to check for the undefined
state first atherwise it will be just the same as message != null
, thanks @Jaider.
I don't think this DateTimePicker has been mentioned before:
A WPF DateTimePicker That Works Like the One in Winforms
That one is in VB and has some bugs. I converted it to C# and made a new version with bug fixes.
Note: I used the Calendar control in WPFToolkit so that I could use .NET 3.5 instead of .NET 4. If you are using .NET 4, just remove references to "wpftc" in the XAML.
this part :
"Your new price is: $"(float(price)
asks python to call this string:
"Your new price is: $"
just like you would a function:
function( some_args)
which will ALWAYS trigger the error:
TypeError: 'str' object is not callable
Here's an example of a Comparator that will work for any zero arg method that returns a Comparable. Does something like this exist in a jdk or library?
import java.lang.reflect.Method;
import java.util.Comparator;
public class NamedMethodComparator implements Comparator<Object> {
//
// instance variables
//
private String methodName;
private boolean isAsc;
//
// constructor
//
public NamedMethodComparator(String methodName, boolean isAsc) {
this.methodName = methodName;
this.isAsc = isAsc;
}
/**
* Method to compare two objects using the method named in the constructor.
*/
@Override
public int compare(Object obj1, Object obj2) {
Comparable comp1 = getValue(obj1, methodName);
Comparable comp2 = getValue(obj2, methodName);
if (isAsc) {
return comp1.compareTo(comp2);
} else {
return comp2.compareTo(comp1);
}
}
//
// implementation
//
private Comparable getValue(Object obj, String methodName) {
Method method = getMethod(obj, methodName);
Comparable comp = getValue(obj, method);
return comp;
}
private Method getMethod(Object obj, String methodName) {
try {
Class[] signature = {};
Method method = obj.getClass().getMethod(methodName, signature);
return method;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
private Comparable getValue(Object obj, Method method) {
Object[] args = {};
try {
Object rtn = method.invoke(obj, args);
Comparable comp = (Comparable) rtn;
return comp;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
}
See http://en.wikipedia.org/wiki/SAP_AG.
In short, SAP is a modular based application that sits on top of a database (as many applications do). Many people mistake SAP as being a database, but in fact it is just the application.
By 'modular based application' I mean that 'SAP Netweaver' is a bit like 'Microsoft Office' in that it is an application or set of applications that contains many components/modules. With SAP you can add modules (such as Finance, HR, Banking, Logistics, etc.) to meet your business requirements.
ABAP is a bespoke programming language that is used within SAP. SAP also now has components that are purely ABAP based, purely JAVA based or a mixture of the two. SAP can also integrate with other technologies such as .net and PHP.
An AsyncTask
is background task which runs in the background thread. It takes an Input, performs Progress and gives Output.
ie
AsyncTask<Input,Progress,Output>
.
In my opinion the main source of confusion comes when we try to memorize the parameters in the AsyncTask
.
The key is Don't memorize.
If you can visualize what your task really needs to do then writing the AsyncTask
with the correct signature would be a piece of cake.
Just figure out what your Input, Progress and Output are and you will be good to go.
doInBackgound()
method is the most important method in an AsyncTask
because
AsyncTask
parameters.So lets see the relationship
doInBackground()
andonPostExecute()
,onProgressUpdate()
are also related
Show me the code
So how will I write the code for DownloadTask?
DownloadTask extends AsyncTask<String,Integer,String>{
@Override
public void onPreExecute()
{}
@Override
public String doInbackGround(String... params)
{
// Download code
int downloadPerc = // calculate that
publish(downloadPerc);
return "Download Success";
}
@Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
}
@Override
public void onProgressUpdate(Integer... params)
{
// show in spinner, access UI elements
}
}
How will you run this Task
new DownLoadTask().execute("Paradise.mp3");
Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect
There is a problem in your query..
statement =con.prepareStatement("SELECT * from employee WHERE userID = "+"''"+userID);
ResultSet rs = statement.executeQuery();
You are using Prepare Statement.. So you need to set your parameter using statement.setInt()
or statement.setString()
depending upon what is the type of your userId
Replace it with: -
statement =con.prepareStatement("SELECT * from employee WHERE userID = :userId");
statement.setString(userId, userID);
ResultSet rs = statement.executeQuery();
Or, you can use ?
in place of named value - :userId
..
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
The shortcut to comment out or uncomment the selected text or current line:
Alternatively, use the menu: Edit > Comment
For the block comment you may want to use:
USE MASTER
GO
DECLARE @Spid INT
DECLARE @ExecSQL VARCHAR(255)
DECLARE KillCursor CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT DISTINCT SPID
FROM MASTER..SysProcesses
WHERE DBID = DB_ID('dbname')
OPEN KillCursor
-- Grab the first SPID
FETCH NEXT
FROM KillCursor
INTO @Spid
WHILE @@FETCH_STATUS = 0
BEGIN
SET @ExecSQL = 'KILL ' + CAST(@Spid AS VARCHAR(50))
EXEC (@ExecSQL)
-- Pull the next SPID
FETCH NEXT
FROM KillCursor
INTO @Spid
END
CLOSE KillCursor
DEALLOCATE KillCursor
You can put it in a different class and then call a function. This works when ajax refresh
$(document).on("change", ".inputQty", function(e) {
//Call a function(input,input);
});
Using command line, you can do this:
AT \\computername time "NET STOP servicename"
AT \\computername time "NET START servicename"
My awk version is 3.1.5.
Yes, the input file is space separated, no tabs.
According to arutaku's answer, here's what I tried that worked:
awk '$8 ~ "ClNonZ"{ print $3; }' test
0.180467091
0.010615711
0.492569002
$ awk '$8 ~ "ClNonZ" { print $3}' test
0.180467091
0.010615711
0.492569002
What didn't work(I don't know why and maybe due to my awk version:),
$awk '$8 ~ "^ClNonZ$"{ print $3; }' test
$awk '$8 == "ClNonZ" { print $3 }' test
Thank you all for your answers, comments and help!
It's not that your file is partially downloaded. It fails authentication and hence downloads e.g "index.html" but it names it myfile.zip (since this is what you want to download).
I followed the link suggested by @thomasbabuj and figured it out eventually.
You should try adding --auth-no-challenge
and as @thomasbabuj suggested replace your password entry
I.e
wget --auth-no-challenge --user=myusername --ask-password https://test.mydomain.com/files/myfile.zip
In your activity class use the method below :
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setlogo();// Your Method
Log.d("Daiya", "ORIENTATION_LANDSCAPE");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setlogoForLandScape();// Your Method
Log.d("Daiya", "ORIENTATION_PORTRAIT");
}
}
Then to declare that your activity handles a configuration change, edit the appropriate element in your manifest file to include the android:configChanges
attribute with a value that represents the configuration you want to handle. Possible values are listed in the documentation for the android:configChanges
attribute (the most commonly used values are "orientation" to prevent restarts when the screen orientation changes and "keyboardHidden" to prevent restarts when the keyboard availability changes). You can declare multiple configuration values in the attribute by separating them with a pipe | character.
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
That's all!!
this will subtract ten days of the current date (before Java 8):
int x = -10;
Calendar cal = GregorianCalendar.getInstance();
cal.add( Calendar.DAY_OF_YEAR, x);
Date tenDaysAgo = cal.getTime();
If you're using Java 8 you can make use of the new Date & Time API (http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html):
LocalDate tenDaysAgo = LocalDate.now().minusDays(10);
For converting the new to the old types and vice versa see: Converting between java.time.LocalDateTime and java.util.Date
In your invoke web request just use the parameter -UseBasicParsing
e.g. in your script (line 2) you should use:
$rss = Invoke-WebRequest -Uri $url -UseBasicParsing
According to the documentation, this parameter is necessary on systems where IE isn't installed or configured:
Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.
This can also happen because github has recently renamed the default branch from "master" to "main" ( https://github.com/github/renaming ), so if you just created a new repository on github use git push origin main
instead of git push origin master
Mention the url
like:
jdbc:mysql://hostname:3306/hibernatedb?autoReconnect=true&useSSL=false
But in xml configuration when you mention &
sign, the IDE shows below error:
The reference to entity "useSSL" must end with the ';' delimiter.
And then you have to explicitly use the &
instead of &
to be determined as &
by xml
thereafter in xml
you have to give the url in xml configuration like this:
<property name="connection.url">jdbc:mysql://hostname:3306/hibernatedb?autoReconnect=true&useSSL=false</property>
Your code should look like:
<?php
if ( that_happened ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
if ( something_else_happened ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
// Your function should return FALSE if something goes wrong
if ( !update_database() ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
// the script can also fail on the above line
// e.g. a mysql error occurred
header('HTTP/1.1 200 OK');
?>
I assume you stop execution if something goes wrong.
Just include this line
android:selectAllOnFocus="false"
in the XML segment corresponding to the EditText layout.
var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
Or even simpler (endDate - startDate) / 1000
as pointed out in the comments unless you're using typescript.
You need to call the getTime()
method for the Date
objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate()
method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime()
method, representing the number of milliseconds since January 1st 1970, 00:00
Depending on what your date related operations are, you might want to invest in integrating a library such as date.js or moment.js which make things so much easier for the developer, but that's just a matter of personal preference.
For example in moment.js we would do moment1.diff(moment2, "seconds")
which is beautiful.
There is an important detail that has been omitted in the answer above.
MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR
column is counted towards the maximum row size, while TEXT
columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR
field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.
Also note that the actual number of bytes required by a VARCHAR
field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4
(which you almost certainly should) it will use up even more of your maximum row size.
Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR
/TEXT
field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)
Reasons to use TEXT
:
Reasons to use VARCHAR
:
Add one more line after initializing file object
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
The
<a href="image2.gif" ><img src="image1.gif"/></a>
technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.
Step 1 is always to first determine where the problem lies. Your title and most of your question seem to suggest that you're running into quite a low length limit on the length of a string in JavaScript / on browsers, an improbably low limit. You're not. Consider:
var str;
document.getElementById('theButton').onclick = function() {
var build, counter;
if (!str) {
str = "0123456789";
build = [];
for (counter = 0; counter < 900; ++counter) {
build.push(str);
}
str = build.join("");
}
else {
str += str;
}
display("str.length = " + str.length);
};
Repeatedly clicking the relevant button keeps making the string longer. With Chrome, Firefox, Opera, Safari, and IE, I've had no trouble with strings more than a million characters long:
str.length = 9000 str.length = 18000 str.length = 36000 str.length = 72000 str.length = 144000 str.length = 288000 str.length = 576000 str.length = 1152000 str.length = 2304000 str.length = 4608000 str.length = 9216000 str.length = 18432000
...and I'm quite sure I could got a lot higher than that.
So it's nothing to do with a length limit in JavaScript. You haven't show your code for sending the data to the server, but most likely you're using GET
which means you're running into the length limit of a GET request, because GET
parameters are put in the query string. Details here.
You need to switch to using POST
instead. In a POST
request, the data is in the body of the request rather than in the URL, and can be very, very large indeed.
You could use the concrete class LinkedList
instead of the general interface List
. Then you have a descendingIterator
for iterating with the reverse direction.
LinkedList<String > linkedList;
for( Iterator<String > it = linkedList.descendingIterator(); it.hasNext(); ) {
String text = it.next();
}
Don't know why there is no descendingIterator
with ArrayList
...
Using some reflection and generics in two extension methods you can achieve that.
Right, others did mostly the same solution, but this uses less reflection which is more performance-wise and way more readable:
public static class ObjectExtensions
{
public static T ToObject<T>(this IDictionary<string, object> source)
where T : class, new()
{
var someObject = new T();
var someObjectType = someObject.GetType();
foreach (var item in source)
{
someObjectType
.GetProperty(item.Key)
.SetValue(someObject, item.Value, null);
}
return someObject;
}
public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
{
return source.GetType().GetProperties(bindingAttr).ToDictionary
(
propInfo => propInfo.Name,
propInfo => propInfo.GetValue(source, null)
);
}
}
class A
{
public string Prop1
{
get;
set;
}
public int Prop2
{
get;
set;
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("Prop1", "hello world!");
dictionary.Add("Prop2", 3893);
A someObject = dictionary.ToObject<A>();
IDictionary<string, object> objectBackToDictionary = someObject.AsDictionary();
}
}
In case you missed it, there's a chapter in the excellent Joshua Bloch's book "Effective Java, 2nd edition".
Just the conclusion :
A minor disadvantage of the use of interfaces to emulate extensible enums is those implementations cannot be inherited from one enum type to another. In the case of our Operation example, the logic to store and retrieve the symbol associated with an operation is duplicated in BasicOperation and ExtendedOperation. In this case, it doesn’t matter because very little code is duplicated. If there were a a larger amount of shared functionality, you could encapsulate it in a helper class or a static helper method to eliminate the code duplication.
In summary, while you cannot write an extensible enum type, you can emulate it by writing an interface to go with a basic enum type that implements the interface. This allows clients to write their own enums that implement the interface. These enums can then be used wherever the basic enum type can be used, assuming APIs are written in terms of the interface.
I just added the following line after you created the dialog:
$(".ui-dialog").prependTo("form");
This problem is beacouse your proyect is named serial.py and the library imported is name serial too , change the name and thats all.
As pointed out by others as well, Volley is officially available on Github:
Add this line to your gradle dependencies for volley:
compile 'com.android.volley:volley:1.0.0'
I like to keep the official volley repository in my app. That way I get it from the official source and can get updates without depending on anyone else and mitigating concerns expressed by other people.
Added volley as a submodule alongside app.
git submodule add -b master https://github.com/google/volley.git volley
In my settings.gradle, added the following line to add volley as a module.
include ':volley'
In my app/build.gradle, I added a compile dependency for the volley project
compile project(':volley')
That's all! Volley can now be used in my project.
Everytime I want to sync the volley module with Google's repo, i run this.
git submodule foreach git pull
Please check you are using //
not \\
by-mistake , like below
Wrong:"http:\\stackoverflow.com"
Right:"http://stackoverflow.com"
The only option I can think of is using width:100%
. If you want to have a padding on the input field too, than just place a container label
around it, move the formatting to that label instead, while also specify the padding to the label. Input fields are rigid.
def idle
<<~aid
This is some description of what idle does.
It does nothing actually, it's just here to show an example of multiline
documentation. Thus said, this is something that is more common in the
python community. That's an important point as it's good to also fit the
expectation of your community of work. Now, if you agree with your team to
go with a solution like this one for documenting your own base code, that's
fine: just discuss about it with them first.
Depending on your editor configuration, it won't be colored like a comment,
like those starting with a "#". But as any keyword can be used for wrapping
an heredoc, it is easy to spot anyway. One could even come with separated
words for different puposes, so selective extraction for different types of
documentation generation would be more practical. Depending on your editor,
you possibly could configure it to use the same syntax highlight used for
monoline comment when the keyword is one like aid or whatever you like.
Also note that the squiggly-heredoc, using "~", allow to position
the closing term with a level of indentation. That avoids to break the visual reading flow, unlike this far too long line.
aid
end
Note that at the moment of the post, the stackoverflow engine doesn't render syntax coloration correctly. Testing how it renders in your editor of choice is let as an exercise. ;)
Auto-correlation comes in two versions: statistical and convolution. They both do the same, except for a little detail: The statistical version is normalized to be on the interval [-1,1]. Here is an example of how you do the statistical one:
def acf(x, length=20):
return numpy.array([1]+[numpy.corrcoef(x[:-i], x[i:])[0,1] \
for i in range(1, length)])
In the Tools -> Visual Studio Options Dialog -> Debugging -> Check the "Redirect All Output Window Text to the Immediate Window".
To put code to NPE's answer, I think the most efficient way to do this is:
def insert(originalfile,string):
with open(originalfile,'r') as f:
with open('newfile.txt','w') as f2:
f2.write(string)
f2.write(f.read())
os.rename('newfile.txt',originalfile)
If you're not using auto-incrementing fields, you can achieve a similar result with something like the following:
insert into Customers (ID, FirstName, LastName)
select max(ID)+1, 'Barack', 'Obama' from Customers;
This will ensure there's no chance of a race condition which could be caused by someone else inserting into the table between your extraction of the maximum ID and your insertion of the new record.
This is using standard SQL, there are no doubt better ways to achieve it with specific DBMS' but they're not necessarily portable (something we take very seriously in our shop).
In Perl 5.14 (it works in now in Perl 5.13), we'll be able to just use keys on the hash reference
use v5.13.7;
foreach my $key (keys $ad_grp_ref) {
...
}
If you're using a NFS, "test" is a better solution, because you can add a timeout to it, in case your NFS is down:
time timeout 3 test -f
/nfs/my_nfs_is_currently_down
real 0m3.004s <<== timeout is taken into account
user 0m0.001s
sys 0m0.004s
echo $?
124 <= 124 means the timeout has been reached
A "[ -e my_file ]" construct will freeze until the NFS is functional again:
if [ -e /nfs/my_nfs_is_currently_down ]; then echo "ok" else echo "ko" ; fi
<no answer from the system, my session is "frozen">
There are many answers to this question, all of which I feel are not satisfactory (some more than others), of the many extensions - code folding, folding by headings etc etc. None do what I want in simple and effective way. I am literally amazed that a solution has not been implemented (as it has for Jupyter Lab).
In fact, I was so dissatisfied that I have developed a very simple notebook extension that can expand/collapse the code in a notebook cell, while keeping it executable.
The GitHub repository: https://github.com/BenedictWilkinsAI/cellfolding
Below is a small demo of what the extension does:
Simply double clicking left of the code cell will collapse it to a single line:
Double clicking again will expand the cell.
The extension can be installed easily with pip:
pip install nbextension-cellfolding
jupyter nbextension install --py cellfolding --user
jupyter nbextension enable --py cellfolding --user
and is also compatible with nbextension configurator. I hope that people will find this useful!
Alright, think I got it...
Little background first: The reason I needed this was to stick Angular on top of Node Express and have Jade process my partials for me.
So here's whatchya gotta do... (drink beer and spend 20+ hours on it first!!!)...
When you set up your module, save the $routeProvider
globally:
// app.js:
var routeProvider
, app = angular.module('Isomorph', ['ngResource']).config(function($routeProvider){
routeProvider = $routeProvider;
$routeProvider
.when('/', {templateUrl: '/login', controller: 'AppCtrl'})
.when('/home', {templateUrl: '/', controller: 'AppCtrl'})
.when('/login', {templateUrl: '/login', controller: 'AppCtrl'})
.when('/SAMPLE', {templateUrl: '/SAMPLE', controller: 'SAMPLECtrl'})
.when('/map', {templateUrl: '/map', controller: 'MapCtrl'})
.when('/chat', {templateUrl: '/chat', controller: 'ChatCtrl'})
.when('/blog', {templateUrl: '/blog', controller: 'BlogCtrl'})
.when('/files', {templateUrl: '/files', controller: 'FilesCtrl'})
.when('/tasks', {templateUrl: '/tasks', controller: 'TasksCtrl'})
.when('/tasks/new', {templateUrl: '/tasks/new', controller: 'NewTaskCtrl'})
.when('/tasks/:id', {templateUrl: '/tasks', controller: 'ViewTaskCtrl'})
.when('/tasks/:id/edit', {templateUrl: '/tasks', controller: 'EditTaskCtrl'})
.when('/tasks/:id/delete', {templateUrl: '/tasks', controller: 'DeleteTaskCtrl'})
.otherwise({redirectTo: '/login'});
});
// ctrls.js
...
app.controller('EditTaskCtrl', function($scope, $routeParams, $location, $http){
var idParam = $routeParams.id;
routeProvider.when('/tasks/:id/edit/', {templateUrl: '/tasks/' + idParam + '/edit'});
$location.path('/tasks/' + idParam + '/edit/');
});
...
That may be more info than what was needed...
Basically, you'll wanna store your Module's $routeProvider
var globally, eg as routeProvider
so that it can be accessed by your Controllers.
Then you can just use routeProvider
and create a NEW route (you can't 'RESET a route' / 'REpromise'; you must create a new one), I just added a slash (/) at the end so that it is as semantic as the first.
Then (inside your Controller), set the templateUrl
to the view you want to hit.
Take out the controller
property of the .when()
object, lest you get an infinite request loop.
And finally (still inside the Controller), use $location.path()
to redirect to the route that was just created.
If you're interested in how to slap an Angular app onto an Express app, you can fork my repo here: https://github.com/cScarlson/isomorph.
And this method also allows for you to keep the AngularJS Bidirectional Data-Bindings in case you want to bind your HTML to your database using WebSockets: otherwise without this method, your Angular data-bindings will just output {{model.param}}
.
If you clone this at this time, you'll need mongoDB on your machine to run it.
Hope this solves this issue!
Cody
Don't drink your bathwater.
I think what you are looking for is:
list(im.getdata())
or, if the image is too big to load entirely into memory, so something like that:
for pixel in iter(im.getdata()):
print pixel
from PIL documentation:
getdata
im.getdata() => sequence
Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.
Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).
Let's say you have a Dictionary called fooDictionary
fooDictionary.Values.ToList().IndexOf(someValue);
Values.ToList() converts your dictionary values into a List of someValue objects.
IndexOf(someValue) searches your new List looking for the someValue object in question and returns the Index which would match the index of the Key/Value pair in the dictionary.
This method does not care about the dictionary keys, it simply returns the index of the value that you are looking for.
This does not however account for the issue that there may be several matching "someValue" objects.