Another thing to check is if you have LogicalName or ManifestResourceName defined on the EmbeddedResource. Make sure those are defined appropriately if your project file is using them as they can cause the resources to live under a name you are not expecting.
According to the MSDN documentation here, The basename argument specifies "The root name of the resource file without its extension but including any fully qualified namespace name. For example, the root name for the resource file named "MyApplication.MyResource.en-US.resources" is "MyApplication.MyResource"."
The ResourceManager will automatically try to retrieve the values for the current UI culture. If you want to use a specific language, you'll need to set the current UI culture to the language you wish to use.
Turning off safe mode in Mysql workbench 6.3.4.0
Edit menu => Preferences => SQL Editor : Other section: click on "Safe updates" ... to uncheck option
Just tried this solution, we don't have to even write int.
int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);
This thing will also work, it automatically detects the type of string.
You might be doing a PUT call for GET operation Please check once
Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.
For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".
Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html
Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx
The best practise is to not force a garbage collection.
According to MSDN:
"It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues. "
However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead...
Just try to make sure objects are cleaned up when you no longer need them. If you have custom objects, look at using the "using statement" and the IDisposable interface.
This link has some good practical advice with regards to freeing up memory / garbage collection etc:
I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.
To undo the two deleted files I had to unstage all of the files:
git reset HEAD .
At that point I was able to do the checkout of the deleted items:
git checkout -- WorkingFolder/FileName.ext
Finally I was able to restage the rest of the files and continue with my commit.
List indexes of -x mean the xth item from the end of the list, so n[-1]
means the last item in the list n
. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1]
to access the last item of a list.
They refer to the same element, the difference is that when you say document.body
you are passing the element directly to jQuery. Alternatively, when you pass the string 'body'
, the jQuery selector engine has to interpret the string to figure out what element(s) it refers to.
In practice either will get the job done.
If you are interested, there is more information in the documentation for the jQuery function.
Way late to this post, but I've got something slightly different to say...
>> "Are email addresses case sensitive?"
Well, "It Depends..." (TM)
Some organizations actually think that's a good idea and their email servers enforce case sensitivity.
So, for those crazy places, "Yes, Emails are case sensitive."
Note: Just because a specification says you can do something does not mean it is a good idea to do so.
The principle of KISS suggests that our systems use case insensitive emails.
Whereas the Robustness principle suggests that we accept case sensitive emails.
Solution:
This would mean that if this email already exists: [email protected]
... and another user comes along and wants to use this email: [email protected]
... that our case insensitive searching logic would return a "That email already exists" error message.
Now, you have a decision to make: Is that solution adequate in your case?
If not, you could charge a convenience fee to those clients that demand support for their case sensitive emails and implement custom logic that allows the [email protected] into your system, even if [email protected] already exists.
In which case your email search/validation logic might look like something this pseudocode:
if (user.paidEmailFee) {
// case sensitive email
query = "select * from users where email LIKE ' + user.email + '"
} else {
// case insensitive email
query = "select * from users where email ILIKE ' + user.email + '"
}
This way, you are mostly enforcing case insensitivity but allowing customers to pay for this support if they are using email systems that support such nonsense.
p.s. ILIKE is a PostgreSQL keyword: http://www.postgresql.org/docs/9.2/static/functions-matching.html
get page content by page name:
<?php
$page = get_page_by_title( 'page-name' );
$content = apply_filters('the_content', $page->post_content);
echo $content;
?>
Most decompilers for Java are based on JAD. It's a great tool, but unfortunately hasn't been updated for a while and does not handle Java 1.5+ classes very well. I have not seen any tools that will properly handle 1.5+ classes.
While technically valid, all these jumps obscure control flow -- especially the continue
statement.
I would use such a trick as a last resort, not first one.
How about
while (something = get_something())
{
switch (something)
{
case A:
case B:
do_something();
}
}
It's shorter and perform its stuff in a more clear way.
For Angular 6+ things have changed a little.
Cli setup is now done in angular.json (replaced .angular-cli.json) in your workspace root directory. The output path in default angular.json should look like this (irrelevant lines removed):
{
"projects": {
"my-app-name": {
"architect": {
"options": {
"outputPath": "dist/my-app-name",
Obviously, this will generate your app in WORKSPACE/dist/my-app-name. Modify outputPath if you prefer another directory.
You can overwrite the output path using command line arguments (e.g. for CI jobs):
ng build -op dist/example
ng build --output-path=dist/example
S.a. https://github.com/angular/angular-cli/wiki/build
Setting the output path, will tell angular where to place the "compiled" files but however you change the output path, when running the app, angular will still assume that the app is hosted in the webserver's document root.
To make it work in a sub directory, you'll have to set the base href.
In angular.json:
{
"projects": {
"my-app-name": {
"architect": {
"options": {
"baseHref": "/my-folder/",
Cli:
ng build --base-href=/my-folder/
If you don't know where the app will be hosted on build time, you can change base tag in generated index.html.
Here's an example how we do it in our docker container:
entrypoint.sh
if [ -n "${BASE_PATH}" ]
then
files=( $(find . -name "index.html") )
cp -n "${files[0]}" "${files[0]}.org"
cp "${files[0]}.org" "${files[0]}"
sed -i "s*<base href=\"/\">*<base href=\"${BASE_PATH}\">*g" "${files[0]}"
fi
A SilverStripe-specific answer worked out from reading: http://api.silverstripe.org/3.0/source-class-SS_Datetime.html#98-110:
Hopefully this will help someone using a SilverStripe template and trying to force reload a cached image on each page visit / refresh. In my case it is a GIF animation which only plays once and therefore did not replay after it was cached. In my template I simply added:
?$Now.Format(dmYHis)
to the end of the file path to create a unique time stamp and to force the browser to treat it as a new file.
I found the answer:
$mail->AddEmbeddedImage('img/2u_cs_mini.jpg', 'logo_2u');
and on the <img>
tag put src='cid:logo_2u'
There is some confusion when using pip install
in Windows. The instructions talk about a specific folder which has youtube-dl.exe
. There is no such folder if you use pip install
.
The solution is to:
bin
folder (there are three exe files) in any folder which is a path
in Windows. I personally use Ananconda, so I placed them in /Anaconda/Scripts
, but you could place it in any folder and add that folder to the path.Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.
Here is the one I most liked.
Or for something completely different... x
slides to 0
.
while (x --\
\
\
\
> 0)
printf("%d ", x);
Not so mathematical, but... every picture paints a thousand words...
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
In Excel for Mac at least, you can do this by saving as "CSV for MS DOS" which adds double quotes for any field which needs them.
For C# MVC 4.5 you need to do like this:
Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".csv\"");
Response.Write(dataNeedToPrint);
Response.End();
return new EmptyResult(); //this line is important else it will not work.
Thank you for all answers! I found it! It calls "Column selection (for Sublime)" and "Column Mode Editing (for Notepad++)" https://www.sublimetext.com/docs/3/column_selection.html
C++20 introduced default comparisons, aka the "spaceship" operator<=>
, which allows you to request compiler-generated <
/<=
/==
/!=
/>=
/ and/or >
operators with the obvious/naive(?) implementation...
auto operator<=>(const MyClass&) const = default;
...but you can customise that for more complicated situations (discussed below). See here for the language proposal, which contains justifications and discussion. This answer remains relevant for C++17 and earlier, and for insight in to when you should customise the implementation of operator<=>
....
It may seem a bit unhelpful of C++ not to have already Standardised this earlier, but often structs/classes have some data members to exclude from comparison (e.g. counters, cached results, container capacity, last operation success/error code, cursors), as well as decisions to make about myriad things including but not limited to:
int
member might eliminate 99% of unequal objects very quickly, while a map<string,string>
member might often have identical entries and be relatively expensive to compare - if the values are loaded at runtime, the programmer may have insights the compiler can't possiblyvector
, list
), and if so whether it's ok to sort them in-place before comparing vs. using extra memory to sort temporaries each time a comparison is doneunion
to compareoperator==
themselves (but might have compare()
or operator<
or str()
or getters...)So, it's kind of nice to have an error until you've explicitly thought about what comparison should mean for your specific structure, rather than letting it compile but not give you a meaningful result at run-time.
All that said, it'd be good if C++ let you say bool operator==() const = default;
when you'd decided a "naive" member-by-member ==
test was ok. Same for !=
. Given multiple members/bases, "default" <
, <=
, >
, and >=
implementations seem hopeless though - cascading on the basis of order of declaration's possible but very unlikely to be what's wanted, given conflicting imperatives for member ordering (bases being necessarily before members, grouping by accessibility, construction/destruction before dependent use). To be more widely useful, C++ would need a new data member/base annotation system to guide choices - that would be a great thing to have in the Standard though, ideally coupled with AST-based user-defined code generation... I expect it'll happen one day.
It's likely that a reasonable and efficient implementation would be:
inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
return lhs.my_struct2 == rhs.my_struct2 &&
lhs.an_int == rhs.an_int;
}
Note that this needs an operator==
for MyStruct2
too.
Implications of this implementation, and alternatives, are discussed under the heading Discussion of specifics of your MyStruct1 below.
It's easy to leverage std::tuple
's comparison operators to compare your own class instances - just use std::tie
to create tuples of references to fields in the desired order of comparison. Generalising my example from here:
inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
return std::tie(lhs.my_struct2, lhs.an_int) ==
std::tie(rhs.my_struct2, rhs.an_int);
}
inline bool operator<(const MyStruct1& lhs, const MyStruct1& rhs)
{
return std::tie(lhs.my_struct2, lhs.an_int) <
std::tie(rhs.my_struct2, rhs.an_int);
}
// ...etc...
When you "own" (i.e. can edit, a factor with corporate and 3rd party libs) the class you want to compare, and especially with C++14's preparedness to deduce function return type from the return
statement, it's often nicer to add a "tie" member function to the class you want to be able to compare:
auto tie() const { return std::tie(my_struct1, an_int); }
Then the comparisons above simplify to:
inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
return lhs.tie() == rhs.tie();
}
If you want a fuller set of comparison operators, I suggest boost operators (search for less_than_comparable
). If it's unsuitable for some reason, you may or may not like the idea of support macros (online):
#define TIED_OP(STRUCT, OP, GET_FIELDS) \
inline bool operator OP(const STRUCT& lhs, const STRUCT& rhs) \
{ \
return std::tie(GET_FIELDS(lhs)) OP std::tie(GET_FIELDS(rhs)); \
}
#define TIED_COMPARISONS(STRUCT, GET_FIELDS) \
TIED_OP(STRUCT, ==, GET_FIELDS) \
TIED_OP(STRUCT, !=, GET_FIELDS) \
TIED_OP(STRUCT, <, GET_FIELDS) \
TIED_OP(STRUCT, <=, GET_FIELDS) \
TIED_OP(STRUCT, >=, GET_FIELDS) \
TIED_OP(STRUCT, >, GET_FIELDS)
...that can then be used a la...
#define MY_STRUCT_FIELDS(X) X.my_struct2, X.an_int
TIED_COMPARISONS(MyStruct1, MY_STRUCT_FIELDS)
(C++14 member-tie version here)
There are implications to the choice to provide a free-standing versus member operator==()
...
Freestanding implementation
You have an interesting decision to make. As your class can be implicitly constructed from a MyStruct2
, a free-standing / non-member bool operator==(const MyStruct2& lhs, const MyStruct2& rhs)
function would support...
my_MyStruct2 == my_MyStruct1
...by first creating a temporary MyStruct1
from my_myStruct2
, then doing the comparison. This would definitely leave MyStruct1::an_int
set to the constructor's default parameter value of -1
. Depending on whether you include an_int
comparison in the implementation of your operator==
, a MyStruct1
might or might not compare equal to a MyStruct2
that itself compares equal to the MyStruct1
's my_struct_2
member! Further, creating a temporary MyStruct1
can be a very inefficient operation, as it involves copying the existing my_struct2
member to a temporary, only to throw it away after the comparison. (Of course, you could prevent this implicit construction of MyStruct1
s for comparison by making that constructor explicit
or removing the default value for an_int
.)
Member implementation
If you want to avoid implicit construction of a MyStruct1
from a MyStruct2
, make the comparison operator a member function:
struct MyStruct1
{
...
bool operator==(const MyStruct1& rhs) const
{
return tie() == rhs.tie(); // or another approach as above
}
};
Note the const
keyword - only needed for the member implementation - advises the compiler that comparing objects doesn't modify them, so can be allowed on const
objects.
Sometimes the easiest way to get the kind of comparison you want can be...
return lhs.to_string() == rhs.to_string();
...which is often very expensive too - those string
s painfully created just to be thrown away! For types with floating point values, comparing visible representations means the number of displayed digits determines the tolerance within which nearly-equal values are treated as equal during comparison.
Use the following css:
* {
font: Verdana, Arial, 'sans-serif' !important;/* <-- fonts */
}
The *
-selector means any/all elements, but will obviously be on the bottom of the food chain when it comes to overriding more specific selectors.
Note that the !important
-flag will render the font
-style for *
to be absolute, even if other selectors have been used to set the text (for example, the body
or maybe a p
).
It turns out I was just missing DECIMAL
on the CAST()
description:
DECIMAL[(M[,D])]
Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.
Thus, the following query worked:
UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));
Emacs 28 adds a redo command (called undo-redo
).
If you want to have more typical undo/redo, the following commands can be used.
(global-set-key (kbd "C-z") 'undo-only)
(global-set-key (kbd "C-S-z") 'undo-redo)
Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.
Step 2: Let's say you're using Java. You would use JSONArray like this:
JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
JSONArray myInteriorArray=myArray.getJSONArray(i);
if (i==0) {
//this is the first one and is special because it holds the name of the query.
}else{
//do your stuff
String stateCode=myInteriorArray.getString(0);
String stateName=myInteriorArray.getString(1);
}
}
Dictionary
is probably the closest. System.Collections.Generic.Dictionary
implements the System.Collections.Generic.IDictionary
interface (which is similar to Java's Map
interface).
Some notable differences that you should be aware of:
put
and get
methods for setting/getting items
myMap.put(key, value)
MyObject value = myMap.get(key)
[]
indexing for setting/getting items
myDictionary[key] = value
MyObject value = myDictionary[key]
null
keys
HashMap
allows null keysDictionary
throws an ArgumentNullException
if you try to add a null keyHashMap
will replace the existing value with the new one.Dictionary
will replace the existing value with the new one if you use []
indexing. If you use the Add
method, it will instead throw an ArgumentException
.HashMap
will return null.Dictionary
will throw a KeyNotFoundException
. You can use the TryGetValue
method instead of the []
indexing to avoid this:MyObject value = null;
if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }
Dictionary
's has a ContainsKey
method that can help deal with the previous two problems.
You have a tuple of tuples.
To convert every tuple to a list:
[list(i) for i in level] # list of lists
--- OR ---
map(list, level)
And after you are done editing, just convert them back:
tuple(tuple(i) for i in edited) # tuple of tuples
--- OR --- (Thanks @jamylak)
tuple(itertools.imap(tuple, edited))
You can also use a numpy array:
>>> a = numpy.array(level1)
>>> a
array([[1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1]])
For manipulating:
if clicked[0] == 1:
x = (mousey + cameraY) // 60 # For readability
y = (mousex + cameraX) // 60 # For readability
a[x][y] = 1
where java
works for me to list all java exe but java -verbose
tells you which rt.jar
is used and thus which jre (full path):
[Opened C:\Program Files\Java\jre6\lib\rt.jar]
...
Edit: win7 and java:
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)
currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');
I would try to save my object as .txt file and then fetch it like this:
$.get('yourJsonFileAsString.txt', function(data) {
console.log( $.parseJSON( data ) );
});
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
I was able to do this using CefSharp (which uses chromium browser).
Here are a couple posts that show this in action:
batchfiles perform simple string substitution with variables. so, a simple
goto :language%language%
echo notfound
...
does this without any need for if.
You can make your own animations. For example create xml file in res/anim like this
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<translate
android:fromXDelta="100%p"
android:toXDelta="0"
android:startOffset="0"
android:duration="500"
/> </set>
Then override animations in selected activity:
overridePendingTransition(R.anim.animationIN, R.anim.animationOUT);
Just change the first line as follows :
include ActionView::Helpers
that will make it works.
UPDATE: For Rails 3 use:
ActionController::Base.helpers.sanitize(str)
Credit goes to lornc's answer
For length including white-space:
$("#id").val().length
For length without white-space:
$("#id").val().replace(/ /g,'').length
For removing only beginning and trailing white-space:
$.trim($("#test").val()).length
For example, the string " t e s t "
would evaluate as:
//" t e s t "
$("#id").val();
//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7
Here is a demo using all of them.
Type regsvr32 name.dll
into the Command Prompt (executed in elevated mode!) and press "Enter." Note that name.dll
should be replaced with the name of the DLL that you want to register. For example, if you want to register the iexplore.dll, type regsvr32 iexplore.dll
.
:set fileformat=unix
to convert from DOS to Unix.
SELECT
hat,
shoe,
boat,
0 as placeholder -- for column having 0 value
FROM
objects
--OR '' as Placeholder -- for blank column
--OR NULL as Placeholder -- for column having null value
I often just open the console and look for the solution in the objects methods. Quite often it's already there:
>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello s'
Short answer: Use string.replace()
.
Another to answer this question available here answered by @nilesh https://stackoverflow.com/a/19934852/2079692
public void setAttributeValue(WebElement elem, String value){
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",
elem, "value", value
);
}
this takes advantage of selenium findElementBy function where xpath can be used also.
What language? and why use regex for this simple task?
If you must:
^(.*)/([^/]*)$
gives you the two parts you wanted. You might need to quote the parentheses:
^\(.*\)/\([^/]*\)$
depending on your preferred language syntax.
But I suggest you just use your language's string search function that finds the last "/" character, and split the string on that index.
Try this:
window.location.href = "http://PlaceYourUrl.com";
Just copied file: org.apache.http.legacy.jar
from Android/Sdk/platforms/android-23/optional
folder into project folder app/libs
.
Worked like charm for 23.1.1.
You seem to be using Windows Forms. Look at the SelectedIndex or SelectedItem properties.
if (this.combo1.SelectedItem == MY_OBJECT)
{
// do stuff
}
Repeat the parent's dependency in child pom.xml and insert the exclusion there:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
There are three parts to this:
Once you have your key stored in a PEM file, you can read it back easily using PemObject and PemReader classes provided by BouncyCastle, as shown in this this tutorial.
Create a PemFile class that encapsulates file handling:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
public class PemFile {
private PemObject pemObject;
public PemFile(String filename) throws FileNotFoundException, IOException {
PemReader pemReader = new PemReader(new InputStreamReader(
new FileInputStream(filename)));
try {
this.pemObject = pemReader.readPemObject();
} finally {
pemReader.close();
}
}
public PemObject getPemObject() {
return pemObject;
}
}
Then instantiate private and public keys as usual:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Main {
protected final static Logger LOGGER = Logger.getLogger(Main.class);
public final static String RESOURCES_DIR = "src/main/resources/rsa-sample/";
public static void main(String[] args) throws FileNotFoundException,
IOException, NoSuchAlgorithmException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
LOGGER.info("BouncyCastle provider added.");
KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
try {
PrivateKey priv = generatePrivateKey(factory, RESOURCES_DIR
+ "id_rsa");
LOGGER.info(String.format("Instantiated private key: %s", priv));
PublicKey pub = generatePublicKey(factory, RESOURCES_DIR
+ "id_rsa.pub");
LOGGER.info(String.format("Instantiated public key: %s", pub));
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
private static PrivateKey generatePrivateKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename);
byte[] content = pemFile.getPemObject().getContent();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
return factory.generatePrivate(privKeySpec);
}
private static PublicKey generatePublicKey(KeyFactory factory,
String filename) throws InvalidKeySpecException,
FileNotFoundException, IOException {
PemFile pemFile = new PemFile(filename);
byte[] content = pemFile.getPemObject().getContent();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
return factory.generatePublic(pubKeySpec);
}
}
Hope this helps.
If you have dynamic element ID where you need to assign the dynamic value, you may use this:
//element_id = you dynamic id.
//dynamic_val = you dynamic value.
let _el = document.getElementById(element_id);
_el.value = dynamic_val.toString();
This works for me.
If anyone is struggling with angular version 4+ (mine was 4.3.6). This was the sample code which worked for me.
First add the required imports
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
Then for the api function. It's a login sample which can be changed as per your needs.
login(username: string, password: string) {
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('email', username);
urlSearchParams.append('password', password);
let body = urlSearchParams.toString()
return this.http.post('http://localhost:3000/api/v1/login', body, {headers: headers})
.map((response: Response) => {
// login successful if user.status = success in the response
let user = response.json();
console.log(user.status)
if (user && "success" == user.status) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user.data));
}
});
}
What about?
If oSheet.QueryTables.Count > 0 Then
oCmbBox.AddItem oSheet.Name
End If
Or
If oSheet.ListObjects.Count > 0 Then
'// Source type 3 = xlSrcQuery
If oSheet.ListObjects(1).SourceType = 3 Then
oCmbBox.AddItem oSheet.Name
End IF
End IF
I fixed it. My actual image file name had spaces in it, and for whatever reason Angular did not like that. When I removed the spaces from my file name, assets/images/myimage.png
worked.
ExPanDaR’s package function prepare_missing_values_graph
can be used to explore panel data:
Mongoose 4.5 support this
Project.find(query)
.populate({
path: 'pages',
populate: {
path: 'components',
model: 'Component'
}
})
.exec(function(err, docs) {});
And you can join more than one deep level
This is how I implemented Spring MVC Multipart Request with JSON Data.
Based on RESTful service in Spring 4.0.2 Release, HTTP request with the first part as XML or JSON formatted data and the second part as a file can be achieved with @RequestPart. Below is the sample implementation.
Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.
@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
@RequestPart("properties") @Valid ConnectionProperties properties,
@RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}
Create a FormData object.
Append the file to the FormData object using one of the below steps.
formData.append("file", document.forms[formName].file.files[0]);
formData.append("file", myFile, "myfile.txt");
OR formData.append("file", myBob, "myfile.txt");
Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.
Send the request to the server.
Request Details:
Content-Type: undefined
. This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.
formData = new FormData();
formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
"name": "root",
"password": "root"
})], {
type: "application/json"
}));
method: "POST",
headers: {
"Content-Type": undefined
},
data: formData
Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--
This blog entry has a way to emulate border-color: transparent
in IE6. The below example includes the "hasLayout" fix that is brought up in the blog entry comments:
/* transparent border */
.testDiv {
width: 200px;
height: 200px;
border: solid 10px transparent;
}
/* IE6 fix */
*html .testDiv {
zoom: 1;
border-color: #FEFEFE;
filter: chroma(color=#FEFEFE);
}
Make sure that the border-color
used in the IE6 fix is not used anywhere in the .testDiv
element. I changed the example from pink
to #FEFEFE
because that seems even less likely to be used.
a quick way to see your errors whilst testing:
$error= $st->errorInfo();
echo $error[2];
I tried subtract, but the result was not consistent.
If I run df1.subtract(df2)
, not all lines of df1 are shown on the result dataframe, probably due distinct
cited on the docs.
This solved my problem:
df1.exceptAll(df2)
Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp
Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:
I hope that helps
To insert a CR into XML, you need to use its character entity
.
This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.
Just add the directory on the command line:
svn checkout svn://192.168.1.1/projectname/ target-directory/
I believe
rgba( 0, 0, 0, 0.8 )
is equivalent in shade with #333
.
Live demo: http://jsfiddle.net/8MVC5/1/
You can simply use the WebDriver
object, and access to the page source code via its @property
field page_source
...
Try this code snippet :-)
from selenium import webdriver
driver = webdriver.Firefox('path/to/executable')
driver.get('https://some-domain.com')
source = driver.page_source
if 'stuff' in source:
print('found...')
else:
print('not in source...')
Specifying the column type as serial for PostgreSQL to generate the id.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order=1, TypeName="serial")]
public int ID { get; set; }
https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL
This provided a simple solution: Set data in Select2 after insert with AJAX
$("#select2").select2('data', {id: newID, text: newText});
I had the same question for macOS.
But the root cause was not installing Six. My macOS shipped Python version 2.7 was being usurped by a Python2 version I inherited by installing a package via brew
.
I fixed my issue with: $ brew uninstall python@2
Some context on here: https://bugs.swift.org/browse/SR-1061
To use session variables, it's necessary to start the session by using the session_start
function, this will allow you to store your data in the global variable $_SESSION
in a productive way.
so your code will finally look like this :
<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['picturenum'] = $_POST['picturenum'];
}
?>
<strong><?php echo $_SESSION['picturenum'];?></strong>
to make it easy to use and to avoid forgetting it again, you can create a session_file.php
which you will want to be included in all your codes and will start the session for you:
session_start.php
<?php
session_start();
?>
and then include it wherever you like :
<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
// including the session file
require_once("session_start.php");
if (isset($_POST['Submit'])) {
$_SESSION['picturenum'] = $_POST['picturenum'];
}
?>
that way it is more portable and easy to maintain in the future.
other remarks
if you are using Apache version 2 or newer, be careful. instead of
<?
to open php's tags, use
<?php
, otherwise your code will not be interpreted
variables names in php are case-sensitive, instead of write $_session, write $_SESSION in capital letters
good work!
I had to transform the divs to list items otherwise all my divs would get that class and only the generated ones should get it Thanks everyone, I love this site and the helpful people on it !!!! You can follow the newbie school project at http://low-budgetwebservice.be/project/webbuilder.html suggestions are always welcome :). So this worked for me:
/* Add Class Heading*/
$(document).ready(function() {
$( document ).on( 'click', 'ul#items li', function () {
$('ul#items li').removeClass('active');
$(this).addClass('active');
});
});
IIS v10 (but this should be the same also for IIS 7.x)
Quick addition for people which are looking for respective max values
Max for maxAllowedContentLength
is: UInt32.MaxValue
4294967295 bytes
: ~4GB
Max for maxRequestLength
is: Int32.MaxValue
2147483647 bytes
: ~2GB
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<!-- ~ 2GB -->
<httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- ~ 4GB -->
<requestLimits maxAllowedContentLength="4294967295" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
$('#list option').each(function(index){
//do stuff
console.log(index);
});
logs the index :)
a more detailed example is below.
function run_each() {_x000D_
_x000D_
var $results = $(".results");_x000D_
_x000D_
$results.empty();_x000D_
_x000D_
$results.append("==================== START 1st each ====================");_x000D_
console.log("==================== START 1st each ====================");_x000D_
_x000D_
$('#my_select option').each(function(index, value) {_x000D_
$results.append("<br>");_x000D_
// log the index_x000D_
$results.append("index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log("index: " + index);_x000D_
// logs the element_x000D_
// $results.append(value); this would actually remove the element_x000D_
$results.append("<br>");_x000D_
console.log(value);_x000D_
// logs element property_x000D_
$results.append(value.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(value.innerHTML);_x000D_
// logs element property_x000D_
$results.append(this.text);_x000D_
$results.append("<br>");_x000D_
console.log(this.text);_x000D_
// jquery_x000D_
$results.append($(this).text());_x000D_
$results.append("<br>");_x000D_
console.log($(this).text());_x000D_
_x000D_
// BEGIN just to see what would happen if nesting an .each within an .each_x000D_
$('p').each(function(index) {_x000D_
$results.append("==================== nested each");_x000D_
$results.append("<br>");_x000D_
$results.append("nested each index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log(index);_x000D_
});_x000D_
// END just to see what would happen if nesting an .each within an .each_x000D_
_x000D_
});_x000D_
_x000D_
$results.append("<br>");_x000D_
$results.append("==================== START 2nd each ====================");_x000D_
console.log("");_x000D_
console.log("==================== START 2nd each ====================");_x000D_
_x000D_
_x000D_
$('ul li').each(function(index, value) {_x000D_
$results.append("<br>");_x000D_
// log the index_x000D_
$results.append("index: " + index);_x000D_
$results.append("<br>");_x000D_
console.log(index);_x000D_
// logs the element_x000D_
// $results.append(value); this would actually remove the element_x000D_
$results.append("<br>");_x000D_
console.log(value);_x000D_
// logs element property_x000D_
$results.append(value.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(value.innerHTML);_x000D_
// logs element property_x000D_
$results.append(this.innerHTML);_x000D_
$results.append("<br>");_x000D_
console.log(this.innerHTML);_x000D_
// jquery_x000D_
$results.append($(this).text());_x000D_
$results.append("<br>");_x000D_
console.log($(this).text());_x000D_
});_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(document).on("click", ".clicker", function() {_x000D_
_x000D_
run_each();_x000D_
_x000D_
});
_x000D_
.results {_x000D_
background: #000;_x000D_
height: 150px;_x000D_
overflow: auto;_x000D_
color: lime;_x000D_
font-family: arial;_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.one,_x000D_
.two,_x000D_
.three {_x000D_
width: 33.3%;_x000D_
}_x000D_
_x000D_
.one {_x000D_
background: yellow;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.two {_x000D_
background: pink;_x000D_
}_x000D_
_x000D_
.three {_x000D_
background: darkgray;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<div class="one">_x000D_
<select id="my_select">_x000D_
<option>apple</option>_x000D_
<option>orange</option>_x000D_
<option>pear</option>_x000D_
</select>_x000D_
</div>_x000D_
_x000D_
<div class="two">_x000D_
<ul id="my_list">_x000D_
<li>canada</li>_x000D_
<li>america</li>_x000D_
<li>france</li>_x000D_
</ul>_x000D_
</div>_x000D_
_x000D_
<div class="three">_x000D_
<p>do</p>_x000D_
<p>re</p>_x000D_
<p>me</p>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<button class="clicker">run_each()</button>_x000D_
_x000D_
_x000D_
<div class="results">_x000D_
_x000D_
_x000D_
</div>
_x000D_
Take out the parentheses and the curly braces, neither are required when adding columns.
Take these steps:
Dbset<Item> Items{get;set;}
and in Nuget Console run these commandsIt will drop table(s) that not exist in Context, but already created in database
Create a stateful color for your button, just like you did for background, for example:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false"
android:color="#ffffff" />
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true"
android:color="#000000" />
<!-- Unfocused and pressed -->
<item android:state_focused="false"
android:state_pressed="true"
android:color="#000000" />
<!-- Default color -->
<item android:color="#ffffff" />
</selector>
Place the xml in a file at res/drawable folder i.e. res/drawable/button_text_color.xml. Then just set the drawable as text color:
android:textColor="@drawable/button_text_color"
There is no easy way to do this. I needed this as well, but wanted a function that can take any two variables and test for equality. That includes non-object values, objects, arrays and any level of nesting.
In your question, you mention wanting to ignore the order of the values in an array. My solution doesn't inherently do that, but you can achieve it by sorting the arrays before comparing for equality
I also wanted the option of casting non-objects to strings so that [1,2]===["1",2]
Since my project uses UnderscoreJs, I decided to make it a mixin rather than a standalone function.
You can test it out on http://jsfiddle.net/nemesarial/T44W4/
Here is my mxin:
_.mixin({
/**
Tests for the equality of two variables
valA: first variable
valB: second variable
stringifyStatics: cast non-objects to string so that "1"===1
**/
equal:function(valA,valB,stringifyStatics){
stringifyStatics=!!stringifyStatics;
//check for same type
if(typeof(valA)!==typeof(valB)){
if((_.isObject(valA) || _.isObject(valB))){
return false;
}
}
//test non-objects for equality
if(!_.isObject(valA)){
if(stringifyStatics){
var valAs=''+valA;
var valBs=''+valB;
ret=(''+valA)===(''+valB);
}else{
ret=valA===valB;
}
return ret;
}
//test for length
if(_.size(valA)!=_.size(valB)){
return false;
}
//test for arrays first
var isArr=_.isArray(valA);
//test whether both are array or both object
if(isArr!==_.isArray(valB)){
return false;
}
var ret=true;
if(isArr){
//do test for arrays
_.each(valA,function(val,idx,lst){
if(!ret){return;}
ret=ret && _.equal(val,valB[idx],stringifyStatics);
});
}else{
//do test for objects
_.each(valA,function(val,idx,lst){
if(!ret){return;}
//test for object member exists
if(!_.has(valB,idx)){
ret=false;
return;
}
// test for member equality
ret=ret && _.equal(val,valB[idx],stringifyStatics);
});
}
return ret;
}
});
This is how you use it:
_.equal([1,2,3],[1,2,"3"],true)
To demonstrate nesting, you can do this:
_.equal(
['a',{b:'b',c:[{'someId':1},2]},[1,2,3]],
['a',{b:'b',c:[{'someId':"1"},2]},["1",'2',3]]
,true);
Go to the repository folder. Delete relevant submodules from .gitmodules. Select show hidden files. Go to .git folder, delete the submodules from module folder and config.
Writing a useful general-purpose floating point IsEqual
is very, very hard, if not outright impossible. Your current code will fail badly for a==0
. How the method should behave for such cases is really a matter of definition, and arguably the code would best be tailored for the specific domain use case.
For this kind of thing, you really, really need a good test suite. That's how I did it for The Floating-Point Guide, this is what I came up with in the end (Java code, should be easy enough to translate):
public static boolean nearlyEqual(float a, float b, float epsilon) {
final float absA = Math.abs(a);
final float absB = Math.abs(b);
final float diff = Math.abs(a - b);
if (a == b) { // shortcut, handles infinities
return true;
} else if (a == 0 || b == 0 || absA + absB < Float.MIN_NORMAL) {
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Float.MIN_NORMAL);
} else { // use relative error
return diff / (absA + absB) < epsilon;
}
}
You can also find the test suite on the site.
Appendix: Same code in c# for doubles (as asked in questions)
public static bool NearlyEqual(double a, double b, double epsilon)
{
const double MinNormal = 2.2250738585072014E-308d;
double absA = Math.Abs(a);
double absB = Math.Abs(b);
double diff = Math.Abs(a - b);
if (a.Equals(b))
{ // shortcut, handles infinities
return true;
}
else if (a == 0 || b == 0 || absA + absB < MinNormal)
{
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * MinNormal);
}
else
{ // use relative error
return diff / (absA + absB) < epsilon;
}
}
I Found Solution Of You Question But In Stack Not Allow to Upload Video See the link below it show better explain
function flatten_array($array, $preserve_keys = 0, &$out = array()) {
# Flatten a multidimensional array to one dimension, optionally preserving keys.
#
# $array - the array to flatten
# $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
# $out - internal use argument for recursion
foreach($array as $key => $child)
if(is_array($child))
$out = flatten_array($child, $preserve_keys, $out);
elseif($preserve_keys + is_string($key) > 1)
$out[$key] = $child;
else
$out[] = $child;
return $out;
}
After Much Fannying about, deleting this that etc, I found the way to delete a "website" from your list (which is, in fact what the original question was - minus all the flaffing) is
That's it… Done.
Remember: for this exercise only Account means Website.
SQLite Boolean Datatype:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
You can convert boolean to int in this way:
int flag = (boolValue)? 1 : 0;
You can convert int back to boolean as follows:
// Select COLUMN_NAME values from db.
// This will be integer value, you can convert this int value back to Boolean as follows
Boolean flag2 = (intValue == 1)? true : false;
If you want to explore sqlite, here is a tutorial.
I have given one answer here. It is working for them.
Read this (supplementary) answer (that is sometimes the answer) to understand where this is going and why some people in this thread complain that "it is still not working"
I wrote exactly same code as one of the answers here. But I still had an issue. I placed break point on
var mi = o.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance );
It executed but mi == null
And it continued behavior like this until I did "re-build" on all projects involved. I was unit testing one assembly while the reflection method was sitting in third assembly. It was totally confusing but I used Immediate Window to discover methods and I found that a private method I tried to unit test had old name (I renamed it). This told me that old assembly or PDB is still out there even if unit test project builds - for some reason project it tests didn't built. "rebuild" worked
I had the same problem recently and this helped me:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="FILENAME"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize("PATH/TO/FILE"));
ob_clean();
flush();
readfile(PATH/TO/FILE);
exit();
I found this answer here
I already said that I was new to exec()
function. After doing some more digging, I came upon 2>&1
which needs to be added at the end of command in exec()
.
Thanks @mattosmat
for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
Assuming line
is a variable which holds your required line number, if you can use head
and tail
, then it is quite simple:
head -n $line file | tail -1
If not, this should work:
x=0
want=5
cat lines | while read line; do
x=$(( x+1 ))
if [ $x -eq "$want" ]; then
echo $line
break
fi
done
OAuth 2.0 spec doesn't define the part. But there could be couple of options:
When resource server gets the token in the Authz Header then it calls the validate/introspect API on Authz server to validate the token. Here Authz server might validate it either from using DB Store or verifying the signature and certain attributes. As part of response, it decodes the token and sends the actual data of token along with remaining expiry time.
Authz Server can encrpt/sign the token using private key and then publickey/cert can be given to Resource Server. When resource server gets the token, it either decrypts/verifies signature to verify the token. Takes the content out and processes the token. It then can either provide access or reject.
To see non-staged (non-added) changes to existing files
git diff
Note that this does not track new files. To see staged, non-commited changes
git diff --cached
Use this command:
egrep -lRZ "\.jpg|\.png|\.gif" . \
| xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'
egrep
: find matching lines using extended regular expressions
-l
: only list matching filenames
-R
: search recursively through all given directories
-Z
: use \0
as record separator
"\.jpg|\.png|\.gif"
: match one of the strings ".jpg"
, ".gif"
or ".png"
.
: start the search in the current directory
xargs
: execute a command with the stdin as argument
-0
: use \0
as record separator. This is important to match the -Z
of egrep
and to avoid being fooled by spaces and newlines in input filenames.
-l
: use one line per command as parameter
sed
: the stream editor
-i
: replace the input file with the output without making a backup
-e
: use the following argument as expression
's/\.jpg\|\.gif\|\.png/.bmp/g'
: replace all occurrences of the strings ".jpg"
, ".gif"
or ".png"
with ".bmp"
IPython is a powerful interactive Python interpreter that is more interactive comparing to the standard interpreter.
To get the standard Python interpreter you type python
and you will get the >>>
prompt from where you can work.
To get IPython interpreter, you need to install it first. pip install ipython
.
You type ipython
and you get In [1]:
as a prompt and you get In [2]:
for the next command. You can call history
to check the list of previous commands, and write %recall 1
to recall the command.
Even you are in Python you can run shell commands directly like !ping www.google.com
.
Looks like a command line Jupiter notebook if you used that before.
From the jQuery docs for processData
:
processData Boolean
Default: true
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
Source: http://api.jquery.com/jquery.ajax
Looks like you are going to have to use processData
to send your data to the server, or modify your php script to support querystring encoded parameters.
I got the same issue while adding dynamic url in Image tag in Angular 7. I searched a lot and found this solution.
First, write below code in the component file.
constructor(private sanitizer: DomSanitizer) {}
public getSantizeUrl(url : string) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}
Now in your html image tag, you can write like this.
<img class="image-holder" [src]=getSantizeUrl(item.imageUrl) />
You can write as per your requirement instead of item.imageUrl
I got a reference from this site.dynamic urls. Hope this solution will help you :)
R has gotten to the point where the OS cannot allocate it another 75.1Mb chunk of RAM. That is the size of memory chunk required to do the next sub-operation. It is not a statement about the amount of contiguous RAM required to complete the entire process. By this point, all your available RAM is exhausted but you need more memory to continue and the OS is unable to make more RAM available to R.
Potential solutions to this are manifold. The obvious one is get hold of a 64-bit machine with more RAM. I forget the details but IIRC on 32-bit Windows, any single process can only use a limited amount of RAM (2GB?) and regardless Windows will retain a chunk of memory for itself, so the RAM available to R will be somewhat less than the 3.4Gb you have. On 64-bit Windows R will be able to use more RAM and the maximum amount of RAM you can fit/install will be increased.
If that is not possible, then consider an alternative approach; perhaps do your simulations in batches with the n per batch much smaller than N
. That way you can draw a much smaller number of simulations, do whatever you wanted, collect results, then repeat this process until you have done sufficient simulations. You don't show what N
is, but I suspect it is big, so try smaller N
a number of times to give you N
over-all.
Class.isAssignableFrom()
- works for interfaces as well. If you don't want that, you'll have to call getSuperclass()
and test until you reach Object
.
Use powershell inside your bat file
PowerShell Remove-Item c:\scripts\* -include *.txt -exclude *test* -force -recurse
You can also exclude from removing some specific folder or file:
PowerShell Remove-Item C:/* -Exclude WINDOWS,autoexec.bat -force -recurse
You could simply use ArrayUtils.contains
from Apache Commons Lang library
.
public boolean contains(final int[] array, final int key) {
return ArrayUtils.contains(array, key);
}
In my case, I had a page where it was an input type='date'
whose reference I had got on page load, but When I tried to interact with it, it showed this exception
and that was quite meaningful as Javascript
had manipulated my control hence it was detached from the document and I had to re-get
its reference after the javascript had performed its job with the control.
So, this is how my code looked before the exception:
if (elemDate != null)
{
elemDate.Clear();
elemDate.SendKeys(model.Age);
}
Code after the exception was raised:
int tries = 0;
do
{
try
{
tries++;
if (elemDate != null)
{
// these lines were causing the exception so I had break after these are successfully executed because if they are executed that means the control was found and attached to the document and we have taken the reference of it again.
elemDate.Clear();
elemDate.SendKeys(model.Age);
break;
}
}
catch (StaleElementReferenceException)
{
System.Threading.Thread.Sleep(10); // put minor fake delay so Javascript on page does its actions with controls
elemDate = driver.FindElement(By.Id(dateId));
}
} while (tries < 3); // Try it three times.
So, Now you can perform further actions with your code or you can quit the driver if it was unsuccessful in getting the control to work.
if(tries > 2)
{
// element was not found, find out what is causing the control detachment.
// driver.Quit();
return;
}
// Hurray!! Control was attached and actions were performed.
// Do something with it...
Something that I have learnt so far is, catching exceptions to know about successful code execution is not a good idea, But, I had to do it and I found this
work-around
to be working well in this case.
PS: After writing all this, I just noticed the tags that this thread was for java
. This code sample is just for demonstration purpose, It might help people who have issue in C#
language. Or it can be easily translated to java
as it doesn't have much C#
specific code.
Try replacing "code" with "pre". The pre tag in HTML marks the text as preformatted and all linefeeds and spaces will appear exactly as you type them.
|| is the logical or operator while | is the bitwise or operator.
boolean a = true;
boolean b = false;
if (a || b) {
}
int a = 0x0001;
a = a | 0x0002;
Try this:
#foo
{
position: absolute;
top: 100%;
right: 0%;
}
The old way:
xcopy [source] [destination] /E
xcopy is deprecated. Robocopy replaces Xcopy. It comes with Windows 8, 8.1 and 10.
robocopy [source] [destination] /E
robocopy has several advantages:
More details here.
It worked in my case
sudo npm uninstall -g angular-cli @angular/cli
sudo npm cache clean --force
npm install npm@latest -g
sudo npm install -g @angular/cli
For set Title :
getActionBar().setTitle("Title");
For set Icon :
getActionBar().setIcon(R.drawable.YOUR_ICON_NAME);
You cannot create migration scripts for existing models.
Resources:
If going the classic way, you'll have to recreate the models via the CLI:
sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text
It will generate these files:
models/myuser.js:
"use strict";_x000D_
module.exports = function(sequelize, DataTypes) {_x000D_
var MyUser = sequelize.define("MyUser", {_x000D_
first_name: DataTypes.STRING,_x000D_
last_name: DataTypes.STRING,_x000D_
bio: DataTypes.TEXT_x000D_
}, {_x000D_
classMethods: {_x000D_
associate: function(models) {_x000D_
// associations can be defined here_x000D_
}_x000D_
}_x000D_
});_x000D_
return MyUser;_x000D_
};
_x000D_
migrations/20150210104840-create-my-user.js:
"use strict";_x000D_
module.exports = {_x000D_
up: function(migration, DataTypes, done) {_x000D_
migration.createTable("MyUsers", {_x000D_
id: {_x000D_
allowNull: false,_x000D_
autoIncrement: true,_x000D_
primaryKey: true,_x000D_
type: DataTypes.INTEGER_x000D_
},_x000D_
first_name: {_x000D_
type: DataTypes.STRING_x000D_
},_x000D_
last_name: {_x000D_
type: DataTypes.STRING_x000D_
},_x000D_
bio: {_x000D_
type: DataTypes.TEXT_x000D_
},_x000D_
createdAt: {_x000D_
allowNull: false,_x000D_
type: DataTypes.DATE_x000D_
},_x000D_
updatedAt: {_x000D_
allowNull: false,_x000D_
type: DataTypes.DATE_x000D_
}_x000D_
}).done(done);_x000D_
},_x000D_
down: function(migration, DataTypes, done) {_x000D_
migration.dropTable("MyUsers").done(done);_x000D_
}_x000D_
};
_x000D_
You can always apply simple if-else logic and add one more if
logic to your code along with a for
loop.
while True:
age = int(input("Please enter your age: "))
if (age >= 18) :
print("You are able to vote in the United States!")
if (age < 18) & (age > 0):
print("You are not able to vote in the United States.")
else:
print("Wrong characters, the input must be numeric")
continue
This will be an infinite loo and you would be asked to enter the age, indefinitely.
I created a function for updating GridView column headers for a list and call it whenever the window is re-sized or the listview updates it's layout.
public void correctColumnWidths()
{
double remainingSpace = myList.ActualWidth;
if (remainingSpace > 0)
{
for (int i = 0; i < (myList.View as GridView).Columns.Count; i++)
if (i != 2)
remainingSpace -= (myList.View as GridView).Columns[i].ActualWidth;
//Leave 15 px free for scrollbar
remainingSpace -= 15;
(myList.View as GridView).Columns[2].Width = remainingSpace;
}
}
I wrote a simple recursive function to do the job:
from xml.etree import ElementTree
root = ElementTree.XML(xml_to_convert)
def xml_to_dict_recursive(root):
if len(root.getchildren()) == 0:
return {root.tag:root.text}
else:
return {root.tag:list(map(xml_to_dict_recursive, root.getchildren()))}
You can use np.logaddexp
(which implements the idea in @gg349's answer):
In [33]: d = np.array([[1089, 1093]])
In [34]: e = np.array([[1000, 4443]])
In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])
In [36]: log_res
Out[36]: -266.99999385580668
In [37]: res = exp(log_res)
In [38]: res
Out[38]: 1.1050349147204485e-116
Or you can use scipy.special.logsumexp
:
In [52]: from scipy.special import logsumexp
In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))
In [54]: res
Out[54]: 1.1050349147204485e-116
Not able to understand your actual problem but your case statement is incorrect
CASE
WHEN
TABLE3.COL3 IS NULL
THEN TABLE2.COL3
ELSE
TABLE3.COL3
END
AS
COL4
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
Override service method like this:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
And Voila!
Ensure you have the maven.google.com repository declared in your module-level build.gradle file
repositories {
maven {
url 'https://maven.google.com'
}
}
2.Add the library as a dependency in the same build.gradle file:
dependencies {
compile 'com.android.support.constraint:constraint-layout:1.0.2'
}
Try this one also...
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<p>Click the button to join two arrays.</p>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
<script>_x000D_
function myFunction() {_x000D_
var hege = [{_x000D_
1: "Cecilie",_x000D_
2: "Lone"_x000D_
}];_x000D_
var stale = [{_x000D_
1: "Emil",_x000D_
2: "Tobias"_x000D_
}];_x000D_
var hege = hege.concat(stale);_x000D_
document.getElementById("demo1").innerHTML = hege;_x000D_
document.getElementById("demo").innerHTML = stale;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Given the following sample
myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)
then
myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)
or you could select your columns altogether and wrap it up nicely:
# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))
levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")
To obtain
> myData
A B Pulse
1 long 1kg 20
2 short 2kg 21
3 long 3kg 22
4 short 1kg 23
5 long 2kg 24
6 short 3kg 25
Problem solved, I've not added the index.html. Which is point out in the web.xml
Note: a project may have more than one web.xml file.
if there are another web.xml in
src/main/webapp/WEB-INF
Then you might need to add another index (this time index.jsp) to
src/main/webapp/WEB-INF/pages/
First you need to allocate an array of the combined length, then use arraycopy to fill it from both sources.
byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = new byte[ciphertext.length + mac.length];
System.arraycopy(ciphertext, 0, out, 0, ciphertext.length);
System.arraycopy(mac, 0, out, ciphertext.length, mac.length);
You are correct that storing the password in a plain-text field is a horrible idea. However, as far as location goes, for most of the cases you're going to encounter (and I honestly can't think of any counter-examples) storing the representation of a password in the database is the proper thing to do. By representation I mean that you want to hash the password using a salt (which should be different for every user) and a secure 1-way algorithm and store that, throwing away the original password. Then, when you want to verify a password, you hash the value (using the same hashing algorithm and salt) and compare it to the hashed value in the database.
So, while it is a good thing you are thinking about this and it is a good question, this is actually a duplicate of these questions (at least):
To clarify a bit further on the salting bit, the danger with simply hashing a password and storing that is that if a trespasser gets a hold of your database, they can still use what are known as rainbow tables to be able to "decrypt" the password (at least those that show up in the rainbow table). To get around this, developers add a salt to passwords which, when properly done, makes rainbow attacks simply infeasible to do. Do note that a common misconception is to simply add the same unique and long string to all passwords; while this is not horrible, it is best to add unique salts to every password. Read this for more.
When you use setcookie
, you can either set the expiration time to 0
or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).
For IE9+
@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
// IE9+ CSS
.selector{
color: red;
}
}
IE Edge 12+
@supports (-ms-ime-align: auto) {
.selector {
color: red;
}
}
This one works on Edge and all IEs
:-ms-lang(x), .selector { color: red; }
I face the same problem, and think that I do know why this happens.
The gmail account that I use is normally used from India, and the webserver that I use is located in The Netherlands.
Google notifies that there was a login attempt from am unusualy location and requires to login from that location via a web browser.
Furthermore I had to accept suspicious access to the gmail account via https://security.google.com/settings/security/activity
But in the end my problem is not yet solved, because I have to login to gmail from a location in The Netherlands.
I hope this will help you a little! (sorry, I do not read email replies on this email address)
The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
. Let's replace it in its context:
i + 1 >= len(x)
<=> i >= 0
, the element x[i+1]
doesn't exist. Here, this element doesn't exist since the beginning of the for loop.To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
.
Framework will handle switching the views for you once you setup your cell's backgroundView
and selectedBackgroundView
, see example from Managing the Visual State for Selections and Highlights:
UIView* backgroundView = [[UIView alloc] initWithFrame:self.bounds];
backgroundView.backgroundColor = [UIColor redColor];
self.backgroundView = backgroundView;
UIView* selectedBGView = [[UIView alloc] initWithFrame:self.bounds];
selectedBGView.backgroundColor = [UIColor whiteColor];
self.selectedBackgroundView = selectedBGView;
you only need in your class that implements UICollectionViewDelegate
enable cells to be highlighted and selected like this:
- (BOOL)collectionView:(UICollectionView *)collectionView
shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (BOOL)collectionView:(UICollectionView *)collectionView
shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath;
{
return YES;
}
This works me.
To find any file location
function get_format($df) {
$str = '';
$str .= ($df->invert == 1) ? ' - ' : '';
if ($df->y > 0) {
// years
$str .= ($df->y > 1) ? $df->y . ' Years ' : $df->y . ' Year ';
} if ($df->m > 0) {
// month
$str .= ($df->m > 1) ? $df->m . ' Months ' : $df->m . ' Month ';
} if ($df->d > 0) {
// days
$str .= ($df->d > 1) ? $df->d . ' Days ' : $df->d . ' Day ';
}
echo $str;
}
$yr=$year;
$dates=$dor;
$myyear='+'.$yr.' years';
$new_date = date('Y-m-d', strtotime($myyear, strtotime($dates)));
$date1 = new DateTime("$new_date");
$date2 = new DateTime("now");
$diff = $date2->diff($date1);
try this using hooks:
const [dynamicClasses, setDynamicClasses] = React.useState([
"dynamicClass1", "dynamicClass2"
]);
and add this in className attribute :
<div className=`wrapper searchDiv ${[...dynamicClasses]}`>
...
</div>
to add class :
const addClass = newClass => {
setDynamicClasses([...dynamicClasses, newClass])
}
to delete class :
const deleteClass= classToDelete => {
setDynamicClasses(dynamicClasses.filter(class = > {
class !== classToDelete
}));
}
How about one of the many wikis?
Kenny: I've used FlexWiki & ScrewTurn (abandoned).
someone else with RepPower to edit my post added this.
Wikipedia is powered by MediaWiki.
Went through the various resources on the net but none of them helped then i deleted the existing server and added the same server again and now it is working fine and the steps are
Window>>ShowView>>Servers>>RightClick>>Delete
and then add the server again as you have added previously.
As an aside to what folks have been posting here, I've heard that concatenation can be much faster than join in modern javascript vms. Meaning:
var a =
[ "hey man, this is on a line",
"and this is on another",
"and this is on a third"
].join('\n');
Will be slower than:
var a = "hey man, this is on a line\n" +
"and this is on another\n" +
"and this is on a third";
In certain cases. http://jsperf.com/string-concat-versus-array-join/3
As another aside, I find this one of the more appealing features in Coffeescript. Yes, yes, I know, haters gonna hate.
html = '''
<strong>
cup of coffeescript
</strong>
'''
Its especially nice for html snippets. I'm not saying its a reason to use it, but I do wish it would land in ecma land :-(.
Josh
It's not a good idea when you want your images and style information to be cached separately. Also if you encode a large image or a significant number of images in to your css file it will take the browser longer to download the file leaving your site without any of the style information until the download completes. For small images that you don't intend on changing often if ever it is a fine solution.
as far as generating the base64 encoding:
Another thing is - if your keys are very complicated sometimes you need to replace the places of the fields and it helps :
if this dosent work:
foreign key (ISBN, Title) references BookTitle (ISBN, Title)
Then this might work (not for this specific example but in general) :
foreign key (Title,ISBN) references BookTitle (Title,ISBN)
Everyone has overcomplicated this answer:
some_int = <256 bit integer>
some_bytes = some_int.to_bytes(32, sys.byteorder)
my_bytearray = bytearray(some_bytes)
You just need to know the number of bytes that you are trying to convert. In my use cases, normally I only use this large of numbers for crypto, and at that point I have to worry about modulus and what-not, so I don't think this is a big problem to be required to know the max number of bytes to return.
Since you are doing it as 768-bit math, then instead of 32 as the argument it would be 96.
in other way, you can do it with javascript , in Jquery you can use something like:
$('div:visible').last()
*reedited
Here is my solution...
String decodedName = JwtJson.substring(startOfName, endOfName);
StringBuilder builtName = new StringBuilder();
int i = 0;
while ( i < decodedName.length() )
{
if ( decodedName.substring(i).startsWith("\\u"))
{
i=i+2;
builtName.append(Character.toChars(Integer.parseInt(decodedName.substring(i,i+4), 16)));
i=i+4;
}
else
{
builtName.append(decodedName.charAt(i));
i = i+1;
}
};
Basically, use whatever makes the code most readable. There are definitely places where one or the other constructs makes for cleaner, more readable and more maintainable. This is far more important that perhaps saving a few nanoseconds in JavaScript code.
And for all input and select:
$("input[required], select[required]").attr("oninvalid", "this.setCustomValidity('Required!')");
$("input[required], select[required]").attr("oninput", "setCustomValidity('')");
#!/usr/bin/python
import sys
import os
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 50000
try:
s.bind((socket.gethostname() , port))
except socket.error as msg:
print(str(msg))
s.listen(10)
conn, addr = s.accept()
print 'Got connection from'+addr[0]+':'+str(addr[1]))
while 1:
msg = s.recv(1024)
print +addr[0]+, ' >> ', msg
msg = raw_input('SERVER >>'),host
s.send(msg)
s.close()
i would suppose to set the EditText
s width to wrap_content
and put the two buttons into a LinearLayout
whose width is fill_parent
and weight set to 1.
Try saving your .c file before building. I believe your computer is referencing a path to a file with no information inside of it.
--Had similar issue when building C projects
In some browsers, fonts are set explicit for textareas and inputs, so they don’t inherit the fonts from higher elements. So, I think you need to apply the font styles for each textarea and input in the document as well (not just the body).
One idea might be to add clases to the body, then use CSS to style the document accordingly.
I found using while IFS='=' read -r
to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop
.
I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).
The solution does sourcing but massages the contents before sourcing:
#!/usr/bin/env bash
source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')
echo $db_uat_user
Explanation:
grep -v '^ *#'
: discard comment lines
grep '[^ ] *='
: discards lines without =
split($0,a,"=")
: splits line at =
and stores into array a
, i.e. a[1] is the key, a[2] is the value
gensub(/\./, "_", "g", a[1])
: replaces .
with _
print gensub... "=" a[2]}
concatenates the result of gensub
above with =
and value.
Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.
eq is used to compare integers use equal '=' instead , example:
if [ 'AAA' = 'ABC' ];
then
echo "the same"
else
echo "not the same"
fi
good luck
(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})
Will match the following cases
http://www.foufos.gr
https://www.foufos.gr
http://foufos.gr
http://www.foufos.gr/kino
http://werer.gr
www.foufos.gr
www.mp3.com
www.t.co
http://t.co
http://www.t.co
https://www.t.co
www.aa.com
http://aa.com
http://www.aa.com
https://www.aa.com
Will NOT match the following
www.foufos
www.foufos-.gr
www.-foufos.gr
foufos.gr
http://www.foufos
http://foufos
www.mp3#.com
var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;_x000D_
var regex = new RegExp(expression);_x000D_
_x000D_
var check = [_x000D_
'http://www.foufos.gr',_x000D_
'https://www.foufos.gr',_x000D_
'http://foufos.gr',_x000D_
'http://www.foufos.gr/kino',_x000D_
'http://werer.gr',_x000D_
'www.foufos.gr',_x000D_
'www.mp3.com',_x000D_
'www.t.co',_x000D_
'http://t.co',_x000D_
'http://www.t.co',_x000D_
'https://www.t.co',_x000D_
'www.aa.com',_x000D_
'http://aa.com',_x000D_
'http://www.aa.com',_x000D_
'https://www.aa.com',_x000D_
'www.foufos',_x000D_
'www.foufos-.gr',_x000D_
'www.-foufos.gr',_x000D_
'foufos.gr',_x000D_
'http://www.foufos',_x000D_
'http://foufos',_x000D_
'www.mp3#.com'_x000D_
];_x000D_
_x000D_
check.forEach(function(entry) {_x000D_
if (entry.match(regex)) {_x000D_
$("#output").append( "<div >Success: " + entry + "</div>" );_x000D_
} else {_x000D_
$("#output").append( "<div>Fail: " + entry + "</div>" );_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="output"></div>
_x000D_
To answer your immutable question:
Collections.singletonList
will create an immutable List.
An immutable List (also referred to as an unmodifiable List) cannot have it's contents changed. The methods to add or remove items will throw exceptions if you try to alter the contents.
A singleton List contains only that item and cannot be altered.
Just declare a method,e.g:if ur button id is button1 then,
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Context, "Hello", Toast.LENGTH_SHORT).show();
}
});
If you want to make the imageview1 visible then in that method write:
imageview1.setVisibility(ImageView.VISIBLE);
As a follow-up to this question - since it relates specifically to creation time and discusses obtaining it via the new nio classes - it seems right now in JDK7's implementation you're out of luck. Addendum: same behaviour is in OpenJDK7.
On Unix filesystems you cannot retrieve the creation timestamp, you simply get a copy of the last modification time. So sad, but unfortunately true. I'm not sure why that is but the code specifically does that as the following will demonstrate.
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
public class TestFA {
static void getAttributes(String pathStr) throws IOException {
Path p = Paths.get(pathStr);
BasicFileAttributes view
= Files.getFileAttributeView(p, BasicFileAttributeView.class)
.readAttributes();
System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
}
public static void main(String[] args) throws IOException {
for (String s : args) {
getAttributes(s);
}
}
}
Grab it from here
Just choose required version and click 'Binary'. e.g direct link to version 2.5
CREATE TABLE `admnih` (
`id` int(255) NOT NULL auto_increment,
`asim` varchar(255) NOT NULL default '',
`brid` varchar(255) NOT NULL default '',
`rwtbah` int(1) NOT NULL default '0',
`esmmwkeh` varchar(255) NOT NULL default '',
`mrwr` varchar(255) NOT NULL default '',
`tid` int(255) NOT NULL default '0',
`alksmfialdlil` int(255) NOT NULL default '0',
`tariktsjil` varchar(255) NOT NULL default '',
`aimwke` varchar(255) NOT NULL default '',
`twkie` text NOT NULL,
`rwtbahkasah` int(255) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;
In my case, I had all of the required features, but I had installed the Team Explorer version (accidentally used the wrong installer) before installing Professional.
When running the Team Explorer version, only the Blank Solution option was available.
The Team Explorer EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\TeamExplorer\Common7\IDE\devenv.exe"
Once I launched the correct EXE, Visual Studio started working as expected.
The Professional EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.exe"
This solved my issue, and the reason was I had enterprise edition previously installed and then uninstalled and installed the professional edition. Team Explorer was not modified later when I moved to professional from enterprise edition.
You can create a new file, setenv.sh (or setenv.bat) inside tomcats bin directory and add following line there
export CLASSPATH=$CLASSPATH:/XX/xx/PATH_TO_DIR
I had the same issue. In my case I was using digitalocean and nginx.
I have first setup a domain example.app and a subdomain dev.exemple.app in digitalocean.
Second,I purchased two ssl certificat from godaddy.
And finaly, I configured two domain in nginx to use those two ssl certificat with the following snipet
My example.app domain config
server {
listen 7000 default_server;
listen [::]:7000 default_server;
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
root /srv/nodejs/echantillonnage1;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name echantillonnage.app;
ssl_certificate /srv/nodejs/certificatSsl/widcardcertificate/echantillonnage.app.chained.crt;
ssl_certificate_key /srv/nodejs/certificatSsl/widcardcertificate/echantillonnage.app.key;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://127.0.0.1:8090;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
#try_files $uri $uri/ =404;
}
}
My dev.example.app
server {
listen 7000 default_server;
listen [::]:7000 default_server;
listen 444 ssl default_server;
listen [::]:444 ssl default_server;
root /srv/nodejs/echantillonnage1;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name dev.echantillonnage.app;
ssl_certificate /srv/nodejs/certificatSsl/dev/dev.echantillonnage.app.chained.crt;
ssl_certificate_key /srv/nodejs/certificatSsl/dev/dev.echantillonnage.app.key;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://127.0.0.1:8091;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
#try_files $uri $uri/ =404;
}
}
When I was launching https://dev.echantillonnage.app , I was getting
Fix CURL (51) SSL error: no alternative certificate subject name matches
My mistake was the two lines bellow
listen 444 ssl default_server;
listen [::]:444 ssl default_server;
I had to change this to:
listen 443 ssl;
listen [::]:443 ssl;
Hi you do it by using this approach, all fragments will remain in the container once added initially and then we are simply revealing the desired fragment and hiding the others within the container.
// Within an activity
private FragmentA fragmentA;
private FragmentB fragmentB;
private FragmentC fragmentC;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
fragmentA = FragmentA.newInstance("foo");
fragmentB = FragmentB.newInstance("bar");
fragmentC = FragmentC.newInstance("baz");
}
}
// Replace the switch method
protected void displayFragmentA() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (fragmentA.isAdded()) { // if the fragment is already in container
ft.show(fragmentA);
} else { // fragment needs to be added to frame container
ft.add(R.id.flContainer, fragmentA, "A");
}
// Hide fragment B
if (fragmentB.isAdded()) { ft.hide(fragmentB); }
// Hide fragment C
if (fragmentC.isAdded()) { ft.hide(fragmentC); }
// Commit changes
ft.commit();
}
Please see https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments for more info. I hope I get to help anyone. Even if it this is an old question.
This is sample and best way for showing badge on notification launcher icon.
Add This Class in your application
public class BadgeUtils {
public static void setBadge(Context context, int count) {
setBadgeSamsung(context, count);
setBadgeSony(context, count);
}
public static void clearBadge(Context context) {
setBadgeSamsung(context, 0);
clearBadgeSony(context);
}
private static void setBadgeSamsung(Context context, int count) {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
}
private static void setBadgeSony(Context context, int count) {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
}
Intent intent = new Intent();
intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));
intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());
context.sendBroadcast(intent);
}
private static void clearBadgeSony(Context context) {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
}
Intent intent = new Intent();
intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(0));
intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());
context.sendBroadcast(intent);
}
private static String getLauncherClassName(Context context) {
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
if (pkgName.equalsIgnoreCase(context.getPackageName())) {
String className = resolveInfo.activityInfo.name;
return className;
}
}
return null;
}
}
==> MyGcmListenerService.java Use BadgeUtils class when notification comes.
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("Msg");
String Type = data.getString("Type");
Intent intent = new Intent(this, SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.BigTextStyle bigTextStyle= new NotificationCompat.BigTextStyle();
bigTextStyle .setBigContentTitle(getString(R.string.app_name))
.bigText(message);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(getNotificationIcon())
.setContentTitle(getString(R.string.app_name))
.setContentText(message)
.setStyle(bigTextStyle)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
int color = getResources().getColor(R.color.appColor);
notificationBuilder.setColor(color);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int unOpenCount=AppUtill.getPreferenceInt("NOTICOUNT",this);
unOpenCount=unOpenCount+1;
AppUtill.savePreferenceLong("NOTICOUNT",unOpenCount,this);
notificationManager.notify(unOpenCount /* ID of notification */, notificationBuilder.build());
// This is for bladge on home icon
BadgeUtils.setBadge(MyGcmListenerService.this,(int)unOpenCount);
}
private int getNotificationIcon() {
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.notification_small_icon : R.drawable.icon_launcher;
}
}
And clear notification from preference and also with badge count
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
AppUtill.savePreferenceLong("NOTICOUNT",0,this);
BadgeUtils.clearBadge(this);
}
}
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />
Print only current month week:
function my_week_range($date) {
$ts = strtotime($date);
$start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
echo $currentWeek = ceil((date("d",strtotime($date)) - date("w",strtotime($date)) - 1) / 7) + 1;
$start_date = date('Y-m-d', $start);$end_date=date('Y-m-d', strtotime('next saturday', $start));
if($currentWeek==1)
{$start_date = date('Y-m-01', strtotime($date));}
else if($currentWeek==5)
{$end_date = date('Y-m-t', strtotime($date));}
else
{}
return array($start_date, $end_date );
}
$date_range=list($start_date, $end_date) = my_week_range($new_fdate);
in laravel, artisan is a file under root/protected page
for example,
c:\xampp\htdocs\my_project\protected\artisan
you can view the content of "artisan" file with any text editor, it's a php command syntax
so when we type
php artisan
we tell php to run php script in "artisan" file
for example:
php artisan change
will show the change of current laravel version
to see the other option, just type
php artisan
Also make sure that the following property is set in your hibernate bean configuration:
<property name="packagesToScan" value="yourpackage" />
This tells spring and hibernate where to find your domain classes annotated as entities.
They will be initialized to false
by default. In Java arrays are created on heap and every element of the array is given a default value depending on its type. For boolean
data type the default value is false
.
Try using Response.AddHeader
instead of Response.Headers.Add()
I believe this will accomplish the same result, without a subquery or a ranking function:
SELECT *
FROM emp
ORDER BY sal DESC
LIMIT 1
OFFSET 2
I use Toad for Oracle and if the table is owned by another username than the one you logged in as and you have access to read the table, you still may need to add the original table owner to the table name.
For example, lets say the table owner's name is 'OWNER1' and you are logged in as 'USER1'. This query may give you a ORA-00904 error:
select * from table_name where x='test';
Prefixing the table_name with the table owner eliminated the error and gives results:
select * from
I recently got this error because the typo, I write 'canavas' instead of 'canvas', hope this could help someone who is searching for this.
I have the same error and trying docker-machine regenerate-certs
or eval..
did not work for me.
This on OS X 10.11.3 (El Capitan) and Docker v1.10.1. I was able to fix it only by deleting and recreating docker-machine again. Source
If running docker-machine ls
, it shows you a similar output to the one below;
DOCKER
Unknown
ERRORS
Unable to query docker version: Cannot connect to the docker engine endpoint
Try removing your Docker machine with;
docker-machine rm -f default
Where default
is your Docker machine name. Then;
docker-machine create -d virtualbox default
Creates a new Docker machine.
Double check that everything looks normal now (no errors or unknown Docker) with:
docker-machine ls
Finally don't forget to run "$(docker-machine env default)"
before you continue or run the Docker Quickstart Terminal which does it for you...
This is not possible in Lombok. Although it would be a really nice feature, it requires resolution to find the constructors of the super class. The super class is only known by name the moment Lombok gets invoked. Using the import statements and the classpath to find the actual class is not trivial. And during compilation you cannot just use reflection to get a list of constructors.
It is not entirely impossible but the results using resolution in val
and @ExtensionMethod
have taught us that is it hard and error-prone.
Disclosure: I am a Lombok developer.
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
See demo at http://jsbin.com/ApuJOSA/1/edit?html,output .
function mousePositionOnCanvas(e) {
var el=e.target, c=el;
var scaleX = c.width/c.offsetWidth || 1;
var scaleY = c.height/c.offsetHeight || 1;
if (!isNaN(e.offsetX))
return { x:e.offsetX*scaleX, y:e.offsetY*scaleY };
var x=e.pageX, y=e.pageY;
do {
x -= el.offsetLeft;
y -= el.offsetTop;
el = el.offsetParent;
} while (el);
return { x: x*scaleX, y: y*scaleY };
}
if the database is InnoDB you dont need to do joins in deletion. only
DELETE FROM spawnlist WHERE spawnlist.type = "monster";
can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.
CREATE TABLE IF NOT EXIST spawnlist (
npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXIST npc (
idTemplate VARCHAR(20) NOT NULL,
FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE
)ENGINE=InnoDB;
if you uses MyISAM you can delete records joining like this
DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';
in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.
You will not be able to retrieve a plain text password from wordpress.
Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.
See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password
Thanks, I found your answers convincing but in my case, I must use the T properties:
log(n!) = T(n·log n) => log(n!) = O(n log n) and log(n!) = O(n log n)
to verify the problem I found this web, where you have all the process explained: http://www.mcs.sdsmt.edu/ecorwin/cs372/handouts/theta_n_factorial.htm
Here is a plotrix solution:
set.seed(0815)
x <- 1:10
F <- runif(10,1,2)
L <- runif(10,0,1)
U <- runif(10,2,3)
require(plotrix)
plotCI(x, F, ui=U, li=L)
And here is a ggplot solution:
set.seed(0815)
df <- data.frame(x =1:10,
F =runif(10,1,2),
L =runif(10,0,1),
U =runif(10,2,3))
require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
geom_point(size = 4) +
geom_errorbar(aes(ymax = U, ymin = L))
UPDATE: Here is a base solution to your edits:
set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
y = x + rnorm(20))
plot(y ~ x, data = df)
# model
mod <- lm(y ~ x, data = df)
# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx),
interval = 'confidence')
# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')
public class UrlContent{
public static void main(String[] args) {
URL url;
try {
// get URL content
String a="http://localhost:8080/TestWeb/index.jsp";
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JS objects have no defined order, they are (by definition) an unsorted set of key-value pairs.
If by "first" you mean "first in lexicographical order", you can however use:
var sortedKeys = Object.keys(myobj).sort();
and then use:
var first = myobj[sortedKeys[0]];
Lucene is nice and all, but their stop word set is awful. I had to manually add a ton of stop words to StopAnalyzer.ENGLISH_STOP_WORDS_SET just to get it anywhere near usable.
I haven't used Sphinx but I know people swear by its speed and near-magical "ease of setup to awesomeness" ratio.
Create-React-App has a simple way to deal with this problem: add a proxy field to the package.json file as shown below
"proxy": "http://localhost:8081",
Based on the @trashgod's comment, this is the simpliest way to calculate >distance:
double distance = Math.hypot(x1-x2, y1-y2);
From documentation of Math.hypot:Returns:
sqrt(x²+ y²)
without intermediate overflow or underflow.Bob
Below Bob's approved comment he said he couldn't explain what the
Math.hypot(x1-x2, y1-y2);
did. To explain a triangle has three sides. With two points you can find the length of those points based on the x,y
of each. Xa=0, Ya=0
If thinking in Cartesian coordinates that is (0,0)
and then Xb=5, Yb=9
Again, cartesian coordinates is (5,9)
. So if you were to plot those on a grid, the distance from from x to another x assuming they are on the same y axis is +5
. and the distance along the Y axis from one to another assuming they are on the same x-axis is +9
. (think number line) Thus one side of the triangle's length is 5, another side is 9. A hypotenuse is
(x^2) + (y^2) = Hypotenuse^2
which is the length of the remaining side of a triangle. Thus being quite the same as a standard distance formula where
Sqrt of (x1-x2)^2 + (y1-y2)^2 = distance
because if you do away with the sqrt on the lefthand side of the operation and instead make distance^2 then you still have to get the sqrt from the distance. So the distance formula is the Pythagorean theorem but in a way that teachers can call it something different to confuse people.
You can use:
@Html.EditorFor(x => x.Created, new { htmlAttributes = new { @class = "date" } })
(At least with ASP.NET MVC 5, but I do not know how that was with ASP.NET MVC 3.)
$('#submit_button').click(function() {
if (!$("input[@name='name']:checked").val()) {
alert('Nothing is checked!');
return false;
}
else {
alert('One of the radio buttons is checked!');
}
});
To get the value of a pointer, just de-reference the pointer.
int *ptr;
int value;
*ptr = 9;
value = *ptr;
value is now 9.
I suggest you read more about pointers, this is their base functionality.
Just close your Xcode and restart your mac. Then try upload your app again. It result from the networking problem,not your operation.
Since Java 1.5, simple one line concatenation with "+" and StringBuilder.append() generate exactly the same bytecode.
So for the sake of code readability, use "+".
2 exceptions :
this is a well documented bug in some versions of android. that is, on google experience builds of android, image capture doesn't work as documented. what i've generally used is something like this in a utilities class.
public boolean hasImageCaptureBug() {
// list of known devices that have the bug
ArrayList<String> devices = new ArrayList<String>();
devices.add("android-devphone1/dream_devphone/dream");
devices.add("generic/sdk/generic");
devices.add("vodafone/vfpioneer/sapphire");
devices.add("tmobile/kila/dream");
devices.add("verizon/voles/sholes");
devices.add("google_ion/google_ion/sapphire");
return devices.contains(android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
+ android.os.Build.DEVICE);
}
then when i launch image capture, i create an intent that checks for the bug.
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (hasImageCaptureBug()) {
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("/sdcard/tmp")));
} else {
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
startActivityForResult(i, mRequestCode);
then in activity that i return to, i do different things based on the device.
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case GlobalConstants.IMAGE_CAPTURE:
Uri u;
if (hasImageCaptureBug()) {
File fi = new File("/sdcard/tmp");
try {
u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), fi.getAbsolutePath(), null, null));
if (!fi.delete()) {
Log.i("logMarker", "Failed to delete " + fi);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
u = intent.getData();
}
}
this saves you having to write a new camera app, but this code isn't great either. the big problems are
you never get full sized images from the devices with the bug. you get pictures that are 512px wide that are inserted into the image content provider. on devices without the bug, everything works as document, you get a big normal picture.
you have to maintain the list. as written, it is possible for devices to be flashed with a version of android (say cyanogenmod's builds) that has the bug fixed. if that happens, your code will crash. the fix is to use the entire device fingerprint.
What you're asking for wouldn't make much sense. Unless I'm incorrect you're suggesting that you want to use XOR to perform Logical operations the same way AND and OR do. Your provided code actually shows what I'm reffering to:
public static boolean logicalXOR(boolean x, boolean y) {
return ( ( x || y ) && ! ( x && y ) );
}
Your function has boolean inputs, and when bitwise XOR is used on booleans the result is the same as the code you've provided. In other words, bitwise XOR is already efficient when comparing individual bits(booleans) or comparing the individual bits in larger values. To put this into context, in terms of binary values any non-zero value is TRUE and only ZERO is false.
So for XOR to be applied the same way Logical AND is applied, you would either only use binary values with just one bit(giving the same result and efficiency) or the binary value would have to be evaluated as a whole instead of per bit. In other words the expression ( 010 ^^ 110 ) = FALSE instead of ( 010 ^^ 110 ) = 100. This would remove most of the semantic meaning from the operation, and represents a logical test you shouldn't be using anyway.
install nvm and try it should help, use below command:-
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash
in Terminal.app
Preferences > Profiles > (Select a Profile) > Shell.
on 'When the shell exits' chosen 'Close the window'
SELECT left(NAME, charindex('_', NAME) - 1)
FROM tempdb..sysobjects
WHERE NAME LIKE '#%'
AND NAME NOT LIKE '##%'
AND upper(xtype) = 'U'
AND NOT object_id('tempdb..' + NAME) IS NULL
you can remove the ## line if you want to include global temp tables.
Alternatively if one does not see "Untrust App Developer" dialog:
Go to your iPhone > Settings > General > Profile > "[email protected]" > Trust
std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; }
else {
while(str.at(0) == ' ') { str.erase(0, 1);}
while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
return str ;
}
}
After years, I want to add another approach by using a view engine in Express.js
var fs = require('fs');
app.get('/test', function(req, res, next) {
var html = fs.readFileSync('./html/test.html', 'utf8')
res.render('test', { html: html })
// or res.send(html)
})
Then, do that in your views/test
if you choose res.render
method at the above code (I'm writing in EJS format):
<%- locals.html %>
That's all.
In this way, you don't need to break your View Engine arrangements.
You can also compare epoch seconds :
$d1->format('U') < $d2->format('U')
Source : http://laughingmeme.org/2007/02/27/looking-at-php5s-datetime-and-datetimezone/ (quite interesting article about DateTime)
Note: If you're using AngularJS, then in addition to changing the step value, you may have to set ng-model-options="{updateOn: 'blur change'}"
on the html input.
The reason for this is in order to have the validators run less often, as they are preventing the user from entering a decimal point. This way, the user can type in a decimal point and the validators go into effect after the user blurs.
I'm writing a library that deals with INotifyPropertyChanged, and the main idea is using a dynamic proxy to notify changes.
the repo is here: CaulyKan/NoMorePropertyChanged
with this library, you can write:
public dynamic Test1Binding { get; set; }
public TestDTO Test1
{
get { return (TestDTO)Test1Binding; }
set { SetBinding(nameof(Test1Binding), value); }
}
Then make all bindings and modifications go to Test1Binding, which will notify PropertyChange and CollectionChanged automatically no matter how complex TestDTO is.
it can also handle dependencies.
[DependsOn("Test1Binding.TestString")]
public string Test2
{
get { return Test1Binding.TestString; }
}
Please give me some suggestions.
Another one solution with C#:
static List<List<T>> GetCombinations<T>(List<T> originalItems, int combinationLength)
{
if (combinationLength < 1)
{
return null;
}
return CreateCombinations<T>(new List<T>(), 0, combinationLength, originalItems);
}
static List<List<T>> CreateCombinations<T>(List<T> initialCombination, int startIndex, int length, List<T> originalItems)
{
List<List<T>> combinations = new List<List<T>>();
for (int i = startIndex; i < originalItems.Count - length + 1; i++)
{
List<T> newCombination = new List<T>(initialCombination);
newCombination.Add(originalItems[i]);
if (length > 1)
{
List<List<T>> newCombinations = CreateCombinations(newCombination, i + 1, length - 1, originalItems);
combinations.AddRange(newCombinations);
}
else
{
combinations.Add(newCombination);
}
}
return combinations;
}
Example of usage:
List<char> initialArray = new List<char>() { 'a','b','c','d'};
int combinationLength = 3;
List<List<char>> combinations = GetCombinations(initialArray, combinationLength);
Use setInterval
instead of setTimeout
. Though in this case either will be fine but setTimeout
inherently triggers only once setInterval
continues indefinitely.
<script language="javascript">
setInterval(function(){
window.location.reload(1);
}, 30000);
</script>
Both means "every item in a set of two things". The two things being "left" and "right"
I posted a fiddle here, showing data, remote and local images embedded in SVG, inside an HTML page:
<!DOCTYPE html>
<html>
<head>
<title>SVG embedded bitmaps in HTML</title>
<style>
body{
background-color:#999;
color:#666;
padding:10px;
}
h1{
font-weight:normal;
font-size:24px;
margin-top:20px;
color:#000;
}
h2{
font-weight:normal;
font-size:20px;
margin-top:20px;
}
p{
color:#FFF;
}
svg{
margin:20px;
display:block;
height:100px;
}
</style>
</head>
<body>
<h1>SVG embedded bitmaps in HTML</h1>
<p>The trick appears to be ensuring the image has the correct width and height atttributes</p>
<h2>Example 1: Embedded data</h2>
<svg id="example1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image x="0" y="0" width="5" height="5" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
</svg>
<h2>Example 2: Remote image</h2>
<svg id="example2" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image x="0" y="0" width="275" height="95" xlink:href="http://www.google.co.uk/images/srpr/logo3w.png" />
</svg>
<h2>Example 3: Local image</h2>
<svg id="example3" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image x="0" y="0" width="136" height="23" xlink:href="/img/logo.png" />
</svg>
</body>
</html>
Noticed this is a 2-years old question, but still want to share my workaround for this particular question:
Firstly, run docker container ls -a
to list all the containers you have and pinpoint the want you want to delete.
Secondly, delete the one with command docker container rm <CONTAINER ID>
(If the container is currently running, you should stop it first, run docker container stop <CONTAINER ID>
to gracefully stop the specified container, if it does not stop it for whatever the reason is, alternatively you can run docker container kill <CONTAINER ID> to force shutdown of the specified container
).
Thirdly, remove the container by running docker container rm <CONTAINER ID>
.
Lastly you can run docker image ls -a
to view all the images and delete the one you want to by running docker image rm <hash>
.
IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.
There are commercial products such as ionCube (which I use), source guardian, and Zen Guard.
There are also postings on the net which claim they can reverse engineer the encoded programs. How reliable they are is questionable, since I have never used them.
Note that most of these solutions require an encoder to be installed on their servers. So you may want to make sure your client is comfortable with that.