I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr
), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:
```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```
Then all the images will be written as PDF files, and LaTeX will be happy.
Your second problem is you are mixing up the HTML units with LaTeX units in out.width
/ out.height
. LaTeX and HTML are very different technologies. You should not expect \maxwidth
to work in HTML, or 200px
in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width
/ out.height
(use fig.width
/ fig.height
and let LaTeX use the original size).
I have reformatted your slow sql query with www.prettysql.net
SELECT *
FROM some_table
WHERE
relevant_field in
(
SELECT relevant_field
FROM some_table
GROUP BY relevant_field
HAVING COUNT ( * ) > 1
);
When using a table in both the query and the subquery, you should always alias both, like this:
SELECT *
FROM some_table as t1
WHERE
t1.relevant_field in
(
SELECT t2.relevant_field
FROM some_table as t2
GROUP BY t2.relevant_field
HAVING COUNT ( t2.relevant_field ) > 1
);
Does that help?
A note for people who created the local copy on Windows and want to create a corresponding remote repository on a Unix-line system, where text files get LF endings on further clones by developers on Unix-like systems, but CRLF endings on Windows.
If you created your Windows repository before setting up line-ending translation then you have a problem. Git's default setting is no translation, so your working set uses CRLF but your repository (i.e. the data stored under .git) has saved the files as CRLF too.
When you push to the remote, the saved files are copied as-is, no line ending translation occurs. (Line ending translation occurs when files are commited to a repository, not when repositories are pushed). You end up with CRLF in your Unix-like repository, which is not what you want.
To get LF in the remote repository you have to make sure LF is in the local repository first, by re-normalizing your Windows repository. This will have no visible effect on your Windows working set, which still has CRLF endings, however when you push to remote, the remote will get LF correctly.
I'm not sure if there's an easy way to tell what line endings you have in your Windows repository - I guess you could test it by setting core.autocrlf=false and then cloning (If the repo has LF endings, the clone will have LF too).
Here is an idea as you may have multiple newline in a textbox:
var text=document.getElementById('post-text').value.split('\n');
var html = text.join('<br />');
This HTML value will preserve newline. Hope this helps.
Following are the results when we use both [MaxLength]
and [StringLength]
attributes, in EF code first
. If both are used, [MaxLength]
wins the race. See the test result in studentname
column in below class
public class Student
{
public Student () {}
[Key]
[Column(Order=1)]
public int StudentKey { get; set; }
//[MaxLength(50),StringLength(60)] //studentname column will be nvarchar(50)
//[StringLength(60)] //studentname column will be nvarchar(60)
[MaxLength(50)] //studentname column will be nvarchar(50)
public string StudentName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
plt.rcParams['figure.figsize'] = (15, 5)
BitmapFactory.decodeResource()
automatically scales the bitmap, so your bitmap may turn out fuzzy. To prevent scaling, do this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(context.getResources(),
R.drawable.resource_name, options);
or
InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
bitmap = BitmapFactory.decodeStream(is);
Try this command
msiexec /x {product-id} /qr
SELECT DISTINCT city
FROM station
WHERE city RLIKE '^[^aeiouAEIOU]'OR city RLIKE'[^aeiouAEIOU]$'
I had the same problem.
This php setting solved my problem:
allow_url_fopen -> 1
Mehrdad makes some good points, but the main thing I noticed is that you never run the query...
SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar);
retval.Direction = ParameterDirection.ReturnValue;
sqlcomm.ExecuteNonQuery(); // MISSING
string retunvalue = (string)sqlcomm.Parameters["@b"].Value;
I resolved the problem with this code:
HTML Form
<input type="checkbox" id="is-business" name="is-business" value="off" onclick="changeValueCheckbox(this)" >
<label for="is-business">Soy empresa</label>
and the javascript function by change the checkbox value form:
//change value of checkbox element
function changeValueCheckbox(element){
if(element.checked){
element.value='on';
}else{
element.value='off';
}
}
and the server checked if the data post is "on" or "off". I used playframework java
final Map<String, String[]> data = request().body().asFormUrlEncoded();
if (data.get("is-business")[0].equals('on')) {
login.setType(new MasterValue(Login.BUSINESS_TYPE));
} else {
login.setType(new MasterValue(Login.USER_TYPE));
}
Reference on PHP net:
http://php.net/manual/en/info.configuration.php#ini.max-input-vars
Please note, you cannot set this directive in run-time with function ini_set(name, newValue)
, e.g.
ini_set('max_input_vars', 3000);
It will not work.
As explained in documentation, this directive may only be set per directory scope, which means via .htaccess file, httpd.conf or .user.ini (since PHP 5.3).
See http://php.net/manual/en/configuration.changes.modes.php
Adding the directive into php.ini or placing following lines into .htaccess will work:
php_value max_input_vars 3000
php_value suhosin.get.max_vars 3000
php_value suhosin.post.max_vars 3000
php_value suhosin.request.max_vars 3000
Try passing columns of the DataFrame
directly to matplotlib, as in the examples below, instead of extracting them as numpy arrays.
df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100
In [5]: df
Out[5]:
col1 col2 col3
0 -1.000075 -0.759910 100
1 0.510382 0.972615 200
2 1.872067 -0.731010 500
3 0.131612 1.075142 1000
4 1.497820 0.237024 1700
plt.scatter(df.col1, df.col2, s=df.col3)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=df.col3)
colors = np.where(df.col3 > 300, 'r', 'k')
plt.scatter(df.col1, df.col2, s=120, c=colors)
# OR (with pandas 0.13 and up)
df.plot(kind='scatter', x='col1', y='col2', s=120, c=colors)
However, the easiest way I've found to create a scatter plot with legend is to call plt.scatter
once for each point type.
cond = df.col3 > 300
subset_a = df[cond].dropna()
subset_b = df[~cond].dropna()
plt.scatter(subset_a.col1, subset_a.col2, s=120, c='b', label='col3 > 300')
plt.scatter(subset_b.col1, subset_b.col2, s=60, c='r', label='col3 <= 300')
plt.legend()
From what I can tell, matplotlib simply skips points with NA x/y coordinates or NA style settings (e.g., color/size). To find points skipped due to NA, try the isnull
method: df[df.col3.isnull()]
To split a list of points into many types, take a look at numpy select
, which is a vectorized if-then-else implementation and accepts an optional default value. For example:
df['subset'] = np.select([df.col3 < 150, df.col3 < 400, df.col3 < 600],
[0, 1, 2], -1)
for color, label in zip('bgrm', [0, 1, 2, -1]):
subset = df[df.subset == label]
plt.scatter(subset.col1, subset.col2, s=120, c=color, label=str(label))
plt.legend()
For not looping this worked for me-
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
I've solved it all here - Entity Framework children serialization with .Net Core 2 WebAPI https://gist.github.com/Kaidanov/f9ad0d79238494432f32b8407942c606
Will appreciate any remarks. maybe someone can use it sometime.
As documented under CREATE TABLE
Syntax:
Note
The olderTYPE
option was synonymous withENGINE
.TYPE
was deprecated in MySQL 4.0 and removed in MySQL 5.5. When upgrading to MySQL 5.5 or later, you must convert existing applications that rely onTYPE
to useENGINE
instead.
Therefore, you want:
CREATE TABLE dave_bannedwords(
id INT(11) NOT NULL AUTO_INCREMENT,
word VARCHAR(60) NOT NULL DEFAULT '',
PRIMARY KEY (id),
KEY id(id) -- this is superfluous in the presence of your PK, ergo unnecessary
) ENGINE = MyISAM ;
ECMAScript is a standard for JavaScript, look at these statements from MDN:
JavaScript (JS) is a lightweight interpreted or JIT-compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as node.js, Apache CouchDB and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles. Read more about JavaScript.
The standard for JavaScript is ECMAScript. As of 2012, all modern browsers fully support ECMAScript 5.1. Older browsers support at least ECMAScript 3. On June 17, 2015, ECMA International published the sixth major version of ECMAScript, which is officially called ECMAScript 2015, and was initially referred to as ECMAScript 6 or ES6. Since then, ECMAScript standards are on yearly release cycles. This documentation refers to the latest draft version, which is currently ECMAScript 2018.
For more info, visit here
You have 2 options, as described bellow:
Distribution package like Glaslos suggested:
# sudo apt-get install python-mysqldb
In this case you can't use virtualenv no-site-packages (default option) but must use:
# virtualenv --system-site-packages myenv
Use clean virtualenv and build your own python-mysql package.
First create virtualenv:
# virtualenv myvirtualenv
# source myvirtualenv/bin/activate
Then install build dependencies:
# sudo apt-get build-dep python-mysqldb
Now you can install python-mysql
# pip install mysql-python
NOTE Ubuntu package is python-mysql*db* , python pypi package is python-mysql (without db)
You can do it without dealing with encoding by using BlockCopy:
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
Update
There is a better write up if this is confusing people; check out finding documents and how queries work in the mongoose manual. If you want to use the fluent api you can get a query object by not providing a callback to the find()
method, otherwise you can specify the parameters as I outline below.
Original
Given a model
object, per the docs on Model, this is how it can work for 2.4.1
:
Post.find({search-spec}, [return field array], {options}, callback)
The search spec
expects an object, but you can pass null
or an empty object.
The second param is the field list as an array of strings, so you would supply ['field','field2']
or null
.
The third param is the options as an object, which includes the ability to sort the result set. You would use { sort: { field: direction } }
where field
is the string fieldname test
(in your case) and direction
is a number where 1
is ascending and -1
is desceding.
The final param (callback
) is the callback function which receives the collection of docs returned by the query.
The Model.find()
implementation (at this version) does a sliding allocation of properties to handle optional params (which is what confused me!):
Model.find = function find (conditions, fields, options, callback) {
if ('function' == typeof conditions) {
callback = conditions;
conditions = {};
fields = null;
options = null;
} else if ('function' == typeof fields) {
callback = fields;
fields = null;
options = null;
} else if ('function' == typeof options) {
callback = options;
options = null;
}
var query = new Query(conditions, options).select(fields).bind(this, 'find');
if ('undefined' === typeof callback)
return query;
this._applyNamedScope(query);
return query.find(callback);
};
HTH
$('#' + id).is(":checked")
That gets if the checkbox is checked.
For an array of checkboxes with the same name you can get the list of checked ones by:
var $boxes = $('input[name=thename]:checked');
Then to loop through them and see what's checked you can do:
$boxes.each(function(){
// Do stuff here with this
});
To find how many are checked you can do:
$boxes.length;
personally I favor validating without a callback:
public bool ValidateSchema(string xmlPath, string xsdPath)
{
XmlDocument xml = new XmlDocument();
xml.Load(xmlPath);
xml.Schemas.Add(null, xsdPath);
try
{
xml.Validate(null);
}
catch (XmlSchemaValidationException)
{
return false;
}
return true;
}
(see Timiz0r's post in Synchronous XML Schema Validation? .NET 3.5)
Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models. Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.
More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize
The snippets to save & load can be found below:
model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')
# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')
A sample output of this :
16 bit installer will not work on windows 7 it's no longer supported by win 7 the most recent supported version of windows that can run 16 bit installer is vista 32-bit even vista 64-bit doesn't support 16-bit installer.... reference http://support.microsoft.com/kb/946765
noexcept
can dramatically improve performance of some operations. This does not happen at the level of generating machine code by the compiler, but by selecting the most effective algorithm: as others mentioned, you do this selection using function std::move_if_noexcept
. For instance, the growth of std::vector
(e.g., when we call reserve
) must provide a strong exception-safety guarantee. If it knows that T
's move constructor doesn't throw, it can just move every element. Otherwise it must copy all T
s. This has been described in detail in this post.
You can add any Git repository (or tarball) as a dependency to yarn
by specifying the remote URL (either HTTPS or SSH):
yarn add <git remote url> installs a package from a remote git repository.
yarn add <git remote url>#<branch/commit/tag> installs a package from a remote git repository at specific git branch, git commit or git tag.
yarn add https://my-project.org/package.tgz installs a package from a remote gzipped tarball.
Here are some examples:
yarn add https://github.com/fancyapps/fancybox [remote url]
yarn add ssh://github.com/fancyapps/fancybox#3.0 [branch]
yarn add https://github.com/fancyapps/fancybox#5cda5b529ce3fb6c167a55d42ee5a316e921d95f [commit]
(Note: Fancybox v2.6.1 isn't available in the Git version.)
To support both npm and yarn, you can use the git+url syntax:
git+https://github.com/owner/package.git#commithashortagorbranch
git+ssh://github.com/owner/package.git#commithashortagorbranch
Today you can select elements with the same id attribute this way:
document.querySelectorAll('[id=test]');
Or this way with jQuery:
$('[id=test]');
CSS selector #test { ... }
should work also for all elements with id = "test"
. ?ut the only thing: document.querySelectorAll('#test')
(or $('#test')
) - will return only a first element with this id.
Is it good, or not - I can't tell . But sometimes it is difficult to follow unique id standart .
For example you have the comment widget, with HTML-ids, and JS-code, working with these HTML-ids. Sooner or later you'll need to render this widget many times, to comment a different objects into a single page: and here the standart will broken (often there is no time or not allow - to rewrite built-in code).
You could do this:
NSNumberFormatter* f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setFormat:@0.00"];
// test
NSNumber* a = @12;
NSString* s = [f stringFromNumber:a];
NSLog(@"%@", s);
When I added IIS_IUSRS permission to site folder - resources, like js and css, still were unaccessible (error 401, forbidden). However, when I added IUSR - it became ok. So for sure "you CANNOT remove the permissions for IUSR without worrying", dear @Travis G@
(And if you have no admin access to the server)
ALTER ROLE <your_login_role> SET search_path TO a,b,c;
Two important things to know about:
a, b, c
matters, as it is also the order in which the schemas will be looked up for tables. So if you have the same table name in more than one schema among the defaults, there will be no ambiguity, the server will always use the table from the first schema you specified for your search_path
.The size of the pointer may be something different than that of int
. Also an implementation could produce better than simple hex value representation of the address when you use %p
.
Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:
json: cannot unmarshal object into Go struct field Comment.author of type string
You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.
It should look like that :
#!/usr/bin/env python
or the real path
#!/usr/bin/python
You should also check the file have the right to be execute. chmod +x file.py
As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)
I have created function to disable previous date, disable flexible weekend days (Like Saturday, Sunday)
We are using beforeShowDay method of jQuery UI datepicker plugin.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
var NotBeforeToday = function(date) {_x000D_
var now = new Date(); //this gets the current date and time_x000D_
if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() >= now.getDate() && (date.getDay() > 0 && date.getDay() < 6) )_x000D_
return [true,""];_x000D_
if (date.getFullYear() >= now.getFullYear() && date.getMonth() > now.getMonth() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
return [true,""];_x000D_
if (date.getFullYear() > now.getFullYear() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
return [true,""];_x000D_
return [false,""];_x000D_
}_x000D_
_x000D_
_x000D_
jQuery("#datepicker").datepicker({_x000D_
beforeShowDay: NotBeforeToday_x000D_
});
_x000D_
Here today's date is 15th Sept. I have disabled Saturday and Sunday.
For a bit of facts here is the relevant text from the specifications
Pointers to objects of the same type can be compared for equality with the 'intuitive' expected results:
From § 5.10 of the C++11 standard:
Pointers of the same type (after pointer conversions) can be compared for equality. Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address (3.9.2).
(leaving out details on comparison of pointers to member and or the null pointer constants - they continue down the same line of 'Do What I Mean':)
- [...] If both operands are null, they compare equal. Otherwise if only one is null, they compare unequal.[...]
The most 'conspicuous' caveat has to do with virtuals, and it does seem to be the logical thing to expect too:
- [...] if either is a pointer to a virtual member function, the result is unspecified. Otherwise they compare equal if and only if they would refer to the same member of the same most derived object (1.8) or the same subobject if they were dereferenced with a hypothetical object of the associated class type. [...]
From § 5.9 of the C++11 standard:
Pointers to objects or functions of the same type (after pointer conversions) can be compared, with a result defined as follows:
- If two pointers p and q of the same type point to the same object or function, or both point one past the end of the same array, or are both null, then
p<=q
andp>=q
both yield true andp<q
andp>q
both yield false.- If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of
p<q,
p>q,
p<=q,
andp>=q
are unspecified.- If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, recursively, the pointer to the later declared member compares greater provided the two members have the same access control (Clause 11) and provided their class is not a union.
- If two pointers point to non-static data members of the same object with different access control (Clause 11) the result is unspecified.
- If two pointers point to non-static data members of the same union object, they compare equal (after conversion to
void*
, if necessary). If two pointers point to elements of the same array or one beyond the end of the array, the pointer to the object with the higher subscript compares higher.- Other pointer comparisons are unspecified.
So, if you had:
int arr[3];
int *a = arr;
int *b = a + 1;
assert(a != b); // OK! well defined
Also OK:
struct X { int x,y; } s;
int *a = &s.x;
int *b = &s.y;
assert(b > a); // OK! well defined
But it depends on the something
in your question:
int g;
int main()
{
int h;
int i;
int *a = &g;
int *b = &h; // can't compare a <=> b
int *c = &i; // can't compare b <=> c, or a <=> c etc.
// but a==b, b!=c, a!=c etc. are supported just fine
}
§ 20.8.5/8: "For templates greater
, less
, greater_equal
, and less_equal
, the specializations for any pointer type yield a total order, even if the built-in operators <
, >
, <=
, >=
do not."
So, you can globally order any odd void*
as long as you use std::less<>
and friends, not bare operator<
.
This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)
targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value
' Close customer workbook
customerWorkbook.Close
In addition to @Aleksandr Tukallo's answer, you could also obtain the output and error message (if occurs). Compressing a folder using tar
is explained pretty well on the following answer.
import traceback
import subprocess
try:
cmd = ['tar', 'czfj', output_filename, file_to_archive]
output = subprocess.check_output(cmd).decode("utf-8").strip()
print(output)
except Exception:
print(f"E: {traceback.format_exc()}")
Node.js
itself offers an HTTP module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server
prototype.
I also encounter with that problem. In my case the problem was that i closed the scanner inside one of the funcs..
public class Main _x000D_
{_x000D_
public static void main(String[] args) _x000D_
{_x000D_
Scanner menu = new Scanner(System.in);_x000D_
boolean exit = new Boolean(false);_x000D_
while(!exit){_x000D_
String choose = menu.nextLine();_x000D_
Part1 t=new Part1()_x000D_
t.start();_x000D_
System.out.println("Noooooo Come back!!!"+choose);_x000D_
}_x000D_
menu.close();_x000D_
}_x000D_
}_x000D_
_x000D_
public class Part1 extends Thread _x000D_
{_x000D_
public void run()_x000D_
{ _x000D_
Scanner s = new Scanner(System.in);_x000D_
String st = s.nextLine();_x000D_
System.out.print("bllaaaaaaa\n"+st);_x000D_
s.close();_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
The code above made the same exaption, the solution was to close the scanner only once at the main.
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
The way to do this to take your nested target array and copy it in single step to a non-nested array. Delete the key(s) and then assign the final trimmed array to the nested node of the earlier array. Here is a code to make it simple:
$temp_array = $list['resultset'][0];
unset($temp_array['badkey1']);
unset($temp_array['badkey2']);
$list['resultset'][0] = $temp_array;
Yes, that is supported.
Check the documentation provided here for the supported keywords inside method names.
You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:
List<Inventory> findByIdIn(List<Long> ids);
I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:
The Entity
@Entity
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
// other fields
// getters/setters
}
The Repository
@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {
List<Inventory> findByIdIn(List<Long> ids);
}
"Add a reference to MySql.Data.dll" means you need to add a library reference to the downloaded connector. The IDE will link the database connection library with your application when it compiles.
I downloaded the binary (no installer) zip package from the MySQL web site, extracted onto the desktop, and did the following:
using MySql.Data.MySqlClient;
. If you've added the reference correctly, IntelliSense should offer to complete this for you.After searching for best implementation how to get best precise user location I managed to combine all the best methods and come up with following class:
/**
* Retrieve accurate location from GPS or network services.
*
*
* Class usage example:
*
* public void onCreate(Bundle savedInstanceState) {
* ...
* my_location = new MyLocation();
* my_location.init(main.this, locationResult);
* }
*
*
* public LocationResult locationResult = new LocationResult(){
* @Override
* public void gotLocation(final Location location){
* // do something
* location.getLongitude();
* location.getLatitude();
* }
* };
*/
class MyLocation{
/**
* If GPS is enabled.
* Use minimal connected satellites count.
*/
private static final int min_gps_sat_count = 5;
/**
* Iteration step time.
*/
private static final int iteration_timeout_step = 500;
LocationResult locationResult;
private Location bestLocation = null;
private Handler handler = new Handler();
private LocationManager myLocationManager;
public Context context;
private boolean gps_enabled = false;
private int counts = 0;
private int sat_count = 0;
private Runnable showTime = new Runnable() {
public void run() {
boolean stop = false;
counts++;
System.println("counts=" + counts);
//if timeout (1 min) exceeded, stop tying
if(counts > 120){
stop = true;
}
//update last best location
bestLocation = getLocation(context);
//if location is not ready or don`t exists, try again
if(bestLocation == null && gps_enabled){
System.println("BestLocation not ready, continue to wait");
handler.postDelayed(this, iteration_timeout_step);
}else{
//if best location is known, calculate if we need to continue to look for better location
//if gps is enabled and min satellites count has not been connected or min check count is smaller then 4 (2 sec)
if(stop == false && !needToStop()){
System.println("Connected " + sat_count + " sattelites. continue waiting..");
handler.postDelayed(this, iteration_timeout_step);
}else{
System.println("#########################################");
System.println("BestLocation finded return result to main. sat_count=" + sat_count);
System.println("#########################################");
// removing all updates and listeners
myLocationManager.removeUpdates(gpsLocationListener);
myLocationManager.removeUpdates(networkLocationListener);
myLocationManager.removeGpsStatusListener(gpsStatusListener);
sat_count = 0;
// send best location to locationResult
locationResult.gotLocation(bestLocation);
}
}
}
};
/**
* Determine if continue to try to find best location
*/
private Boolean needToStop(){
if(!gps_enabled){
return true;
}
else if(counts <= 4){
return false;
}
if(sat_count < min_gps_sat_count){
//if 20-25 sec and 3 satellites found then stop
if(counts >= 40 && sat_count >= 3){
return true;
}
return false;
}
}
return true;
}
/**
* Best location abstract result class
*/
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
/**
* Initialize starting values and starting best location listeners
*
* @param Context ctx
* @param LocationResult result
*/
public void init(Context ctx, LocationResult result){
context = ctx;
locationResult = result;
myLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = (Boolean) myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
bestLocation = null;
counts = 0;
// turning on location updates
myLocationManager.requestLocationUpdates("network", 0, 0, networkLocationListener);
myLocationManager.requestLocationUpdates("gps", 0, 0, gpsLocationListener);
myLocationManager.addGpsStatusListener(gpsStatusListener);
// starting best location finder loop
handler.postDelayed(showTime, iteration_timeout_step);
}
/**
* GpsStatus listener. OnChainged counts connected satellites count.
*/
public final GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {
public void onGpsStatusChanged(int event) {
if(event == GpsStatus.GPS_EVENT_SATELLITE_STATUS){
try {
// Check number of satellites in list to determine fix state
GpsStatus status = myLocationManager.getGpsStatus(null);
Iterable<GpsSatellite>satellites = status.getSatellites();
sat_count = 0;
Iterator<GpsSatellite>satI = satellites.iterator();
while(satI.hasNext()) {
GpsSatellite satellite = satI.next();
System.println("Satellite: snr=" + satellite.getSnr() + ", elevation=" + satellite.getElevation());
sat_count++;
}
} catch (Exception e) {
e.printStackTrace();
sat_count = min_gps_sat_count + 1;
}
System.println("#### sat_count = " + sat_count);
}
}
};
/**
* Gps location listener.
*/
public final LocationListener gpsLocationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location){
}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status, Bundle extras){}
};
/**
* Network location listener.
*/
public final LocationListener networkLocationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location){
}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status, Bundle extras){}
};
/**
* Returns best location using LocationManager.getBestProvider()
*
* @param context
* @return Location|null
*/
public static Location getLocation(Context context){
System.println("getLocation()");
// fetch last known location and update it
try {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
String strLocationProvider = lm.getBestProvider(criteria, true);
System.println("strLocationProvider=" + strLocationProvider);
Location location = lm.getLastKnownLocation(strLocationProvider);
if(location != null){
return location;
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
This class tries to connect to min_gps_sat_count
satellites if GPS is enabled. Else returns LocationManager.getBestProvider()
location. Check the code!
I can't find anything that deals with clock times exactly, so I'd just use some functions from package:lubridate and work with seconds-since-midnight:
require(lubridate)
clockS = function(t){hour(t)*3600+minute(t)*60+second(t)}
plot(clockS(times),val)
You might then want to look at some of the axis code to figure out how to label axes nicely.
Unless there is a specific optimization that checks if the argument passed to removeAll()
is the collection itself (and I highly doubt that such an optimization is there) it will be significantly slower than a simple .clear()
.
Apart from that (and at least equally important): arraylist.removeAll(arraylist)
is just obtuse, confusing code. It is a very backwards way of saying "clear this collection". What advantage would it have over the very understandable arraylist.clear()
?
Latest and greatest way to do this:
Node supports file and buffer operations with the base64
encoding:
const fs = require('fs');
const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});
Or using the new promises API:
const fs = require('fs').promises;
const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});
onkeyup, onpaste, onchange, oninput
seems to be failing when the browser performs autofill on the textboxes. To handle such a case include "autocomplete='off'
" in your textfield to prevent browser from autofilling the textbox,
Eg,
<input id="inputDatabaseName" autocomplete='off' onchange="check();"
onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" />
<script>
function check(){
alert("Input box changed");
// Things to do when the textbox changes
}
</script>
This situation happens because you haven't installed/start service of ASP.net.
Use below command in windows 7,8,10.
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
Another solution could be using jquery button selector inside the if else statement $("#buttonId").text("your text");
function showFilterItem() {
if (filterstatus == 0) {
filterstatus = 1;
$find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
$("#ShowButton").text("Hide Filter");
}
else {
filterstatus = 0;
$find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
$("#ShowButton").text("Show Filter");
}}
In addition to the CheckedChangedEvent wiring one could use the Controls "Tag" property to distinguish between the radio buttons... an (spaghetti code) alternative would be the "TabIndex" property ;P
First, you need to add HttpHeaders with HttpClient
import { HttpClient,HttpHeaders } from '@angular/common/http';
your constructor should be like this.
constructor(private http: HttpClient) { }
then you can use like this
let header = new HttpHeaders({ "Authorization": "Bearer "+token});
const requestOptions = { headers: header};
return this.http.get<any>(url, requestOptions)
.toPromise()
.then(data=> {
//...
return data;
});
if you use more thread ExecutionServices SEQUENTIALLY and want to wait EACH EXECUTIONSERVICE to be finished. The best way is like below;
ExecutorService executer1 = Executors.newFixedThreadPool(THREAD_SIZE1);
for (<loop>) {
executer1.execute(new Runnable() {
@Override
public void run() {
...
}
});
}
executer1.shutdown();
try{
executer1.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
ExecutorService executer2 = Executors.newFixedThreadPool(THREAD_SIZE2);
for (true) {
executer2.execute(new Runnable() {
@Override
public void run() {
...
}
});
}
executer2.shutdown();
} catch (Exception e){
...
}
Your command line should have a -d/--data inserted before the string you want to send in the PUT, and you want to set the Content-Type and not Accept.
curl -H 'Content-Type: application/json' -X PUT -d '[JSON]' \
http://example.com/service
Using the exact JSON data from the question, the full command line would become:
curl -H 'Content-Type: application/json' -X PUT \
-d '{"tags":["tag1","tag2"],
"question":"Which band?",
"answers":[{"id":"a0","answer":"Answer1"},
{"id":"a1","answer":"answer2"}]}' \
http://example.com/service
Note: JSON data wrapped only for readability, not valid for curl
request.
I think you should try this
From php5.6 to php7.1
sudo a2dismod php5.6
sudo a2enmod php7.1
sudo service apache2 restart
sudo update-alternatives --set php /usr/bin/php7.1
sudo update-alternatives --set phar /usr/bin/phar7.1
sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.1
From php7.1 to php5.6
sudo a2dismod php7.1
sudo a2enmod php5.6
sudo service apache2 restart
sudo update-alternatives --set php /usr/bin/php5.6
sudo update-alternatives --set phar /usr/bin/phar5.6
sudo update-alternatives --set phar.phar /usr/bin/phar.phar5.6
In order to build your repo after new commits, use Bitbucket Plugin.
There is just one thing to notice: When creating a POST Hook (notice that it is POST hook, not Jenkins hook), the URL works when it has a "/" in the end. Like:
URL: JENKINS_URL/bitbucket-hook/
e.g. someAddress:8080/bitbucket-hook/
Do not forget to check "Build when a change is pushed to Bitbucket" in your job configuration.
something like below
var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
friends.ForEach(a=>a.msgSentBy='1234');
db.SaveChanges();
}
you can update multiple fields as below
friends.ForEach(a =>
{
a.property1 = value1;
a.property2 = value2;
});
The options
property contains all the <options>
- from there you can look at .text
document.getElementById('test').options[0].text == 'Text One'
Zookeeper is a centralized open-source server for maintaining and managing configuration information, naming conventions and synchronization for distributed cluster environment. Zookeeper helps the distributed systems to reduce their management complexity by providing low latency and high availability. Zookeeper was initially a sub-project for Hadoop but now it's a top level independent project of Apache Software Foundation.
For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.
For example, the open function takes a buffer size argument.
http://docs.python.org/library/functions.html#open
"The optional buffering argument specifies the file’s desired buffer size:"
code:
bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)
Interestingly enough, very often len(unique())
is a few times (3x-15x) faster than nunique()
.
sometimes this error came beacause failed to compile in middlest of any build. The best way to try is by doing make clean and again make the whole code .
Try this:
$fruits = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );_x000D_
echo reset($fruits)."\n";
_x000D_
var myCallback = function(data) {
console.log('got data: '+data);
};
var usingItNow = function(callback) {
callback('get it?');
};
Now open node or browser console and paste the above definitions.
Finally use it with this next line:
usingItNow(myCallback);
With Respect to the Node-Style Error Conventions
Costa asked what this would look like if we were to honor the node error callback conventions.
In this convention, the callback should expect to receive at least one argument, the first argument, as an error. Optionally we will have one or more additional arguments, depending on the context. In this case, the context is our above example.
Here I rewrite our example in this convention.
var myCallback = function(err, data) {
if (err) throw err; // Check for the error and throw if it exists.
console.log('got data: '+data); // Otherwise proceed as usual.
};
var usingItNow = function(callback) {
callback(null, 'get it?'); // I dont want to throw an error, so I pass null for the error argument
};
If we want to simulate an error case, we can define usingItNow like this
var usingItNow = function(callback) {
var myError = new Error('My custom error!');
callback(myError, 'get it?'); // I send my error as the first argument.
};
The final usage is exactly the same as in above:
usingItNow(myCallback);
The only difference in behavior would be contingent on which version of usingItNow
you've defined: the one that feeds a "truthy value" (an Error object) to the callback for the first argument, or the one that feeds it null for the error argument.
In addition to all the other answers you received, I want to explain the unknown option -- o
error: Your command was
$ adb shell 'su -c mount -o rw,remount /system'
which calls su through adb. You properly quoted the whole su command in order to pass it as one argument to adb shell
. However, su -c <cmd>
also needs you to quote the command with arguments it shall pass to the shell's -c
option. (YMMV depending on su
variants.) Therefore, you might want to try
$ adb shell 'su -c "mount -o rw,remount /system"'
(and potentially add the actual device listed in the output of mount | grep system
before the /system
arg – see the other answers.)
If you'll check smaller than 10, you haven't to create a new function for that. Just assign a variable into brackets and return it with ternary operator.
(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`
I used the first answer, but I felt was missing a recursion in it.
The result was this:
function dump(obj) {
var out = '';
for (var i in obj) {
if(typeof obj[i] === 'object'){
dump(obj[i]);
}else{
out += i + ": " + obj[i] + "\n";
}
}
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre);
}
The problem with most of these is that the user can still scroll up and see the addressbar. To make a permanent solution, you need to add this as well.
//WHENEVER the user scrolls
$(window).scroll(function(){
//if you reach the top
if ($(window).scrollTop() == 0)
//scroll back down
{window.scrollTo(1,1)}
})
XSLT 1.0 does not have an integer data type, only double. You can use number()
to convert a string to a number.
If your using Visual Studio just run the application with Crtl + F5 instead of F5. This will leave the console open when it's finished executing.
app.manifest
should be like this:
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
</asmv1:assembly>
df.where(df.col("friend_id").isNull)
Another related tip is to use "%~1" instead of "%1". Type "CALL /?" at the command line in Windows to get more details.
You can also use 2 methods from java.time.YearMonth
( Since Java 8 ):
import java.time.YearMonth;
...
int year = YearMonth.now().getYear();
int month = YearMonth.now().getMonthValue();
echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts
the >>
appends the output of echo
to the file.
Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.
First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.
Second, it requires you to add an entry for every host name on a domain; just adding websitename.com
will not block www.websitename.com
, for example.
Another way of saying it is that the i
in your function is bound at the time of executing the function, not the time of creating the function.
When you create the closure, i
is a reference to the variable defined in the outside scope, not a copy of it as it was when you created the closure. It will be evaluated at the time of execution.
Most of the other answers provide ways to work around by creating another variable that won't change the value for you.
Just thought I'd add an explanation for clarity. For a solution, personally, I'd go with Harto's since it is the most self-explanatory way of doing it from the answers here. Any of the code posted will work, but I'd opt for a closure factory over having to write a pile of comments to explain why I'm declaring a new variable(Freddy and 1800's) or have weird embedded closure syntax(apphacker).
Here is how do it with single statement
WITH deleted_rows AS (
DELETE FROM source_table WHERE id = 1
RETURNING *
)
INSERT INTO destination_table
SELECT * FROM deleted_rows;
EXAMPLE:
postgres=# select * from test1 ;
id | name
----+--------
1 | yogesh
2 | Raunak
3 | Varun
(3 rows)
postgres=# select * from test2;
id | name
----+------
(0 rows)
postgres=# WITH deleted_rows AS (
postgres(# DELETE FROM test1 WHERE id = 1
postgres(# RETURNING *
postgres(# )
postgres-# INSERT INTO test2
postgres-# SELECT * FROM deleted_rows;
INSERT 0 1
postgres=# select * from test2;
id | name
----+--------
1 | yogesh
(1 row)
postgres=# select * from test1;
id | name
----+--------
2 | Raunak
3 | Varun
Now you can use device file explorer instead of device monitor. Go to
view > tool windows > device file explorer
screenshot: opening device file explorer in android studio 3.1.3
More details
Android Studio saves files you open this way in a temporary directory outside of your project. If you make modifications to a file you opened using the Device File Explorer, and would like to save your changes back to the device, you must manually upload the modified version of the file to the device.
screenshot: The Device File Explorer tool window
When exploring a device's files, the following directories are particularly useful:
data/data/app_name/
Contains data files for your app stored on internal storage
sdcard/
Contains user files stored on external user storage (pictures, etc.)
Note: Not all files on a hardware device are visible in the Device File Explorer. For example, in the data/data/ directory, entries corresponding to apps on the device that are not debuggable cannot be expanded in the Device File Explorer.
If you wanted to stay with a class level selector then you could do something like this (using the same jfiddle from Mahn)
$("div.fetch_results input:text").each(function() {
this.value = "testing";
})?
This will select only the text input boxes within the div with a fetch_results class.
As with any jQuery this is just one way to do it. Ask 10 jQuery people this question and you will get 12 answers.
Just to simplify the example of Tyler.
test:
-prefix is not needed.
So according to his example:
In the sbt
-console:
testOnly *LoginServiceSpec
And in the terminal:
sbt "testOnly *LoginServiceSpec"
For anyone still reading this: setTargetFragment()
has been deprecated. It is now recommended to use the FragmentResultListener
API like this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setFragmentResultListener("requestKey") { key, bundle ->
val result = bundle.getString("resultKey")
// Do something with the result...
}
...
// Somewhere show your dialog
MyDialogFragment.newInstance().show(parentFragmentManager, "tag")
}
Then in your MyDialogFragment
set the result:
button.setOnClickListener{
val result = "some string"
setFragmentResult("requestKey", bundleOf("resultKey" to result))
dismiss()
}
Using a collection initializer
From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:
var human = new Human(1, "Address", "Name") {
ContactNumbers = new List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
}
}
Specializing the Human
constructor
You can change the constructor of the Human
class to provide a way to populate the ContactNumbers
property:
public class Human
{
public Human(int id, string address, string name, IEnumerable<ContactNumber> contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
}
// Using the first constructor:
List<ContactNumber> numbers = List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
};
var human = new Human(1, "Address", "Name", numbers);
// Using the second constructor:
var human = new Human(1, "Address", "Name",
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
);
Bottom line
Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...
You can use below class to schedule your task every day particular time
package interfaces;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class CronDemo implements Runnable{
public static void main(String[] args) {
Long delayTime;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final Long initialDelay = LocalDateTime.now().until(LocalDate.now().plusDays(1).atTime(12, 30), ChronoUnit.MINUTES);
if (initialDelay > TimeUnit.DAYS.toMinutes(1)) {
delayTime = LocalDateTime.now().until(LocalDate.now().atTime(12, 30), ChronoUnit.MINUTES);
} else {
delayTime = initialDelay;
}
scheduler.scheduleAtFixedRate(new CronDemo(), delayTime, TimeUnit.DAYS.toMinutes(1), TimeUnit.MINUTES);
}
@Override
public void run() {
System.out.println("I am your job executin at:" + new Date());
}
}
Avoid hardcoding try making the code that is dynamic below is the code it will work for any xml I have used SAX Parser you can use dom,xpath it's upto you
I am storing all the tags name and values in the map after that it becomes easy to retrieve any values you want I hope this helps
SAMPLE XML:
<parent>
<child >
<child1> value 1 </child1>
<child2> value 2 </child2>
<child3> value 3 </child3>
</child>
<child >
<child4> value 4 </child4>
<child5> value 5</child5>
<child6> value 6 </child6>
</child>
</parent>
JAVA CODE:
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class saxParser {
static Map<String,String> tmpAtrb=null;
static Map<String,String> xmlVal= new LinkedHashMap<String, String>();
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, VerifyError {
/**
* We can pass the class name of the XML parser
* to the SAXParserFactory.newInstance().
*/
//SAXParserFactory saxDoc = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);
SAXParserFactory saxDoc = SAXParserFactory.newInstance();
SAXParser saxParser = saxDoc.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
String tmpElementName = null;
String tmpElementValue = null;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
tmpElementValue = "";
tmpElementName = qName;
tmpAtrb=new HashMap();
//System.out.println("Start Element :" + qName);
/**
* Store attributes in HashMap
*/
for (int i=0; i<attributes.getLength(); i++) {
String aname = attributes.getLocalName(i);
String value = attributes.getValue(i);
tmpAtrb.put(aname, value);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(tmpElementName.equals(qName)){
System.out.println("Element Name :"+tmpElementName);
/**
* Retrive attributes from HashMap
*/ for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
System.out.println("Attribute Name :"+ entrySet.getKey() + "Attribute Value :"+ entrySet.getValue());
}
System.out.println("Element Value :"+tmpElementValue);
xmlVal.put(tmpElementName, tmpElementValue);
System.out.println(xmlVal);
//Fetching The Values From The Map
String getKeyValues=xmlVal.get(tmpElementName);
System.out.println("XmlTag:"+tmpElementName+":::::"+"ValueFetchedFromTheMap:"+getKeyValues);
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
tmpElementValue = new String(ch, start, length) ;
}
};
/**
* Below two line used if we use SAX 2.0
* Then last line not needed.
*/
//saxParser.setContentHandler(handler);
//saxParser.parse(new InputSource("c:/file.xml"));
saxParser.parse(new File("D:/Test _ XML/file.xml"), handler);
}
}
OUTPUT:
Element Name :child1
Element Value : value 1
XmlTag:<child1>:::::ValueFetchedFromTheMap: value 1
Element Name :child2
Element Value : value 2
XmlTag:<child2>:::::ValueFetchedFromTheMap: value 2
Element Name :child3
Element Value : value 3
XmlTag:<child3>:::::ValueFetchedFromTheMap: value 3
Element Name :child4
Element Value : value 4
XmlTag:<child4>:::::ValueFetchedFromTheMap: value 4
Element Name :child5
Element Value : value 5
XmlTag:<child5>:::::ValueFetchedFromTheMap: value 5
Element Name :child6
Element Value : value 6
XmlTag:<child6>:::::ValueFetchedFromTheMap: value 6
Values Inside The Map:{child1= value 1 , child2= value 2 , child3= value 3 , child4= value 4 , child5= value 5, child6= value 6 }
Import-Csv $path | Foreach-Object {
foreach ($property in $_.PSObject.Properties)
{
doSomething $property.Name, $property.Value
}
}
I do not think there is a "correct" way.
I would use:
with open ('myfile', 'a') as f: f.write ('hi there\n')
In memoriam Tim Toady.
Note: Do not do this in production code, use http instead, or the actual self signed public key as suggested above.
On HttpClient 4.xx:
import static org.junit.Assert.assertEquals;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;
public class HttpClientTrustingAllCertsTest {
@Test
public void shouldAcceptUnsafeCerts() throws Exception {
DefaultHttpClient httpclient = httpClientTrustingAllSSLCerts();
HttpGet httpGet = new HttpGet("https://host_with_self_signed_cert");
HttpResponse response = httpclient.execute( httpGet );
assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());
}
private DefaultHttpClient httpClientTrustingAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
DefaultHttpClient httpclient = new DefaultHttpClient();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, getTrustingManager(), new java.security.SecureRandom());
SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
Scheme sch = new Scheme("https", 443, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
return httpclient;
}
private TrustManager[] getTrustingManager() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// Do nothing
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// Do nothing
}
} };
return trustAllCerts;
}
}
You can update with MERGE
Command with much more control over MATCHED
and NOT MATCHED
:(I slightly changed the source code to demonstrate my point)
USE tempdb;
GO
IF(OBJECT_ID('target') > 0)DROP TABLE dbo.target
IF(OBJECT_ID('source') > 0)DROP TABLE dbo.source
CREATE TABLE dbo.Target
(
EmployeeID INT ,
EmployeeName VARCHAR(100) ,
CONSTRAINT Target_PK PRIMARY KEY ( EmployeeID )
);
CREATE TABLE dbo.Source
(
EmployeeID INT ,
EmployeeName VARCHAR(100) ,
CONSTRAINT Source_PK PRIMARY KEY ( EmployeeID )
);
GO
INSERT dbo.Target
( EmployeeID, EmployeeName )
VALUES ( 100, 'Mary' );
INSERT dbo.Target
( EmployeeID, EmployeeName )
VALUES ( 101, 'Sara' );
INSERT dbo.Target
( EmployeeID, EmployeeName )
VALUES ( 102, 'Stefano' );
GO
INSERT dbo.Source
( EmployeeID, EmployeeName )
VALUES ( 100, 'Bob' );
INSERT dbo.Source
( EmployeeID, EmployeeName )
VALUES ( 104, 'Steve' );
GO
SELECT * FROM dbo.Source
SELECT * FROM dbo.Target
MERGE Target AS T
USING Source AS S
ON ( T.EmployeeID = S.EmployeeID )
WHEN MATCHED THEN
UPDATE SET T.EmployeeName = S.EmployeeName + '[Updated]';
GO
SELECT '-------After Merge----------'
SELECT * FROM dbo.Source
SELECT * FROM dbo.Target
I had the same error and SOLVED by removing the DB roles db_denydatawriter
and db_denydatreader
of the DB user. For that, select the appropriate DB user on logins >> properties >> user mappings >> find out DB and select it >> uncheck the mentioned Db user roles. Thats it !!
Update: appears to have stopped working since Chrome 80
Drag & Drop the '.crx' file on to the 'Extensions' page
Settings - icon > Tools > Extensions
( the 'hamburger' icon in the top-right corner )Enable Developer Mode ( toggle button in top-right corner )
Drag and drop the '.crx' extension file onto the Extensions page from step 1
( crx file should likely be in your Downloads directory )Install
Source: Chrome YouTube Downloader - install instructions
S3 now expects the rules to be in Array Json format.
You can find this in s3 bucket -> Permissions then -> scroll below -> () Cross-origin resource sharing (CORS)
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"HEAD"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 3000
}
]
Just use UniversalImageLoader and set
DisplayImageOptions.Builder()
.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.build();
and no scale settings on ImageView
I had a similar error with Tomcat 8.0 / MySQL . Changing the jdbc url value from localhost to 127.0.0.1 resolved the issue.
Just in case if any one is stuck like me. After going though the post and some hit and trial this worked for me.
input:not([type="checkbox"])input:not([type="radio"])
1.
@click="$event.target.classList.toggle('active')"
2.
:class="{ active }"
@click="active = !active"
3.
:class="'initial ' + (active ? 'active' : '')"
@click="active = !active"
4.
:class="['initial', { active }]"
@click="active = !active"
Reference link: https://vuejs.org/v2/guide/class-and-style.html
Demo:
new Vue({_x000D_
el: '#app1'_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
el: '#app2',_x000D_
data: { active: false }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
el: '#app3',_x000D_
data: { active: false }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
el: '#app4',_x000D_
data: { active: false }_x000D_
});
_x000D_
.initial {_x000D_
width: 300px;_x000D_
height: 100px;_x000D_
background: gray;_x000D_
}_x000D_
_x000D_
.active {_x000D_
background: red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<!-- directly manipulation: not recommended -->_x000D_
<div id="app1">_x000D_
<button _x000D_
class="initial" _x000D_
@click="$event.target.classList.toggle('active')"_x000D_
>$event.target.classList.toggle('active')</button>_x000D_
</div>_x000D_
_x000D_
<!-- binding by object -->_x000D_
<div id="app2">_x000D_
<button _x000D_
class="initial" _x000D_
:class="{ active }"_x000D_
@click="active = !active"_x000D_
>class="initial" :class="{ active }"</button>_x000D_
</div>_x000D_
_x000D_
<!-- binding by expression -->_x000D_
<div id="app3">_x000D_
<button _x000D_
:class="'initial ' + (active ? 'active' : '')" _x000D_
@click="active = !active"_x000D_
>'initial ' + (active ? 'active' : '')</button>_x000D_
</div>_x000D_
_x000D_
<!-- binding with object combined array -->_x000D_
<div id="app4">_x000D_
<button _x000D_
:class="['initial', { active }]" _x000D_
@click="active = !active"_x000D_
>['initial', { active }]</button>_x000D_
</div>
_x000D_
I don't believe the currently accepted answer is correct. For example, I have the following .htaccess
file in the root of a virtual server (apache 2.4):
<Files "reminder.php">
require all denied
require host localhost
require ip 127.0.0.1
require ip xxx.yyy.zzz.aaa
</Files>
This prevents external access to reminder.php
which is in a subdirectory.
I have a similar .htaccess
file on my Apache 2.2 server with the same effect:
<Files "reminder.php">
Order Deny,Allow
Deny from all
Allow from localhost
Allow from 127.0.0.1
Allow from xxx.yyy.zzz.aaa
</Files>
I don't know for sure but I suspect it's the attempt to define the subdirectory specifically in the .htaccess
file, viz <Files ./inscription/log.txt>
which is causing it to fail. It would be simpler to put the .htaccess
file in the same directory as log.txt
i.e. in the inscription
directory and it will work there.
The @
operator calls the array's __matmul__
method, not dot
. This method is also present in the API as the function np.matmul
.
>>> a = np.random.rand(8,13,13)
>>> b = np.random.rand(8,13,13)
>>> np.matmul(a, b).shape
(8, 13, 13)
From the documentation:
matmul
differs fromdot
in two important ways.
- Multiplication by scalars is not allowed.
- Stacks of matrices are broadcast together as if the matrices were elements.
The last point makes it clear that dot
and matmul
methods behave differently when passed 3D (or higher dimensional) arrays. Quoting from the documentation some more:
For matmul
:
If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.
For np.dot
:
For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b
You can use preg_replace in this case;
$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );
$res return 6 in this case.
If want also to include decimal separator or thousand separator check this example:
$res = preg_replace("/[^0-9.]/", "", "$ 123.099");
$res returns "123.099" in this case
Include period as decimal separator or thousand separator: "/[^0-9.]/"
Include coma as decimal separator or thousand separator: "/[^0-9,]/"
Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"
The above were really close. Here's my solution:
Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
Dim i As Integer
outClone = inClone.Clone
Dim dv As DataView = inClone.Tables(0).DefaultView
dv.RowFilter = matchStr
Dim dt As New DataTable
dt = dv.ToTable
For i = 0 To dv.Count - 1
outClone.Tables(0).ImportRow(dv.Item(i).Row)
Next
End Sub
"::" represents scope resolution operator. Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.
Check current scrollTop
vs previous scrollTop
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st;
});
Playing with JavaScript in an HTA I had no luck with a driver={SQL Server};...
connection string, but a named DSN was OK :
I set up TestDSN and it tested OK, and then var strConn= "DSN=TestDSN";
worked, so I carried on experimenting for my in-house testing and learning purposes.
Our server has several instances running, e.g. server1\dev and server1\Test which made things slightly more tricky as I managed to waste some time forgetting to escape the \
as \\
:)
After some dead-ends with server=server1;instanceName=dev
in the connection strings, I eventually got this one to work :
var strConn= "Provider=SQLOLEDB;Data Source=server1\\dev;Trusted_Connection=Yes;Initial Catalog=MyDatabase;"
Using Windows credentials rather than supplying a user/pwd, I found an interesting diversion was discovering the subtleties of Integrated Security = true
v Integrated Security = SSPI
v Trusted_Connection=Yes
- see Difference between Integrated Security = True and Integrated Security = SSPI
Beware that RecordCount will come back as -1
if using the default adOpenForwardOnly type. If you're working with small result sets and/or don't mind the whole lot in memory at once, use rs.Open(strQuery, objConnection, 3);
(3=adOpenStatic) and this gives a valid rs.RecordCount
In your terminal/console (only Linux, in windows you need Putty)
ssh user@ip
php -i | grep "Loaded Configuration File"
And it will show you something like this Loaded Configuration File => /etc/php.ini
.
ALTERNATIVE METHOD
You can make a php file on your website, which run: <?php phpinfo(); ?>
, and you can see the php.ini location on the line with: "Loaded Configuration File".
Update This command gives the path right away
cli_php_ini=php -i | grep /.+/php.ini -oE #ref. https://stackoverflow.com/a/15763333/248616
php_ini="${cli_php_ini/cli/apache2}" #replace cli by apache2 ref. https://stackoverflow.com/a/13210909/248616
document.write()
doesn't work with XHTML. It's executed after the page has finished loading and does nothing more than write out a string of HTML.
Since the actual in-memory representation of HTML is the DOM, the best way to update a given page is to manipulate the DOM directly.
The way you'd go about doing this would be to programmatically create your nodes and then attach them to an existing place in the DOM. For [purposes of a contrived] example, assuming that I've got a div
element maintaining an ID
attribute of "header," then I could introduce some dynamic text by doing this:
// create my text
var sHeader = document.createTextNode('Hello world!');
// create an element for the text and append it
var spanHeader = document.createElement('span');
spanHeader.appendChild(sHeader);
// grab a reference to the div header
var divHeader = document.getElementById('header');
// append the new element to the header
divHeader.appendChild(spanHeader);
Your best bet will be looking at the WifiManager class. Specifically the setWifiEnabled(bool)
function.
See the documentation at: http://developer.android.com/reference/android/net/wifi/WifiManager.html#setWifiEnabled(boolean)
A tutorial on how to use it (including what permissions you need) can be found here: http://www.tutorialforandroid.com/2009/10/turn-off-turn-on-wifi-in-android-using.html
You seem close.
I would try to set the URI like this :
String folderPath = Environment.getExternalStorageDirectory()+"/pathTo/folder";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri , "file/*");
startActivity(intent);
But it's not so different from what you have tried. Tell us if it changes anything ?
Also make sure the targeted folder exists, and have a look on the resulting Uri object before to send it to the intent, it may not be what we are expected.
I have 3 fields to fetch from Oracle Database,Which is for Forex and Currency Application.
SELECT BUY.RATE FROM FRBU.CURRENCY WHERE CURRENCY.MARKET =10 AND CURRENCY.CODE IN (‘USD’, ’AUD’, ‘SGD’)
I run an SP to DROP the table(s) and then use a DTS package to import the most recent production table(s) onto my development box. Then I go home and come back the following morning. It's not elegant; but it works for me.
In Windows when a process terminates, the OS closes the associated window. This happens with all programs (and is generally desirable behaviour), but people never cease to be surprised when it happens to the ones they write themselves.
I am being slightly harsh perhaps; many IDE's execute the user's process in a shell as a child process, so that it does not own the window so it won't close when the process terminates. Although this would be trivial, Dev-C++ does not do that.
Be aware that when Dev-C++ was popular, this question appeard at least twice a day on Dev-C++'s own forum on Sourceforge. For that reason the forum has a "Read First" thread that provides a suggested solution amongst solutions to many other common problems. You should read it here.
Note that Dev-C++ is somewhat old and no longer actively maintained. It suffers most significantly from an almost unusable and very limited debugger integration. Traffic on the Dev-C++ forum has been dropping off since the release of VC++ 2005 Express, and is now down to a two or three posts a week rather than the 10 or so a day it had in 2005. All this suggest that you should consider an alternative tool IMO.
The browser support status is this:
IE8, Firefox, Opera: $("html")
Chrome, Safari: $("body")
So this works:
bodyelem = $.browser.safari ? $("body") : $("html") ;
bodyelem.animate( {scrollTop: 0}, 500 );
Only methods with WebGet can be accessed from browser IE ; you can access other http verbs by just typing address
You can either try Restful service startup kit of codeples or use fiddler to test your other http verbs
As the recent developed Web Applications are using JavaScript, jQuery, AngularJS, ReactJS etc there is a possibility that to retrieve an attribute of an element through Selenium you have to induce WebDriverWait to synchronize the WebDriver instance with the lagging Web Client i.e. the Web Browser before trying to retrieve any of the attributes.
Some examples:
Python:
To retrieve any attribute form a visible element (e.g. <h1>
tag) you need to use the expected_conditions as visibility_of_element_located(locator)
as follows:
attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
To retrieve any attribute form an interactive element (e.g. <input>
tag) you need to use the expected_conditions as element_to_be_clickable(locator)
as follows:
attribute_value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "org"))).get_attribute("attribute_name")
Below is a list of some attributes often used in HTML
Note: A complete list of all attributes for each HTML element, is listed in: HTML Attribute Reference
I did some test to see how the theory actually works: kennethxu.blogspot.com/2009/05/interlocked-vs-monitor-performance.html. My test was more focused on CompareExchnage but the result for Increment is similar. Interlocked is not necessary faster in multi-cpu environment. Here is the test result for Increment on a 2 years old 16 CPU server. Bare in mind that the test also involves the safe read after increase, which is typical in real world.
D:\>InterlockVsMonitor.exe 16
Using 16 threads:
InterlockAtomic.RunIncrement (ns): 8355 Average, 8302 Minimal, 8409 Maxmial
MonitorVolatileAtomic.RunIncrement (ns): 7077 Average, 6843 Minimal, 7243 Maxmial
D:\>InterlockVsMonitor.exe 4
Using 4 threads:
InterlockAtomic.RunIncrement (ns): 4319 Average, 4319 Minimal, 4321 Maxmial
MonitorVolatileAtomic.RunIncrement (ns): 933 Average, 802 Minimal, 1018 Maxmial
First of all be sure to add this line in manifest tag
xmlns:tools="https://schemas.android.com/tools"
Then add tools replace your suggested one in Android studio
You can get around this even more easily with the Rebase extension, just use hg pull --rebase
and your commits are automatically re-comitted to the pulled revision, avoiding the branching issue.
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
Enter command mode and run
:r! sed -n '<start_line_num>, <end_line_num> p' file_to_extract_text_from
E.g to extract lines 20-30
from filename
into the currently opened file
:r! sed -n '20, 30p' filename
If --grace-period=0
is not working then you can do:
kubectl delete pods <pod> --grace-period=0 --force
I would just not add it in the first place:
var sb = new StringBuilder();
bool first = true;
foreach (var foo in items) {
if (first)
first = false;
else
sb.Append('&');
// for example:
var escapedValue = System.Web.HttpUtility.UrlEncode(foo);
sb.Append(key).Append('=').Append(escapedValue);
}
var s = sb.ToString();
I know that's an old one question, but its high in the search results.
If anyone wants timestamp conversion directly to a DateTime object, there's a simple one-liner:
$timestamp = 1299446702;
$date = DateTime::createFromFormat('U', $timestamp);
Following @sromero comment, timezone parameter (the 3rd param in DateTime::createFromFormat()) is ignored when unix timestamp is passed, so the below code is unnecessary.
$date = DateTime::createFromFormat('U', $timestamp, new DateTimeZone('UTC'); // not needed, 3rd parameter is ignored
You may check PHP's manual for DateTime::createFromFormat for more info and options.
Another alternative can be to execute the Keydown or KeyUp in the tag of the Form
<form name="nameForm" [formGroup]="groupForm" (keydown.enter)="executeFunction()" >
Here is a different solution, that also allows the replacement of a single group in multiple matches. It uses stacks to reverse the execution order, so the string operation can be safely executed.
private static void demo () {
final String sourceString = "hello world!";
final String regex = "(hello) (world)(!)";
final Pattern pattern = Pattern.compile(regex);
String result = replaceTextOfMatchGroup(sourceString, pattern, 2, world -> world.toUpperCase());
System.out.println(result); // output: hello WORLD!
}
public static String replaceTextOfMatchGroup(String sourceString, Pattern pattern, int groupToReplace, Function<String,String> replaceStrategy) {
Stack<Integer> startPositions = new Stack<>();
Stack<Integer> endPositions = new Stack<>();
Matcher matcher = pattern.matcher(sourceString);
while (matcher.find()) {
startPositions.push(matcher.start(groupToReplace));
endPositions.push(matcher.end(groupToReplace));
}
StringBuilder sb = new StringBuilder(sourceString);
while (! startPositions.isEmpty()) {
int start = startPositions.pop();
int end = endPositions.pop();
if (start >= 0 && end >= 0) {
sb.replace(start, end, replaceStrategy.apply(sourceString.substring(start, end)));
}
}
return sb.toString();
}
First of all, you should be using json.loads
, not json.dumps
. loads
converts JSON source text to a Python value, while dumps
goes the other way.
After you fix that, based on the JSON snippet at the top of your question, readable_json
will be a list, and so readable_json['firstName']
is meaningless. The correct way to get the 'firstName'
field of every element of a list is to eliminate the playerstuff = readable_json['firstName']
line and change for i in playerstuff:
to for i in readable_json:
.
Indeed, if you perform some complex calculations inside the loop, then the performance of the array indexer versus the list indexer may be so marginally small, that eventually, it doesn't matter.
Some of the solutions described here did not work for me. Others did, however they produced warnings on runtime and javadoc was still not linked. After some experimenting, I managed to solve this. The steps are:
Install the Google Play Services as recommended on Android Developers.
Set up your project as recommended on Android Developers.
If you followed 1. and 2., you should see two projects in your workspace: your project and google-play-services_lib project. Copy the docs
folder which contains the javadoc from <android-sdk>/extras/google/google_play_services/
to libs
folder of your project.
Copy google-play-services.jar
from <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/libs
to 'libs' folder of your project.
In google-play-services_lib
project, edit libs/google-play-services.jar.properties . The <path>
in doc=<path>
should point to the subfolder reference
of the folder docs
, which you created in step 3.
In Eclipse, do Project > Clean. Done, javadoc is now linked.
If you're going to call a python script from some other process (say, from the command line), use pythonw.exe
. Otherwise, your user will continuously see a cmd
window launching the python process. It'll still run your script just the same, but it won't intrude on the user experience.
An example might be sending an email; python.exe
will pop up a CLI window, send the email, then close the window. It'll appear as a quick flash, and can be considered somewhat annoying. pythonw.exe
avoids this, but still sends the email.
Use getName()
as the key and Choice
itself as the value of the map:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));
Just for the record, here is the difference between If and IIf:
IIf(condition, true-part, false-part):
If(condition, true-part, false-part):
MAC OSX
For yesterday's date:
date -v-1d +%F
where 1d defines current day minus 1 day. Similarly,
date -v-1w +%F - for previous week date
date -v-1m +%F - for previous month date
IF YOU HAVE GNU DATE,
date --date="1 day ago"
More info: https://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html
I think most solutions talk here about List Comprehension, but if you'd like to perform in place deletion and keep the space complexity to O(1); The solution is:
i = 0
for j in range(len(arr)):
if (arr[j] != 0):
arr[i] = arr[j]
i +=1
arr = arr[:i]
fromEvent<KeyboardEvent>(document.querySelector('#searcha') as HTMLInputElement , 'keyup')
.pipe(
debounceTime(500),
distinctUntilChanged(),
map(e => {
return e.target['value']; // <-- target does not exist on {}
})
).subscribe(k => console.log(k));
Maybe something like the above could help. Change it based on the real code. The issue is ........ target['value']
File.GetLastWriteTime
to Get last modified
File.CreationTime
to get Created time
The new fontawesome (version 4.0.3) makes this really easy to do. We simply use the following classes:
<ul class="fa-ul">
<li><i class="fa-li fa fa-check-square"></i>List icons (like these)</li>
<li><i class="fa-li fa fa-check-square"></i>can be used</li>
<li><i class="fa-li fa fa-spinner fa-spin"></i>to replace</li>
<li><i class="fa-li fa fa-square"></i>default bullets in lists</li>
</ul>
As per this (new) url: http://fontawesome.io/examples/#list
To add to @migontech's answer and also his address his comment that you could "probably make it more generic", here's a way to do it. The below will allow you to search by any property:
.filter('getByProperty', function() {
return function(propertyName, propertyValue, collection) {
var i=0, len=collection.length;
for (; i<len; i++) {
if (collection[i][propertyName] == +propertyValue) {
return collection[i];
}
}
return null;
}
});
The call to filter would then become:
var found = $filter('getByProperty')('id', fish_id, $scope.fish);
Note, I removed the unary(+) operator to allow for string-based matches...
recyclerView.addOnItemTouchListener(object : AdapterView.OnItemClickListener,
RecyclerView.OnItemTouchListener {
override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
TODO("Not yet implemented")
}
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
TODO("Not yet implemented")
}
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
TODO("Not yet implemented")
}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
TODO("Not yet implemented")
}
})
If use Kotlin
Try this:
apt-get install lib32stdc++6
Default text size vary from device to devices
Type Dimension Micro 12 sp Small 14 sp Medium 18 sp Large 22 sp
I came across ParamUnittest the other day when looking at the source code for radon (example usage on the GitHub repository). It should work with other frameworks that extend TestCase (like Nose).
Here is an example:
import unittest
import paramunittest
@paramunittest.parametrized(
('1', '2'),
#(4, 3), <---- Uncomment to have a failing test
('2', '3'),
(('4', ), {'b': '5'}),
((), {'a': 5, 'b': 6}),
{'a': 5, 'b': 6},
)
class TestBar(TestCase):
def setParameters(self, a, b):
self.a = a
self.b = b
def testLess(self):
self.assertLess(self.a, self.b)
A more reliable REST endpoint would be http://freegeoip.net/json/
Returns the ip address along with the geo-location too. Also has cross-domain requests enabled (Access-Control-Allow-Origin: *) so you don't have to code around JSONP.
^[0-9]([.,][0-9]{1,3})?$
It allows:
0
1
1.2
1.02
1.003
1.030
1,2
1,23
1,234
BUT NOT:
.1
,1
12.1
12,1
1.
1,
1.2345
1,2345
You can try:
function onlyAlphabets(e, t) {
return (e.charCode > 64 && e.charCode < 91) || (e.charCode > 96 && e.charCode < 123) || e.charCode == 32;
}
check it out!
a = [[1, 2], [2, 3], [3, 4]]
a2 = zip(*a)
a2[0]
it is the same thing as above except somehow it is neater the zip does the work but requires single arrays as arguments, the *a syntax unpacks the multidimensional array into single array arguments
A View object is a component of the user interface (UI) like a button or a text box, and it's also called widget.
A ViewGroup object is a layout, that is, a container of other ViewGroup objects (layouts) and View objects (widgets). It's possible to have a layout inside another layout. It's called nested layout but it can increase the time needed to draw the user interface.
The user interface for an app is built using a hierarchy of ViewGroup and View objects. In Android Studio it is possible to use the Component Tree window to visualise this hierarchy.
The Layout Editor in Android Studio can be used to drag and drop View objects (widgets) in the layout. It simplifies the creation of a layout.
header('Location: http://linkhere.com/' . $your_variable);
Just remove/comment the following line from your httpd.conf file (etc/httpd/conf)
Require all granted
This is needed till Apache Version 2.2 and is not required from thereon.
In Python 3, I find pathlib is the easiest way to do this. Request's response.content marries up nicely with pathlib's write_bytes.
from pathlib import Path
import requests
filename = Path('metadata.pdf')
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
response = requests.get(url)
filename.write_bytes(response.content)
If a website's directory does NOT have an "index...." file, AND .htaccess has NOT been used to block access to the directory itself, then Apache will create an "index of" page for that directory. You can save that page, and its icons, using "Save page as..." along with the "Web page, complete" option (Firefox example). If you own the website, temporarily rename any "index...." file, and reference the directory locally. Then restore your "index...." file.
You must press enter after continuation character
Note: Space after continuation character leads to error
cost = {"apples": [3.5, 2.4, 2.3], "bananas": [1.2, 1.8]}
0.9 * average(cost["apples"]) + \ """enter here"""
0.1 * average(cost["bananas"])
For me the error was:
Error: unexpected input in "?"
and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.
EDIT: OP requested an example. Here it goes.
? ~ cat a.R
cat('hello world\n')
? ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f ...cat('hello wo
00000010: 726c 645c 6e27 290a rld\n').
? ~ R -f a.R
R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> cat('hello world\n')
Error: unexpected input in "?"
Execution halted
Enable cross-origin requests in ASP.NET Web API click for more info
Enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:
Install-Package Microsoft.AspNet.WebApi.Cors
This command installs the latest package and updates all dependencies, including the core Web API libraries. Use the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:
using System.Web.Http;
namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Next, add the [EnableCors] attribute to your controller/ controller methods
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebService.Controllers
{
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
To handle the possibility of int
, float
, and empty string values, I'd use a combination of a list comprehension, dictionary comprehension, along with conditional expressions, as shown:
dicts = [{'a': '1' , 'b': '' , 'c': '3.14159'},
{'d': '4' , 'e': '5' , 'f': '6'}]
print [{k: int(v) if v and '.' not in v else float(v) if v else None
for k, v in d.iteritems()}
for d in dicts]
# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]
However dictionary comprehensions weren't added to Python 2 until version 2.7. It can still be done in earlier versions as a single expression, but has to be written using the dict
constructor like the following:
# for pre-Python 2.7
print [dict([k, int(v) if v and '.' not in v else float(v) if v else None]
for k, v in d.iteritems())
for d in dicts]
# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]
Note that either way this creates a new dictionary of lists, instead of modifying the original one in-place (which would need to be done differently).
To add color to an input, Use the following css code:
input{
color: black;
}
CryptoSwift Example
Updated SWIFT 4.*
func aesEncrypt() throws -> String {
let encrypted = try AES(key: KEY, iv: IV, padding: .pkcs7).encrypt([UInt8](self.data(using: .utf8)!))
return Data(encrypted).base64EncodedString()
}
func aesDecrypt() throws -> String {
guard let data = Data(base64Encoded: self) else { return "" }
let decrypted = try AES(key: KEY, iv: IV, padding: .pkcs7).decrypt([UInt8](data))
return String(bytes: decrypted, encoding: .utf8) ?? self
}
I did debugging and finally returned my 'stuffed' query to it it's normal way.
Simply
select * from myTable for xml path('myTable')
gives me contents of the table to write to a log table from a trigger I debug.
I just came across this error, and here's what I found out in case this helps anyone: I discovered that you can right click the error message in Xcode and choose expand to get more details, including a description of the problem.
In my case, I had two copies of my developer certificate with the same name in different keychain files, and Xcode couldn't figure out which one to use.
A simple solution without using external modules:
from datetime import datetime, timezone
dt = datetime(2008, 1, 1, 0, 0, 0, 0)
int(dt.replace(tzinfo=timezone.utc).timestamp())
Use numpy.apply_along_axis()
. Assuming your matrix is 2D, you can use like:
import numpy as np
mymatrix = np.matrix([[11,12,13],
[21,22,23],
[31,32,33]])
def myfunction( x ):
return sum(x)
print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]
You can kill two birds with one regex stone:
>>> r = """
... \n\tName: John Smith
... \n\t Home: Anytown USA
... \n\t Phone: 555-555-555
... \n\t Other Home: Somewhere Else
... \n\t Notes: Other data
... \n\tName: Jane Smith
... \n\t Misc: Data with spaces
... """
>>> import re
>>> print re.findall(r'(\S[^:]+):\s*(.*\S)', r)
[('Name', 'John Smith'), ('Home', 'Anytown USA'), ('Phone', '555-555-555'), ('Other Home', 'Somewhere Else'), ('Notes', 'Other data'), ('Name', 'Jane Smith'), ('Misc', 'Data with spaces')]
>>>
Use LayoutParams. If you are using a LinearLayout you have to import android.widget.LinearLayout.LayoutParams, else import the proper version of LayoutParams for the layout you're using, or it will cause a ClassCastException, then:
LayoutParams layoutParams = new LayoutParams(int width, int height);
layoutParams.setMargins(int left, int top, int right, int bottom);
imageView.setLayoutParams(layoutParams);
NB: Note that you can use also imageView.setLeft(int dim), BUT THIS WON'T set the position of the component, it will set only the position of the left border of the component, the rest will remain at the same position.
In .Net 1.1 and earlier, Application.Exit was not a wise choice and the MSDN docs specifically recommended against it because all message processing stopped immediately.
In later versions however, calling Application.Exit will result in Form.Close being called on all open forms in the application, thus giving you a chance to clean up after yourself, or even cancel the operation all together.
You have specified the ajax call response dataType as:
'json'
where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.
The best approach that I would recommend is to change the dataType to:
'text'
and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'text',
data: {viewID: $("#view").val()},
success: function (data) {
try {
var output = JSON.parse(data);
alert(output);
} catch (e) {
alert("Output is not valid JSON: " + data);
}
}, error: function (request, error) {
alert("AJAX Call Error: " + error);
}
});
For those who have updated to the latest version of google-play-services_lib and/or have this error Google Play services out of date. Requires 3136100 but found 2012110
this newer version of com.google.android.gms.apk (Google Play Services 3.1.36) and com.android.vending.apk (Google Play Store 4.1.6) should work.
Test with this configuration on Android SDK Tools 22.0.1. Another configuration that targets pure Android, not the Google one, should work too.
...
Execute this in the terminal / cmd
adb -e install com.google.android.gms.apk
adb -e install com.android.vending.apk
Restart the AVD
I found this way to be the easiest, cleanest and it works with the newest version of the software, which allow you to get all the bug fixes.
You can use the --ignore-table option. So you could do
mysqldump -u USERNAME -pPASSWORD DATABASE --ignore-table=DATABASE.table1 > database.sql
There is no whitespace after -p
(this is not a typo).
To ignore multiple tables, use this option multiple times, this is documented to work since at least version 5.0.
If you want an alternative way to ignore multiple tables you can use a script like this:
#!/bin/bash
PASSWORD=XXXXXX
HOST=XXXXXX
USER=XXXXXX
DATABASE=databasename
DB_FILE=dump.sql
EXCLUDED_TABLES=(
table1
table2
table3
table4
tableN
)
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done
echo "Dump structure"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE} > ${DB_FILE}
echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
what @yabin ya says is a cool solution, just remind you that: if u still get the same problem,go to Settings-Version Control-GitHub and uncheck the Clone git repositories using ssh
.
For what it's worth, here's the previously provided code encapsulated within a function.
openWindowWithPost("http://www.example.com/index.php", {
p: "view.map",
coords: encodeURIComponent(coords)
});
Function definition:
function openWindowWithPost(url, data) {
var form = document.createElement("form");
form.target = "_blank";
form.method = "POST";
form.action = url;
form.style.display = "none";
for (var key in data) {
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = data[key];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top;
if (!isNaN(top)) {
$("#app_scroler").click(function () {
$('html, body').animate({
scrollTop: top
}, 100);
});
}
if you want to scroll a little above or below from specific div that add value to the top like this.....like I add 800
var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top + 800;
Add line:
import java.util.Scanner;
Then create an object of Scanner
class:
Scanner s = new Scanner(System.in);
Now you can call any time:
int a = Integer.parseInt(s.nextLine());
This will store integer
value from your keyboard.
You can use select ... into ...
to create and populate a temp table and then query the temp table to return the result.
select *
into #TempTable
from YourTable
select *
from #TempTable
the simple way I found out: add a "li" tag on the right side of an "a" tag List item
<li></span><a><span id="expand1"></span></a></li>
On CSS file create this below:
#expand1 {
padding-left: 40px;
}
I had this same issue just now in React.
I figured out that in the Router, Route. We cannot do this as it causes this issue of closing the mobile keyboard.
<Route
path = "some-path"
component = {props => <MyComponent />}
/>
Make sure and use the render instead in this situation
<Route
path = "some-path"
render = {props => <MyComponent />}
/>
Hope this helps someone
Daniel
In your web.config (on the server) add
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\logs\Traces.svclog"/>
</listeners>
</source>
</sources>
</system.diagnostics>
To run the python file on mac.
Click on the install in the preferences to install packages.
Search for package "script" and click on install
Now open the python file(with .py extension ) you want to run and press 'control + r ' (^ + r)
This will do the trick!
div {
height: 100vh;
width: 100vw;
}
I have the same issue, but I see that port 80 listened by Nginx:
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 9730/nginx
But when I try to restart it, I have the error:
service nginx restart
Stopping nginx: [FAILED]
Starting nginx: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:443 failed (98: Address already in use)
nginx: [emerg] still could not bind()
My issue was in the config file, I am set PID file, and seems system cant catch it properly:
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
When I removed it, it worked.
String.prototype.replaceAll = function(character,replaceChar){
var word = this.valueOf();
while(word.indexOf(character) != -1)
word = word.replace(character,replaceChar);
return word;
}
For that you can use the Application
object.
Startup path, just the folder, use Application.StartupPath()
Dim appPath As String = Application.StartupPath()
Full .exe path, including the program.exe name on the end:, use Application.ExecutablePath()
Dim exePath As String = Application.ExecutablePath()
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
You can't send application/json
directly -- it has to be a parameter of a GET/POST request.
So something like
$.post(url, {json: "...json..."}, function());
I normally use action="", which is XHTML valid and retains the GET data in the URL.
All modern browsers (tested with Chrome 4, Firefox 3.5, IE8, Opera 10 and Safari 4) will always request a favicon.ico
unless you've specified a shortcut icon via <link>
. So if you don't explicitly specify one, it's best to always have a favicon.ico
file, to avoid a 404. Yahoo! suggests you make it small and cacheable.
And you don't have to go for a PNG just for the alpha transparency either. ICO files support alpha transparency just fine (i.e. 32-bit color), though hardly any tools allow you to create them. I regularly use Dynamic Drive's FavIcon Generator to create favicon.ico
files with alpha transparency. It's the only online tool I know of that can do it.
There's also a free Photoshop plug-in that can create them.
It is also possible to include bitmaps. I think you also can use transformations on that.
<Directory /your/directorypath/>
php_admin_value engine Off
</Directory>
Another solution, you can do it using ResourceLoader
like this:
import org.springframework.core.io.Resource;
import org.apache.commons.io.FileUtils;
@Autowire
private ResourceLoader resourceLoader;
...
Resource resource = resourceLoader.getResource("classpath:/path/to/you/dir");
File file = resource.getFile();
Iterator<File> fi = FileUtils.iterateFiles(file, null, true);
while(fi.hasNext()) {
load(fi.next())
}
Comments suggest that git reset --merge
is an alias for git merge --abort
. It is worth noticing that git merge --abort
is only equivalent to git reset --merge
given that a MERGE_HEAD
is present. This can be read in the git help for merge command.
git merge --abort is equivalent to git reset --merge when MERGE_HEAD is present.
After a failed merge, when there is no MERGE_HEAD
, the failed merge can be undone with git reset --merge
, but not necessarily with git merge --abort
. They are not only old and new syntax for the same thing.
Personally, I find git reset --merge
much more powerful for scenarios similar to the described one, and failed merges in general.
String str = "1234.56";
float num = 0.0f;
int digits = str.length()- str.indexOf('.') - 1;
float factor = 1f;
for(int i=0;i<digits;i++) factor /= 10;
for(int i=str.length()-1;i>=0;i--){
if(str.charAt(i) == '.'){
factor = 1;
System.out.println("Reset, value="+num);
continue;
}
num += (str.charAt(i) - '0') * factor;
factor *= 10;
}
System.out.println(num);
Tools-> Android -> Android Device Monitor
will open a separate window
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
Usually, what I do is put the normal audio tag, and then put autoplay="true"
and I don't add: controls ="true" and that usually works for me
I put this in a snippet and also made a jsfiddel here
Hope this helps :)
<audio autoplay="true" _x000D_
src="https://res.cloudinary.com/foxyplays989/video/upload/v1558369838/LetsGo.mp3"> _x000D_
</audio>
_x000D_
The best code is no code, and with stored procedures you have to write at least some code in the database and code in the application to call it , whereas with LINQ to SQL or LINQ to Entities, you don't have to write any additional code beyond any other LINQ query aside from instantiating a context object.
I had this problem (403 error for each package) and I found nothing great in the internet to solve it.
My .npmrc
file inside my user folder was wrong and misunderstood.
I changed this npmrc line from
proxy=http://XX.XX.XXX.XXX:XXX/
to :
proxy = XX.XX.XXX.XXX:XXXX
The BASE acronym was defined by Eric Brewer, who is also known for formulating the CAP theorem.
The CAP theorem states that a distributed computer system cannot guarantee all of the following three properties at the same time:
A BASE system gives up on consistency.
Brewer does admit that the acronym is contrived:
I came up with [the BASE] acronym with my students in their office earlier that year. I agree it is contrived a bit, but so is "ACID" -- much more than people realize, so we figured it was good enough.
I doubt there is anyway to force a browser to do anything. It would depend on the system configuration, the font used, browser settings, etc. It sounds like BS to me too.
As a note, always use relative sizes not PX.
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
Looks like your IndexPartial
action method has an argument which is a complex object. If you are passing a a lot of data (complex object), It might be a good idea to convert your action method to a HttpPost
action method and use jQuery post
to post data to that. GET has limitation on the query string value.
[HttpPost]
public PartialViewResult IndexPartial(DashboardViewModel m)
{
//May be you want to pass the posted model to the parial view?
return PartialView("_IndexPartial");
}
Your script should be
var url = "@Url.Action("IndexPartial","YourControllerName")";
var model = { Name :"Shyju", Location:"Detroit"};
$.post(url, model, function(res){
//res contains the markup returned by the partial view
//You probably want to set that to some Div.
$("#SomeDivToShowTheResult").html(res);
});
Assuming Name
and Location
are properties of your DashboardViewModel
class and SomeDivToShowTheResult
is the id of a div in your page where you want to load the content coming from the partialview.
You can build more complex object in js if you want. Model binding will work as long as your structure matches with the viewmodel class
var model = { Name :"Shyju",
Location:"Detroit",
Interests : ["Code","Coffee","Stackoverflow"]
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json"
}).done(function (res) {
$("#SomeDivToShowTheResult").html(res);
});
For the above js model to be transformed to your method parameter, Your View Model should be like this.
public class DashboardViewModel
{
public string Name {set;get;}
public string Location {set;get;}
public List<string> Interests {set;get;}
}
And in your action method, specify [FromBody]
[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
return PartialView("_IndexPartial",m);
}
A brute force approach:
.gitmodules
file in the supermodule to point to the new submodule url,supermodule/.gitmodules
,.gitmodules
file are reflected in the clone),git submodule update --init path-to-submodule
on the submodule,et voilà! The submodule in the new clone of the supermodule is properly configured!
Less code is better code.
[NSThread sleepForTimeInterval:0.06];
Swift:
Thread.sleep(forTimeInterval: 0.06)
You use class media.FaceDetector in android to detect face for free.
This is an example of face detection: https://github.com/betri28/FaceDetectCamera
Have you tried to remove the proxy username and password? A similar poster encountered that issue:
Failing that I found the following worked:
mvn dependency:resolve