If you are using the scripts of metro UI css (excellent free metro UI set from http://metroui.org.ua/) , that can clash too. In my case, this was the problem recently.
So, removed the scripts reference of metro UI (as I was not using its components), datepicker is showing.
But you cant get metro look for datepicker of jQuery-ui
But in most cases, as others mentioned, its clash with duplicate versions of jQuery-UI javascripts.
To create an option that needs no value, set the action
[docs] of it to 'store_const'
, 'store_true'
or 'store_false'
.
Example:
parser.add_argument('-s', '--simulate', action='store_true')
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
Which version of HTML are you using?
In HTML 5, it is totally valid to have custom attributes prefixed with data-, e.g.
<div data-internalid="1337"></div>
In XHTML, this is not really valid. If you are in XHTML 1.1 mode, the browser will probably complain about it, but in 1.0 mode, most browsers will just silently ignore it.
If I were you, I would follow the script based approach. You could make it automatically generated on server side so that it's not a pain in the back to maintain.
You can also create a new jsp file sayng that form is submited and in your main action file just write its file name
Eg. Your form is submited is in a file succes.jsp Then your action file will have
Request.sendRedirect("success.jsp")
The Solution for me was just to do following things:
pull = fetch + merge.
You need to commit what you have done before merging.
So pull after commit.
I had multiple provider
s specified in my web.config.
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
</providers>
I simply removed one of those and it worked.
I am using MySQL though, not TSQL
I added this answer to clarify that the accepted answer shows CPU time which may not be the time you want. Because according to the reference, there are CPU time and wall clock time. Wall clock time is the time which shows the actual elapsed time regardless of any other conditions like CPU shared by other processes. For example, I used multiple processors to do a certain task and the CPU time was high 18s where it actually took 2s in actual wall clock time.
To get the actual time you do,
#include <chrono>
auto t_start = std::chrono::high_resolution_clock::now();
// the work...
auto t_end = std::chrono::high_resolution_clock::now();
double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end-t_start).count();
Write bytes and Create the file if not exists:
f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()
wb
means open the file in write binary
mode.
Add this instead of the pre-defined class
class ViewController: UIViewController, UITextFieldDelegate {
To remove keyboard when clicked outside the keyboard
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
and to remove keyboard when pressed enter
add this line in viewDidLoad()
inputField is the name of the textField used.
self.inputField.delegate = self
and add this function
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
JSONP stands for JSON with Padding.
Here is the site, with great examples, with the explanation from the simplest use of this technique to the most advanced in plane JavaScript:
One of my more favorite techniques described above is Dynamic JSON Result, which allow to send JSON to the PHP file in URL parameter, and let the PHP file also return a JSON object based on the information it gets.
Tools like jQuery also have facilities to use JSONP:
jQuery.ajax({
url: "https://data.acgov.org/resource/k9se-aps6.json?city=Berkeley",
jsonp: "callbackName",
dataType: "jsonp"
}).done(
response => console.log(response)
);
Not quite answering the question, but, there is a nice library for those kind of problems: https://github.com/typestack/class-transformer (although it won't work for generic types, as they don't really exists at run-time (here all work is done with class names (which are classes constructors)))
For instance:
import {Type, plainToClass, deserialize} from "class-transformer";
export class Foo
{
@Type(Bar)
public nestedClass: Bar;
public someVar: string;
public someMethod(): string
{
return this.nestedClass.someVar + this.someVar;
}
}
export class Bar
{
public someVar: string;
}
const json = '{"someVar": "a", "nestedClass": {"someVar": "B"}}';
const optionA = plainToClass(Foo, JSON.parse(json));
const optionB = deserialize(Foo, json);
optionA.someMethod(); // works
optionB.someMethod(); // works
usually we talking Maven Terminology about Group Id , Artifact Id and Snapshot Version
Group Id:identity of the group of the project Artifact Id:identity of the project Snapshot version:the version used by the project.
Artifact is nothing but some resulting file like Jar, War, Ear....
simply says Artifacts are nothing but packages.
The below code gives you the simple extrapolation module. k is the value to which the data set y has to be extrapolated based on the data set x. The numpy
module is required.
def extrapol(k,x,y):
xm=np.mean(x);
ym=np.mean(y);
sumnr=0;
sumdr=0;
length=len(x);
for i in range(0,length):
sumnr=sumnr+((x[i]-xm)*(y[i]-ym));
sumdr=sumdr+((x[i]-xm)*(x[i]-xm));
m=sumnr/sumdr;
c=ym-(m*xm);
return((m*k)+c)
Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter()
for this:
String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");
The HttpServletRequest
should already be available to you inside Spring MVC as one of the method arguments of the handleRequest()
method.
const char* args[] = {"01", "02", "03", "04"};
std::vector<std::string> v(args, args + 4);
And in C++0x, you can take advantage of std::initializer_list<>
:
npm install -g npm-install-peers
it will add all the missing peers and remove all the error
You want to use position: absolute
while inside the other div.
Along the same lines as @Eric's answer, but without using a 'NULL'
symbol.
(Field1 = Field2) OR (ISNULL(Field1, Field2) IS NULL)
This will be true only if both values are non-NULL
, and equal each other, or both values are NULL
https://services.gradle.org/distributions/
Download The Latest Gradle Distribution File and Extract It, Then Copy all Files and Paste it Under:
C:\Users\{USERNAME}\.gradle\wrapper\dists\
This is a tricky question.
There a set of problems about file permissions. If you can do this at the command line
$ sudo chown myaccount /path/to/file
then you have a standard permissions problem. Make sure you own the file and have permission to modify the directory.
If you cannnot get permissions, then you have probably mounted a FAT-32 filesystem. If you ls -l
the file, and you find it is owned by root and a member of the "plugdev" group, then you are certain its the issue. FAT-32 permissions are set at the time of mounting, using the line of /etc/fstab file. You can set the uid/gid of all the files like this:
UUID=C14C-CE25 /big vfat utf8,umask=007,uid=1000,gid=1000 0 1
Also, note that the FAT-32 won't take symbolic links.
Wrote the whole thing up at http://www.charlesmerriam.com/blog/2009/12/operation-not-permitted-and-the-fat-32-system/
If the type is all that distinguishes the one value from another, then it can only be for the conversion of one type to another. If you have the same value that is being converted between types, chances are you should be doing this in a function dedicated to conversion. (I have seen hungarianed VB6 leftovers use strings on all of their method parameters simply because they could not figure out how to deserialize a JSON object, or properly comprehend how to declare or use nullable types.) If you have two variables distinguished only by the Hungarian prefix, and they are not a conversion from one to the other, then you need to elaborate on your intention with them.
I have found that Hungarian notation makes people lazy with their variable names. They have something to distinguish it by, and they feel no need to elaborate to its purpose. This is what you will typically find in Hungarian notated code vs. modern: sSQL vs. groupSelectSql (or usually no sSQL at all because they are supposed to be using the ORM that was put in by earlier developers.), sValue vs. formCollectionValue (or usually no sValue either, because they happen to be in MVC and should be using its model binding features), sType vs. publishSource, etc.
It can't be readability. I see more sTemp1, sTemp2... sTempN from any given hungarianed VB6 leftover than everybody else combined.
This would be by virtue of number 2, which is false.
As it has already been mentioned in che's answer about adding the remote part, which I believe you are still missing.
Regarding your edit for adding remote on your local USB drive. First of all you must have a 'bare repository' if you want your repository to be a shared repository i.e. to be able to push/pull/fetch/merge etc..
To create a bare/shared repository, go to your desired location. In your case:
$ cd /Volumes/500gb/
$ git init --bare myproject.git
See here for more info on creating bare repository
Once you have a bare repository set up in your desired location you can now add it to your working copy as a remote.
$ git remote add origin /Volumes/500gb/myproject.git
And now you can push your changes to your repository
$ git push origin master
It's not necessary to cast both of them. Result datatype for a division is always the one with the higher data type precedence. Thus the solution must be:
SELECT CAST(1 AS float) / 3
or
SELECT 1 / CAST(3 AS float)
Bootstrap 4 uses flex-box and you can create your own column definitions
This is close to a 1.5, tweak to your own needs.
.col-1-5 {
flex: 0 0 12.3%;
max-width: 12.3%;
position: relative;
width: 100%;
padding-right: 15px;
padding-left: 15px;
}
from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))
You can run loop for each column but this is the simplest way to convert string column into integer.
Using the Range.Find method, as pointed out above, along with a loop for each worksheet in the workbook, is the fastest way to do this. The following, for example, locates the string "Question?" in each worksheet and replaces it with the string "Answered!".
Sub FindAndExecute()
Dim Sh As Worksheet
Dim Loc As Range
For Each Sh In ThisWorkbook.Worksheets
With Sh.UsedRange
Set Loc = .Cells.Find(What:="Question?")
If Not Loc Is Nothing Then
Do Until Loc Is Nothing
Loc.Value = "Answered!"
Set Loc = .FindNext(Loc)
Loop
End If
End With
Set Loc = Nothing
Next
End Sub
The simplest approach would be to make use of the to:object
within link
as mentioned in documentation:
https://reactrouter.com/web/api/Link/to-object
<Link
to={{
pathname: "/courses",
search: "?sort=name",
hash: "#the-hash",
state: { fromDashboard: true, id: 1 }
}}
/>
We can retrieve above params (state) as below:
this.props.location.state // { fromDashboard: true ,id: 1 }
Another way,
for i, v in enumerate(numbers): numbers[i] = int(v)
Here is the latest method using the .map
function in javascript.
Simple table code..
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Tour</th>
<th scope="col">Day</th>
<th scope="col">Time</th>
<th scope="col">Highlights</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
and here is javascript code to append something in the table body.
const data = "some kind of json data or object of arrays";
const tableData = data.map(function(value){
return (
`<tr>
<td>${value.Name}</td>
<td>${value.Day}</td>
<td>${value.Time}</td>
<td>${value.Highlights}</td>
<td class="text-center"><a class="btn btn-primary" href="route.html?id=${value.ID}" role="button">Details</a></td>
</tr>`
);
}).join('');
const tabelBody = document.querySelector("#tableBody");
tableBody.innerHTML = tableData;
If you are using pdo, it will look like
$sql = "UPDATE users SET firstname = :firstname, lastname = :lastname WHERE id= :id";
$query = $this->pdo->prepare($sql);
$result = $query->execute(array(':firstname' => $firstname, ':lastname' => $lastname, ':id' => $id));
DECODE(SUBSTR(STATUS,1,1),'a','Active','i','Inactive','t','Terminated','N/A')
I have just wrestled with this for 3 hours. I credit the answer from Dherik (Bonus material about AMQP) for bringing me within striking distance of MY answer, YMMV.
I registered the JavaTimeModule in my object mapper in my SpringBootApplication like this:
@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.build();
objectMapper.registerModule(new JavaTimeModule());
return objectMapper;
}
However my Instants that were coming over the STOMP connection were still not deserialising. Then I realised I had inadvertantly created a MappingJackson2MessageConverter which creates a second ObjectMapper. So I guess the moral of the story is: Are you sure you have adjusted all your ObjectMappers? In my case I replaced the MappingJackson2MessageConverter.objectMapper with the outer version that has the JavaTimeModule registered, and all is well:
@Autowired
ObjectMapper objectMapper;
@Bean
public WebSocketStompClient webSocketStompClient(WebSocketClient webSocketClient,
StompSessionHandler stompSessionHandler) {
WebSocketStompClient webSocketStompClient = new WebSocketStompClient(webSocketClient);
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setObjectMapper(objectMapper);
webSocketStompClient.setMessageConverter(converter);
webSocketStompClient.connect("http://localhost:8080/myapp", stompSessionHandler);
return webSocketStompClient;
}
That's still a constant. See the JLS for more information regarding the naming convention for constants. But in reality, it's all a matter of preference.
The names of constants in interface types should be, and
final
variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore"_"
characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants includeMIN_VALUE
,MAX_VALUE
,MIN_RADIX
, andMAX_RADIX
of the classCharacter
.A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:
interface ProcessStates { int PS_RUNNING = 0; int PS_SUSPENDED = 1; }
Obscuring involving constant names is rare:
- Constant names normally have no lowercase letters, so they will not normally obscure names of packages or types, nor will they normally shadow fields, whose names typically contain at least one lowercase letter.
- Constant names cannot obscure method names, because they are distinguished syntactically.
I had the same issue. I found that I forgot to add selenium-2.53.0/selenium-java-2.53.0-srcs.jar file to my project's Reference library.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I did this once in a postgres app by running:
EXPLAIN SELECT * FROM foo;
Then examining the output with a regex, or similar logic. For a simple SELECT *, the first line of output should look something like this:
Seq Scan on uids (cost=0.00..1.21 rows=8 width=75)
You can use the rows=(\d+)
value as a rough estimate of the number of rows that would be returned, then only do the actual SELECT COUNT(*)
if the estimate is, say, less than 1.5x your threshold (or whatever number you deem makes sense for your application).
Depending on the complexity of your query, this number may become less and less accurate. In fact, in my application, as we added joins and complex conditions, it became so inaccurate it was completely worthless, even to know how within a power of 100 how many rows we'd have returned, so we had to abandon that strategy.
But if your query is simple enough that Pg can predict within some reasonable margin of error how many rows it will return, it may work for you.
I did not add any dependencies, I just change the way I was consuming them.
(Uncomment this code if you are using elastic search version < 7.0)
IndexRequest indexRequest = new IndexRequest(
"twitter",
"tweets",
id // this is to make our consumer idempotent
).source(record.value(), XContentType.JSON);
IndexRequest indexRequest = new IndexRequest("tweets")
.source(record.value(), XContentType.JSON)
.id(id); // this is to make our consumer idempotent
I am using bulkrequest and with that I remove that error.
For those of you who like me still got errors after trying all the other answers :
Check the version of php apache uses, latest laravel only works with php7.1. So you have to :
sudo a2dismod php[yourversion]
sudo a2enmod php7.1
sudo systemctl restart apache2
hope this helps
Guard clauses or pre-conditions (as you can probably see) check to see if a certain condition is met and then breaks the flow of the program. They're great for places where you're really only interested in one outcome of an if
statement. So rather than say:
if (something) {
// a lot of indented code
}
You reverse the condition and break if that reversed condition is fulfilled
if (!something) return false; // or another value to show your other code the function did not execute
// all the code from before, save a lot of tabs
return
is nowhere near as dirty as goto
. It allows you to pass a value to show the rest of your code that the function couldn't run.
You'll see the best examples of where this can be applied in nested conditions:
if (something) {
do-something();
if (something-else) {
do-another-thing();
} else {
do-something-else();
}
}
vs:
if (!something) return;
do-something();
if (!something-else) return do-something-else();
do-another-thing();
You'll find few people arguing the first is cleaner but of course, it's completely subjective. Some programmers like to know what conditions something is operating under by indentation, while I'd much rather keep method flow linear.
I won't suggest for one moment that precons will change your life or get you laid but you might find your code just that little bit easier to read.
It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.
You can, however, use jQuery:
if ($(this).is('[href$=?]'))
You can also just look at the "href" value:
if (/\?$/.test(this.href))
Based on the answer I linked to in my comment above, this should work:
delete from
(
select pf.* From PRODUCTFILTERS pf
where pf.id>=200
And pf.rowid in
(
Select rowid from PRODUCTFILTERS
inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID
And PRODUCTS.NAME= 'Mark'
)
);
or
delete from PRODUCTFILTERS where rowid in
(
select pf.rowid From PRODUCTFILTERS pf
where pf.id>=200
And pf.rowid in
(
Select PRODUCTFILTERS.rowid from PRODUCTFILTERS
inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID
And PRODUCTS.NAME= 'Mark'
)
);
If, like me, you had dynamically created buttons on your page, the
$("#your-bs-button's-id").on("click", function(event) {
or
$(".your-bs-button's-class").on("click", function(event) {
methods won't work because they only work on current elements (not future elements). Instead you need to reference a parent item that existed at the initial loading of the web page.
$(document).on("click", "#your-bs-button's-id", function(event) {
or more generally
$("#pre-existing-element-id").on("click", ".your-bs-button's-class", function(event) {
There are many other references to this issue on stack overflow here and here.
There are three types of variables:
The default values for instance and static variables are the same and depends on the type:
An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.
Once the array is created all of its elements are assiged with the default type value. For example:
private boolean[] list; // default value is null
private Boolean[] list; // default value is null
once is initialized:
private boolean[] list = new boolean[10]; // all ten elements are assigned to false
private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)
If you take a look at the MSIL as it's being executed you'll see that it doesn't compile down to the exact same code. When you use IsNothing() it actually makes a call to that method as opposed to just evaluating the expression.
The reason I would tend to lean towards using "Is Nothing" is when I'm negating it becomes "IsNot Nothing' rather than "Not IsNothing(object)" which I personally feel looks more readable.
In plain English, the syntax explained:
if(condition){
do_something_if_condition_is_met;
}
else{
do_something_else_if_condition_is_not_met;
}
Can be written as:
condition ? do_something_if_condition_is_met : do_something_else_if_condition_is_not_met;
If you are exporting the data from the CSV file it can be as simple as this :
df = pd.read_csv(file_csv, na_values=' ')
This will create the data frame as well as replace blank values as Na
We all know that wait(), notify() and notifyAll() methods are used for inter-threaded communications. To get rid of missed signal and spurious wake up problems, waiting thread always waits on some conditions. e.g.-
boolean wasNotified = false;
while(!wasNotified) {
wait();
}
Then notifying thread sets wasNotified variable to true and notify.
Every thread has their local cache so all the changes first get written there and then promoted to main memory gradually.
Had these methods not invoked within synchronized block, the wasNotified variable would not be flushed into main memory and would be there in thread's local cache so the waiting thread will keep waiting for the signal although it was reset by notifying thread.
To fix these types of problems, these methods are always invoked inside synchronized block which assures that when synchronized block starts then everything will be read from main memory and will be flushed into main memory before exiting the synchronized block.
synchronized(monitor) {
boolean wasNotified = false;
while(!wasNotified) {
wait();
}
}
Thanks, hope it clarifies.
an Activity is a specialization of Context so, if you have a Context you already know which activity you intend to use and can simply cast a into c; where a is an Activity and c is a Context.
Activity a = (Activity) c;
The .sh
is for *nix systems and .bat
should be for Windows. Since your example shows a bash error and you mention Terminal, I'm assuming it's OS X you're using.
In this case you should go to the folder and type:
./startup.sh
./
just means that you should call the script located in the current directory. (Alternatively, just type the full path of the startup.sh
). If it doesn't work then, check if startup.sh
has execute permissions.
No, there is no better way; yours is canonical.
[October 2015]
Answer because the current accepted answersudo apt-get install golang
isn't uptodate and if you don't want to install GVM
follow these steps.
sudo tar -C /usr/local -xzf go$VERSION.$OS-$ARCH.tar.gz
go
to your path export PATH=$PATH:/usr/local/go/bin
go version
to check the current version installedIf you get a go version xgcc (Ubuntu 4.9.1-0ubuntu1) 4.9.1 linux/amd64
then you did something wrong, so check out this post: Go is printing xgcc version but not go installed version
On Mac:
?+CTRL+g
However, you can reset any key any way you'd like using "Customize your Sublime Text 2 configuration for awesome coding." for Mac.
On Windows/Linux:
Alt+F3
If anyone has how-tos or articles on this, I'd be more than happy to update.
public static void duplicatesInteger(int arr[]){
Arrays.sort(arr);
int count=0;
Set s=new HashSet();
for(int i=0;i<=arr.length-1;i++){
for(int j=i+1;j<=arr.length-1;j++){
if(arr[i]==arr[j] && s.add(arr[i])){
count=count+1;
}
}
System.out.println(count);
}
}
There's a section of @media print
code in the css file (Bootstrap 3.3.1 [UPDATE:] to 3.3.5), this strips virtually all the styling, so you get fairly bland print-outs even when it is working.
For now I've had to resort to stripping out the @media print
section from bootstrap.css - which I'm really not happy about but my users want direct screen-grabs so this'll have to do for now. If anyone knows how to suppress it without changes to the bootstrap files I'd be very interested.
Here's the 'offending' code block, starts at line #192:
@media print {
*,
*:before,enter code here
*:after {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
select {
background: #fff !important;
}
.navbar {
display: none;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table td,
.table th {
background-color: #fff !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
Way to instantly get first value:
$neededObject = array_reduce(
$arrayOfObjects,
function ($result, $item) use ($searchedValue) {
return $item->id == $searchedValue ? $item : $result;
}
);
You can use System.Diagnostics.Process.Start
.
Or use the WinApi directly with something like the following, which will launch explorer.exe. You can use the fourth parameter to ShellExecute to give it a starting directory.
public partial class Window1 : Window
{
public Window1()
{
ShellExecute(IntPtr.Zero, "open", "explorer.exe", "", "", ShowCommands.SW_NORMAL);
InitializeComponent();
}
public enum ShowCommands : int
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_FORCEMINIMIZE = 11,
SW_MAX = 11
}
[DllImport("shell32.dll")]
static extern IntPtr ShellExecute(
IntPtr hwnd,
string lpOperation,
string lpFile,
string lpParameters,
string lpDirectory,
ShowCommands nShowCmd);
}
The declarations come from the pinvoke.net website.
Here is your very own groupBy
function which is a generalization of the code from: https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore
function groupBy(xs, f) {_x000D_
return xs.reduce((r, v, i, a, k = f(v)) => ((r[k] || (r[k] = [])).push(v), r), {});_x000D_
}_x000D_
_x000D_
const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }];_x000D_
_x000D_
const result = groupBy(cars, (c) => c.make);_x000D_
console.log(result);
_x000D_
you can find your recursive function in crome browser,press ctrl+shift+j and then source tab, which gives you code compilation flow and you can find using break point in code.
In addition to the above answer and restarting the IDE didn't do, try restarting "Jetbrains Toolbox" if you use it, this did it for me
JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.
An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight
You can find a lot more info on the official JSON web site.
JSON is built on two structures:
Here is an example of JSON data:
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}
JSON (in Javascript) is a string!
People often assume all Javascript objects are JSON and that JSON is a Javascript object. This is incorrect.
In Javascript var x = {x:y}
is not JSON, this is a Javascript object. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be var x = '{"x":"y"}'
. x
is an object of type string not an object in it's own right. To turn this into a fully fledged Javascript object you must first parse it, var x = JSON.parse('{"x":"y"}');
, x
is now an object but this is not JSON anymore.
When working with JSON and JavaScript, you may be tempted to use the eval
function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).
Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.
Example on how to use the JSON parser (with the json from the above code snippet):
//The callback function that will be executed once data is received from the server
var callback = function (result) {
var johnny = JSON.parse(result);
//Now, the variable 'johnny' is an object that contains all of the properties
//from the above code snippet (the json example)
alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};
The JSON parser also offers another very useful method, stringify
. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:
var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}
The above two methods (parse
and stringify
) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)
Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.
Disclaimer: While the top answer is probably a better solution, as a beginner it's a lot to take in when all you want is something very simple. This is intended as a more direct answer to your original question "How can I select certain elements in React"
I think the confusion in your question is because you have React components which you are being passed the id "Progress1", "Progress2" etc. I believe this is not setting the html attribute 'id', but the React component property. e.g.
class ProgressBar extends React.Component {
constructor(props) {
super(props)
this.state = {
id: this.props.id <--- ID set from <ProgressBar id="Progress1"/>
}
}
}
As mentioned in some of the answers above you absolutely can use document.querySelector
inside of your React app, but you have to be clear that it is selecting the html output of your components' render methods. So assuming your render output looks like this:
render () {
const id = this.state.id
return (<div id={"progress-bar-" + id}></div>)
}
Then you can elsewhere do a normal javascript querySelector call like this:
let element = document.querySelector('#progress-bar-Progress1')
I know this thread is a bit old, but it took me some time to get to the heart of this, so I wanted to share.
In my project, I had the main script in a parent directory, and, to differentiate the modules, I put all the supporting modules in a sub-folder called "modules". In my main script, I import these modules like this (for a module called report.py):
from modules.report import report, reportError
If I call my main script, this works. HOWEVER, I wanted to test each module by including a main()
in each, and calling each directly, as:
python modules/report.py
Now Python complains that it can't find "a module called modules". The key here is that, by default, Python includes the folder of the script in its search path, BUT NOT THE CWD. So what this error says, really, is "I can't find a modules subfolder". The is because there is no "modules" subdirectory from the directory where the report.py module resides.
I find that the neatest solution to this is to append the CWD in Python search path by including this at the top:
import sys
sys.path.append(".")
Now Python searches the CWD (current directory), finds the "modules" sub-folder, and all is well.
I know this question asked quite long time ago but for the new users of this question. Please read this article where contains complete description on upcasting, downcasting and use of instanceof operator
There's no need to upcast manually, it happens on its own:
Mammal m = (Mammal)new Cat();
equals to Mammal m = new Cat();
But downcasting must always be done manually:
Cat c1 = new Cat();
Animal a = c1; //automatic upcasting to Animal
Cat c2 = (Cat) a; //manual downcasting back to a Cat
Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing ClassCastException. This is where is should introduce an useful feature called "instanceof", which tests if an object is instance of some Class.
Cat c1 = new Cat();
Animal a = c1; //upcasting to Animal
if(a instanceof Cat){ // testing if the Animal is a Cat
System.out.println("It's a Cat! Now i can safely downcast it to a Cat, without a fear of failure.");
Cat c2 = (Cat)a;
}
For more information please read this article
Using mockito, you can make the exception happen.
when(testingClassObj.testSomeMethod).thenThrow(new CustomException());
Using Junit5, you can assert exception, asserts whether that exception is thrown when testing method is invoked.
@Test
@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
final ExpectCustomException expectEx = new ExpectCustomException();
InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
expectEx.constructErrorMessage("sample ","error");
});
assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
}
Find a sample here: assert exception junit
make has a very stupid relationship with tabs. All actions of every rule are identified by tabs. And, no, four spaces don't make a tab. Only a tab makes a tab.
To check, I use the command cat -e -t -v makefile_name
.
It shows the presence of tabs with ^I
and line endings with $
. Both are vital to ensure that dependencies end properly and tabs mark the action for the rules so that they are easily identifiable to the make utility.
Example:
Kaizen ~/so_test $ cat -e -t -v mk.t
all:ll$ ## here the $ is end of line ...
$
ll:ll.c $
^Igcc -c -Wall -Werror -02 c.c ll.c -o ll $@ $<$
## the ^I above means a tab was there before the action part, so this line is ok .
$
clean :$
\rm -fr ll$
## see here there is no ^I which means , tab is not present ....
## in this case you need to open the file again and edit/ensure a tab
## starts the action part
First off, some clarifications to KLE's answer:
Unconstrained (nullable) one-to-one association is the only one that can not be proxied without bytecode instrumentation. The reason for this is that owner entity MUST know whether association property should contain a proxy object or NULL and it can't determine that by looking at its base table's columns due to one-to-one normally being mapped via shared PK, so it has to be eagerly fetched anyway making proxy pointless. Here's a more detailed explanation.
many-to-one associations (and one-to-many, obviously) do not suffer from this issue. Owner entity can easily check its own FK (and in case of one-to-many, empty collection proxy is created initially and populated on demand), so the association can be lazy.
Replacing one-to-one with one-to-many is pretty much never a good idea. You can replace it with unique many-to-one but there are other (possibly better) options.
Rob H. has a valid point, however you may not be able to implement it depending on your model (e.g. if your one-to-one association is nullable).
Now, as far as original question goes:
A) @ManyToOne(fetch=FetchType.LAZY)
should work just fine. Are you sure it's not being overwritten in the query itself? It's possible to specify join fetch
in HQL and / or explicitly set fetch mode via Criteria API which would take precedence over class annotation. If that's not the case and you're still having problems, please post your classes, query and resulting SQL for more to-the-point conversation.
B) @OneToOne
is trickier. If it's definitely not nullable, go with Rob H.'s suggestion and specify it as such:
@OneToOne(optional = false, fetch = FetchType.LAZY)
Otherwise, if you can change your database (add a foreign key column to owner table), do so and map it as "joined":
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="other_entity_fk")
public OtherEntity getOther()
and in OtherEntity:
@OneToOne(mappedBy = "other")
public OwnerEntity getOwner()
If you can't do that (and can't live with eager fetching) bytecode instrumentation is your only option. I have to agree with CPerkins, however - if you have 80!!! joins due to eager OneToOne associations, you've got bigger problems then this :-)
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
You'll need to create an array of the values in the enum, which can be created by calling System.Enum.GetValues(), passing it the Type
of the enum that you want the items of.
If you specify this for the ItemsSource
property, then it should be populated with all of the enum's values. You probably want to bind SelectedItem
to EffectStyle
(assuming it is a property of the same enum, and contains the current value).
This is what fixed it for me:
max-height: 100%;
overflow-y: auto;
EDIT: I now use the same method currently used on Twitter where the modal acts sort of like a separate page on top of the current content and the content behind the modal does not move as you scroll.
In essence it is this:
var scrollBarWidth = window.innerWidth - document.body.offsetWidth;
$('body').css({
marginRight: scrollBarWidth,
overflow: 'hidden'
});
$modal.show();
With this CSS on the modal:
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: auto;
JSFiddle: https://jsfiddle.net/0x0049/koodkcng/
Pure JS version (IE9+): https://jsfiddle.net/0x0049/koodkcng/1/
This works no matter the height or width of the page or modal dialog, allows scrolling no matter where your mouse/finger is, doesn't have the jarring jump some solutions have that disable scroll on the main content, and looks great too.
To replace multiples columns convert to numpy array using .values
:
df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2
There are several ways to do this. Both are very simple. Each of the examples works great. You can copy it into your project and test it.
The first method is preferable, the second is a bit outdated, but so far it works too.
1) Solution 1
// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [ProductService, ProductModule],
bootstrap: [AppComponent]
})
export class AppModule { }
// File - product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators'; // Important! Be sure to connect operators
// There may be your any object. For example, we will have a product object
import { ProductModule } from './product.module';
@Injectable()
export class ProductService{
// Initialize the properties.
constructor(private http: HttpClient, private product: ProductModule){}
// If there are no errors, then the object will be returned with the product data.
// And if there are errors, we will get into catchError and catch them.
getProducts(): Observable<ProductModule[]>{
const url = 'YOUR URL HERE';
return this.http.get<ProductModule[]>(url).pipe(
tap((data: any) => {
console.log(data);
}),
catchError((err) => {
throw 'Error in source. Details: ' + err; // Use console.log(err) for detail
})
);
}
}
2) Solution 2. It is old way but still works.
// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule
],
providers: [ProductService, ProductModule],
bootstrap: [AppComponent]
})
export class AppModule { }
// File - product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class ProductService{
// Initialize the properties.
constructor(private http: Http){}
// If there are no errors, then the object will be returned with the product data.
// And if there are errors, we will to into catch section and catch error.
getProducts(){
const url = '';
return this.http.get(url).map(
(response: Response) => {
const data = response.json();
console.log(data);
return data;
}
).catch(
(error: Response) => {
console.log(error);
return Observable.throw(error);
}
);
}
}
for me the clearest way is this:
doubleList.stream().reduce((a,b)->a+b).get();
or
doubleList.parallelStream().reduce((a,b)->a+b).get();
It also use internal loops, but it is not possible without loops.
In addition to backslash, if a line ends with |
or &&
or ||
, it will be continued on the next line.
If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you.
It can be as simple as this : $("#element").transition({x:'90px'})
.
Take it from this link : http://ricostacruz.com/jquery.transit/
Adding to what deceze said above. This is a parse error, so in order to debug a parse error, create a new file in the root named debugSyntax.php. Put this in it:
<?php
/////// SYNTAX ERROR CHECK ////////////
error_reporting(E_ALL);
ini_set('display_errors','On');
//replace "pageToTest.php" with the file path that you want to test.
include('pageToTest.php');
?>
Run the debugSyntax.php page and it will display parse errors from the page that you chose to test.
I faced the same problem, and resolved it by changing the BodyStyle attribut value to "WebMessageBodyStyle.Bare" :
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProjectWithGeocodings/{projectId}")]
GeoCod_Project GetProjectWithGeocodings(string projectId);
The returned object will no longer be wrapped.
If you want to go all fancy-pants, here's how you can extend it to be able to do this:
@(Html.ActionLink<ArticlesController>(x => x.Details(), article.Title, new { id = article.ArticleID }))
You will need to put this in the System.Web.Mvc
namespace:
public static class MyProjectExtensions
{
public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
var link = new TagBuilder("a");
string actionName = ExpressionHelper.GetExpressionText(expression);
string controllerName = typeof(TController).Name.Replace("Controller", "");
link.MergeAttribute("href", urlHelper.Action(actionName, controllerName));
link.SetInnerText(linkText);
return new MvcHtmlString(link.ToString());
}
public static MvcHtmlString ActionLink<TController, TAction>(this HtmlHelper htmlHelper, Expression<Action<TController, TAction>> expression, string linkText, object routeValues)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
var link = new TagBuilder("a");
string actionName = ExpressionHelper.GetExpressionText(expression);
string controllerName = typeof(TController).Name.Replace("Controller", "");
link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
link.SetInnerText(linkText);
return new MvcHtmlString(link.ToString());
}
public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText, object routeValues, object htmlAttributes) where TController : Controller
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
var attributes = AnonymousObjectToKeyValue(htmlAttributes);
var link = new TagBuilder("a");
string actionName = ExpressionHelper.GetExpressionText(expression);
string controllerName = typeof(TController).Name.Replace("Controller", "");
link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
link.MergeAttributes(attributes, true);
link.SetInnerText(linkText);
return new MvcHtmlString(link.ToString());
}
private static Dictionary<string, object> AnonymousObjectToKeyValue(object anonymousObject)
{
var dictionary = new Dictionary<string, object>();
if (anonymousObject == null) return dictionary;
foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))
{
dictionary.Add(propertyDescriptor.Name, propertyDescriptor.GetValue(anonymousObject));
}
return dictionary;
}
}
This includes two overrides for Route Values
and HTML Attributes
, also, all of your views would need to add: @using YourProject.Controllers
or you can add it to your web.config <pages><namespaces>
you should load jquery first because bootstrap use jquery features. like this:
<!doctype html>
<html>
<head>
<link type="text/css" rel="stylesheet" src="css/animate.css">
<link type="text/css" rel="stylesheet" src="css/bootstrap-theme.min.css">
<link type="text/css" rel="stylesheet" src="css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="css/custom.css">
<!-- Shuffle your scripts HERE -->
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/wow.min.js"></script>
<!-- End -->
<title>pyMeLy Interface</title>
</head>
<body>
<p class="title1"><strong>pyMeLy</strong></p>
<p class="title2"><em> A stylish way to view your media</em></p>
<div style="text-align:center;">
<button type="button" class="btn btn-primary">Movies</button>
<button type="button" class="btn btn-primary btn-lg">Large button</button>
</div>
</body>
</html>
This error happened to me when I implemented a class method with a scope resolution operator in the header file, instead of .cpp file.
PS: And I was programming in C++ on Macbook Yosemite.
Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.
I had same issue on windows. I had v1.6 installed as well as v2.0. Uninstalling v1.6 allowed me to login.
You could use the LINQ select
clause and reference the property that relates to your Name column.
Since I think you are new with Python, lets do the long way, iterate thru your list using for loop and multiply and append each element to a new list.
using for loop
lst = [5, 20 ,15]
product = []
for i in lst:
product.append(i*5)
print product
using list comprehension, this is also same as using for-loop but more 'pythonic'
lst = [5, 20 ,15]
prod = [i * 5 for i in lst]
print prod
This can be done through the youtube player API:
Working example:
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
The '\r'
character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.
From the old telnet specification (RFC 854) (page 11):
The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").
However, from the latest specification (RFC5198) (page 13):
...
In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.
LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).
So newline in Telnet should always be '\r\n'
but most implementations have either not been updated, or keeps the old '\n\r'
for backwards compatibility.
For me this solution didn't work out:
background-color: #6DB3F2;
background-image: url('images/checked.png');
But instead it worked the other way:
<div class="block">
<span>
...
</span>
</div>
the css:
.block{
background-image: url('img.jpg') no-repeat;
position: relative;
}
.block::before{
background-color: rgba(0, 0, 0, 0.37);
content: '';
display: block;
height: 100%;
position: absolute;
width: 100%;
}
Short answer: You can't.
CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.
Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.
There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.
There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.
Use the Javascript string split() function.
var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');
// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc
without disabling the selected value on submitting..
$('#selectID option:not(:selected)').prop('disabled', true);
If you use Jquery version lesser than 1.7
$('#selectID option:not(:selected)').attr('disabled', true);
It works for me..
It's programmer preference. Personally, I love using this
since it explicitly marks the object members. Of course the _
does the same thing (only when you follow the convention)
I had right amount of memory settings but for me it was using a 64bit intellij with 32 bit jvm. Once I switched to 64 bit VM, the error was gone.
Try this one it will work
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.add("Nokia");
adapter.notifyDataSetChanged();
}
}
Assuming I am understanding your question and setup correctly,
If you're trying to use the build number in your script, you have two options:
1) When calling ant, use: ant -Dbuild_parameter=${BUILD_NUMBER}
2) Change your script so that:
<property environment="env" />
<property name="build_parameter" value="${env.BUILD_NUMBER}"/>
Whatever you return from a promise will be wrapped into a promise to be unwrapped at the next .then()
stage.
It becomes interesting when you need to return one or more promise(s) alongside one or more synchronous value(s) such as;
Promise.resolve([Promise.resolve(1), Promise.resolve(2), 3, 4])
.then(([p1,p2,n1,n2]) => /* p1 and p2 are still promises */);
In these cases it would be essential to use Promise.all()
to get p1
and p2
promises unwrapped at the next .then()
stage such as
Promise.resolve(Promise.all([Promise.resolve(1), Promise.resolve(2), 3, 4]))
.then(([p1,p2,n1,n2]) => /* p1 is 1, p2 is 2, n1 is 3 and n2 is 4 */);
Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
Your query will work in MYSQL
if you set to disable ONLY_FULL_GROUP_BY
server mode (and by default It is). But in this case, you are using different RDBMS. So to make your query work, add all non-aggregated columns to your GROUP BY
clause, eg
SELECT col1, col2, SUM(col3) totalSUM
FROM tableName
GROUP BY col1, col2
Non-Aggregated columns means the column is not pass into aggregated functions like SUM
, MAX
, COUNT
, etc..
The concept of http location and disk location is different. What you need to do is:
summer.jpg
c:\images\summer.jpg
summer.jpg
<img src="images/summer.jpg" />
c:\images\
under your application's /images
. If you cannot do this then in step #2 you need to save somewhere under your web root, e.g c:\my-applications\demo-app\build\images
The extended configuration section in a previous response with
...
...
<rollingStyle value="Composite" />
...
...
listed works but I did not have to use
<staticLogFileName value="false" />
. I think the RollingAppender must (logically) ignore that setting since by definition the file gets rebuilt each day when the application restarts/reused. Perhaps it does matter for immediate rollover EVERY time the application starts.
You can replace the first letter (preceded by a digit
) of each word using regex:
re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')
output:
1Bob 5Sandy
There is a library ng-device-detector which makes detecting entities like browser, os easy.
Here is tutorial that explains how to use this library. Detect OS, browser and device in AngularJS
You need to add re-tree.js and ng-device-detector.js scripts into your html
Inject "ng.deviceDetector" as dependency in your module.
Then inject "deviceDetector" service provided by the library into your controller or factory where ever you want the data.
"deviceDetector" contains all data regarding browser, os and device.
To filter by multiple attributes use something like:
//for AND
$collection = Mage::getModel('sales/order')->getCollection()
->addAttributeToSelect('*')
->addFieldToFilter('my_field1', 'my_value1')
->addFieldToFilter('my_field2', 'my_value2');
echo $collection->getSelect()->__toString();
//for OR - please note 'attribute' is the key name and must remain the same, only replace //the value (my_field1, my_field2) with your attribute name
$collection = Mage::getModel('sales/order')->getCollection()
->addAttributeToSelect('*')
->addFieldToFilter(
array(
array('attribute'=>'my_field1','eq'=>'my_value1'),
array('attribute'=>'my_field2', 'eq'=>'my_value2')
)
);
For more information check: http://docs.magentocommerce.com/Varien/Varien_Data/Varien_Data_Collection_Db.html#_getConditionSql
First, get Pdftk:
sudo apt-get install pdftk
Now, as shown on example page, use
pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf
for merging pdf files into one.
Step 1: Declaring Permission in Android Manifest
First thing to do in your first Android Project is you declare required permissions in your ‘AndroidManifest.xml’ file.
For Android Download Image from URL, we need permission to access the internet to download file and read and write internal storage to save image to internal storage.
Add following lines of code at the top of tag of AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Step 2: Request required permission from user
Android allows every app to run in a sandbox. If an app needs to access certain resources or information outside that sandbox, it needs to request permission from user.
From Android 6.0 onward, Google wants developers to request permission from user from within the app, for more details on permissions read this.
Therefore for Android Download Image from URL, you’ll need to request Read Storage and Write
For this, we will use the following lines of code to first check if the required permission is already granted by the user, if not then we will request permission for storage read and write permission.
We’re creating a method ‘Downlaod Image’, you can simple call this wherever you need to download the image.
void DownloadImage(String ImageUrl) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
showToast("Need Permission to access storage for Downloading Image");
} else {
showToast("Downloading Image...");
//Asynctask to create a thread to downlaod image in the background
new DownloadsImage().execute(ImageUrl);
}
}
Now that we have requested and been granted the user permission, to start with android download image from url, we will create an AsyncTask, as you are not allowed to run a background process in the main thread.
class DownloadsImage extends AsyncTask<String, Void,Void>{
@Override
protected Void doInBackground(String... strings) {
URL url = null;
try {
url = new URL(strings[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Bitmap bm = null;
try {
bm = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
//Create Path to save Image
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+ "/AndroidDvlpr"); //Creates app specific folder
if(!path.exists()) {
path.mkdirs();
}
File imageFile = new File(path, String.valueOf(System.currentTimeMillis())+".png"); // Imagename.png
FileOutputStream out = null;
try {
out = new FileOutputStream(imageFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try{
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(MainActivity.this,new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// Log.i("ExternalStorage", "Scanned " + path + ":");
// Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch(Exception e) {
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
showToast("Image Saved!");
}
}
In the above give lines of code, a URL and Bitmap is created, using BitmapFactory.decodeStream, file is downloaded.
The File path is created to save the image (We have created a folder named ‘AndroidDvlpr’ in DIRECTORY_PICTURES) and download is initialized.
After downloading the file MediaScannerConnection, is called to read metadata from the file and add the file to the media content provider so the image is available for the user.
In the above lines of code, we have also created a method, showToast() to show Toast. complete code here:
void showToast(String msg){
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
I though the perfect solution would be to have a timer handle the delayed action. FxCop doesn't like when you have an interval less then one second. I need to delay my actions until AFTER my DataGrid has completed sorting by column. I figured a one-shot timer (AutoReset = false) would be the solution, and it works perfectly. AND, FxCop will not let me suppress the warning!
I found.
The url is For Exapmle: https://example.com/xD?foo=bar&uri=https%3A%2F%2Fexample.com%2FxD
You need Found $_GET['uri'] is encoded or not:
preg_match("/.*uri=(.*)&?.*/", $_SERVER['REQUEST_URI'], $r);
if (isset($_GET['uri']) && urldecode($r['1']) === $r['1']) {
// Code Here if url is not encoded
}
There is no real solution to this - even in the links to other questions given above. In the end I have decided to use setTimeout
and call a method that checks every second! Not an ideal solution, but a solution that works and code I am calling is simple enough to not have an effect on performance by being called all the time.
function InitPageControls() {
CheckIfChanged();
}
function CheckIfChanged() {
// do logic
setTimeout(function () {
CheckIfChanged();
}, 1000);
}
Hope this helps someone in the future as it seems there is no surefire way of acheiving this using event handlers...
public class SomeClass
{
public void SomeMethod()
{
StackFrame frame = new StackFrame(1);
var method = frame.GetMethod();
var type = method.DeclaringType;
var name = method.Name;
}
}
Now let's say you have another class like this:
public class Caller
{
public void Call()
{
SomeClass s = new SomeClass();
s.SomeMethod();
}
}
name will be "Call" and type will be "Caller"
UPDATE Two years later since I'm still getting upvotes on this
In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute
Going with the previous example:
public class SomeClass
{
public void SomeMethod([CallerMemberName]string memberName = "")
{
Console.WriteLine(memberName); //output will be name of calling method
}
}
The other answers provide a lot of details about retrieving the markup of a WebElement. However, an important aspect is, modern websites are increasingly implementing JavaScript, ReactJS, jQuery, Ajax, Vue.js, Ember.js, GWT, etc. to render the dynamic elements within the DOM tree. Hence there is a necessity to wait for the element and its children to completely render before retrieving the markup.
Hence, ideally you need to induce WebDriverWait for the visibility_of_element_located()
and you can use either of the following Locator Strategies:
Using get_attribute("outerHTML")
:
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
print(element.get_attribute("outerHTML"))
Using execute_script()
:
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
print(driver.execute_script("return arguments[0].outerHTML;", element))
Note: You have to add the following imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
to work this with unicode or fontawesome, you should add a span with class like below, because input tag not support pseudo classes like :after. this is not a direct solution
in html:
<span class="button1 search"></span>
<input name="username">
in css:
.button1 {
background-color: #B9D5AD;
border-radius: 0.2em 0 0 0.2em;
box-shadow: 1px 0 0 rgba(0, 0, 0, 0.5), 2px 0 0 rgba(255, 255, 255, 0.5);
pointer-events: none;
margin:1px 12px;
border-radius: 0.2em;
color: #333333;
cursor: pointer;
position: absolute;
padding: 3px;
text-decoration: none;
}
They can be in separate containers, and indeed, if the application was also intended to run in a larger environment, they probably would be.
A multi-container system would require some more orchestration to be able to bring up all the required dependencies, though in Docker v0.6.5+, there is a new facility to help with that built into Docker itself - Linking. With a multi-machine solution, its still something that has to be arranged from outside the Docker environment however.
With two different containers, the two parts still communicate over TCP/IP, but unless the ports have been locked down specifically (not recommended, as you'd be unable to run more than one copy), you would have to pass the new port that the database has been exposed as to the application, so that it could communicate with Mongo. This is again, something that Linking can help with.
For a simpler, small installation, where all the dependencies are going in the same container, having both the database and Python runtime started by the program that is initially called as the ENTRYPOINT is also possible. This can be as simple as a shell script, or some other process controller - Supervisord is quite popular, and a number of examples exist in the public Dockerfiles.
In my case, setting SQL Server Database Engine service startup account to NT AUTHORITY\NETWORK SERVICE failed, but setting it to NT Authority\System allowed me to succesfully install my SQL Server 2016 STD instance.
Just check the following snapshot.
For further details, check @Shanky's answer at https://dba.stackexchange.com/a/71798/66179
Remember: you can avoid server rebooting using setup's SkipRules switch:
setup.exe /ACTION=INSTALL /SkipRules=RebootRequiredCheck
setup.exe /ACTION=UNINSTALL /SkipRules=RebootRequiredCheck
Getters and setters in JavaScript are used for defining computed properties, or accessors. A computed property is one that uses a function to get or set an object value. The basic theory is doing something like this:
var user = { /* ... object with getters and setters ... */ };
user.phone = '+1 (123) 456-7890'; // updates a database
console.log( user.areaCode ); // displays '123'
console.log( user.area ); // displays 'Anytown, USA'
This is useful for automatically doing things behind-the-scenes when a property is accessed, like keeping numbers in range, reformatting strings, triggering value-has-changed events, updating relational data, providing access to private properties, and more.
The examples below show the basic syntax, though they simply get and set the internal object value without doing anything special. In real-world cases you would modify the input and/or output value to suit your needs, as noted above.
ECMAScript 5 supports get
and set
keywords for defining computed properties. They work with all modern browsers except IE 8 and below.
var foo = {
bar : 123,
get bar(){ return bar; },
set bar( value ){ this.bar = value; }
};
foo.bar = 456;
var gaz = foo.bar;
get
and set
aren't reserved words, so they can be overloaded to create your own custom, cross-browser computed property functions. This will work in any browser.
var foo = {
_bar : 123,
get : function( name ){ return this[ '_' + name ]; },
set : function( name, value ){ this[ '_' + name ] = value; }
};
foo.set( 'bar', 456 );
var gaz = foo.get( 'bar' );
Or for a more compact approach, a single function may be used.
var foo = {
_bar : 123,
value : function( name /*, value */ ){
if( arguments.length < 2 ){ return this[ '_' + name ]; }
this[ '_' + name ] = value;
}
};
foo.value( 'bar', 456 );
var gaz = foo.value( 'bar' );
Avoid doing something like this, which can lead to code bloat.
var foo = {
_a : 123, _b : 456, _c : 789,
getA : function(){ return this._a; },
getB : ..., getC : ..., setA : ..., setB : ..., setC : ...
};
For the above examples, the internal property names are abstracted with an underscore in order to discourage users from simply doing foo.bar
vs. foo.get( 'bar' )
and getting an "uncooked" value. You can use conditional code to do different things depending on the name of the property being accessed (via the name
parameter).
Using Object.defineProperty()
is another way to add getters and setters, and can be used on objects after they're defined. It can also be used to set configurable and enumerable behaviors. This syntax also works with IE 8, but unfortunately only on DOM objects.
var foo = { _bar : 123 };
Object.defineProperty( foo, 'bar', {
get : function(){ return this._bar; },
set : function( value ){ this._bar = value; }
} );
foo.bar = 456;
var gaz = foo.bar;
Finally, __defineGetter__()
is another option. It's deprecated, but still widely used around the web and thus unlikely to disappear anytime soon. It works on all browsers except IE 10 and below. Though the other options also work well on non-IE, so this one isn't that useful.
var foo = { _bar : 123; }
foo.__defineGetter__( 'bar', function(){ return this._bar; } );
foo.__defineSetter__( 'bar', function( value ){ this._bar = value; } );
Also worth noting is that in the latter examples, the internal names must be different than the accessor names to avoid recursion (ie, foo.bar
calling foo.get(bar)
calling foo.bar
calling foo.get(bar)
...).
MDN get, set,
Object.defineProperty(), __defineGetter__(), __defineSetter__()
MSDN
IE8 Getter Support
This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.
Obviously, replace new_file_loc with whatever your new file location will be.
@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
call :open "%%i"
exit /B 0
)
:open
start "window title" "cmd /K copy %~1 new_file_loc"
exit /B 0
$rootScope.$broadcast is a convenient way to raise a "global" event which all child scopes can listen for. You only need to use $rootScope
to broadcast the message, since all the descendant scopes can listen for it.
The root scope broadcasts the event:
$rootScope.$broadcast("myEvent");
Any child Scope can listen for the event:
$scope.$on("myEvent",function () {console.log('my event occurred');} );
Why we use $rootScope.$broadcast? You can use $watch
to listen for variable changes and execute functions when the variable state changes. However, in some cases, you simply want to raise an event that other parts of the application can listen for, regardless of any change in scope variable state. This is when $broadcast
is helpful.
I was running on Win7, Tomcat7 with maven-pom setup on Eclipse Mars with maven project enabled. On a NOT running server I only had to change from 3.1 to 3.0 on this screen:
For me it was important to have Dynamic Web Module disabled! Then change the version and then enable Dynamic Web Module again.
I use this one:
LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
For example, using a 1s interval:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
the time is in milliseconds, the distance is in meters.
This automatically calls:
public void onLocationChanged(Location location) {
//Code here, location.getAccuracy(), location.getLongitude() etc...
}
I also had these included in the script but didnt actually use them:
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
In short:
public class GPSClass implements LocationListener {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
}
}
this : is the DOM Element $(this) : Jquery objct, which wrapped with Dom Element, you can check this answer also this vs $(this)
try like this Attr(). Get the value of an attribute for the first element in the set of matched elements.
$(document).ready(function () {
$(".inputs").click(function () {
alert(" or " + $(this).attr("id"));
});
});
The simplest way today would be to simply request the Material Icons font from Google Fonts, for example in your HTML header tag:
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
or in your stylesheet:
@import url(https://fonts.googleapis.com/icon?family=Material+Icons);
and then use as font icon with ligatures as explained in the md-icon directive. For example:
<md-icon aria-label="Menu" class="material-icons">menu</md-icon>
The complete list of icons/ligatures is at https://www.google.com/design/icons/
is_uploaded_file()
is great to use, specially for checking whether it is an uploaded file or a local file (for security purposes).
However, if you want to check whether the user uploaded a file,
use $_FILES['file']['error'] == UPLOAD_ERR_OK
.
See the PHP manual on file upload error messages. If you just want to check for no file, use UPLOAD_ERR_NO_FILE
.
in my case as I've a bottom tool bar I had a problem when testing the previous solutions, the android system buttons are covered with my bottom menu my solution is to add within the activity:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// force full screen mode requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main_activity_container);
Add this to activity's xml in layout folder:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/prod_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
Make toolbar clickable, add these to onCreate method:
Toolbar toolbar = (Toolbar) findViewById(R.id.prod_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
With the dplyr
-package loaded use
bob=bob%>%mutate_at("phenotype", as.character)
if you only want to change the phenotype
-column specifically.
Windows 10
It could be that your server doesn't start automatically on windows 10 and you need to start it yourself after setting your Postgresql path using the following command in cmd:
pg_ctl -D "C:\Program Files\PostgreSQL\11.4\data" start
You need to be inside "C:\Program Files\PostgreSQL\11.4\bin" directory to execute the above command.
EX:
You still need to be inside the bin directory to work with psql
A variable prefixed with @
is an instance variable, while one prefixed with @@
is a class variable. Check out the following example; its output is in the comments at the end of the puts
lines:
class Test
@@shared = 1
def value
@@shared
end
def value=(value)
@@shared = value
end
end
class AnotherTest < Test; end
t = Test.new
puts "t.value is #{t.value}" # 1
t.value = 2
puts "t.value is #{t.value}" # 2
x = Test.new
puts "x.value is #{x.value}" # 2
a = AnotherTest.new
puts "a.value is #{a.value}" # 2
a.value = 3
puts "a.value is #{a.value}" # 3
puts "t.value is #{t.value}" # 3
puts "x.value is #{x.value}" # 3
You can see that @@shared
is shared between the classes; setting the value in an instance of one changes the value for all other instances of that class and even child classes, where a variable named @shared
, with one @
, would not be.
[Update]
As Phrogz mentions in the comments, it's a common idiom in Ruby to track class-level data with an instance variable on the class itself. This can be a tricky subject to wrap your mind around, and there is plenty of additional reading on the subject, but think about it as modifying the Class
class, but only the instance of the Class
class you're working with. An example:
class Polygon
class << self
attr_accessor :sides
end
end
class Triangle < Polygon
@sides = 3
end
class Rectangle < Polygon
@sides = 4
end
class Square < Rectangle
end
class Hexagon < Polygon
@sides = 6
end
puts "Triangle.sides: #{Triangle.sides.inspect}" # 3
puts "Rectangle.sides: #{Rectangle.sides.inspect}" # 4
puts "Square.sides: #{Square.sides.inspect}" # nil
puts "Hexagon.sides: #{Hexagon.sides.inspect}" # 6
I included the Square
example (which outputs nil
) to demonstrate that this may not behave 100% as you expect; the article I linked above has plenty of additional information on the subject.
Also keep in mind that, as with most data, you should be extremely careful with class variables in a multithreaded environment, as per dmarkow's comment.
if Your Android Studio Version Greater than 3.0
Looks like we can not directly use the apk after running on the device from the build -->output->apk folder.
After upgrading to android studio 3.0 you need to go to Build -> Build Apk(s) then copy the apk from build -> output -> apk -> debug
In a more general case:
N( A union B) = N(A) + N(B) - N(A intersect B)
= COUNTIFS(A1:A196,"Yes",J1:J196,"Agree")+COUNTIFS(A1:A196,"No",J1:J196,"Agree")-A1:A196,"Yes",A1:A196,"No")
The convention is to ask a question in the name.
Here are a few examples that can be found in the JDK:
isEmpty()
hasChildren()
That way, the names are read like they would have a question mark on the end.
Is the Collection empty?
Does this Node have children?
And, then, true
means yes, and false
means no.
Or, you could read it like an assertion:
The Collection is empty.
The node has children
Note:
Sometimes you may want to name a method something like createFreshSnapshot?
. Without the question mark, the name implies that the method should be creating a snapshot, instead of checking to see if one is required.
In this case you should rethink what you are actually asking. Something like isSnapshotExpired
is a much better name, and conveys what the method will tell you when it is called. Following a pattern like this can also help keep more of your functions pure and without side effects.
If you do a Google Search for isEmpty()
in the Java API, you get lots of results.
I asked the same question recently:
Format file size as MB, GB, etc.
While there is no out-of-the-box answer, I can live with the solution:
private static final long K = 1024;
private static final long M = K * K;
private static final long G = M * K;
private static final long T = G * K;
public static String convertToStringRepresentation(final long value){
final long[] dividers = new long[] { T, G, M, K, 1 };
final String[] units = new String[] { "TB", "GB", "MB", "KB", "B" };
if(value < 1)
throw new IllegalArgumentException("Invalid file size: " + value);
String result = null;
for(int i = 0; i < dividers.length; i++){
final long divider = dividers[i];
if(value >= divider){
result = format(value, divider, units[i]);
break;
}
}
return result;
}
private static String format(final long value,
final long divider,
final String unit){
final double result =
divider > 1 ? (double) value / (double) divider : (double) value;
return new DecimalFormat("#,##0.#").format(result) + " " + unit;
}
Test code:
public static void main(final String[] args){
final long[] l = new long[] { 1l, 4343l, 43434334l, 3563543743l };
for(final long ll : l){
System.out.println(convertToStringRepresentation(ll));
}
}
Output (on my German locale):
1 B
4,2 KB
41,4 MB
3,3 GB
I have opened an issue requesting this functionality for Google Guava. Perhaps someone would care to support it.
I'd recommend getting the source with urllib and, if you're going to parse, use something like Beautiful Soup.
import urllib
url = urllib.urlopen("http://example.com") # Open the URL.
content = url.readlines() # Read the source and save it to a variable.
insert into TABLENAMEA (A,B,C,D)
select A::integer,B,C,D from TABLENAMEB
outlist <- list(resultsa)
outlist[2] <- list(resultsb)
outlist[3] <- list(resultsc)
append
's help file says it is for vectors. But it can be used here. I thought I had tried that before but there were some strange anomalies in the OP's code that may have mislead me:
outlist <- list(resultsa)
outlist <- append(outlist,list(resultsb))
outlist <- append(outlist,list(resultsc))
Same results.
I know it's been a while, but I'll this here in case it helps someone out.
The right answer by far is (and the selected one) the one from CommonsWare. I was having the same problem as posted, the following
MyFragmentClass fragmentList =
(MyFragmentClass) getSupportFragmentManager().findFragmentById(R.id.fragementID);
kept on returning null. My mistake was really silly, in my xml file:
<fragment
android:tag="@+id/fragementID"
android:name="com.sf.lidgit_android.content.MyFragmentClass"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
The mistake was that I had android:tag INSTEAD OF android:id.
I think this does the best job
https://angular.io/api/platform-browser/EventManager
for instance in app.component
constructor(private eventManager: EventManager) {
const removeGlobalEventListener = this.eventManager.addGlobalEventListener(
'document',
'keypress',
(ev) => {
console.log('ev', ev);
}
);
}
Get the number of days, then divide by 365.2425 (the mean Gregorian year) for years. Divide by 30.436875 (the mean Gregorian month) for months.
JSONObject jsonobject=new JSONObject();
jsonobject.put("error","Invalid username");
response.getWriter().write(jsonobject.toString());
in javascript:
f(data!=success){
var errorMessage=jQuery.parseJson(data);
alert(errorMessage.error);
}
That would be the ALL_DIRECTORIES view:
http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/statviews_1075.htm#i1576965
If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.
If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.
What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:
#ifdef LIBRARY_EXPORTS
# define LIBRARY_API __declspec(dllexport)
#else
# define LIBRARY_API __declspec(dllimport)
#endif
Then on a function that you want to be exported you use LIBRARY_API
:
LIBRARY_API int GetCoolInteger();
In your library build project create a define LIBRARY_EXPORTS
this will cause your functions to be exported for your DLL build.
Since LIBRARY_EXPORTS
will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.
If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:
#ifdef _WIN32
# ifdef LIBRARY_EXPORTS
# define LIBRARY_API __declspec(dllexport)
# else
# define LIBRARY_API __declspec(dllimport)
# endif
#elif
# define LIBRARY_API
#endif
When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.
If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C"
inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:
The Code:
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
EXTERN_DLL_EXPORT int getEngineVersion() {
return 1;
}
EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
K.getGraphicsServer().addGraphicsDriver(
auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
);
}
And here's what the exports look like with Dumpbin /exports:
Dump of file opengl_plugin.dll
File Type: DLL
Section contains the following exports for opengl_plugin.dll
00000000 characteristics
49866068 time date stamp Sun Feb 01 19:54:32 2009
0.00 version
1 ordinal base
2 number of functions
2 number of names
ordinal hint RVA name
1 0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
2 1 00011028 registerPlugin = @ILT+35(_registerPlugin)
So this code works fine:
m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");
m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
::GetProcAddress(m_hDLL, "registerPlugin")
);
var formatedDate = DateTime.Now.ToString("yyyy-MM-dd",System.Globalization.CultureInfo.InvariantCulture);
To ensure the user's local settings don't affect it
You should check out this plugin:
https://github.com/kemayo/maphilight
and the demo:
http://davidlynch.org/js/maphilight/docs/demo_usa.html
if anything, you might be able to borrow some code from it to fix yours.
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
Here are two worthy caveats from the comments.
Either you want user to be of type
User | {}
orPartial<User>
, or you need to redefine theUser
type to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. –jcalz
I don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property
Username
is left undefined, while the type annotation is saying it can't be undefined. –Ian Liu Rodrigues
One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.
type User = {
Username: string;
Email: string;
}
const user01 = {} as User;
const user02 = <User>{};
user01.Email = "[email protected]";
Here is a working example for you.
The simplest way to do it is to put a simple IF before you do the SWITCH , and that IF test your condition for exiting the loop .......... as simple as it can be
At first glance, your code will not compile. Since the nested if statement doesn't have any braces, it will consider the next line the code that it should execute. Also, you are comparing a char against a String, " ". Try comparing the values as chars instead. I think the correct syntax would be:
if(c == ' '){
//do something here
}
But then again, I am not familiar with the "Equal"
class
With google you can do it using the spherical api, google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);
.
However, if the precision of a spherical projection or a haversine solution is not precise enough for you (e.g. if you're close to the pole or computing longer distances), you should use a different library.
Most information on the subject I found on Wikipedia here.
A trick to see if the precision of any given algorithm is adequate is to fill in the maximum and minimum radius of the earth and see if the difference might cause problems for your use case. Many more details can be found in this article
In the end the google api or haversine will serve most purposes without problems.
Just use this css method:
body{
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
You can find the same answer here: How to disable text selection highlighting using CSS?
myfunc("string*& val") this itself doesn't make any sense. "string*& val" implies "string val",* and & cancels each other. Finally one can not pas string variable to a function("string val"). Only basic data types can be passed to a function, for other data types need to pass as pointer or reference. You can have either string& val or string* val to a function.
I had same problem when I did git pull
git pull fatal: protocol error: bad line length character: <htm fatal: the remote end hung up unexpectedly
I changed my remote url HTTP to SSH, and it worked for me.
git remote set-url origin "HTTP" to "SSH"
$( 'input[name="testGroup"]:radio' ).on('change', function(e) {_x000D_
console.log(e.type);_x000D_
return false;_x000D_
});
_x000D_
This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On
Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.
Lastly, I'm simply showing an alternative syntax to attach the event to the element.
This is the job for style
property:
document.getElementById("remember").style.visibility = "visible";
ALTER TABLE dbo.table
DROP CONSTRAINT uq_testConstrain
constraint name uq_testConstrain
can be found under database->table->keys folder
A function uses the globals of the module it's defined in. Instead of setting a = 3
, for example, you should be setting module1.a = 3
. So, if you want cur
available as a global in utilities_module
, set utilities_module.cur
.
A better solution: don't use globals. Pass the variables you need into the functions that need it, or create a class to bundle all the data together, and pass it when initializing the instance.
For those situations where you need a bit more customisation of the output (separator or decimal symbol), or who have large dataset (over 65k rows), I wrote the following:
Option Explicit
Sub rng2csv(rng As Range, fileName As String, Optional sep As String = ";", Optional decimalSign As String)
'export range data to a CSV file, allowing to chose the separator and decimal symbol
'can export using rng number formatting!
'by Patrick Honorez --- www.idevlop.com
Dim f As Integer, i As Long, c As Long, r
Dim ar, rowAr, sOut As String
Dim replaceDecimal As Boolean, oldDec As String
Dim a As Application: Set a = Application
ar = rng
f = FreeFile()
Open fileName For Output As #f
oldDec = Format(0, ".") 'current client's decimal symbol
replaceDecimal = (decimalSign <> "") And (decimalSign <> oldDec)
For Each r In rng.Rows
rowAr = a.Transpose(a.Transpose(r.Value))
If replaceDecimal Then
For c = 1 To UBound(rowAr)
'use isnumber() to avoid cells with numbers formatted as strings
If a.IsNumber(rowAr(c)) Then
'uncomment the next 3 lines to export numbers using source number formatting
' If r.cells(1, c).NumberFormat <> "General" Then
' rowAr(c) = Format$(rowAr(c), r.cells(1, c).NumberFormat)
' End If
rowAr(c) = Replace(rowAr(c), oldDec, decimalSign, 1, 1)
End If
Next c
End If
sOut = Join(rowAr, sep)
Print #f, sOut
Next r
Close #f
End Sub
Sub export()
Debug.Print Now, "Start export"
rng2csv shOutput.Range("a1").CurrentRegion, RemoveExt(ThisWorkbook.FullName) & ".csv", ";", "."
Debug.Print Now, "Export done"
End Sub
If you know the data and the action the installed package react on, you simply should add these information to your intent instance before starting it.
If you have access to the AndroidManifest of the other app, you can see all needed information there.
df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))
df %>%
mutate(d= a/2) %>%
select(a, b, d, c)
results
a b d c
1 1 3 0.5 5
2 2 4 1.0 6
I suggest to use dplyr::select
after dplyr::mutate
. It has many helpers to select/de-select subset of columns.
In the context of this question the order by which you select will be reflected in the output data.frame.
When using data binding and you need to know a RecyclerView click position from inside of an item's click listener:
Kotlin
val recyclerView = view.parent as RecyclerView
val position = recyclerView.getChildAdapterPosition(view)
You can hit the key q (for quit) and it should take you to the prompt.
Please see this link.
What you should do is create a service to share data between controllers.
Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk
If they are two integers you can try a quick and dirty trick: Map<String, ?>
using the key as i+"#"+j
.
If the key i+"#"+j
is the same as j+"#"+i
try min(i,j)+"#"+max(i,j)
.
I think you want this syntax:
ALTER TABLE tb_TableName
add constraint cnt_Record_Status Default '' for Record_Status
Based on some of your comments, I am going to guess that you might already have null
values in your table which is causing the alter of the column to not null
to fail. If that is the case, then you should run an UPDATE
first. Your script will be:
update tb_TableName
set Record_Status = ''
where Record_Status is null
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL
ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
there is also a way, to do it without JQuery!
check out this:
document.addEventListener("mousedown", function(evt) {
switch(evt.buttons) {
case 1: // left mouse
case 2: // right mouse
case 3: // middle mouse <- I didn't tested that, I just got a touchpad
}
});
An easier way to open a document from an unidentified developer, if you know it's safe, is to control-click on the file icon and then select "Open." You will then be given the option of opening it regardless of its unidentified source.
I'm using the following
type Props = { children: React.ReactNode };
const MyComponent: React.FC<Props> = ({children}) => {
return (
<div>
{ children }
</div>
);
export default MyComponent;
If you have an app with extensions and/or a watch app and you have multiple provisioning profiles for each extension/watch app then you should use this script to re-sign the ipa file.
Here is an example of how to use this script:
./resign.sh YourApp.ipa "iPhone Distribution: YourCompanyOrDeveloperName" -p <path_to_provisioning_profile_for_app>.mobileprovision -p <path_to_provisioning_profile_for_watchkitextension>.mobileprovision -p <path_to_provisioning_profile_for_watchkitapp>.mobileprovision -p <path_to_provisioning_profile_for_todayextension>.mobileprovision resignedYourApp.ipa
You can include other extension provisioning profiles too by adding it with yet another -p option.
For me - all the provisioning profiles were signed by the same certificate/signing identity.
no need to do so many things. for set value using multiple select2 var selectedvalue="1,2,3"; //if first 3 products are selected. $('#ddlProduct').val(selectedvalue);
You can change the class of the entire table and use the cascade in the CSS: http://jsbin.com/oyunuy/1/
I've managed to find a CSS workaround to preventing bouncing of the viewport. The key was to wrap the content in 3 divs with -webkit-touch-overflow:scroll applied to them. The final div should have a min-height of 101%. In addition, you should explicitly set fixed widths/heights on the body tag representing the size of your device. I've added a red background on the body to demonstrate that it is the content that is now bouncing and not the mobile safari viewport.
Source code below and here is a plunker (this has been tested on iOS7 GM too). http://embed.plnkr.co/NCOFoY/preview
If you intend to run this as a full-screen app on iPhone 5, modify the height to 1136px (when apple-mobile-web-app-status-bar-style is set to 'black-translucent' or 1096px when set to 'black'). 920x is the height of the viewport once the chrome of mobile safari has been taken into account).
<!doctype html>
<html>
<head>
<meta name="viewport" content="initial-scale=0.5,maximum-scale=0.5,minimum-scale=0.5,user-scalable=no" />
<style>
body { width: 640px; height: 920px; overflow: hidden; margin: 0; padding: 0; background: red; }
.no-bounce { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
.no-bounce > div { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
.no-bounce > div > div { width: 100%; min-height: 101%; font-size: 30px; }
p { display: block; height: 50px; }
</style>
</head>
<body>
<div class="no-bounce">
<div>
<div>
<h1>Some title</h1>
<p>item 1</p>
<p>item 2</p>
<p>item 3</p>
<p>item 4</p>
<p>item 5</p>
<p>item 6</p>
<p>item 7</p>
<p>item 8</p>
<p>item 9</p>
<p>item 10</p>
<p>item 11</p>
<p>item 12</p>
<p>item 13</p>
<p>item 14</p>
<p>item 15</p>
<p>item 16</p>
<p>item 17</p>
<p>item 18</p>
<p>item 19</p>
<p>item 20</p>
</div>
</div>
</div>
</body>
</html>
I know this is an old question, but if you encounter this problem in MVC 3 then you can decorate your ActionMethod
with [ValidateInput(false)]
and just switch off request validation for a single ActionMethod
, which is handy. And you don't need to make any changes to the web.config
file, so you can still use the .NET 4 request validation everywhere else.
e.g.
[ValidateInput(false)]
public ActionMethod Edit(int id, string value)
{
// Do your own checking of value since it could contain XSS stuff!
return View();
}
Try:
select v.*, row_number() over (partition by id order by elem) rn from
(select
id,
unnest(string_to_array(elements, ',')) AS elem
from myTable) v
I solved the issue removing gulp and installing gulp-cli again:
rm /usr/local/bin/gulp
npm install -g gulp-cli
You can also use get_object_or_404(), it will raise a Http404
if the object wasn't found:
user_pass = log_in(request.POST) #form class
if user_pass.is_valid():
cleaned_info = user_pass.cleaned_data
user_object = get_object_or_404(User, email=cleaned_info['username'])
# User object found, you are good to go!
...
As soon as the page loads, the init
function is fired and the page is redirected:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script>
function init()
{
window.location.href = "www.wherever.com";
}
</script>
</head>
<body onload="init()">
</body>
</html>
Look in your JBoss bin folder for the file run.bat (run.sh on Unix)
look for the line
set JAVA_OPTS
, (or just JAVA_OPTS on Unix) at the end of that line add -Xmx512m. Change the number to the amount of memory you want to allocate to JBoss.
If you are using a custom script to start your jboss instance, you can add the set JAVA_OPTS option there as well.
At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:
IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END
Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.
If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.
IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE clockDate = '08/10/2012' AND userName = 'test'
END
As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.
In case Chrome tells you "This can only be added from the Chrome Web Store", you can try the following:
tar -czf workspace.tar.gz .??* *
Specifying .??*
will include "dot" files and directories that have at least 2 characters after the dot. The down side is it will not include files/directories with a single character after the dot, such as .a
, if there are any.
In your Info.plist you need to define View controller-based status bar appearance to any value.
If you define it YES then you should override preferredStatusBarStyle function in each view controller.
If you define it NO then you can set style in AppDelegate using
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
It is well defined behaviour. You cannot get the old value for a mutated object. That's because both the newVal
and oldVal
refer to the same object. Vue will not keep an old copy of an object that you mutated.
Had you replaced the object with another one, Vue would have provided you with correct references.
Read the Note
section in the docs. (vm.$watch
)
This will give you the deadline :
select id,
title,
created_at + interval '1' day * claim_window as deadline
from projects
Alternatively the function make_interval
can be used:
select id,
title,
created_at + make_interval(days => claim_window) as deadline
from projects
To get all projects where the deadline is over, use:
select *
from (
select id,
created_at + interval '1' day * claim_window as deadline
from projects
) t
where localtimestamp at time zone 'UTC' > deadline
[]
extracts a list, [[]]
extracts elements within the list
alist <- list(c("a", "b", "c"), c(1,2,3,4), c(8e6, 5.2e9, -9.3e7))
str(alist[[1]])
chr [1:3] "a" "b" "c"
str(alist[1])
List of 1
$ : chr [1:3] "a" "b" "c"
str(alist[[1]][1])
chr "a"
@Zoidberg is right, example:
<h1>title</h1> <h2>date</h2>
will not display space between header markup, with
& nbsp ;
will do space :)
I think you may have missed this part in the tutorial:
Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:
System.Data.Common and System.Data.SqlClient.
Currently this creates dependency in project.json –> aspnetcore50 section to these two libraries.
"aspnetcore50": { "dependencies": { "System.Runtime": "4.0.20-beta-22523", "System.Data.Common": "4.0.0.0-beta-22605", "System.Data.SqlClient": "4.0.0.0-beta-22605" } }
Try getting System.Data.Common and System.Data.SqlClient via Nuget and see if this adds the above dependencies for you, but in a nutshell you are missing System.Runtime.
Edit: As per Mozarts answer, if you are using .NET Core 3+, reference Microsoft.Data.SqlClient
instead.
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
I had the same problem, on Ubuntu though, started just over a month ago. What did it for me was to revert my Nvidia driver back to its stable version (I've been using the alleged unstable version for a couple of months now).
Anyway, it's worth a shot: Open "System Settings" and under the "Hardware Tab" go to "Additional Drivers". You should see on the list a driver called: "Nvidia Binary Xorg Driver..." - activate it.
Hope this helps to Ubuntu users out there..
I made a reusable plugin that can do this... I left the binding to events outside the plugin itself because I feel it is too intrusive for such a little helper....
jQuery(function ($) {
/**
* This small plugin will scrollTo a target, smoothly
*
* First argument = time to scroll to the target
* Second argument = set the hash in the current url yes or no
*/
$.fn.smoothScroll = function(t, setHash) {
// Set time to t variable to if undefined 500 for 500ms transition
t = t || 500;
setHash = (typeof setHash == 'undefined') ? true : setHash;
// Return this as a proper jQuery plugin should
return this.each(function() {
$('html, body').animate({
scrollTop: $(this).offset().top
}, t);
// Lets set the hash to the current ID since if an event was prevented this doesn't get done
if (this.id && setHash) {
window.location.hash = this.id;
}
});
};
});
Now next, we can onload just do this, check for a hash and if its there try to use it directly as a selector for jQuery. Now I couldn't easily test this at the time but I made similar stuff for production sites not long ago, if this doesn't immediatly work let me know and I'll look into the solution I got there.
(script should be within an onload section)
if (window.location.hash) {
window.scrollTo(0,0);
$(window.location.hash).smoothScroll();
}
Next we bind the plugin to onclick of anchors which only contain a hash in their href attribute.
(script should be within an onload section)
$('a[href^="#"]').click(function(e) {
e.preventDefault();
$($(this).attr('href')).smoothScroll();
});
Since jQuery doesn't do anything if the match itself fails we have a nice fallback for when a target on a page can't be found yay \o/
Update
Alternative onclick handler to scroll to the top when theres only a hash:
$('a[href^="#"]').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
// In this case we have only a hash, so maybe we want to scroll to the top of the page?
if(href.length === 1) { href = 'body' }
$(href).smoothScroll();
});
Here is also a simple jsfiddle that demonstrates the scrolling within page, onload is a little hard to set up...
http://jsfiddle.net/sg3s/bZnWN/
Update 2
So you might get in trouble with the window already scrolling to the element onload. This fixes that: window.scrollTo(0,0);
it just scrolls the page to the left top. Added it to the code snippet above.
def flatten_it(d):
if isinstance(d, list) or isinstance(d, tuple):
return tuple([flatten_it(item) for item in d])
elif isinstance(d, dict):
return tuple([(flatten_it(k), flatten_it(v)) for k, v in sorted(d.items())])
else:
return d
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 1}
print set(flatten_it(dict1)) - set(flatten_it(dict2)) # set([('b', 2), ('c', 3)])
# or
print set(flatten_it(dict2)) - set(flatten_it(dict1)) # set([('b', 1)])
You need to look for some replaceAll option
str = str.replace(/ /g, "+");
this is a regular expression way of doing a replaceAll.
function ReplaceAll(Source, stringToFind, stringToReplace) {
var temp = Source;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
I was having the same issue. My problem was that the computer that generated the initial certificate request had crashed before the extended ssl validation process was completed. I needed to generate a new private key and then import the updated certificate from the certificate provider. If the private key doesn't exist on your computer then you can't export the certificate as pfx. They option is greyed out.
Additional: when you save df to .csv format, the datetime (year in this specific case) is saved as object, so you need to convert it into integer (year in this specific case) when you do the merge. That is why when you upload both df from csv files, you can do the merge easily, while above error will show up if one df is uploaded from csv files and the other is from an existing df. This is somewhat annoying, but have an easy solution if kept in mind.
I have some simple logic for that:
<?php
per_days_diff('2011-12-12','2011-12-29')
function per_days_diff($start_date, $end_date) {
$per_days = 0;
$noOfWeek = 0;
$noOfWeekEnd = 0;
$highSeason=array("7", "8");
$current_date = strtotime($start_date);
$current_date += (24 * 3600);
$end_date = strtotime($end_date);
$seassion = (in_array(date('m', $current_date), $highSeason))?"2":"1";
$noOfdays = array('');
while ($current_date <= $end_date) {
if ($current_date <= $end_date) {
$date = date('N', $current_date);
array_push($noOfdays,$date);
$current_date = strtotime('+1 day', $current_date);
}
}
$finalDays = array_shift($noOfdays);
//print_r($noOfdays);
$weekFirst = array("week"=>array(),"weekEnd"=>array());
for($i = 0; $i < count($noOfdays); $i++)
{
if ($noOfdays[$i] == 1)
{
//echo "This is week";
//echo "<br/>";
if($noOfdays[$i+6]==7)
{
$noOfWeek++;
$i=$i+6;
}
else
{
$per_days++;
}
//array_push($weekFirst["week"],$day);
}
else if($noOfdays[$i]==5)
{
//echo "This is weekend";
//echo "<br/>";
if($noOfdays[$i+2] ==7)
{
$noOfWeekEnd++;
$i = $i+2;
}
else
{
$per_days++;
}
//echo "After weekend value:- ".$i;
//echo "<br/>";
}
else
{
$per_days++;
}
}
/*echo $noOfWeek;
echo "<br/>";
echo $noOfWeekEnd;
echo "<br/>";
print_r($per_days);
echo "<br/>";
print_r($weekFirst);
*/
$duration = array("weeks"=>$noOfWeek, "weekends"=>$noOfWeekEnd, "perDay"=>$per_days, "seassion"=>$seassion);
return $duration;
?>
Late for the answer but here are the list of things which I tried.So it will be in one place if anyone wants to try to fix the issue.
Clarifications to the preceding posts:
References are NOT a guarantee of getting a non-null pointer. (Though we often treat them as such.)
While horrifically bad code, as in take you out behind the woodshed bad code, the following will compile & run: (At least under my compiler.)
bool test( int & a)
{
return (&a) == (int *) NULL;
}
int
main()
{
int * i = (int *)NULL;
cout << ( test(*i) ) << endl;
};
The real issue I have with references lies with other programmers, henceforth termed IDIOTS, who allocate in the constructor, deallocate in the destructor, and fail to supply a copy constructor or operator=().
Suddenly there's a world of difference between foo(BAR bar) and foo(BAR & bar). (Automatic bitwise copy operation gets invoked. Deallocation in destructor gets invoked twice.)
Thankfully modern compilers will pick up this double-deallocation of the same pointer. 15 years ago, they didn't. (Under gcc/g++, use setenv MALLOC_CHECK_ 0 to revisit the old ways.) Resulting, under DEC UNIX, in the same memory being allocated to two different objects. Lots of debugging fun there...
More practically:
You need to put that code into the constructor of your class:
private Reminders reminder = new Reminders();
private dynamic defaultReminder;
public YourClass()
{
defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}
The reason is that you can't use one instance variable to initialize another one using a field initializer.
os.path.getsize(path)
Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.
You want to use the NSDate compare:, laterDate:, earlierDate:, or isEqualToDate: methods. Using the < and > operators in this situation is comparing the pointers, not the dates
In my case, the VS debugger was attached to the w3wp process. After detaching the debugger, I was able to restart the Application Pool