You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
Louis' answer is great, but I thought I would try to sum it up succinctly:
The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".
An example statement that uses a sub-select :
select * into MyNewTable
from
(
select
*
from
[SomeOtherTablename]
where
EventStartDatetime >= '01/JAN/2018'
)
) mysourcedata
;
note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.
The database should reply with a message like: (9999 row(s) affected)
Clean project,Clean build folder,Restart Xcode. i just remove path at project goto > Build Settings > Search the keyword. Swift Compiler - General -> Objective-C Bridging header worked for me.
If you are just looping through 10k rows in column A, then dump the row into a variant array and then loop through that.
You can then either add the elements to a new array (while adding rows when needed) and using Transpose() to put the array onto your range in one move, or you can use your iterator variable to track which row you are on and add rows that way.
Dim i As Long
Dim varray As Variant
varray = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value
For i = 1 To UBound(varray, 1)
' do stuff to varray(i, 1)
Next
Here is an example of how you could add rows after evaluating each cell. This example just inserts a row after every row that has the word "foo" in column A. Not that the "+2" is added to the variable i during the insert since we are starting on A2. It would be +1 if we were starting our array with A1.
Sub test()
Dim varray As Variant
Dim i As Long
varray = Range("A2:A10").Value
'must step back or it'll be infinite loop
For i = UBound(varray, 1) To LBound(varray, 1) Step -1
'do your logic and evaluation here
If varray(i, 1) = "foo" Then
'not how to offset the i variable
Range("A" & i + 2).EntireRow.Insert
End If
Next
End Sub
This is probably not the best answer, but there is one more creative solution to this. As pointed out by koala_dev the column offsetting works only for even column sizes. However, by nesting rows you can achieve centering uneven columns as well.
To stick with the original question where you want to center a column of 1 inside a grid of 12.
For example:
<div class="container">
<div class="row">
<div class="col-md-offset-5 col-md-2">
<div class="row">
<div class="col-md-offset-3 col-md-6">
centered column with that has an "original width" of 1 col
</div>
</div>
</div>
</div>
</div>
See this fiddle, please note that you have to increase the size of the output window in order too see the result, otherwise the columns will wrap.
DECLARE @String NVARCHAR(MAX);
USE Databse Name;
SELECT @String
=
(
SELECT 'ALTER INDEX [' + dbindexes.[name] + '] ON [' + db.name + '].[' + dbschemas.[name] + '].[' + dbtables.[name]
+ '] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE);' + CHAR(10) AS [text()]
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables
ON dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas
ON dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes
ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
INNER JOIN sys.databases AS db
ON db.database_id = indexstats.database_id
WHERE dbindexes.name IS NOT NULL
AND indexstats.database_id = DB_ID()
AND indexstats.avg_fragmentation_in_percent >= 10
ORDER BY indexstats.page_count DESC
FOR XML PATH('')
);
EXEC (@String);
Before proceeding with this post, it is important to understand the difference between NaN and None. One is a float type, the other is an object type. Pandas is better suited to working with scalar types as many methods on these types can be vectorised. Pandas does try to handle None and NaN consistently, but NumPy cannot.
My suggestion (and Andy's) is to stick with NaN.
But to answer your question...
na_values=['-']
argument with read_csv
If you loaded this data from CSV/Excel, I have good news for you. You can quash this at the root during data loading instead of having to write a fix with code as a subsequent step.
Most of the pd.read_*
functions (such as read_csv
and read_excel
) accept a na_values
attribute.
file.csv
A,B
-,1
3,-
2,-
5,3
1,-2
-5,4
-1,-1
-,0
9,0
Now, to convert the -
characters into NaNs, do,
import pandas as pd
df = pd.read_csv('file.csv', na_values=['-'])
df
A B
0 NaN 1.0
1 3.0 NaN
2 2.0 NaN
3 5.0 3.0
4 1.0 -2.0
5 -5.0 4.0
6 -1.0 -1.0
7 NaN 0.0
8 9.0 0.0
And similar for other functions/file formats.
P.S.: On v0.24+, you can preserve integer type even if your column has NaNs (yes, talk about having the cake and eating it too). You can specify dtype='Int32'
df = pd.read_csv('file.csv', na_values=['-'], dtype='Int32')
df
A B
0 NaN 1
1 3 NaN
2 2 NaN
3 5 3
4 1 -2
5 -5 4
6 -1 -1
7 NaN 0
8 9 0
df.dtypes
A Int32
B Int32
dtype: object
The dtype is not a conventional int type... but rather, a Nullable Integer Type. There are other options.
pd.to_numeric
with errors='coerce
If you're dealing with numeric data, a faster solution is to use pd.to_numeric
with the errors='coerce'
argument, which coerces invalid values (values that cannot be cast to numeric) to NaN.
pd.to_numeric(df['A'], errors='coerce')
0 NaN
1 3.0
2 2.0
3 5.0
4 1.0
5 -5.0
6 -1.0
7 NaN
8 9.0
Name: A, dtype: float64
To retain (nullable) integer dtype, use
pd.to_numeric(df['A'], errors='coerce').astype('Int32')
0 NaN
1 3
2 2
3 5
4 1
5 -5
6 -1
7 NaN
8 9
Name: A, dtype: Int32
To coerce multiple columns, use apply
:
df[['A', 'B']].apply(pd.to_numeric, errors='coerce').astype('Int32')
A B
0 NaN 1
1 3 NaN
2 2 NaN
3 5 3
4 1 -2
5 -5 4
6 -1 -1
7 NaN 0
8 9 0
...and assign the result back after.
More information can be found in this answer.
This solution implements a generator, to avoid holding all the permutations on memory:
def permutations (orig_list):
if not isinstance(orig_list, list):
orig_list = list(orig_list)
yield orig_list
if len(orig_list) == 1:
return
for n in sorted(orig_list):
new_list = orig_list[:]
pos = new_list.index(n)
del(new_list[pos])
new_list.insert(0, n)
for resto in permutations(new_list[1:]):
if new_list[:1] + resto <> orig_list:
yield new_list[:1] + resto
What you need is to set this.text
to an empty string in your submitForm
function:
submitForm(e){
this.todos.push(
{
text: this.text,
completed: false
}
);
this.text = "";
// To prevent the form from submitting
e.preventDefault();
}
Remember that binding works both ways: The (input) view can update the (string) model, or the model can update the view.
Some other cases where setTimeout is useful:
You want to break a long-running loop or calculation into smaller components so that the browser doesn't appear to 'freeze' or say "Script on page is busy".
You want to disable a form submit button when clicked, but if you disable the button in the onClick handler the form will not be submitted. setTimeout with a time of zero does the trick, allowing the event to end, the form to begin submitting, then your button can be disabled.
With the images located in /screen-shots
directory. The outer <div>
allows the images to be positioned. Padding is achieved using <img width="desired-padding" height="0">
.
<div align="center">
<img width="45%" src="screen-shots/about.PNG" alt="About screen" title="About screen"</img>
<img height="0" width="8px">
<img width="45%" src="screen-shots/list.PNG" alt="List screen" title="List screen"></img>
</div>
The nohup command is a signal masking utility and catches the hangup signal. Where as ampersand doesn’t catch the hang up signals. The shell will terminate the sub command with the hang up signal when running a command using & and exiting the shell. This can be prevented by using nohup, as it catches the signal. Nohup command accept hang up signal which can be sent to a process by the kernel and block them. Nohup command is helpful in when a user wants to start long running application log out or close the window in which the process was initiated. Either of these actions normally prompts the kernel to hang up on the application, but a nohup wrapper will allow the process to continue. Using the ampersand will run the command in a child process and this child of the current bash session. When you exit the session, all of the child processes of that process will be killed. The ampersand relates to job control for the active shell. This is useful for running a process in a session in the background.
The replace
method is what you're looking for.
For example:
String replacedString = someString.replace("HelloBrother", "Brother");
Regarding to Peter's answer and Micheal's addition to it you may find How Do I Automatically Generate A .jar File In An Eclipse Java Project useful. Because even you have "*.jardesc" file on your project you have to run it manually. It may cools down your "eclipse click hassle" a bit.
In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.
Just refresh the port in your ajax url string to the appropriate one.
conn = new WebSocket('ws://localhost:3030'); //should solve the issue
Have you tried using Timestamp.valueOf(String)
? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons:
import java.sql.*;
public class Test {
public static void main(String[] args) {
String text = "2011-10-02 18:48:05.123456";
Timestamp ts = Timestamp.valueOf(text);
System.out.println(ts.getNanos());
}
}
Assuming you've already validated the string length, this will convert to the right format:
static String convertSeparators(String input) {
char[] chars = input.toCharArray();
chars[10] = ' ';
chars[13] = ':';
chars[16] = ':';
return new String(chars);
}
Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat
(I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt
. You can then combine the values pretty easily:
Date date = parseDateFromFirstPart();
int micros = parseJustLastThreeDigits();
Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(ts.getNanos() + micros * 1000);
"How to attach url link to an image?"
You do it like this:
<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>
See it in action.
All the above answers are valid, however, there are some cases that the String Literal Type is part of another complex type. Consider the following example:
// in foo.ts
export type ToolbarTheme = {
size: 'large' | 'small',
};
// in bar.ts
import { ToolbarTheme } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
// Here you will get the following error:
// Type 'string' is not assignable to type '"small" | "large"'.ts(2322)
['large', 'small'].forEach(size => (
useToolbarTheme({ size })
));
You have multiple solutions to fix this. Each solution is valid and has its own use cases.
1) The first solution is to define a type for the size and export it from the foo.ts. This is good if when you need to work with the size parameter by its own. For example, you have a function that accepts or returns a parameter of type size and you want to type it.
// in foo.ts
export type ToolbarThemeSize = 'large' | 'small';
export type ToolbarTheme = {
size: ToolbarThemeSize
};
// in bar.ts
import { ToolbarTheme, ToolbarThemeSize } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
function getToolbarSize(): ToolbarThemeSize {/* ... */}
['large', 'small'].forEach(size => (
useToolbarTheme({ size: size as ToolbarThemeSize })
));
2) The second option is to just cast it to the type ToolbarTheme. In this case, you don't need to expose the internal of ToolbarTheme if you don't need.
// in foo.ts
export type ToolbarTheme = {
size: 'large' | 'small'
};
// in bar.ts
import { ToolbarTheme } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
['large', 'small'].forEach(size => (
useToolbarTheme({ size } as ToolbarTheme)
));
getID3 supports video formats. See: http://getid3.sourceforge.net/
Edit: So, in code format, that'd be like:
include_once('pathto/getid3.php');
$getID3 = new getID3;
$file = $getID3->analyze($filename);
echo("Duration: ".$file['playtime_string'].
" / Dimensions: ".$file['video']['resolution_x']." wide by ".$file['video']['resolution_y']." tall".
" / Filesize: ".$file['filesize']." bytes<br />");
Note: You must include the getID3 classes before this will work! See the above link.
Edit: If you have the ability to modify the PHP installation on your server, a PHP extension for this purpose is ffmpeg-php. See: http://ffmpeg-php.sourceforge.net/
Using an apostrophe ’
(Unicode: \u2019
) instead of a single quote '
fixed the issue without doubling the \'
.
Simple, right click on your project in Android Studio, then click on the Optimize Imports that should work.
To do same thing which I described above, you can do same just pressing Ctrl+Alt+O, it will optimize imports of your current file and your entire project depends on your selection in a dialog.
Try this:
counter=0
while true; do
if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
echo "Files Present" | mailx -s "File Present" -r [email protected] [email protected]
break
elif [[ "$counter" -gt 20 ]]; then
echo "Counter limit reached, exit script."
exit 1
else
let counter++
echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected]
sleep 1800
fi
done
Explanation
break
- if files are present, it will break and allow the script to process the files.[[ "$counter" -gt 20 ]]
- if the counter variable is greater than 20, the script will exit.let counter++
- increments the counter by 1 at each pass.I got another one that may be useful to someone. Was receiving the same error message after upgrading from PHP 5.6 => 7.0. We had changed the PHP upload settings, and forgot to change once copied over. Even though i wasn't uploading images at the time, Silverstripe (our CMS) was refusing to save and throwing that error. Increased the image upload size and it worked straight away.
Ruby String provides the codepoints
method after 1.9.1.
str = 'hello world'
str.codepoints.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
str = "????"
str.codepoints.to_a
=> [20320, 22909, 19990, 30028]
The alternative, if you don't want to install libjpeg:
CFLAGS="--disable-jpeg" pip install pillow
From https://pillow.readthedocs.io/en/3.0.0/installation.html#external-libraries
I prefer to open all links inside the standalone web app mode except ones that have target="_blank". Using jQuery, of course.
$(document).on('click', 'a', function(e) {
if ($(this).attr('target') !== '_blank') {
e.preventDefault();
window.location = $(this).attr('href');
}
});
You could do this using SUMIF
. This allows you to SUM a value in a cell IF a value in another cell meets the specified criteria. Here's an example:
- A B
1 100 YES
2 100 YES
3 100 NO
Using the formula: =SUMIF(B1:B3, "YES", A1:A3)
, you will get the result of 200
.
Here's a screenshot of a working example I just did in Excel:
In my case it was OneTab chrome extension.
I had to transfer texts from an Excel file to an xliff file. We had some texts that were originally in uppercase but those translators didn't use uppercase so I used notepad++ as intermediate to do the conversion.
Since I had the mouse in one hand (to mark in Excel and activate the different windows) I disliked the predefined shortcut (Ctrl+Shift+U) as "U" is too far away for my left hand. I first switched it to Ctrl+Shift+X which worked.
Then I realized, that you can create macros easily, so I recorded one doing:
That macro got assigned that very shortcut (Ctrl+Shift+X) and made my life easy :)
You can use this:
var token = "SOME_TOKEN";
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
jqXHR.setRequestHeader('X-CSRF-Token', token);
});
From documentation:
jQuery.ajaxPrefilter( [dataTypes ], handler(options, originalOptions, jqXHR) )
Description: Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().
I had a similar issues fresh install and same error surprising. Finally I figured out it was a problem with browser cookies...
Try cleaning your browser cookies and see it helps to resolve this issue, before even trying any configuration changes.
Try using XAMPP Control panel "Admin" button instead of usual http://localhost
or http://localhost/phpmyadmin
Try direct link: http://localhost/phpmyadmin/main.php
or http://127.0.0.1/phpmyadmin/main.php
Finally try this: http://localhost/phpmyadmin/index.php?db=phpmyadmin&server=1&target=db_structure.php
Somehow if you have old installation and you upgraded to new version it keeps track of your old settings through cookies.
If this solution helped let me know.
You can see all available keybindings on the official documentation.
Here's the relevant bit for osx:
Key Command
?K ?C Add Line Comment
?K ?U Remove Line Comment
?/ Toggle Line Comment
??A Toggle Block Comment
You will need to select the lines you want to comment first, then execute above shortcut, i.e. ?/
on osx Ctrl/
on Windows.
Your understanding is correct, an artifact in the Jenkins sense is the result of a build - the intended output of the build process.
A common convention is to put the result of a build into a build
, target
or bin
directory.
The Jenkins archiver can use globs (target/*.jar
) to easily pick up the right file even if you have a unique name per build.
I know I'm late to the party but I thought I'd add what I ended up using for this - which is to simply check if the file upload input does not contain a truthy value with the not operator & JQuery like so:
if (!$('#videoUploadFile').val()) {
alert('Please Upload File');
}
Note that if this is in a form, you may also want to wrap it with the following handler to prevent the form from submitting:
$(document).on("click", ":submit", function (e) {
if (!$('#videoUploadFile').val()) {
e.preventDefault();
alert('Please Upload File');
}
}
In English:
It's a
List
of some type that extends the classHasWord
, includingHasWord
In general the ?
in generics means any class. And the extends SomeClass
specifies that that object must extend SomeClass
(or be that class).
Use array or common container for objects only if they have default and copy constructors.
Store pointers otherwise (or smart pointers, but may meet some issues in this case).
PS: Always define own default and copy constructors otherwise auto-generated will be used
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.each { |x| puts x if x % 2 == 0 }
2 4 6 8 10
This is not like Collections.sort()
where the parameter reference gets sorted. In this case you just get a sorted stream that you need to collect and assign to another variable eventually:
List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
compareTo(o2.getItem().getValue())).
collect(Collectors.toList());
You've just missed to assign the result
REST
I understand the main idea of REST is extremely simple. We have used web browsers for years and we have seen how easy, flexible, performing, etc web sites are. HTML sites use hyperlinks and forms as the primary means of user interaction. Their main goal is to allow us, clients, to know only those links that we can use in the current state. And REST simply says 'why not use the same principles to drive computer rather than human clients through our application?' Combine this with the power of the WWW infrastructure and you'll get a killer tool for building great distributed applications.
Another possible explanation is for mathematically thinking people. Each application is basically a state machine with business logic actions being state transitions. The idea of REST is to map each transition onto some request to a resource and provide clients with links representing transitions available in the current state. Thus it models the state machine via representations and links. This is why it's called REpresentational State Transfer.
It's quite surprising that all answers seem to focus either on message format, or on HTTP verbs usage. In fact, the message format doesn't matter at all, REST can use any one provided that the service developer documents it. HTTP verbs only make a service a CRUD service, but not yet RESTful. What really turns a service into a REST service are hyperlinks (aka hypermedia controls) embedded into server responses together with data, and their amount must be enough for any client to choose the next action from those links.
Unfortunately, it's rather difficult to find correct info on REST on the Web, except for the Roy Fielding's thesis. (He's the one who derived REST). I would recommend the 'REST in Practice' book as it gives a comprehensive step-by-step tutorial on how to evolve from SOAP to REST.
SOAP
This is one of the possible forms of RPC (remote procedure call) architecture style. In essence, it's just a technology that allows clients call methods of server via service boundaries (network, processes, etc) as if they were calling local methods. Of course, it actually differs from calling local methods in speed, reliability and so on, but the idea is that simple.
Compared
The details like transport protocols, message formats, xsd, wsdl, etc. don't matter when comparing any form of RPC to REST. The main difference is that an RPC service reinvents bicycle by designing it's own application protocol in the RPC API with the semantics that only it knows. Therefore, all clients have to understand this protocol prior to using the service, and no generic infrastructure like caches can be built because of proprietary semantics of all requests. Furthermore, RPC APIs do not suggest what actions are allowed in the current state, this has to be derived from additional documentation. REST on the other hand implies using uniform interfaces to allow various clients to have some understanding of API semantics, and hypermedia controls (links) to highlight available options in each state. Thus, it allows for caching responses to scale services and making correct API usage easily discoverable without additional documentation.
In a way, SOAP (as any other RPC) is an attempt to tunnel through a service boundary treating the connecting media as a black box capable of transmitting messages only. REST is a decision to acknowledge that the Web is a huge distributed information system, to accept the world as is and learn to master it instead of fighting against it.
SOAP seems to be great for internal network APIs, when you control both the server and the clients, and while the interactions are not too complex. It's more natural for developers to use it. However, for a public API that is used by many independent parties, is complex and big, REST should fit better. But this last comparison is very fuzzy.
Update
My experience has unexpectedly shown REST development to be more difficult than SOAP. At least for .NET. While there are great frameworks like ASP.NET Web API, there's no tooling that would automatically generate client-side proxy. Nothing like 'Add Web Service Reference' or 'Add WCF Service Reference'. One has to write all serialization and service querying code by hand. And man, that's lots of boilerplate code. I think REST development needs something similar to WSDL and tooling implementation for each development platform. In fact, there seems to be a good ground: WADL or WSDL 2.0, but neither of the standards seems to be well-supported.
Update (Jan 2016)
Turns out there is now a wide variety of tools for REST API definition. My personal preference is currently RAML.
How Web Services work
Well, this is a too broad question, because it depends on the architecture and technology used in the specific web service. But in general, a web service is simply some application in the Web that can accept requests from clients and return responses. It's exposed to the Web, thus it's a web service, and it's typically available 24/7, that's why it's a service. Of course, it solves some problem (otherwise why would someone ever use a web service) for its clients.
For me it was under:
/Users/{your username}/Library/Developer/Xcode/DerivedData...
and NOT in /Library/Developer/Xcode/DerivedData...
Run command:
Get-PsDrive -PsProvider FileSystem
For more info see:
You can add Row in a single line
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
The modern solution that works in node and across over 90% of all browsers (except IE and Opera Mini) is to use Number.isInteger followed by a simple positive check.
Number.isInteger(x) && x > 0
This was finalized in ECMAScript 2015.
function isPositiveInteger(x) {
return Number.isInteger(x) && x > 0
}
The Polyfil is:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value;
};
If you need to support input that might be in string or number form then you can use this function I wrote a large test suite against after all the existing answers (2/1/2018) failed on some form of input.
function isPositiveInteger(v) {
var i;
return v && (i = parseInt(v)) && i > 0 && (i === v || ''+i === v);
}
It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.
Map:
class Map<T> {
private items: { [key: string]: T };
constructor() {
this.items = {};
}
add(key: string, value: T): void {
this.items[key] = value;
}
has(key: string): boolean {
return key in this.items;
}
get(key: string): T {
return this.items[key];
}
}
List:
class List<T> {
private items: Array<T>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(value);
}
get(index: number): T {
return this.items[index];
}
}
I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...
As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:
class ListItem<T> {
private list: List<T>;
private index: number;
public value: T;
constructor(list: List<T>, value: T, index: number) {
this.list = list;
this.index = index;
this.value = value;
}
prev(): ListItem<T> {
return this.list.get(this.index - 1);
}
next(): ListItem<T> {
return this.list.get(this.index + 1);
}
}
class List<T> {
private items: Array<ListItem<T>>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(new ListItem<T>(this, value, this.size()));
}
get(index: number): ListItem<T> {
return this.items[index];
}
}
Here too you're looking at untested code..
Hope this helps.
Javascript has a native Map object so there's no need to create your own:
let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1
I had met a similar problem, after i add a scope property of servlet dependency in pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Then it was ok . maybe that will help you.
The simple reason why it doesn't work is not because of the ;
indicating the end of the anonymous function. It is because without the ()
on the end of a function call, it is not a function call. That is,
function help() {return true;}
If you call result = help();
this is a call to a function and will return true.
If you call result = help;
this is not a call. It is an assignment where help is treated like data to be assigned to result.
What you did was declaring/instantiating an anonymous function by adding the semicolon,
(function (msg) { /* Code here */ });
and then tried to call it in another statement by using just parentheses... Obviously because the function has no name, but this will not work:
('SO');
The interpreter sees the parentheses on the second line as a new instruction/statement, and thus it does not work, even if you did it like this:
(function (msg){/*code here*/});('SO');
It still doesn't work, but it works when you remove the semicolon because the interpreter ignores white spaces and carriages and sees the complete code as one statement.
(function (msg){/*code here*/}) // This space is ignored by the interpreter
('SO');
Conclusion: a function call is not a function call without the ()
on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".
If your variable is not declared nor defined:
if ( typeof query !== 'undefined' ) { ... }
If your variable is declared but undefined. (assuming the case here is that the variable might not be defined but it can be any other falsy value like false
or ""
)
if ( query ) { ... }
If your variable is declared but can be undefined
or null
:
if ( query != null ) { ... } // undefined == null
Well I guess I have found the solution for my own question, here is how I did it:
Eventhough I was being able to successfully run the program using normal python command as well as successfully run pyinstaller and be able to execute the app "new_app.exe" using the command line mentioned in the question which in both cases display the GUI with no problem at all. However, only when I click the application it won't allow to display the GUI and no error is generated.
So, What I did is I added an extra parameter --debug in the pyinstaller command and removing the --windowed parameter so that I can see what is actually happening when the app is clicked and I found out there was an error which made a lot of sense when I trace it, it basically complained that "some_image.jpg" no such file or directory.
The reason why it complains and didn't complain when I ran the script from the first place or even using the command line "./" is because the file image existed in the same path as the script located but when pyinstaller created "dist" directory which has the app product it makes a perfect sense that the image file is not there and so I basically moved it to that dist directory where the clickable app is there!
If you absolutely want to combine integers and NaNs in a column, you can use the 'object' data type:
df['col'] = (
df['col'].fillna(0)
.astype(int)
.astype(object)
.where(df['col'].notnull())
)
This will replace NaNs with an integer (doesn't matter which), convert to int, convert to object and finally reinsert NaNs.
If your goal is to set a static string in the toolbar, the easiest way to do it is to simply set the activity label in AndroidManifest.xml:
<activity android:name=".xxxxActivity"
android:label="@string/string_id" />
The toolbar will get this string without any code. (works for me with v27 libraries.)
Please Check URL you have pasted and It takes additional h after clone.
So either you have paste full git clone http://<URL>.git
or just remove additional letter before git repository URL.
Working JSFIDDLE
If your form is like
<form action="" method="get" id="hidden-element-test">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
<br><br>
<button id="add-input">Add hidden input</button>
<button id="add-textarea">Add hidden textarea</button>
You can add hidden input and textarea to form like this
$(document).ready(function(){
$("#add-input").on('click', function(){
$('#hidden-element-test').prepend('<input type="hidden" name="ipaddress" value="192.168.1.201" />');
alert('Hideen Input Added.');
});
$("#add-textarea").on('click', function(){
$('#hidden-element-test').prepend('<textarea name="instructions" style="display:none;">this is a test textarea</textarea>');
alert('Hideen Textarea Added.');
});
});
Check working jsfiddle here
This is what i did and It worked...
C#
ViewBag.DisplaylList = listData;
javascript
var dispalyList= @Html.Raw(Json.Encode(this.ViewBag.DisplaylList));
for(var i=0;i<dispalyList.length; i++){
var row = dispalyList[i];
..............
..............
}
what about Destructuring_assignment
var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]
which can also be extended to
[src order elements] => [dest order elements]
Add: Architectures: $(ARCHS_STANDARD_INCLUDING_64_BIT)
Valid architectures: arm64 armv7 armv7s
if ($string =~ m/something/) {
# Do work
}
Where something
is a regular expression.
Simply do this
var key = "keyOne";
var obj = {};
obj[key] = someValue;
$(document).ready(function(){
$('#shares').val('');
});
We use a lot of Action delegate functionality in tests. When we need to build some default object and later need to modify it. I made little example. To build default person (John Doe) object we use BuildPerson()
function. Later we add Jane Doe too, but we modify her birthdate and name and height.
public class Program
{
public static void Main(string[] args)
{
var person1 = BuildPerson();
Console.WriteLine(person1.Firstname);
Console.WriteLine(person1.Lastname);
Console.WriteLine(person1.BirthDate);
Console.WriteLine(person1.Height);
var person2 = BuildPerson(p =>
{
p.Firstname = "Jane";
p.BirthDate = DateTime.Today;
p.Height = 1.76;
});
Console.WriteLine(person2.Firstname);
Console.WriteLine(person2.Lastname);
Console.WriteLine(person2.BirthDate);
Console.WriteLine(person2.Height);
Console.Read();
}
public static Person BuildPerson(Action<Person> overrideAction = null)
{
var person = new Person()
{
Firstname = "John",
Lastname = "Doe",
BirthDate = new DateTime(2012, 2, 2)
};
if (overrideAction != null)
overrideAction(person);
return person;
}
}
public class Person
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public DateTime BirthDate { get; set; }
public double Height { get; set; }
}
If your are working in a web service and the v2.0 assembly is a dependency that has been loaded by WcfSvcHost.exe then you must include
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" />
</startup>
in ..\Microsoft Visual Studio 10.0\Common7\IDE\ WcfSvcHost.exe.config file
This way, Visual Studio will be able to send the right information through the loader at runtime.
numpy has a great tool for this task ("numpy.reshape") link to reshape documentation
a = [[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]]
`numpy.reshape(a,(3,3))`
you can also use the "-1" trick
`a = a.reshape(-1,3)`
the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3
so yes.. this would also work:
a = a.reshape(3,-1)
and this:
a = a.reshape(-1,2)
would do nothing
and this:
a = a.reshape(-1,9)
would change the shape to (2,9)
All error codes are on "CFNetwork Errors Codes References" on the documentation (link)
A small extraction for CFURL and CFURLConnection Errors:
kCFURLErrorUnknown = -998,
kCFURLErrorCancelled = -999,
kCFURLErrorBadURL = -1000,
kCFURLErrorTimedOut = -1001,
kCFURLErrorUnsupportedURL = -1002,
kCFURLErrorCannotFindHost = -1003,
kCFURLErrorCannotConnectToHost = -1004,
kCFURLErrorNetworkConnectionLost = -1005,
kCFURLErrorDNSLookupFailed = -1006,
kCFURLErrorHTTPTooManyRedirects = -1007,
kCFURLErrorResourceUnavailable = -1008,
kCFURLErrorNotConnectedToInternet = -1009,
kCFURLErrorRedirectToNonExistentLocation = -1010,
kCFURLErrorBadServerResponse = -1011,
kCFURLErrorUserCancelledAuthentication = -1012,
kCFURLErrorUserAuthenticationRequired = -1013,
kCFURLErrorZeroByteResource = -1014,
kCFURLErrorCannotDecodeRawData = -1015,
kCFURLErrorCannotDecodeContentData = -1016,
kCFURLErrorCannotParseResponse = -1017,
kCFURLErrorInternationalRoamingOff = -1018,
kCFURLErrorCallIsActive = -1019,
kCFURLErrorDataNotAllowed = -1020,
kCFURLErrorRequestBodyStreamExhausted = -1021,
kCFURLErrorFileDoesNotExist = -1100,
kCFURLErrorFileIsDirectory = -1101,
kCFURLErrorNoPermissionsToReadFile = -1102,
kCFURLErrorDataLengthExceedsMaximum = -1103,
Try this one. Here "LoginViewController" is the storyboardID specified in storyboard.
See below
let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as LoginViewController
self.navigationController?.pushViewController(secondViewController, animated: true)
start=$(date +%Y%m%d%H%M%S);
for x in {1..5};
do echo $x;
sleep 1; done;
end=$(date +%Y%m%d%H%M%S);
elapsed=$(($end-$start));
ftime=$(for((i=1;i<=$((${#end}-${#elapsed}));i++));
do echo -n "-";
done;
echo ${elapsed});
echo -e "Start : ${start}\nStop : ${end}\nElapsed: ${ftime}"
Start : 20171108005304
Stop : 20171108005310
Elapsed: -------------6
I'm unsure of the context on why this was needed, so this may not return enough information for you but this is what I was able to do:
if(typeof(ModelName).GetProperty("Name of Property") != null)
{
//whatevver you were wanting to do.
}
In my case I'm running through properties from a form submission and also have default values to use if the entry is left blank - so I needed to know if the there was a value to use - I prefixed all my default values in the model with Default so all I needed to do is check if there was a property that started with that.
Recently I used an AS3 engine: PushButton (now is dead, but it's still functional and you could use something else) to do this job. To make it works with Android and iOS, the project was compiled in AIR for both platforms and everything worked with no performance damage. Since Flash Builder is kinda expensive ($249), you could use FlashDevelop (there is some tutorials to compile in AIR with it).
Flash could be an option since is very easy to learn.
This worked for me when you have to center align image and your parent div to image has covers whole screen. i.e. height:100% and width:100%
#img{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
You are posting the data, so it should be $_POST. But 'name' is not the best name to use.
name = "name"
will only cause confusion IMO.
I have just experienced the same error, in my case it was caused by the second parameter in angular.module
being missing- hopefully this may help someone with the same issue.
angular.module('MyApp');
angular.module('MyApp', []);
It depends on if you mean '\n' (linefeed) or '\r\n' (carriage return + linefeed). The former is not the Windows default and will not show properly in some text editors (like Notepad).
You can do
sb.Append(Environment.NewLine);
sb.Append("\t");
or
sb.Append("\r\n\t");
Here are three Observables A
, B
, and C
with marble diagrams to explore the difference between first
, take
, and single
operators:
* Legend:
--o--
value
----!
error
----|
completion
Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .
Already having all the answers, I wanted to add a more visual explanation
Hope it helps someone
The accepted answer doesn't involve the annotations usage since Spring introduced support for various annotations for configuration.
There the another way to wire the classes up alongside using a XML file: the annotations. Let's use the example from the accepted answer and register the bean directly on the class using one of the annotations @Component
, @Service
, @Repository
or @Configuration
:
@Component
public class UserListerDB implements UserLister {
public List<User> getUsers() {
// DB access code here
}
}
This way when the view is created it magically will have a UserLister ready to work.
The above statement is valid with a little bonus of no need of any XML file usage and wiring with another annotation @Autowired
that finds a relevant implementation and inject it in.
@Autowired
private UserLister userLister;
Use the @Bean
annotation on a method used to get the bean implementation to inject.
I need to do something like this I ended up going with the following solution.
I have a specific website URL that will open a page with two buttons
1) Button One go to website
2) Button Two go to application (iphone / android phone / tablet) you can fall back to a default location from here if the app is not installed (like another url or an app store)
3) cookie to remember users choice
<head>
<title>Mobile Router Example </title>
<script type="text/javascript">
function set_cookie(name,value)
{
// js code to write cookie
}
function read_cookie(name) {
// jsCode to read cookie
}
function goToApp(appLocation) {
setTimeout(function() {
window.location = appLocation;
//this is a fallback if the app is not installed. Could direct to an app store or a website telling user how to get app
}, 25);
window.location = "custom-uri://AppShouldListenForThis";
}
function goToWeb(webLocation) {
window.location = webLocation;
}
if (readCookie('appLinkIgnoreWeb') == 'true' ) {
goToWeb('http://somewebsite');
}
else if (readCookie('appLinkIgnoreApp') == 'true') {
goToApp('http://fallbackLocation');
}
</script>
</head>
<body>
<div class="iphone_table_padding">
<table border="0" cellspacing="0" cellpadding="0" style="width:100%;">
<tr>
<td class="iphone_table_leftRight"> </td>
<td>
<!-- INTRO -->
<span class="iphone_copy_intro">Check out our new app or go to website</span>
</td>
<td class="iphone_table_leftRight"> </td>
</tr>
<tr>
<td class="iphone_table_leftRight"> </td>
<td>
<div class="iphone_btn_padding">
<!-- GET IPHONE APP BTN -->
<table border="0" cellspacing="0" cellpadding="0" class="iphone_btn" onclick="set_cookie('appLinkIgnoreApp',document.getElementById('chkDontShow').checked);goToApp('http://getappfallback')">
<tr>
<td class="iphone_btn_on_left"> </td>
<td class="iphone_btn_on_mid">
<span class="iphone_copy_btn">
Get The Mobile Applications
</span>
</td>
<td class="iphone_btn_on_right"> </td>
</tr>
</table>
</div>
</td>
<td class="iphone_table_leftRight"> </td>
</tr>
<tr>
<td class="iphone_table_leftRight"> </td>
<td>
<div class="iphone_btn_padding">
<table border="0" cellspacing="0" cellpadding="0" class="iphone_btn" onclick="set_cookie('appLinkIgnoreWeb',document.getElementById('chkDontShow').checked);goToWeb('http://www.website.com')">
<tr>
<td class="iphone_btn_left"> </td>
<td class="iphone_btn_mid">
<span class="iphone_copy_btn">
Visit Website.com
</span>
</td>
<td class="iphone_btn_right"> </td>
</tr>
</table>
</div>
</td>
<td class="iphone_table_leftRight"> </td>
</tr>
<tr>
<td class="iphone_table_leftRight"> </td>
<td>
<div class="iphone_chk_padding">
<!-- CHECK BOX -->
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input type="checkbox" id="chkDontShow" /></td>
<td>
<span class="iphone_copy_chk">
<label for="chkDontShow"> Don’t show this screen again.</label>
</span>
</td>
</tr>
</table>
</div>
</td>
<td class="iphone_table_leftRight"> </td>
</tr>
</table>
</div>
</body>
</html>
You could also setup your executable as an external tool, and mark the tool for Use output window. That way the output of the tool will be visible within Visual Studio itself, not a separate window.
status tell you what to do.
Unmerged paths:
(use "git reset HEAD <file>..." to unstage)
(use "git add <file>..." to mark resolution)
you probably applied a stash or something else that cause a conflict.
either add, reset, or rm.
I had the same issue, but I just wrapped the arguments like this and it works now.
$args = array();
$args['Header'] = array(
'CustomerCode' => 'dsadsad',
'Language' => 'fdsfasdf'
);
$args['RequestObject'] = $whatever;
// this was the catch, double array with "Request"
$response = $this->client->__soapCall($name, array(array( 'Request' => $args )));
Using this function:
print_r($this->client->__getLastRequest());
You can see the Request XML whether it's changing or not depending on your arguments.
Use [ trace = 1, exceptions = 0 ] in SoapClient options.
Associative array in PHP actually considered as a dictionary.
An array in PHP is actually an ordered map. A map is a type that associates values to keys. it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
An array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index.
UPDATE: 2019-12-30
It seem that this tool is no longer working!
[Request for update!]
UPDATE 2019-01-06: You can bypass X-Frame-Options
in an <iframe>
using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.
You can use it as follows:
(Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:
<script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
Include the X-Frame-Bypass JS module:
<script type="module" src="x-frame-bypass.js"></script>
Insert the X-Frame-Bypass Custom Element:
<iframe is="x-frame-bypass" src="https://example.org/"></iframe>
foreach($array as $key=>$value) {
// do stuff
}
$key is the index of each $array element
The short answer: the setting needs to be setup when the connection to the MySQL server is established. For example, if using MYSQLi / PHP, it will look something like this:
$ myConn = mysqli_init();
$ myConn->options(MYSQLI_INIT_COMMAND, 'SET SESSION group_concat_max_len = 1000000');
Therefore, if you are using a home-brewed framework, well, you need to look for the place in the code when the connection is establish and provide a sensible value.
I am still using Codeigniter 3 on 2020, so in this framework, the code to add is in the application/system/database/drivers/mysqli/mysqli_driver.php, the function is named db_connect();
public function db_connect($persistent = FALSE)
{
// Do we have a socket path?
if ($this->hostname[0] === '/')
{
$hostname = NULL;
$port = NULL;
$socket = $this->hostname;
}
else
{
$hostname = ($persistent === TRUE)
? 'p:'.$this->hostname : $this->hostname;
$port = empty($this->port) ? NULL : $this->port;
$socket = NULL;
}
$client_flags = ($this->compress === TRUE) ? MYSQLI_CLIENT_COMPRESS : 0;
$this->_mysqli = mysqli_init();
$this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
$this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION group_concat_max_len = 1000000');
...
}
Somehow all examples, while work well, are overcomplicated:
new Array()
, which is an overkill (and an overhead) for a simple associative array (AKA dictionary).new Object()
. It works fine, but why all this extra typing?This question is tagged "beginner", so let's make it simple.
The über-simple way to use a dictionary in JavaScript or "Why doesn't JavaScript have a special dictionary object?":
// Create an empty associative array (in JavaScript it is called ... Object)
var dict = {}; // Huh? {} is a shortcut for "new Object()"
// Add a key named fred with value 42
dict.fred = 42; // We can do that because "fred" is a constant
// and conforms to id rules
// Add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!"; // We use the subscript notation because
// the key is arbitrary (not id)
// Add an arbitrary dynamic key with a dynamic value
var key = ..., // Insanely complex calculations for the key
val = ...; // Insanely complex calculations for the value
dict[key] = val;
// Read value of "fred"
val = dict.fred;
// Read value of 2bob2
val = dict["2bob2"];
// Read value of our cool secret key
val = dict[key];
Now let's change values:
// Change the value of fred
dict.fred = "astra";
// The assignment creates and/or replaces key-value pairs
// Change the value of 2bob2
dict["2bob2"] = [1, 2, 3]; // Any legal value can be used
// Change value of our secret key
dict[key] = undefined;
// Contrary to popular beliefs, assigning "undefined" does not remove the key
// Go over all keys and values in our dictionary
for (key in dict) {
// A for-in loop goes over all properties, including inherited properties
// Let's use only our own properties
if (dict.hasOwnProperty(key)) {
console.log("key = " + key + ", value = " + dict[key]);
}
}
Deleting values is easy too:
// Let's delete fred
delete dict.fred;
// fred is removed, but the rest is still intact
// Let's delete 2bob2
delete dict["2bob2"];
// Let's delete our secret key
delete dict[key];
// Now dict is empty
// Let's replace it, recreating all original data
dict = {
fred: 42,
"2bob2": "twins!"
// We can't add the original secret key because it was dynamic, but
// we can only add static keys
// ...
// oh well
temp1: val
};
// Let's rename temp1 into our secret key:
if (key != "temp1") {
dict[key] = dict.temp1; // Copy the value
delete dict.temp1; // Kill the old key
} else {
// Do nothing; we are good ;-)
}
Improving upon @barry-stae and @Sandeep answers for regular users of elinks you would add the following to .bashrc:
function mdviewer() {
pandoc $* | elinks --force-html
}
Don't forget to install pandoc (and elinks).
Sometimes autocomplete on the browser still autocompletes when you just have the code in the <form>
element.
I tried putting it in the <input>
element as well and it worked better.
<form autocomplete="off"> AND <input autocomplete="off">
Support for this attribute however is ceasing, please read https://bugzilla.mozilla.org/show_bug.cgi?id=956906#c1
https://bugzilla.mozilla.org/show_bug.cgi?id=956906
Another work around that I've found is taking out placeholders inside of the input fields that suggest that it is an email, username, or phone field (ie. "Your Email", "Email", etc.")
This makes it so that browsers don't know what kind of field it is, thus doesn't try to autocomplete it.
With your example:
<input type="checkbox" id="c2" name="c2" value="DE039230952"/>
Replace $$ with document.querySelectorAll in the examples:
$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230
Use the examples directly with:
const $$ = document.querySelectorAll.bind(document);
Some additions:
$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()
public static int reverseInt(int i) {
int reservedInt = 0;
try{
String s = String.valueOf(i);
String reversed = reverseWithStringBuilder(s);
reservedInt = Integer.parseInt(reversed);
}catch (NumberFormatException e){
System.out.println("exception caught was " + e.getMessage());
}
return reservedInt;
}
public static String reverseWithStringBuilder(String str) {
System.out.println(str);
StringBuilder sb = new StringBuilder(str);
StringBuilder reversed = sb.reverse();
return reversed.toString();
}
use try-catch to see real error occurred on you
try
{
//Your insert code here
}
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
}
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
"Better" is subjective.
querySelector
is the newer feature.
getElementById
is better supported than querySelector
.
querySelector
is better supported than getElementsByClassName
.
querySelector
lets you find elements with rules that can't be expressed with getElementById
and getElementsByClassName
You need to pick the appropriate tool for any given task.
(In the above, for querySelector
read querySelector
/ querySelectorAll
).
There's a few things you can look for help solve this.
Has anything changed or been extended in the core CodeIgniter files. Check that system/core/Input.php
is an original copy and the contents of application/library
and application/core
for additional files
Do the other input methods work? What is the result of this when run beside your print_r
call?
echo $this->input->user_agent();
What data is output from print_r
? Look in application/config/config.php
for the line $config['global_xss_filtering']
. Is this set to TRUE
or FALSE
? If TRUE
maybe the cross site scripting filter has a problem with the data you're posting (this is unlikely I think)
Validate against online schemas
Source xmlFile = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("your.xml"));
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(Thread.currentThread().getContextClassLoader().getResource("your.xsd"));
Validator validator = schema.newValidator();
validator.validate(xmlFile);
Validate against local schemas
axios
by itself comes with two useful "methods" the interceptors
that are none but middlewares between the request and the response. so if on each request you want to send the token. Use the interceptor.request
.
I made apackage that helps you out:
$ npm i axios-es6-class
Now you can use axios as class
export class UserApi extends Api {
constructor (config) {
super(config);
// this middleware is been called right before the http request is made.
this.interceptors.request.use(param => {
return {
...param,
defaults: {
headers: {
...param.headers,
"Authorization": `Bearer ${this.getToken()}`
},
}
}
});
this.login = this.login.bind(this);
this.getSome = this.getSome.bind(this);
}
login (credentials) {
return this.post("/end-point", {...credentials})
.then(response => this.setToken(response.data))
.catch(this.error);
}
getSome () {
return this.get("/end-point")
.then(this.success)
.catch(this.error);
}
}
I mean the implementation of the middleware
depends on you, or if you prefer to create your own axios-es6-class
https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a
it is the medium post where it came from
SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.
Here comes a modernization of my previous answer which can be seen below. This one is running with Gradle 4.4 and Android Studio 3.1.1.
What this script does:
projectDir/apk
to make it more accessible.This script will create a version number which looks like v1.3.4 (123)
and build an apk file like AppName-v1.3.4.apk.
Major version ? ? Build version
v1.3.4 (123)
Minor version ^|^ Patch version
Major version: Has to be changed manually for bigger changes.
Minor version: Has to be changed manually for slightly less big changes.
Patch version: Increases when running gradle assembleRelease
Build version: Increases every build
Version Number: Same as Patch version, this is for the version code which Play Store needs to have increased for each new apk upload.
Just change the content in the comments labeled 1 - 3 below and the script should do the rest. :)
android {
compileSdkVersion 27
buildToolsVersion '27.0.3'
def versionPropsFile = file('version.properties')
def value = 0
Properties versionProps = new Properties()
if (!versionPropsFile.exists()) {
versionProps['VERSION_PATCH'] = "0"
versionProps['VERSION_NUMBER'] = "0"
versionProps['VERSION_BUILD'] = "-1" // I set it to minus one so the first build is 0 which isn't super important.
versionProps.store(versionPropsFile.newWriter(), null)
}
def runTasks = gradle.startParameter.taskNames
if ('assembleRelease' in runTasks) {
value = 1
}
def mVersionName = ""
def mFileName = ""
if (versionPropsFile.canRead()) {
versionProps.load(new FileInputStream(versionPropsFile))
versionProps['VERSION_PATCH'] = (versionProps['VERSION_PATCH'].toInteger() + value).toString()
versionProps['VERSION_NUMBER'] = (versionProps['VERSION_NUMBER'].toInteger() + value).toString()
versionProps['VERSION_BUILD'] = (versionProps['VERSION_BUILD'].toInteger() + 1).toString()
versionProps.store(versionPropsFile.newWriter(), null)
// 1: change major and minor version here
mVersionName = "v1.0.${versionProps['VERSION_PATCH']}"
// 2: change AppName for your app name
mFileName = "AppName-${mVersionName}.apk"
defaultConfig {
minSdkVersion 21
targetSdkVersion 27
applicationId "com.example.appname" // 3: change to your package name
versionCode versionProps['VERSION_NUMBER'].toInteger()
versionName "${mVersionName} Build: ${versionProps['VERSION_BUILD']}"
}
} else {
throw new FileNotFoundException("Could not read version.properties!")
}
if ('assembleRelease' in runTasks) {
applicationVariants.all { variant ->
variant.outputs.all { output ->
if (output.outputFile != null && output.outputFile.name.endsWith('.apk')) {
outputFileName = mFileName
}
}
}
}
task copyApkFiles(type: Copy){
from 'build/outputs/apk/release'
into '../apk'
include mFileName
}
afterEvaluate {
assembleRelease.doLast {
tasks.copyApkFiles.execute()
}
}
signingConfigs {
...
}
buildTypes {
...
}
}
INITIAL ANSWER:
I want the versionName to increase automatically as well. So this is just an addition to the answer by CommonsWare which worked perfectly for me. This is what works for me
defaultConfig {
versionCode code
versionName "1.1." + code
minSdkVersion 14
targetSdkVersion 18
}
EDIT:
As I am a bit lazy I want my versioning to work as automatically as possible. What I want is to have a Build Version that increases with each build, while the Version Number and Version Name only increases when I make a release build.
This is what I have been using for the past year, the basics are from CommonsWare's answer and my previous answer, plus some more. This results in the following versioning:
Version Name: 1.0.5 (123) --> Major.Minor.Patch (Build), Major and Minor are changed manually.
In build.gradle:
...
android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def value = 0
def runTasks = gradle.startParameter.taskNames
if ('assemble' in runTasks || 'assembleRelease' in runTasks || 'aR' in runTasks) {
value = 1;
}
def versionMajor = 1
def versionMinor = 0
def versionPatch = versionProps['VERSION_PATCH'].toInteger() + value
def versionBuild = versionProps['VERSION_BUILD'].toInteger() + 1
def versionNumber = versionProps['VERSION_NUMBER'].toInteger() + value
versionProps['VERSION_PATCH'] = versionPatch.toString()
versionProps['VERSION_BUILD'] = versionBuild.toString()
versionProps['VERSION_NUMBER'] = versionNumber.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
versionCode versionNumber
versionName "${versionMajor}.${versionMinor}.${versionPatch} (${versionBuild}) Release"
minSdkVersion 14
targetSdkVersion 23
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def fileNaming = "apk/RELEASES"
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
output.outputFile = new File(getProject().getRootDir(), "${fileNaming}-${versionMajor}.${versionMinor}.${versionPatch}-${outputFile.name}")
}
}
}
}
} else {
throw new GradleException("Could not read version.properties!")
}
...
}
...
Patch and versionCode is increased if you assemble your project through the terminal with 'assemble', 'assembleRelease' or 'aR' which creates a new folder in your project root called apk/RELEASE so you don't have to look through build/outputs/more/more/more to find your apk.
Your version properties would need to look like this:
VERSION_NUMBER=1
VERSION_BUILD=645
VERSION_PATCH=1
Obviously start with 0. :)
var clonedArray = array.concat();
All of the answers (at the time of this writing) assume each of Redis, MongoDB, and perhaps an SQL-based relational database are essentially the same tool: "store data". They don't consider data models at all.
MongoDB is a document store. To compare with an SQL-driven relational database: relational databases simplify to indexed CSV files, each file being a table; document stores simplify to indexed JSON files, each file being a document, with multiple files grouped together.
JSON files are similar in structure to XML and YAML files, and to dictionaries as in Python, so think of your data in that sort of hierarchy. When indexing, the structure is the key: A document contains named keys, which contain either further documents, arrays, or scalar values. Consider the below document.
{
_id: 0x194f38dc491a,
Name: "John Smith",
PhoneNumber:
Home: "555 999-1234",
Work: "555 999-9876",
Mobile: "555 634-5789"
Accounts:
- "379-1111"
- "379-2574"
- "414-6731"
}
The above document has a key, PhoneNumber.Mobile
, which has value 555 634-5789
. You can search through a collection of documents where the key, PhoneNumber.Mobile
, has some value; they're indexed.
It also has an array of Accounts
which hold multiple indexes. It is possible to query for a document where Accounts
contains exactly some subset of values, all of some subset of values, or any of some subset of values. That means you can search for Accounts = ["379-1111", "379-2574"]
and not find the above; you can search for Accounts includes ["379-1111"]
and find the above document; and you can search for Accounts includes any of ["974-3785","414-6731"]
and find the above and whatever document includes account "974-3785", if any.
Documents go as deep as you want. PhoneNumber.Mobile
could hold an array, or even a sub-document (PhoneNumber.Mobile.Work
and PhoneNumber.Mobile.Personal
). If your data is highly structured, documents are a large step up from relational databases.
If your data is mostly flat, relational, and rigidly structured, you're better off with a relational database. Again, the big sign is whether your data models best to a collection of interrelated CSV files or a collection of XML/JSON/YAML files.
For most projects, you'll have to compromise, accepting a minor work-around in some small areas where either SQL or Document Stores don't fit; for some large, complex projects storing a broad spread of data (many columns; rows are irrelevant), it will make sense to store some data in one model and other data in another model. Facebook uses both SQL and a graph database (where data is put into nodes, and nodes are connected to other nodes); Craigslist used to use MySQL and MongoDB, but had been looking into moving entirely onto MongoDB. These are places where the span and relationship of the data faces significant handicaps if put under one model.
Redis is, most basically, a key-value store. Redis lets you give it a key and look up a single value. Redis itself can store strings, lists, hashes, and a few other things; however, it only looks up by name.
Cache invalidation is one of computer science's hard problems; the other is naming things. That means you'll use Redis when you want to avoid hundreds of excess look-ups to a back-end, but you'll have to figure out when you need a new look-up.
The most obvious case of invalidation is update on write: if you read user:Simon:lingots = NOTFOUND
, you might SELECT Lingots FROM Store s INNER JOIN UserProfile u ON s.UserID = u.UserID WHERE u.Username = Simon
and store the result, 100
, as SET user:Simon:lingots = 100
. Then when you award Simon 5 lingots, you read user:Simon:lingots = 100
, SET user:Simon:lingots = 105
, and UPDATE Store s INNER JOIN UserProfile u ON s.UserID = u.UserID SET s.Lingots = 105 WHERE u.Username = Simon
. Now you have 105 in your database and in Redis, and can get user:Simon:lingots
without querying the database.
The second case is updating dependent information. Let's say you generate chunks of a page and cache their output. The header shows the player's experience, level, and amount of money; the player's Profile page has a block that shows their statistics; and so forth. The player gains some experience. Well, now you have several templates:Header:Simon
, templates:StatsBox:Simon
, templates:GrowthGraph:Simon
, and so forth fields where you've cached the output of a half-dozen database queries run through a template engine. Normally, when you display these pages, you say:
$t = GetStringFromRedis("templates:StatsBox:" + $playerName);
if ($t == null) {
$t = BuildTemplate("StatsBox.tmpl",
GetStatsFromDatabase($playerName));
SetStringInRedis("Templates:StatsBox:" + $playerName, $t);
}
print $t;
Because you just updated the results of GetStatsFromDatabase("Simon")
, you have to drop templates:*:Simon
out of your key-value cache. When you try to render any of these templates, your application will churn away fetching data from your database (PostgreSQL, MongoDB) and inserting it into your template; then it will store the result in Redis and, hopefully, not bother making database queries and rendering templates the next time it displays that block of output.
Redis also lets you do publisher-subscribe message queues and such. That's another topic entirely. Point here is Redis is a key-value cache, which differs from a relational database or a document store.
Pick your tools based on your needs. The largest need is usually data model, as that determines how complex and error-prone your code is. Specialized applications will lean on performance, places where you write everything in a mixture of C and Assembly; most applications will just handle the generalized case and use a caching system such as Redis or Memcached, which is a lot faster than either a high-performance SQL database or a document store.
You can use different syntax to achieve different things. If it is windows authentication you want, you could try this:
sqlcmd /S /d -E
If you want to use SQL Server authentication you could try this:
sqlcmd /S /d -U -P
Definitions:
/S = the servername/instance name. Example: Pete's Laptop/SQLSERV
/d = the database name. Example: Botlek1
-E = Windows authentication.
-U = SQL Server authentication/user. Example: Pete
-P = password that belongs to the user. Example: 1234
Hope this helps!
If you're talking about the database password, as opposed to the password coming from a browser, the standard practice seems to be to put the database password in a PHP config file on the server.
You just need to be sure that the php file containing the password has appropriate permissions on it. I.e. it should be readable only by the web server and by your user account.
The accepted answer is outdated as of February 2019. Here's an answer that will work until sdkmanager
migrates to a newer version of Java. But by then, you won't have this problem anymore.
OpenJDK 10 was superseeded by OpenJDK 11, which doesn't implement
java.se.ee
at all. This means that the hack of adding--add-modules java.se.ee
doesn't do anything anymore. It also means that OpenJDK 10 will be automatically removed from your system and replaced with OpenJDK 11 the next time you update, if your updates are configured properly.Modify
sdkmanager
to use Java 8 by settingJAVA_HOME
insidesdkmanager
to a Java 8 installation. It's, by default, at~/Android/Sdk/tools/bin/sdkmanager
.# Add default JVM options here. You can also use JAVA_OPTS and SDKMANAGER_OPTS to pass JVM options $ JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64 DEFAULT_JVM_OPTS='"-Dcom.android.sdklib.toolsdir=$APP_HOME" -XX:+IgnoreUnrecognizedVMOptions'
@rem Add default JVM options here. You can also use JAVA_OPTS and SDKMANAGER_OPTS to pass JVM options to this script. set JAVA_HOME="C:\ProgramData\scoop\apps\android-studio\current\jre" set DEFAULT_JVM_OPTS="-Dcom.android.sdklib.toolsdir=%~dp0\.."
This way, you can keep using a sane and maintained version of Java on your system while simultaneously using
sdkmanager
.# Java export JAVA_HOME=/usr/lib/jvm/default-java
And now I've got some pipelines to repair.
You can use bookmarklets (javascript code in a bookmark) - this also means they sync across devices.
I have loads - I prefix the name with zzz, so they are eazy to type in to the address bar and show in drop down predictions.
To get them to operate on a page you need to go to the page and then in the address bar type the bookmarklet name - this will cause the bookmarklet to execute in the context of the page.
edit
Just to highlight - for this to work, the bookmarklet name must be typed into the address bar while the page you want to operate in is being displayed - if you go off to select the bookmarklet in some other way the page context gets lost, and the bookmarklet operates on a new empty page.
I use zzzpocket - send to pocket. zzztwitter tweet this page zzzmail email this page zzzpressthis send this page to wordpress zzztrello send this page to trello and more...
and it works in chrome whatever platform I am currently logged on to.
How big is your sample? Here is another option to test your data against any distribution using OpenTURNS library. In the example below, I generate a sample x of 1.000.000 numbers from a Uniform distribution and test it against a Normal distribution.
You can replace x by your data if you reshape it as x= [[x1], [x2], .., [xn]]
import openturns as ot
x = ot.Uniform().getSample(1000000)
g = ot.VisualTest.DrawQQplot(x, ot.Normal())
g
In my Jupyter Notebook, I see:
If you are writing a script, you can do it more properly
from openturns.viewer import View`
import matplotlib.pyplot as plt
View(g)
plt.show()
there is a function called isNaN
it return true if it's (Not-a-number) , so u can check for a number this way
if(!isNaN(miscCharge))
{
//do some thing if it's a number
}else{
//do some thing if it's NOT a number
}
hope it works
delay()
doesn't halt the flow of code then re-run it. There's no practical way to do that in JavaScript. Everything has to be done with functions which take callbacks such as setTimeout
which others have mentioned.
The purpose of jQuery's delay()
is to make an animation queue wait before executing. So for example $(element).delay(3000).fadeIn(250);
will make the element fade in after 3 seconds.
SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).
The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).
Another possibility is:
d = datetime.datetime.utcnow()
epoch = datetime.datetime(1970,1,1)
t = (d - epoch).total_seconds()
This works as both "d" and "epoch" are naive datetimes, making the "-" operator valid, and returning an interval. total_seconds()
turns the interval into seconds. Note that total_seconds()
returns a float, even d.microsecond == 0
In my case, I needed a viewpager with a wrap_content for the currently selected element and animation when applying the size. Below you can see my implementation. Can someone come in handy.
package one.xcorp.widget
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import one.xcorp.widget.R
import kotlin.properties.Delegates.observable
class ViewPager : android.support.v4.view.ViewPager {
var enableAnimation by observable(false) { _, _, enable ->
if (enable) {
addOnPageChangeListener(onPageChangeListener)
} else {
removeOnPageChangeListener(onPageChangeListener)
}
}
private var animationDuration = 0L
private var animator: ValueAnimator? = null
constructor (context: Context) : super(context) {
init(context, null)
}
constructor (context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
context.theme.obtainStyledAttributes(
attrs,
R.styleable.ViewPager,
0,
0
).apply {
try {
enableAnimation = getBoolean(
R.styleable.ViewPager_enableAnimation,
enableAnimation
)
animationDuration = getInteger(
R.styleable.ViewPager_animationDuration,
resources.getInteger(android.R.integer.config_shortAnimTime)
).toLong()
} finally {
recycle()
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
val measuredHeight = if (heightMode == MeasureSpec.EXACTLY) {
MeasureSpec.getSize(heightMeasureSpec)
} else {
val currentViewHeight = findViewByPosition(currentItem)?.also {
measureView(it)
}?.measuredHeight ?: 0
if (heightMode != MeasureSpec.AT_MOST) {
currentViewHeight
} else {
Math.min(
currentViewHeight,
MeasureSpec.getSize(heightMeasureSpec)
)
}
}
super.onMeasure(
widthMeasureSpec,
MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY)
)
}
private fun measureView(view: View) = with(view) {
val horizontalMode: Int
val horizontalSize: Int
when (layoutParams.width) {
MATCH_PARENT -> {
horizontalMode = MeasureSpec.EXACTLY
horizontalSize = [email protected]
}
WRAP_CONTENT -> {
horizontalMode = MeasureSpec.UNSPECIFIED
horizontalSize = 0
}
else -> {
horizontalMode = MeasureSpec.EXACTLY
horizontalSize = layoutParams.width
}
}
val verticalMode: Int
val verticalSize: Int
when (layoutParams.height) {
MATCH_PARENT -> {
verticalMode = MeasureSpec.EXACTLY
verticalSize = [email protected]
}
WRAP_CONTENT -> {
verticalMode = MeasureSpec.UNSPECIFIED
verticalSize = 0
}
else -> {
verticalMode = MeasureSpec.EXACTLY
verticalSize = layoutParams.height
}
}
val horizontalMeasureSpec = MeasureSpec.makeMeasureSpec(horizontalSize, horizontalMode)
val verticalMeasureSpec = MeasureSpec.makeMeasureSpec(verticalSize, verticalMode)
measure(horizontalMeasureSpec, verticalMeasureSpec)
}
private fun findViewByPosition(position: Int): View? {
for (i in 0 until childCount) {
val childView = getChildAt(i)
val childLayoutParams = childView.layoutParams as LayoutParams
val childPosition by lazy {
val field = childLayoutParams.javaClass.getDeclaredField("position")
field.isAccessible = true
field.get(childLayoutParams) as Int
}
if (!childLayoutParams.isDecor && position == childPosition) {
return childView
}
}
return null
}
private fun animateContentHeight(childView: View, fromHeight: Int, toHeight: Int) {
animator?.cancel()
if (fromHeight == toHeight) {
return
}
animator = ValueAnimator.ofInt(fromHeight, toHeight).apply {
addUpdateListener {
measureView(childView)
if (childView.measuredHeight != toHeight) {
animateContentHeight(childView, height, childView.measuredHeight)
} else {
layoutParams.height = animatedValue as Int
requestLayout()
}
}
duration = animationDuration
start()
}
}
private val onPageChangeListener = object : OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
/* do nothing */
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
/* do nothing */
}
override fun onPageSelected(position: Int) {
if (!isAttachedToWindow) {
return
}
findViewByPosition(position)?.let { childView ->
measureView(childView)
animateContentHeight(childView, height, childView.measuredHeight)
}
}
}
}
Add attrs.xml in project:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ViewPager">
<attr name="enableAnimation" format="boolean" />
<attr name="animationDuration" format="integer" />
</declare-styleable>
</resources>
And use:
<one.xcorp.widget.ViewPager
android:id="@+id/wt_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:enableAnimation="true" />
SQL Locator (free) has worked great for me. It comes with a lot of options and it's fairly easy to use.
This is how to implement a simple singleton:
public class Singleton {
// It must be static and final to prevent later modification
private static final Singleton INSTANCE = new Singleton();
/** The constructor must be private to prevent external instantiation */
private Singleton(){}
/** The public static method allowing to get the instance */
public static Singleton getInstance() {
return INSTANCE;
}
}
This is how to properly lazy create your singleton:
public class Singleton {
// The constructor must be private to prevent external instantiation
private Singleton(){}
/** The public static method allowing to get the instance */
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
/**
* The static inner class responsible for creating your instance only on demand,
* because the static fields of a class are only initialized when the class
* is explicitly called and a class initialization is synchronized such that only
* one thread can perform it, this rule is also applicable to inner static class
* So here INSTANCE will be created only when SingletonHolder.INSTANCE
* will be called
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
}
Perhaps you want something like:
<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
<item name="android:checkboxStyle">@style/customCheckBoxStyle</item>
</style>
<style name="customCheckBoxStyle" parent="@android:style/Widget.CompoundButton.CheckBox">
<item name="android:textColor">@android:color/black</item>
</style>
Note, the textColor item.
Step 1
If you have a small file Read all the file data in to memory
Step 2
Convert file data string into Array
Step 3
Search the array to find a location where you want to insert the text
Step 4
Once you have the location insert your text
yourArray.splice(index,0,"new added test");
Step 5
convert your array to string
yourArray.join("");
Step 6
write your file like so
fs.createWriteStream(yourArray);
This is not advised if your file is too big
var label = $('#current_month');
var month = label.val('month');
var year = label.val('year');
var text = label.text();
alert(text);
<label year="2010" month="6" id="current_month"> June 2010</label>
You've missed the id out before the NOT; it needs to be specified.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
I would recommend Apache HttpComponents HttpClient, a successor of Commons HttpClient
I would also recommend to take a look at HtmlUnit. HtmlUnit is a "GUI-Less browser for Java programs". http://htmlunit.sourceforge.net/
You should use the addAll
method. It appends all of the elements in the specified collection to the end of the copy list. It will be a copy of your list.
List<String> myList = new ArrayList<>();
myList.add("a");
myList.add("b");
List<String> copyList = new ArrayList<>();
copyList.addAll(myList);
I'll give you a couple examples of using properties that might get the gears turning:
You're close; you should use dot notation in your use of the $
update operator to do that:
Person.update({'items.id': 2}, {'$set': {
'items.$.name': 'updated item2',
'items.$.value': 'two updated'
}}, function(err) { ...
preg_replace('/^[^:\/?]+:\/\//','',$url);
some results:
input: http://php.net/preg_replace output: php.net/preg_replace input: https://www.php.net/preg_replace output: www.php.net/preg_replace input: ftp://www.php.net/preg_replace output: www.php.net/preg_replace input: https://php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com input: php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com input: php.net?site=http://whatever.com output: php.net?site=http://whatever.com
Why is MichalBE getting downvoted? He's right - using jQuery (or any library) just to fire a function on page load is overkill, potentially costing people money on mobile connections and slowing down the user experience. If the original poster doesn't want to use onload in the body tag (and he's quite right not to), add this after the draw() function:
if (draw) window.onload = draw;
Or this, by Simon Willison, if you want more than one function to be executed:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
$('iframe').load(function(){
$(".loading").remove();
alert("iframe is done loading")
}).show();
<iframe src="http://www.google.com" style="display:none;" width="600" height="300"/>
<div class="loading" style="width:600px;height:300px;">iframe loading</div>
Have you tried the __name__
attribute of the class? ie type(x).__name__
will give you the name of the class, which I think is what you want.
>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:
x.__class__.__name__
you can use this command by getting your data. this will extract your data...
select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';
CURRENT_DATE
and CURRENT_TIMESTAMP
return the current date and time in the session time zone.
SYSDATE
and SYSTIMESTAMP
return the system date and time - that is, of the system on which the database resides.
If your client session isn't in the same timezone as the server the database is on (or says it isn't anyway, via your NLS settings), mixing the SYS*
and CURRENT_*
functions will return different values. They are all correct, they just represent different things. It looks like your server is (or thinks it is) in a +4:00 timezone, while your client session is in a +4:30 timezone.
You might also see small differences in the time if the clocks aren't synchronised, which doesn't seem to be an issue here.
I would omit the * { text-align:center }
declaration, as it sets center alignment for all elements.
Usually with a fixed width container margin: 0 auto
should be enough
Sure you can:
Option Explicit
'***** User defined type
Public Type MyType
MyInt As Integer
MyString As String
MyDoubleArr(2) As Double
End Type
'***** Testing MyType as single variable
Public Sub MyFirstSub()
Dim MyVar As MyType
MyVar.MyInt = 2
MyVar.MyString = "cool"
MyVar.MyDoubleArr(0) = 1
MyVar.MyDoubleArr(1) = 2
MyVar.MyDoubleArr(2) = 3
Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub
'***** Testing MyType as an array
Public Sub MySecondSub()
Dim MyArr(2) As MyType
Dim i As Integer
MyArr(0).MyInt = 31
MyArr(0).MyString = "VBA"
MyArr(0).MyDoubleArr(0) = 1
MyArr(0).MyDoubleArr(1) = 2
MyArr(0).MyDoubleArr(2) = 3
MyArr(1).MyInt = 32
MyArr(1).MyString = "is"
MyArr(1).MyDoubleArr(0) = 11
MyArr(1).MyDoubleArr(1) = 22
MyArr(1).MyDoubleArr(2) = 33
MyArr(2).MyInt = 33
MyArr(2).MyString = "cool"
MyArr(2).MyDoubleArr(0) = 111
MyArr(2).MyDoubleArr(1) = 222
MyArr(2).MyDoubleArr(2) = 333
For i = LBound(MyArr) To UBound(MyArr)
Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
Next
End Sub
Promises are an abstraction over statements that allow us to express ourselves synchronously with asynchronous code. They represent a execution of a one time task.
They also provide exception handling, just like normal code, you can return from a promise or you can throw.
What you'd want in synchronous code is:
try{
try{
var res = $http.getSync("url");
res = someProcessingOf(res);
} catch (e) {
console.log("Got an error!",e);
throw e; // rethrow to not marked as handled
}
// do more stuff with res
} catch (e){
// handle errors in processing or in error.
}
The promisified version is very similar:
$http.get("url").
then(someProcessingOf).
catch(function(e){
console.log("got an error in initial processing",e);
throw e; // rethrow to not marked as handled,
// in $q it's better to `return $q.reject(e)` here
}).then(function(res){
// do more stuff
}).catch(function(e){
// handle errors in processing or in error.
});
Note: I am assuming the array is sorted.
Code:
int[] input = new int[]{1, 1, 3, 7, 7, 8, 9, 9, 9, 10};
int current = input[0];
boolean found = false;
for (int i = 0; i < input.length; i++) {
if (current == input[i] && !found) {
found = true;
} else if (current != input[i]) {
System.out.print(" " + current);
current = input[i];
found = false;
}
}
System.out.print(" " + current);
output:
1 3 7 8 9 10
Try to add like this:
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
instead of having
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
This worked for me .
I am taking Stephen Grider's React Native on Udemy and one of the students posted this in Lecture 50. Pasted verbatim in the command line (w/o '$' of course).
$ export "ANDROID_HOME=/usr/local/opt/android-sdk" >~/.bash_profile
In the last statement you are converting the duration to time which also considers the timezone. I assume that your timezone is +530, so 5 hours and 30 minutes gets added to 30 minutes. You can do as given below.
var eventTime= 1366549200; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTime = 1366547400; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime*1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration - interval, 'milliseconds');
$('.countdown').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);
In PrimeFaces 3.0, that style get applied on the generated inner <div>
of the table cell, not on the <td>
as you (and I) would expect. The following example should work out for you:
<p:dataTable styleClass="myTable">
with
.myTable td:nth-child(1) {
width: 20px;
}
In PrimeFaces 3.5 and above, it should work exactly the way you coded and expected.
Dynamic Programming
Definition
Dynamic programming (DP) is a general algorithm design technique for solving problems with overlapping sub-problems. This technique was invented by American mathematician “Richard Bellman” in 1950s.
Key Idea
The key idea is to save answers of overlapping smaller sub-problems to avoid recomputation.
Dynamic Programming Properties
http://oreilly.com/catalog/javacook/chapter/ch18.html
Search for :
"Problem
You want to process the data from an HTML form in a servlet. "
Perhaps you're asking about keeping such things going...
Of course you'll invoke a full table scan for the queries and if the table containing the scores that need to be tallied (aggregations) is large you might want a better performing solution, you can create a secondary table and use rules, such as on insert
- you might look into it.
Not all RDBMS engines have rules, though!
With EF Core in .NET Core you can use the keyword ThenInclude
:
return DatabaseContext.Applications
.Include(a => a.Children).ThenInclude(c => c.ChildRelationshipType);
Include childs from childrens collection :
return DatabaseContext.Applications
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1)
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2);
There is also the option of turning off the cache for network resources. This might be best for developing environments.
I believe you can manipulate it with the overflow
CSS attribute, but they have limited browser support. One source said it was Internet Explorer 5 (and later), Firefox 1.5 (and later), and Safari 3 (and later) - maybe enough for your purposes.
Scrolling, Scrolling, Scrolling has a good discussion.
In the definition of your Card
class, a declaration for a default construction appears:
class Card
{
// ...
Card(); // <== Declaration of default constructor!
// ...
};
But no corresponding definition is given. In fact, this function definition (from card.cpp
):
void Card() {
//nothing
}
Does not define a constructor, but rather a global function called Card
that returns void
. You probably meant to write this instead:
Card::Card() {
//nothing
}
Unless you do that, since the default constructor is declared but not defined, the linker will produce error about undefined references when a call to the default constructor is found.
The same applies to your constructor accepting two arguments. This:
void Card(Card::Rank rank, Card::Suit suit) {
cardRank = rank;
cardSuit = suit;
}
Should be rewritten into this:
Card::Card(Card::Rank rank, Card::Suit suit) {
cardRank = rank;
cardSuit = suit;
}
And the same also applies for other member functions: it seems you did not add the Card::
qualifier before the member function names in their definitions. Without it, those functions are global functions rather than definitions of member functions.
Your destructor, on the other hand, is declared but never defined. Just provide a definition for it in card.cpp
:
Card::~Card() { }
You need to follow this instructions https://cloud.google.com/compute/docs/instances/connecting-to-instance#generatesshkeypair
If get "Permission denied (publickey)." with the follow command
ssh -i ~/.ssh/my-ssh-key [USERNAME]@[IP_ADDRESS]
you need to modify the /etc/ssh/sshd_config file and add the line
AllowUsers [USERNAME]
Then restart the ssh service with
service ssh restart
if you get the message "Could not load host key: /etc/ssh/ssh_host_ed25519_key" execute:
ssh-keygen -A
and finally restart the ssh service again.
service ssh restart
$('a[href$="ABC"]')...
Selector documentation can be found at http://docs.jquery.com/Selectors
For attributes:
= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")
Set a system variable named http_proxy
with the value of ProxyServer:Port
.
That is the simplest solution. Respectively, use https_proxy
as daefu pointed out in the comments.
Setting gitproxy (as sleske mentions) is another option, but that requires a "command", which is not as straightforward as the above solution.
References: http://bardofschool.blogspot.com/2008/11/use-git-behind-proxy.html
Your problem is that you are NOT testing the length of the array until it is too late.
But I just want to point out that the way to solve this problem is to READ THE STACK TRACE.
The exception message will clearly tell you are trying to create an array with length -1, and the trace will tell you exactly which line of your code is doing this. The rest is simple logic ... working back to why the length you are using is -1.
There are a couple of tests using the URL constructor which do not delineate whether the input is a string or URL object.
// Testing whether something is a URL
function isURL(url) {
return toString.call(url) === "[object URL]";
}
// Testing whether the input is both a string and valid url:
function isUrl(url) {
try {
return toString.call(url) === "[object String]" && !!(new URL(url));
} catch (_) {
return false;
}
}
I started out with this article
http://en.tekstenuitleg.net/articles/software/database-design-tutorial/intro.html
It's pretty concise compared to reading an entire book and it explains the basics of database design (normalization, types of relationships) very well.
Try the "-o StrictHostKeyChecking=no" option to ssh("-o" being the flag that tells ssh that your are going to use an option). This accepts any incoming RSA key from your ssh connection, even if the key is not in the "known host" list.
sshpass -p 'password' ssh -o StrictHostKeyChecking=no user@host 'command'
Absolute positioning means that the element is taken completely out of the normal flow of the page layout. As far as the rest of the elements on the page are concerned, the absolutely positioned element simply doesn't exist. The element itself is then drawn separately, sort of "on top" of everything else, at the position you specify using the left, right, top and bottom
attributes.
Using the position you specify with these attributes, the element is then placed at that position within its last ancestor element which has a position attribute of anything other than static
(page elements default to static when no position attribute specified), or the document body (browser viewport) if no such ancestor exists.
For example, if I had this code:
<body>
<div style="position:absolute; left: 20px; top: 20px;"></div>
</body>
...the <div>
would be positioned 20px from the top of the browser viewport, and 20px from the left edge of same.
However, if I did something like this:
<div id="outer" style="position:relative">
<div id="inner" style="position:absolute; left: 20px; top: 20px;"></div>
</div>
...then the inner
div would be positioned 20px from the top of the outer
div, and 20px from the left edge of same, because the outer
div isn't positioned with position:static
because we've explicitly set it to use position:relative
.
Relative positioning, on the other hand, is just like stating no positioning at all, but the left, right, top and bottom
attributes "nudge" the element out of their normal layout. The rest of the elements on the page still get laid out as if the element was in its normal spot though.
For example, if I had this code:
<span>Span1</span>
<span>Span2</span>
<span>Span3</span>
...then all three <span>
elements would sit next to each other without overlapping.
If I set the second <span>
to use relative positioning, like this:
<span>Span1</span>
<span style="position: relative; left: -5px;">Span2</span>
<span>Span3</span>
...then Span2 would overlap the right side of Span1 by 5px. Span1 and Span3 would sit in exactly the same place as they did in the first example, leaving a 5px gap between the right side of Span2 and the left side of Span3.
Hope that clarifies things a bit.
While pure JavaScript is sufficient here, I still prefer the jQuery approach. After all, the ask was to get the hostname using jQuery.
var hostName = $(location).attr('hostname'); // www.example.com
Use following code to show menu instead go to href addres
function show_more_menu(e) {_x000D_
if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();_x000D_
}
_x000D_
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>
_x000D_
You can present MFMessageComposeViewController, which can send SMS, but with user prompt(he taps send button). No way to do that without user permission. On iOS 11, you can make extension, that can be like filter for incoming messages , telling iOS either its spam or not. Nothing more with SMS cannot be done
Just happened to me when trying to send_keys to a search input box - that has autoupdate depending on what you type in. As mentioned by Eero, this can happen if your element does some Ajax updated while you are typing in your text inside the input element. The solution is to send one character at a time and search again for the input element. (Ex. in ruby shown below)
def send_keys_eachchar(webdriver, elem_locator, text_to_send)
text_to_send.each_char do |char|
input_elem = webdriver.find_element(elem_locator)
input_elem.send_keys(char)
end
end
Remove pod name from Podfile
then
Open Terminal, set project folder path and
Run pod update
command.
NOTE: pod update
will update all the libraries to the latest version and will also remove those libraries whose name have been removed from podfile.
As GateKiller said you need to change the maxRequestLength. You may also need to change the executionTimeout in case the upload speed is too slow. Note that you don't want either of these settings to be too big otherwise you'll be open to DOS attacks.
The default for the executionTimeout is 360 seconds or 6 minutes.
You can change the maxRequestLength and executionTimeout with the httpRuntime Element.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime maxRequestLength="102400" executionTimeout="1200" />
</system.web>
</configuration>
EDIT:
If you want to handle the exception regardless then as has been stated already you'll need to handle it in Global.asax. Here's a link to a code example.
The answers in question you linked-to are all about configuring git so that you can enter very short git push
commands and have them do whatever you want. Which is great, if you know what you want and how to spell that in Git-Ese, but you're new to git! :-)
In your case, Petr Mensik's answer is the (well, "a") right one. Here's why:
The command git push remote
roots around in your .git/config
file to find the named "remote" (e.g., origin
). The config file lists:
ssh://hostname/path
)git fetch remote
When you first cloned the repo—whenever that was—git set up default values for some of these. The URL is whatever you cloned from and the rest, if set or unset, are all "reasonable" defaults ... or, hmm, are they?
The issue with these is that people have changed their minds, over time, as to what is "reasonable". So now (depending on your version of git and whether you've configured things in detail), git may print a lot of warnings about defaults changing in the future. Adding the name of the "branch to push"—amd_qlp_tester
—(1) shuts it up, and (2) pushes just that one branch.
If you want to push more conveniently, you could do that with:
git push origin
or even:
git push
but whether that does what you want, depends on whether you agree with "early git authors" that the original defaults are reasonable, or "later git authors" that the original defaults aren't reasonable. So, when you want to do all the configuration stuff (eventually), see the question (and answers) you linked-to.
As for the name origin/amd_qlp_tester
in the first place: that's actually a local entity (a name kept inside your repo), even though it's called a "remote branch". It's git's best guess at "where amd_qlp_tester
is over there". Git updates it when it can.
This is everything you need:
$week_start = strtotime('last Sunday', time());
$week_end = strtotime('next Sunday', time());
$month_start = strtotime('first day of this month', time());
$month_end = strtotime('last day of this month', time());
$year_start = strtotime('first day of January', time());
$year_end = strtotime('last day of December', time());
echo date('D, M jS Y', $week_start).'<br/>';
echo date('D, M jS Y', $week_end).'<br/>';
echo date('D, M jS Y', $month_start).'<br/>';
echo date('D, M jS Y', $month_end).'<br/>';
echo date('D, M jS Y', $year_start).'<br/>';
echo date('D, M jS Y', $year_end).'<br/>';
Here are the few things that I found regarding this topic.
During compilation, the compiler tries to find classes that are used in the code from the .* import and the corresponding byte code will be generated by selecting the used classes from .* import. So the byte code of using .* import or .class names import will be same and the runtime performance will also be the same because of the same byte code.
In each compilation, the compiler has to scan all the classes of .* package to match the classes that are actually used in the code. So, code with .* import takes more time during the compilation process as compared to using .class name imports.
Using .* import helps to make code more cleaner
Using .* import can create ambiguity when we use two classes of the same name from two different packages. Eg, Date is available in both packages.
import java.util.*;
import java.sql.*;
public class DateDemo {
private Date utilDate;
private Date sqlDate;
}
Okay, I assume you using php7.2 (or higher) on Ubuntu 16 or higher
if none of this worked, you must know nginx-fastCGI uses different pid and .sock for different sites hosted on the same server.
To troubleshoot 'No input file specified' problem, you must tell the nginx yoursite.conf file which one of the sock file to use.
Uncomment the default fastcgi_pass unix:/var/run/php7.2-fpm.sock
Make sure you have the following directives in place on the conf file,
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
try_files $uri /index.php =404;
#fastcgi_pass unix:/var/run/php7.2-fpm.sock;
fastcgi_pass unix:/var/php-nginx/158521651519246.sock/socket;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
ls -la /var/php-nginx/
(if you have recently added the file, it should be the last one on the list)3.copy the filename of the .sock file (usually a 15 digit number) and paste it to your location ~ \.php
directive
fastcgi_pass unix:/var/php-nginx/{15digitNumber}.sock/socket;
and restart nginx. Let me know if it worked.
If you are using Kotlin
and Material Design
, you can change color of your MaterialButton
like this:
myButton.background.setTintList(ContextCompat.getColorStateList(context, R.color.myColor))
You can improve it even better by creating an extension function for your MaterialButton
in order to make you code more readable and your coding little more convenient:
fun MaterialButton.changeColor(color: Int) {
this.background.setTintList(ContextCompat.getColorStateList(context, color))
}
Then, you can use your function everywhere like this:
myButton.changeColor(R.color.myColor)
You can use textView.setTextColor(Color.BLACK)
to use any of the in-built colors of the Color
class.
You can also use textView.setTextColor(Color.parseColor(hexRGBvalue))
to define custom colors.
Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.
You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.
I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.
But fortunately, with the MySQL FOREIGN_KEY_CHECKS variable, you don't have to worry about the order of your DROP TABLE statements at all, and you can write them in any order you like -- even the exact opposite -- like this:
SET FOREIGN_KEY_CHECKS = 0;
drop table if exists customers;
drop table if exists orders;
drop table if exists order_details;
SET FOREIGN_KEY_CHECKS = 1;
For more clarification, check out the link below:
http://alvinalexander.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys/
From a pipe
# This Is a cat
'This', 'Is', 'a', 'cat' | & {"$input"}
# This-Is-a-cat
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"}
Write-Host
# This Is a cat
Write-Host 'This', 'Is', 'a', 'cat'
# This-Is-a-cat
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat'
It's your choice. There are basically three ways in a Java web application archive (WAR):
So that you can load it by ClassLoader#getResourceAsStream()
with a classpath-relative path:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("foo.properties");
// ...
Properties properties = new Properties();
properties.load(input);
Here foo.properties
is supposed to be placed in one of the roots which are covered by the default classpath of a webapp, e.g. webapp's /WEB-INF/lib
and /WEB-INF/classes
, server's /lib
, or JDK/JRE's /lib
. If the propertiesfile is webapp-specific, best is to place it in /WEB-INF/classes
. If you're developing a standard WAR project in an IDE, drop it in src
folder (the project's source folder). If you're using a Maven project, drop it in /main/resources
folder.
You can alternatively also put it somewhere outside the default classpath and add its path to the classpath of the appserver. In for example Tomcat you can configure it as shared.loader
property of Tomcat/conf/catalina.properties
.
If you have placed the foo.properties
it in a Java package structure like com.example
, then you need to load it as below
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/foo.properties");
// ...
Note that this path of a context class loader should not start with a /
. Only when you're using a "relative" class loader such as SomeClass.class.getClassLoader()
, then you indeed need to start it with a /
.
ClassLoader classLoader = getClass().getClassLoader();
InputStream input = classLoader.getResourceAsStream("/com/example/foo.properties");
// ...
However, the visibility of the properties file depends then on the class loader in question. It's only visible to the same class loader as the one which loaded the class. So, if the class is loaded by e.g. server common classloader instead of webapp classloader, and the properties file is inside webapp itself, then it's invisible. The context class loader is your safest bet so you can place the properties file "everywhere" in the classpath and/or you intend to be able to override a server-provided one from the webapp on.
So that you can load it by ServletContext#getResourceAsStream()
with a webcontent-relative path:
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/foo.properties");
// ...
Note that I have demonstrated to place the file in /WEB-INF
folder, otherwise it would have been public accessible by any webbrowser. Also note that the ServletContext
is in any HttpServlet
class just accessible by the inherited GenericServlet#getServletContext()
and in Filter
by FilterConfig#getServletContext()
. In case you're not in a servlet class, it's usually just injectable via @Inject
.
So that you can load it the usual java.io
way with an absolute local disk file system path:
InputStream input = new FileInputStream("/absolute/path/to/foo.properties");
// ...
Note the importance of using an absolute path. Relative local disk file system paths are an absolute no-go in a Java EE web application. See also the first "See also" link below.
Just weigh the advantages/disadvantages in your own opinion of maintainability.
If the properties files are "static" and never needs to change during runtime, then you could keep them in the WAR.
If you prefer being able to edit properties files from outside the web application without the need to rebuild and redeploy the WAR every time, then put it in the classpath outside the project (if necessary add the directory to the classpath).
If you prefer being able to edit properties files programmatically from inside the web application using Properties#store()
method, put it outside the web application. As the Properties#store()
requires a Writer
, you can't go around using a disk file system path. That path can in turn be passed to the web application as a VM argument or system property. As a precaution, never use getRealPath()
. All changes in deploy folder will get lost on a redeploy for the simple reason that the changes are not reflected back in original WAR file.
If you want to use a format that allows you to keep the number like your entry this format works for me:
"# \\%"
While others have pointed out that there is no built-in implementation of an insertion-order preserving set in Python (yet), I am feeling that this question is missing an answer which states what there is to be found on PyPI.
There are the packages:
Some of these implementations are based on the recipe posted by Raymond Hettinger to ActiveState which is also mentioned in other answers here.
my_set[5]
)remove(item)
Both implementations have O(1) for add(item)
and __contains__(item)
(item in my_set
).
Open a command prompt. Enter the command spyder
. Does anything appear? If an exception is preventing it from opening, you would be able to see the reason here. If the command is not found, update your environment variables to point to the Python3.6/Scripts folder, and run spyder
again (in a new cmd prompt).
So ... you need to change some things in your code
<form method="POST" id="form-pass">
Password: <input type="text" name="pwd" id="input-pwd">
<input type="submit" value="Submit">
</form>
<script>
var form = document.querySelector('#form-pass');
var pwd = document.querySelector('#input-pwd');
pwd.focus();
form.onsubmit = checkForm;
function checkForm() {
alert(pwd.value);
}
</script>
Try this way.
ul li + li:before
{
content:url(imgs/separator.gif);
}
Simplest solution in Swift 3.0 & Swift 4.0 & Swift 5.0
func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
completion()
}
}
Usage
delayWithSeconds(1) {
//Do something
}
<%!
private void myFunc(String Bits, javax.servlet.jsp.JspWriter myOut)
{
try{ myOut.println("<div>"+Bits+"</div>"); }
catch(Exception eek) { }
}
%>
...
<%
myFunc("more difficult than it should be",out);
%>
Try this, it worked for me!
If possible I would suggest creating the Path
directly from the path elements:
Path path = Paths.get("C:", "dir1", "dir2", "dir3");
// if needed
String textPath = path.toString(); // "C:\\dir1\\dir2\\dir3"
Here is a function that I use (slightly redacted). It allows input and output parameters. I only have uniqueidentifier and varchar types implemented, but any other types are easy to add. If you use parameterized stored procedures (or just parameterized sql...this code is easily adapted to that), this will make your life a lot easier.
To call the function, you need a connection to the SQL server (say $conn),
$res=exec-storedprocedure -storedProcName 'stp_myProc' -parameters @{Param1="Hello";Param2=50} -outparams @{ID="uniqueidentifier"} $conn
retrieve proc output from returned object
$res.data #dataset containing the datatables returned by selects
$res.outputparams.ID #output parameter ID (uniqueidentifier)
The function:
function exec-storedprocedure($storedProcName,
[hashtable] $parameters=@{},
[hashtable] $outparams=@{},
$conn,[switch]$help){
function put-outputparameters($cmd, $outparams){
foreach($outp in $outparams.Keys){
$cmd.Parameters.Add("@$outp", (get-paramtype $outparams[$outp])).Direction=[System.Data.ParameterDirection]::Output
}
}
function get-outputparameters($cmd,$outparams){
foreach($p in $cmd.Parameters){
if ($p.Direction -eq [System.Data.ParameterDirection]::Output){
$outparams[$p.ParameterName.Replace("@","")]=$p.Value
}
}
}
function get-paramtype($typename,[switch]$help){
switch ($typename){
'uniqueidentifier' {[System.Data.SqlDbType]::UniqueIdentifier}
'int' {[System.Data.SqlDbType]::Int}
'xml' {[System.Data.SqlDbType]::Xml}
'nvarchar' {[System.Data.SqlDbType]::NVarchar}
default {[System.Data.SqlDbType]::Varchar}
}
}
if ($help){
$msg = @"
Execute a sql statement. Parameters are allowed.
Input parameters should be a dictionary of parameter names and values.
Output parameters should be a dictionary of parameter names and types.
Return value will usually be a list of datarows.
Usage: exec-query sql [inputparameters] [outputparameters] [conn] [-help]
"@
Write-Host $msg
return
}
$close=($conn.State -eq [System.Data.ConnectionState]'Closed')
if ($close) {
$conn.Open()
}
$cmd=new-object system.Data.SqlClient.SqlCommand($sql,$conn)
$cmd.CommandType=[System.Data.CommandType]'StoredProcedure'
$cmd.CommandText=$storedProcName
foreach($p in $parameters.Keys){
$cmd.Parameters.AddWithValue("@$p",[string]$parameters[$p]).Direction=
[System.Data.ParameterDirection]::Input
}
put-outputparameters $cmd $outparams
$ds=New-Object system.Data.DataSet
$da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
[Void]$da.fill($ds)
if ($close) {
$conn.Close()
}
get-outputparameters $cmd $outparams
return @{data=$ds;outputparams=$outparams}
}
You should set body
and html
to position:fixed;
, and then set right:
, left:
, top:
, and bottom:
to 0;
. That way, even if content overflows it will not extend past the limits of the viewport.
For example:
<html>
<body>
<div id="wrapper"></div>
</body>
</html>
CSS:
html, body, {
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
}
Caveat: Using this method, if the user makes their window smaller, content will be cut off.
In Mac there is a fast method with brew:
brew search node
You see some version, for example: node@10 node@12 ... Then
brew unlink node
And now select a before version for example node@12
brew link --overwrite --force node@12
Ready, you have downgraded you node version.
Copy the .war file (E.g.: prj.war) to %CATALINA_HOME%\webapps
( E.g.: C:\tomcat\webapps )
Run %CATALINA_HOME%\bin\startup.bat
Your .war file will be extracted automatically to a folder that has the same name (without extension) (E.g.: prj)
Go to %CATALINA_HOME%\conf\server.xml
and take the port for the HTTP protocol. <Connector port="8080" ... />
. The default value is 8080.
Access the following URL:
[<protocol>://]localhost:<port>/folder/resourceName
(E.g.: localhost:8080/folder/resourceName
)
Don't try to access the URL without the resourceName
because it won't work if there is no file like index.html
, or if there is no url pattern like "/
" or "/*
" in web.xml.
The available main paths are here: [<protocol>://]localhost:<port>/manager/html
(E.g.: http://localhost:8080/manager/html
) and they have true
on the "Running" column.
Go to [<protocol>://]localhost:<port>/manager/html/
(usually localhost:8080/manager/html/
)
This is also achievable from [<protocol>://]localhost:<port>
> Manager App)
If you get:
403 Access Denied
go to %CATALINA_HOME%\conf\tomcat-users.xml
and check that you have enabled a line like this:
<user username="tomcat" password="tomcat" roles="tomcat,role1,manager-gui"/>
In the Deploy section, WAR file to deploy subsection, click on Browse....
Select the .war file (E.g.: prj.war) > click on Deploy.
At first glance one really wants to use New-PSDrive
supplying it credentials.
> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user
New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.
The documentation states that you can provide a PSCredential
object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.
Therefore you can either use net use
or the WScript.Network
object, calling the MapNetworkDrive
function:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")
Apparently with newer versions of PowerShell, the New-PSDrive
cmdlet works to map network shares with credentials!
New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist
Just a fyi for people enabling mod_rewrite on Debian with Apache2:
To check whether mod_rewrite is enabled:
Look in mods_enabled for a link to the module by running
ls /etc/apache2/mods-enabled | grep rewrite
If this outputs rewrite.load
then the module is enabled. (Note: your path to apache2 may not be /etc/, though it's likely to be.)
To enable mod_rewrite if it's not already:
Enable the module (essentially creates the link we were looking for above):
a2enmod rewrite
Reload all apache config files:
service apache2 restart
<script type="text/javascript">
<!--
function newPage(num) {
var url=new Array();
url[0]="http://www.htmlforums.com";
url[1]="http://www.codingforums.com.";
url[2]="http://www.w3schools.com";
url[3]="http://www.webmasterworld.com";
window.location=url[num];``
}
// -->
</script>
</head>
<body>
<form action="#">
<div id="container">
<input class="butts" type="button" value="htmlforums" onclick="newPage(0)"/>
<input class="butts" type="button" value="codingforums" onclick="newPage(1)"/>
<input class="butts" type="button" value="w3schools" onclick="newPage(2)"/>
<input class="butts" type="button" value="webmasterworld" onclick="newPage(3)"/>
</div>
</form>
</body>
Here's the other way, it's simpler than the other one.
<input id="inp" type="button" value="Home Page" onclick="location.href='AdminPage.jsp';" />
It's simpler.
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
For Finding All the ChildNodes you can use the below Snippet
List<WebElement> childs = MyCurrentWebElement.findElements(By.xpath("./child::*"));
for (WebElement e : childs)
{
System.out.println(e.getTagName());
}
Note that this will give all the Child Nodes at same level -> Like if you have structure like this :
<Html>
<body>
<div> ---suppose this is current WebElement
<a>
<a>
<img>
<a>
<img>
<a>
It will give me tag names of 3 anchor tags here only . If you want all the child Elements recursively , you can replace the above code with MyCurrentWebElement.findElements(By.xpath(".//*"));
Hope That Helps !!
if ( condition ) {
return;
}
The return
exits the function returning undefined
.
The exit
statement doesn't exist in javascript.
The break
statement allows you to exit a loop, not a function. For example:
var i = 0;
while ( i < 10 ) {
i++;
if ( i === 5 ) {
break;
}
}
This also works with the for
and the switch
loops.
This work for me
Demo: jsfiddle
$(function()
{
Fixed_Header();
});
function Fixed_Header()
{
$('.User_Table thead').css({'position': 'absolute'});
$('.User_Table tbody tr:eq("2") td').each(function(index,e){
$('.User_Table thead tr th:eq("'+index+'")').css({'width' : $(this).outerWidth() +"px" });
});
var Header_Height = $('.User_Table thead').outerHeight();
$('.User_Table thead').css({'margin-top' : "-"+Header_Height+"px"});
$('.User_Table').css({'margin-top' : Header_Height+"px"});
}
As previously mentioned, the FileSystem and File APIs, along with the FileWriter API, can be used to read and write files from the context of a browser tab/window to a client machine.
There are several things pertaining to the FileSystem and FileWriter APIs which you should be aware of, some of which were mentioned, but are worth repeating:
Here are simple examples of how the APIs are used, directly and indirectly, in tandem to do these things:
Write file:
bakedGoods.set({
data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
Read file:
bakedGoods.get({
data: ["testFile"],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(resultDataObj, byStorageTypeErrorObj){}
});
Using the raw File, FileWriter, and FileSystem APIs
Write file:
function onQuotaRequestSuccess(grantedQuota)
{
function saveFile(directoryEntry)
{
function createFileWriter(fileEntry)
{
function write(fileWriter)
{
var dataBlob = new Blob(["Hello world!"], {type: "text/plain"});
fileWriter.write(dataBlob);
}
fileEntry.createWriter(write);
}
directoryEntry.getFile(
"testFile",
{create: true, exclusive: true},
createFileWriter
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
Read file:
function onQuotaRequestSuccess(grantedQuota)
{
function getfile(directoryEntry)
{
function readFile(fileEntry)
{
function read(file)
{
var fileReader = new FileReader();
fileReader.onload = function(){var fileData = fileReader.result};
fileReader.readAsText(file);
}
fileEntry.file(read);
}
directoryEntry.getFile(
"testFile",
{create: false},
readFile
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
Though the FileSystem and FileWriter APIs are no longer on the standards track, their use can be justified in some cases, in my opinion, because:
Whether "some cases" encompasses your own, however, is for you to decide.
*BakedGoods is maintained by none other than this guy right here :)
if tableFields
is an array , you can loop through elements as following :
for (item in tableFields); {
console.log(tableFields[item]);
}
by the way i saw a logical error in you'r code.just remove ;
from end of for loop
right here :
for (item in tableFields); {
.
this will cause you'r loop to do just nothing.and the following line will be executed only once :
// Do stuff
If the selector is contained within a variable, the code below may be helpful:
selector_name = $this.attr('name');
//selector_name = users[0][first:name]
escaped_selector_name = selector_name.replace(/(:|\.|\[|\])/g,'\\$1');
//escaped_selector_name = users\\[0\\]\\[first\\:name\\]
In this case we prefix all special characters with double backslash.
Use the preprocessor #
operator:
#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);
A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.
IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).
A Double
in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double
object.
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
print(myInt.runtimeType);
var myDouble = double.parse('123.45');
assert(myInt is double);
print(myDouble); // 123.45
print(myDouble.runtimeType);
I was facing the same problem all the time the only solution I figurae out is typing CONSUMER_KEY
and CONSUMER_SECRET
directly to new TwitterOAuth class defination .
$connection = new TwitterOAuth( "MY_CK" , "MY_CS" );
Don't use variable or statics on this and see if the issue sloved .
I think that .Net Framework does this automatically but just in case. First, make sure to select what you want to erase, and then call the garbage collector:
randomClass object1 = new randomClass
...
...
// Give a null value to the code you want to delete
object1 = null;
// Then call the garbage collector to erase what you gave the null value
GC.Collect();
I think that's it.. Hope I help someone.
since the data ex1221new was not given, so I have created a dummy data and added it to a data frame. Also, the question which was asked has few changes in codes like then ggplot package has deprecated the use of
"scale_area()" and nows uses scale_size_area()
"opts()" has changed to theme()
In my answer,I have stored the plot in mygraph variable and then I have used
mygraph$labels$x="Discharge of materials" #changes x axis title
mygraph$labels$y="Area Affected" # changes y axis title
And the work is done. Below is the complete answer.
install.packages("Sleuth2")
library(Sleuth2)
library(ggplot2)
ex1221new<-data.frame(Discharge<-c(100:109),Area<-c(120:129),NO3<-seq(2,5,length.out = 10))
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
mygraph<-p + geom_point(aes(size= nitrogen)) +
scale_size_area() + ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")+
theme(
plot.title = element_text(color="Blue", size=30, hjust = 0.5),
# change the styling of both the axis simultaneously from this-
axis.title = element_text(color = "Green", size = 20, family="Courier",)
# you can change the axis title from the code below
mygraph$labels$x="Discharge of materials" #changes x axis title
mygraph$labels$y="Area Affected" # changes y axis title
mygraph
Also, you can change the labels title from the same formula used above -
mygraph$labels$size= "N2" #size contains the nitrogen level
Alright so I guess the thing to do is add my answer here to this long list versus creating a duplicate question...
If you are getting this in 2019, using .NET Core 3.0 (Preview at this time), the solution is to ensure all projects are targeting the same .NET Core version (in my case 3.0). I think I had one project in the solution targeting 2.1 and the rest were 2.2 so I probably could have stuck with 2.2...
I don't even have Newtonsoft.Json installed in any of the projects, and naturally adding it to them did not fix the issue.
If you have .NET Standard class libraries or w/e in your solution, they don't need to be on the same version, though they should probably be the latest you can go. For example, my .NET Standard class libraries are on 2.2 as there is not a .NET Standard 3.0 yet.
$('#toptitle').html('New world');
or
$('#toptitle').text('New world');
I had a similar problem setting up eclipse.
I changed: NATIVE connection to MANUAL and cleared the proxy settings for SOCKS in Windows
-> Preferences
-> General
-> Network connection
. That fixed the problem for me.
LIFO is the way browser parses CSS properties..If you are using Sass declare a variable called as
"$header-background: red;"
use it instead of directly assigning values like red or blue. When you want to override just reassign the value to
"$header-background:blue"
then
background-color:$header-background;
it should smoothly override. Using "!important" is not always the right choice..Its just a hotfix
Do you need to do it from mgmt studio? Here's how we do it from cmd line:
"C:\Program Files\Microsoft SQL Server\MSSQL\Binn\TEXTCOPY.exe" /S < Server> /D < DataBase> /T mytable /C mypictureblob /F "C:\picture.png" /W"where RecId=" /I
You can do as the example on Mozilla docs:
document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
P.S
Of course, there will be an issue if humanity still uses your code on the first minute of year 10000 :)
I would suggest to use CSS over jquery ( if possible) otherwise you can use something like this
$("div.myclass").hover(function() {
$(this).css("background-color","red")
});
You can change your selector as per your need.
As commented by @A.Wolff, If you want to use this hover effect to multiple classes, you can use it like this
$(".myclass, .myclass2").hover(function(e) {
$(this).css("background-color",e.type === "mouseenter"?"red":"transparent")
})
This is super old, but I figured I'd add my 2c. DATE_FORMAT
does indeed return a string, but I was looking for the CAST
function, in the situation that I already had a datetime string in the database and needed to pattern match against it:
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
In this case, you'd use:
CAST(date_value AS char)
This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.
Posix governs interoperability, portability, and in other areas such as the usage and mechanism of fork, permissions and filesystem standards such as /etc, /var, /usr and so on . Hence, when developers write a program under a Posix compliant system such as for example Linux, it is generally, not always, guaranteed to run on another posix compliant system such as IBM's AIX system or other commercial variants of Unix. Posix is a good thing to have as such it eases the software development for maximum portability which it strives for. Hope this answer makes sense.
Thanks to Jed Smith & Tinkertim for pointing out my error - my bad!!! :(
Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).
If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.
For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.
For example:
Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table
Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.
Changes to Enterprise App Distribution Coming in iOS 9
iOS 9 introduces a new feature to help protect users from installing in-house apps from untrusted sources. While no new app signing or provisioning methods are required, the way your enterprise users manage in-house apps installed on their iOS 9 devices will change.
In-house apps installed using an MDM solution are explicitly trusted and will no longer prompt the user to trust the developer that signed and provisioned the app. If your enterprise app does not use an MDM solution, users who install your app for the first time will be prompted to trust the developer. All users who install your app for the first time will need an internet connection.
Using a new restriction, organizations can limit the apps installed on their devices to the in-house apps that they create. And a new interface in Settings allows users to see all enterprise apps installed from their organization.
Source: Official email sent from [email protected] to existing enterprise app developers.
I had same problem as yours, but my concern was list view. When i try to scroll list view fixed header also scroll little bit. Problem was list view height smaller than viewport (browser) height. You just need to reduce your viewport height lower than content tag (list view within content tag) height. Here is my meta tag;
<meta name="viewport" content="width=device-width,height=90%, user-scalable = no">
Hope this will help.Thnks.
Using getcwd()
to extract in the same directory
<?php
$unzip = new ZipArchive;
$out = $unzip->open('wordpress.zip');
if ($out === TRUE) {
$unzip->extractTo(getcwd());
$unzip->close();
echo 'File unzipped';
} else {
echo 'Error';
}
?>