I found a faster way of embedding:
Here is the complete example for previewing image before it gets upload.
HTML :
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://goo.gl/r57ze"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
JavaScript :
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
You can try this.
func convertToJSONString(value: AnyObject) -> String? {
if JSONSerialization.isValidJSONObject(value) {
do{
let data = try JSONSerialization.data(withJSONObject: value, options: [])
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
return string as String
}
}catch{
}
}
return nil
}
I would suggest you check out the various tutorials that are coming out lately. My current fav is:
Hope this helps.
I use javascript to check file extension. Here is my code:
HTML
<input name="fileToUpload" type="file" onchange="check_file()" >
.. ..
javascript
function check_file(){
str=document.getElementById('fileToUpload').value.toUpperCase();
suffix=".JPG";
suffix2=".JPEG";
if(str.indexOf(suffix, str.length - suffix.length) == -1||
str.indexOf(suffix2, str.length - suffix2.length) == -1){
alert('File type not allowed,\nAllowed file: *.jpg,*.jpeg');
document.getElementById('fileToUpload').value='';
}
}
You will have to over ride onPageStarted and onPageFinished callbacks
mWebView.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (progressBar!= null && progressBar.isShowing()) {
progressBar.dismiss();
}
progressBar = ProgressDialog.show(WebViewActivity.this, "Application Name", "Loading...");
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
It might be easier to use JavaScript or jquery for this. Assuming that the height of the header and the footer is 200 then the code will be:
function SetHeight(){
var h = $(window).height();
$("#inner-right").height(h-200);
}
$(document).ready(SetHeight);
$(window).resize(SetHeight);
It is better to include stdlib.h
. Since without stdlibg it takes long as long
Make sure that you aren't still in the mounted device when you are trying to umount.
Short and flexible with support for negative values, although by using two comma expressions :)
function timeUnitsBetween(startDate, endDate) {
let delta = Math.abs(endDate - startDate) / 1000;
const isNegative = startDate > endDate ? -1 : 1;
return [
['days', 24 * 60 * 60],
['hours', 60 * 60],
['minutes', 60],
['seconds', 1]
].reduce((acc, [key, value]) => (acc[key] = Math.floor(delta / value) * isNegative, delta -= acc[key] * isNegative * value, acc), {});
}
Example:
timeUnitsBetween(new Date("2019-02-11T02:12:03+00:00"), new Date("2019-02-11T01:00:00+00:00"));
// { days: -0, hours: -1, minutes: -12, seconds: -3 }
Inspired by RienNeVaPlu?s solution.
setTimeout will help you to execute any JavaScript code based on the time you set.
Syntax
setTimeout(code, millisec, lang)
Usage,
setTimeout("function1()", 1000);
For more details, see http://www.w3schools.com/jsref/met_win_settimeout.asp
Simple, without any other API:
To add 8 days:
Date today=new Date();
long ltime=today.getTime()+8*24*60*60*1000;
Date today8=new Date(ltime);
You can use this jQuery function instead of plus Bootstrap tooltip
function DDLSToolTipping(ddlsArray) {
$(ddlsArray).each(function (index, ddl) {
DDLToolTipping(ddl)
});
}
function DDLToolTipping(ddlID, maxLength, allowDots) {
if (maxLength == null) { maxLength = 12 }
if (allowDots == null) { allowDots = true }
var selectedOption = $(ddlID).find('option:selected').text();
if (selectedOption.length > maxLength) {
$(ddlID).attr('data-toggle', "tooltip")
.attr('title', selectedOption);
if (allowDots) {
$(ddlID).prev('sup').remove();
$(ddlID).before(
"<sup style='font-size: 9.5pt;position: relative;top: -1px;left: -17px;z-index: 1000;background-color: #f7f7f7;border-radius: 229px;font-weight: bold;color: #666;'>...</sup>"
)
}
}
else if ($(ddlID).attr('title') != null) {
$(ddlID).removeAttr('data-toggle')
.removeAttr('title');
}
}
When using SASS
I use the following 2 @media queries
to target IE 6-10 & EDGE.
@media screen\9
@import ie_styles
@media screen\0
@import ie_styles
http://keithclark.co.uk/articles/moving-ie-specific-css-into-media-blocks/
Edit
I also target later versions of EDGE using @support queries
(add as many as you need)
@supports (-ms-ime-align:auto)
@import ie_styles
@supports (-ms-accelerator:auto)
@import ie_styles
https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/
Another scenario that can cause this exception is with DataBinding, that is when you use something like this in your layout
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="model"
type="point.to.your.model"/>
</data>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@{model.someIntegerVariable}"/>
</layout>
Notice that the variable I'm using is an Integer and I'm assigning it to the text field of the TextView. Since the TextView already has a method with signature of setText(int)
it will use this method instead of using the setText(String)
and cast the value. Thus the TextView thinks of your input number as a resource value which obviously is not valid.
Solution is to cast your int value to string like this
android:text="@{String.valueOf(model.someIntegerVariable)}"
There's a bit of confusion in your question:
Date
datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE
into a Date
.TO_CHAR
function. In Oracle, a Date
has no format: it is a point in time.TO_TIMESTAMP_TZ
to convert a VARCHAR2
to a TIMESTAMP
, but this won't convert a Date
to a TIMESTAMP
.FROM_TZ
to add the time zone information to a TIMESTAMP
(or a Date
).CST
is a time zone but CDT
is not. CDT
is a daylight saving information.CST/CDT
(-05:00
) and CST/CST
(-06:00
) will have different values obviously, but the time zone CST
will inherit the daylight saving information depending upon the date by default.So your conversion may not be as simple as it looks.
Assuming that you want to convert a Date
d
that you know is valid at time zone CST/CST
to the equivalent at time zone CST/CDT
, you would use:
SQL> SELECT from_tz(d, '-06:00') initial_ts,
2 from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
3 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
4 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
5 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00
My default timestamp format has been used here. I can specify a format explicitely:
SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
2 to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
3 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
4 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
5 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
6 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00 2012-10-09 02:10:21 -05:00
how to access iFrame parent page using jquery
window.parent.document.
jQuery is a library on top of JavaScript, not a complete replacement for it. You don't have to replace every last JavaScript expression with something involving $.
You can't "execute" a DLL. You can execute functions within the DLL, as explained in the other answers. Although .EXE files and .DLL files are essentially identical in terms of format, the distinguishing feature of an .EXE is that it contains a designated "entry point" to go and do the thing the EXE was created to do. DLLs actually have something similar, but the purpose of the "dll main" is just to perform initialization and not fulfill the primary purpose of the DLL; that is for the (presumably) various other functions it contains.
You can execute any of the functions exported by a DLL, assuming you know which one you want to execute; an EXE may contain a whole lot of functions, but one and only one is specially designated to be executed simply by "running" it.
One easy way to map that country name that you have to an int
to be used in the setImageResource
method is:
int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);
But you should really try to use different folders resources for the countries that you want to support.
According to Google Maps' own help:
Swift :
func runSpinAnimationOnView(view:UIView , duration:Float, rotations:Double, repeatt:Float ) ->()
{
let rotationAnimation=CABasicAnimation();
rotationAnimation.keyPath="transform.rotation.z"
let toValue = M_PI * 2.0 * rotations ;
// passing it a float
let someInterval = CFTimeInterval(duration)
rotationAnimation.toValue=toValue;
rotationAnimation.duration=someInterval;
rotationAnimation.cumulative=true;
rotationAnimation.repeatCount=repeatt;
view.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation")
}
You have to use curly braces ({}
) to access fields
, since the fieldnames
function returns a cell array of strings:
for i = 1:numel(fields)
teststruct.(fields{i})
end
Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:
>> fields(1) % Get the first cell of the cell array
ans =
'a' % This is how the 1-element cell array is displayed
>> fields{1} % Get the contents of the first cell of the cell array
ans =
a % This is how the single character is displayed
there you go
date('d.m.Y',strtotime("-1 days"));
this will work also if month change
Assuming your row number is in B1
, you can use INDIRECT
:
=INDIRECT("A" & B1)
This takes a cell reference as a string (in this case, the concatenation of A
and the value of B1
- 5), and returns the value at that cell.
uintptr_t
is an unsigned integer type that is capable of storing a data pointer. Which typically means that it's the same size as a pointer.
It is optionally defined in C++11 and later standards.
A common reason to want an integer type that can hold an architecture's pointer type is to perform integer-specific operations on a pointer, or to obscure the type of a pointer by providing it as an integer "handle".
Python
__init__
andself
what do they do?What does
self
do? What is it meant to be? Is it mandatory?What does the
__init__
method do? Why is it necessary? (etc.)
The example given is not correct, so let me create a correct example based on it:
class SomeObject(object):
def __init__(self, blah):
self.blah = blah
def method(self):
return self.blah
When we create an instance of the object, the __init__
is called to customize the object after it has been created. That is, when we call SomeObject
with 'blah'
below (which could be anything), it gets passed to the __init__
function as the argument, blah
:
an_object = SomeObject('blah')
The self
argument is the instance of SomeObject
that will be assigned to an_object
.
Later, we might want to call a method on this object:
an_object.method()
Doing the dotted lookup, that is, an_object.method
, binds the instance to an instance of the function, and the method (as called above) is now a "bound" method - which means we do not need to explicitly pass the instance to the method call.
The method call gets the instance because it was bound on the dotted lookup, and when called, then executes whatever code it was programmed to perform.
The implicitly passed self
argument is called self
by convention. We could use any other legal Python name, but you will likely get tarred and feathered by other Python programmers if you change it to something else.
__init__
is a special method, documented in the Python datamodel documentation. It is called immediately after the instance is created (usually via __new__
- although __new__
is not required unless you are subclassing an immutable datatype).
To set ANDROID_HOME
, variable, you need to know how you installed android dev setup.
If you don't know you can check if the following paths exist in your machine. Add the following to .bashrc
, .zshrc
, or .profile
depending on what you use
If you installed with homebrew,
export ANDROID_HOME=/usr/local/opt/android-sdk
Check if this path exists:
If you installed android studio following the website,
export ANDROID_HOME=~/Library/Android/sdk
Finally add it to path:
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
If you're too lazy to open an editor do this:
echo "export ANDROID_HOME=~/Library/Android/sdk" >> ~/.bashrc
echo "export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools" >> ~/.bashrc
To pull a copy of the branch and force overwrite of local files from the origin use:
git reset --hard origin/current_branch
All current work will be lost and it will then be the same as the origin branch
document.cookie = "cookiename=Some Name; path=/";
This will do
The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.
Example
This one works!
SELECT t.device,
SUM(case when transits.direction = 1 then 1 else 0 end) ,
SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t
where t.device in ('A','B') group by t.device
This one not (omitted t.device from the select)
SELECT
SUM(case when transits.direction = 1 then 1 else 0 end) ,
SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t
where t.device in ('A','B') group by t.device
This will produce your error complaining that I'm grouping for something that is not included in the select
Please, provide all the query to get more support.
Version 1.1.1 is the correct version for Yosemite. You need to download this directly from intel's site: https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.
The one downloaded by SDK Manager is the older version (1.1.0). If you still want to run with version 1.1.0 - refer to the solution here - http://www.csell.net/2014/09/03/VTNX_Not_Enabled/
You can also set your error handler as an anonymous function that calls an Exception and use a try / catch on that exception.
set_error_handler(
function ($severity, $message, $file, $line) {
throw new ErrorException($message, $severity, $severity, $file, $line);
}
);
try {
file_get_contents('www.google.com');
}
catch (Exception $e) {
echo $e->getMessage();
}
restore_error_handler();
Seems like a lot of code to catch one little error, but if you're using exceptions throughout your app, you would only need to do this once, way at the top (in an included config file, for instance), and it will convert all your errors to Exceptions throughout.
I have never seen it done that way in JavaScript. If you want a function with optional parameters that get assigned default values if the parameters are omitted, here's a way to do it:
function(a, b) {
if (typeof a == "undefined") {
a = 10;
}
if (typeof b == "undefined") {
a = 20;
}
alert("a: " + a + " b: " + b);
}
public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) {
JSONObject resp = new JSONObject();
resp.put("status", 0);
resp.put("id", id);
return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}
getAttribute() -> It fetches the text that contains one of any attribute in the HTML tag. Suppose there is an HTML tag like
<input name="Name Locator" value="selenium">Hello</input>
Now getAttribute() fetches the data of the attribute of 'value', which is "Selenium".
Returns:
The attribute's current value or null if the value is not set.
driver.findElement(By.name("Name Locator")).getAttribute("value") //
The field value is retrieved by the getAttribute("value") Selenium WebDriver predefined method and assigned to the String object.
getText() -> delivers the innerText of a WebElement. Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.
driver.findElement(By.name("Name Locator")).getText();
'Hello' will appear
Adding a novalidate
attribute to the form will help:
<form name="myform" novalidate>
In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:
$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"
If you are using Go 1.5 above, you can try to use vendoring feature. It allows you to put your local package under vendor folder and import it with shorter path. In your case, you can put your common and routers folder inside vendor folder so it would be like
myapp/
--vendor/
----common/
----routers/
------middleware/
--main.go
and import it like this
import (
"common"
"routers"
"routers/middleware"
)
This will work because Go will try to lookup your package starting at your project’s vendor directory (if it has at least one .go file) instead of $GOPATH/src.
FYI: You can do more with vendor, because this feature allows you to put "all your dependency’s code" for a package inside your own project's directory so it will be able to always get the same dependencies versions for all builds. It's like npm or pip in python, but you need to manually copy your dependencies to you project, or if you want to make it easy, try to look govendor by Daniel Theophanes
For more learning about this feature, try to look up here
Understanding and Using Vendor Folder by Daniel Theophanes
Understanding Go Dependency Management by Lucas Fernandes da Costa
I hope you or someone else find it helpfully
I got similar error after deleting a subproject, removed
"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"
in build.gradle
(dependencies) under Gradle Scripts
Here is C code to check if two points are on the opposite sides of the line segment. Using this code you can check if two segments intersect as well.
// true if points p1, p2 lie on the opposite sides of segment s1--s2
bool oppositeSide (Point2f s1, Point2f s2, Point2f p1, Point2f p2) {
//calculate normal to the segment
Point2f vec = s1-s2;
Point2f normal(vec.y, -vec.x); // no need to normalize
// vectors to the points
Point2f v1 = p1-s1;
Point2f v2 = p2-s1;
// compare signs of the projections of v1, v2 onto the normal
float proj1 = v1.dot(normal);
float proj2 = v2.dot(normal);
if (proj1==0 || proj2==0)
cout<<"collinear points"<<endl;
return(SIGN(proj1) != SIGN(proj2));
}
You can get it at PuTTY: Extreme Makeover Using PuTTY Connection Manager.
You can first find the image ID using:
$ docker images -a
Then find the image's layers and their sizes:
$ docker history --no-trunc <Image ID>
Note: I'm using Docker version 1.13.1
$ docker -v
Docker version 1.13.1, build 092cba3
I wondered if it would be possible to avoid some of the disadvantages of using global variables (see e.g. http://wiki.c2.com/?GlobalVariablesAreBad) by using a class namespace rather than a global/module namespace to pass values of variables. The following code indicates that the two methods are essentially identical. There is a slight advantage in using class namespaces as explained below.
The following code fragments also show that attributes or variables may be dynamically created and deleted in both global/module namespaces and class namespaces.
wall.py
# Note no definition of global variables
class router:
""" Empty class """
I call this module 'wall' since it is used to bounce variables off of. It will act as a space to temporarily define global variables and class-wide attributes of the empty class 'router'.
source.py
import wall
def sourcefn():
msg = 'Hello world!'
wall.msg = msg
wall.router.msg = msg
This module imports wall and defines a single function sourcefn
which defines a message and emits it by two different mechanisms, one via globals and one via the router function. Note that the variables wall.msg
and wall.router.message
are defined here for the first time in their respective namespaces.
dest.py
import wall
def destfn():
if hasattr(wall, 'msg'):
print 'global: ' + wall.msg
del wall.msg
else:
print 'global: ' + 'no message'
if hasattr(wall.router, 'msg'):
print 'router: ' + wall.router.msg
del wall.router.msg
else:
print 'router: ' + 'no message'
This module defines a function destfn
which uses the two different mechanisms to receive the messages emitted by source. It allows for the possibility that the variable 'msg' may not exist. destfn
also deletes the variables once they have been displayed.
main.py
import source, dest
source.sourcefn()
dest.destfn() # variables deleted after this call
dest.destfn()
This module calls the previously defined functions in sequence. After the first call to dest.destfn
the variables wall.msg
and wall.router.msg
no longer exist.
The output from the program is:
global: Hello world!
router: Hello world!
global: no message
router: no message
The above code fragments show that the module/global and the class/class variable mechanisms are essentially identical.
If a lot of variables are to be shared, namespace pollution can be managed either by using several wall-type modules, e.g. wall1, wall2 etc. or by defining several router-type classes in a single file. The latter is slightly tidier, so perhaps represents a marginal advantage for use of the class-variable mechanism.
Modify the JavaScript property document.body.style.background
.
For example:
function changeBackground(color) {
document.body.style.background = color;
}
window.addEventListener("load",function() { changeBackground('red') });
Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.
I mostly prefer Criteria Queries for dynamic queries. For example it is much easier to add some ordering dynamically or leave some parts (e.g. restrictions) out depending on some parameter.
On the other hand I'm using HQL for static and complex queries, because it's much easier to understand/read HQL. Also, HQL is a bit more powerful, I think, e.g. for different join types.
For those that must keep compileSdkVersion 27
and are unable to upgrade to androidx yet, you must not upgrade to (or over) the versions of dependencies in the following links. These links are where the breaking change was introduced. You must find an earlier version that doesn't use androidx.
https://firebase.google.com/support/release-notes/android#update_-_june_17_2019
https://developers.google.com/android/guides/releases#june_17_2019
For instance, the following are compatible with compileSdkVersion 27
:
dependencies {
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-messaging:18.0.0'
}
The following will break with compileSdkVersion 27
and are only compatible with compileSdkVersion 28
:
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-messaging:19.0.0'
}
According to the documentation:
$validator = Validator::make($request->all(), [
'file' => 'max:500000',
]);
The value is in kilobytes. I.e. max:10240
= max 10 MB.
If you are considering using multidimensional arrays, then there is one additional difference between std::array and std::vector. A multidimensional std::array will have the elements packed in memory in all dimensions, just as a c style array is. A multidimensional std::vector will not be packed in all dimensions.
Given the following declarations:
int cConc[3][5];
std::array<std::array<int, 5>, 3> aConc;
int **ptrConc; // initialized to [3][5] via new and destructed via delete
std::vector<std::vector<int>> vConc; // initialized to [3][5]
A pointer to the first element in the c-style array (cConc) or the std::array (aConc) can be iterated through the entire array by adding 1 to each preceding element. They are tightly packed.
A pointer to the first element in the vector array (vConc) or the pointer array (ptrConc) can only be iterated through the first 5 (in this case) elements, and then there are 12 bytes (on my system) of overhead for the next vector.
This means that a std::vector> array initialized as a [3][1000] array will be much smaller in memory than one initialized as a [1000][3] array, and both will be larger in memory than a std:array allocated either way.
This also means that you can't simply pass a multidimensional vector (or pointer) array to, say, openGL without accounting for the memory overhead, but you can naively pass a multidimensional std::array to openGL and have it work out.
None of the answers seemed to work well with buttons. Bootstrap v4.1.1
<div class="card bg-light">
<div class="card-body">
<button type="submit" class="btn btn-primary">
Save
</button>
<a href="/" class="btn btn-secondary">
Cancel
</a>
</div>
</div>
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
Suppose constructors were inherited... then because every class eventually derives from Object, every class would end up with a parameterless constructor. That's a bad idea. What exactly would you expect:
FileInputStream stream = new FileInputStream();
to do?
Now potentially there should be a way of easily creating the "pass-through" constructors which are fairly common, but I don't think it should be the default. The parameters needed to construct a subclass are often different from those required by the superclass.
If the problem still persists even after putting the after build in the correct project try using "copy" instead of xcopy. This worked for me.
For passing a single integer I agree with Reed Copsey's answer. If in the future you are going to pass more complicated constucts I personally like to pass all my variables as an Anonymous Type. It will look something like this:
foreach(int id in myIdsToCheck)
{
Task.Factory.StartNew( (Object obj) =>
{
var data = (dynamic)obj;
CheckFiles(data.id, theBlockingCollection,
cancelCheckFile.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}, new { id = id }); // Parameter value
}
You can learn more about it in my blog
Best way is to use lifecycle rule to delete whole bucket contents. Programmatically you can use following code (PHP) to PUT lifecycle rule.
$expiration = array('Date' => date('U', strtotime('GMT midnight')));
$result = $s3->putBucketLifecycle(array(
'Bucket' => 'bucket-name',
'Rules' => array(
array(
'Expiration' => $expiration,
'ID' => 'rule-name',
'Prefix' => '',
'Status' => 'Enabled',
),
),
));
In above case all the objects will be deleted starting Date - "Today GMT midnight".
You can also specify Days as follows. But with Days it will wait for at least 24 hrs (1 day is minimum) to start deleting the bucket contents.
$expiration = array('Days' => 1);
From menu, Code -> Comment with Line Commment. So simple.
equals
if hashCode
differs.hashCode
if (obj1 == obj2)
.hashCode
and/or equals
just to iterate - you're not comparing objectsYou might need to change your path by:
import os
path=os.chdir(str('Here should be the path to your file')) #This command changes directory
This is what worked for me at least! Hope it works for you too!
I believe the REAL answer to this question is an explanation as to how you configure what editor to use by default, if you are not comfortable with Vim.
This is how to configure Notepad for example, useful in Windows:
git config --global core.editor "notepad"
Gedit, more Linux friendly:
git config --global core.editor "gedit"
You can read the current configuration like this:
git config core.editor
Alternate approach : without installation of Redistributable package.
Check out in some github for the relevant dll, some people upload the reference dll for their application dependency.
you can download and use them in your project , I have used and run them successfully.
example : https://github.com/Emotiv/community-sdk/find/master
I'm using monotouch, so the names and code will be a bit different, but you can do this by making sure that the width of the collectionview equals (x * cell width) + (x-1) * MinimumSpacing with x = amount of cells per row.
Just do following steps based on your MinimumInteritemSpacing and the Width of the Cell
1) We calculate amount of items per row based on cell size + current insets + minimum spacing
float currentTotalWidth = CollectionView.Frame.Width - Layout.SectionInset.Left - Layout.SectionInset.Right (Layout = flowlayout)
int amountOfCellsPerRow = (currentTotalWidth + MinimumSpacing) / (cell width + MinimumSpacing)
2) Now you have all info to calculate the expected width for the collection view
float totalWidth =(amountOfCellsPerRow * cell width) + (amountOfCellsPerRow-1) * MinimumSpacing
3) So the difference between the current width and the expected width is
float difference = currentTotalWidth - totalWidth;
4) Now adjust the insets (in this example we add it to the right, so the left position of the collectionview stays the same
Layout.SectionInset.Right = Layout.SectionInset.Right + difference;
def eratosthenes(n):
multiples = []
for i in range(2, n+1):
if i not in multiples:
print (i)
for j in range(i*i, n+1, i):
multiples.append(j)
eratosthenes(100)
@objc
inference? What is going on?In Swift 3
, the compiler infers @objc
in a number of places so you wouldn't have to. In other words, it makes sure to add @objc
for you!
In Swift 4
, the compiler no longer does this (as much). You now must add @objc
explicitly.
By default, if you have a pre-Swift 4 project, you will get warnings about this. In a Swift 4 project, you will get build errors. This is controlled via the SWIFT_SWIFT3_OBJC_INFERENCE
build setting. In a pre-Swift 4 project this is set to On
. I would recommend to set this to Default
(or Off
), which is now the default option on a new project.
It will take some time to convert everything, but since it's the default for Swift 4, it's worth doing it.
There are two ways to go about converting your code so the compiler doesn't complain.
One is to use @objc
on each function or variable that needs to be exposed to the Objective-C runtime:
@objc func foo() {
}
The other is to use @objcMembers
by a Class
declaration. This makes sure to automatically add @objc
to ALL the functions and variables in the class. This is the easy way, but it has a cost, for example, it can increase the size of your application by exposing functions that did not need to be exposed.
@objcMembers class Test {
}
@objc
and why is it necessary?If you introduce new methods or variables to a Swift class, marking them as @objc
exposes them to the Objective-C runtime. This is necessary when you have Objective-C code that uses your Swift class, or, if you are using Objective-C-type features like Selectors
. For example, the target-action pattern:
button.addTarget(self, action:#selector(didPressButton), for:.touchUpInside)
@objc
?There are negatives that come with marking something as @objc
:
Please keep in mind that this is a very high-level summary and that it is more complicated than I wrote. I would recommend reading the actual proposal for more information.
You can also push markers into an array. See code example, this works for me:
/*create array:*/
var marker = new Array();
/*Some Coordinates (here simulating somehow json string)*/
var items = [{"lat":"51.000","lon":"13.000"},{"lat":"52.000","lon":"13.010"},{"lat":"52.000","lon":"13.020"}];
/*pushing items into array each by each and then add markers*/
function itemWrap() {
for(i=0;i<items.length;i++){
var LamMarker = new L.marker([items[i].lat, items[i].lon]);
marker.push(LamMarker);
map.addLayer(marker[i]);
}
}
/*Going through these marker-items again removing them*/
function markerDelAgain() {
for(i=0;i<marker.length;i++) {
map.removeLayer(marker[i]);
}
}
It's really easy to specify your own decimal separator. Just took me about 2 hours to figure it out :D.
You see that you were using the current ou other culture that you specify right? Well, the only thing the parser needs is an IFormatProvider. If you give it the
CultureInfo.CurrentCulture.NumberFormat
as a formatter, it will format the double according to your current culture's NumberDecimalSeparator
. What I did was just to create a new instance of the NumberFormatInfo
class and set it's NumberDecimalSeparator
property to whichever separator string I wanted. Complete code below:
double value = 2.3d;
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = "-";
string x = value.ToString(nfi);
The result? "2-3"
Honestly, it's trivial to write a program to compare the performance:
#include <ctime>
#include <iostream>
namespace {
class empty { }; // even empty classes take up 1 byte of space, minimum
}
int main()
{
std::clock_t start = std::clock();
for (int i = 0; i < 100000; ++i)
empty e;
std::clock_t duration = std::clock() - start;
std::cout << "stack allocation took " << duration << " clock ticks\n";
start = std::clock();
for (int i = 0; i < 100000; ++i) {
empty* e = new empty;
delete e;
};
duration = std::clock() - start;
std::cout << "heap allocation took " << duration << " clock ticks\n";
}
It's said that a foolish consistency is the hobgoblin of little minds. Apparently optimizing compilers are the hobgoblins of many programmers' minds. This discussion used to be at the bottom of the answer, but people apparently can't be bothered to read that far, so I'm moving it up here to avoid getting questions that I've already answered.
An optimizing compiler may notice that this code does nothing, and may optimize it all away. It is the optimizer's job to do stuff like that, and fighting the optimizer is a fool's errand.
I would recommend compiling this code with optimization turned off because there is no good way to fool every optimizer currently in use or that will be in use in the future.
Anybody who turns the optimizer on and then complains about fighting it should be subject to public ridicule.
If I cared about nanosecond precision I wouldn't use std::clock()
. If I wanted to publish the results as a doctoral thesis I would make a bigger deal about this, and I would probably compare GCC, Tendra/Ten15, LLVM, Watcom, Borland, Visual C++, Digital Mars, ICC and other compilers. As it is, heap allocation takes hundreds of times longer than stack allocation, and I don't see anything useful about investigating the question any further.
The optimizer has a mission to get rid of the code I'm testing. I don't see any reason to tell the optimizer to run and then try to fool the optimizer into not actually optimizing. But if I saw value in doing that, I would do one or more of the following:
Add a data member to empty
, and access that data member in the loop; but if I only ever read from the data member the optimizer can do constant folding and remove the loop; if I only ever write to the data member, the optimizer may skip all but the very last iteration of the loop. Additionally, the question wasn't "stack allocation and data access vs. heap allocation and data access."
Declare e
volatile
, but volatile
is often compiled incorrectly (PDF).
Take the address of e
inside the loop (and maybe assign it to a variable that is declared extern
and defined in another file). But even in this case, the compiler may notice that -- on the stack at least -- e
will always be allocated at the same memory address, and then do constant folding like in (1) above. I get all iterations of the loop, but the object is never actually allocated.
Beyond the obvious, this test is flawed in that it measures both allocation and deallocation, and the original question didn't ask about deallocation. Of course variables allocated on the stack are automatically deallocated at the end of their scope, so not calling delete
would (1) skew the numbers (stack deallocation is included in the numbers about stack allocation, so it's only fair to measure heap deallocation) and (2) cause a pretty bad memory leak, unless we keep a reference to the new pointer and call delete
after we've got our time measurement.
On my machine, using g++ 3.4.4 on Windows, I get "0 clock ticks" for both stack and heap allocation for anything less than 100000 allocations, and even then I get "0 clock ticks" for stack allocation and "15 clock ticks" for heap allocation. When I measure 10,000,000 allocations, stack allocation takes 31 clock ticks and heap allocation takes 1562 clock ticks.
Yes, an optimizing compiler may elide creating the empty objects. If I understand correctly, it may even elide the whole first loop. When I bumped up the iterations to 10,000,000 stack allocation took 31 clock ticks and heap allocation took 1562 clock ticks. I think it's safe to say that without telling g++ to optimize the executable, g++ did not elide the constructors.
In the years since I wrote this, the preference on Stack Overflow has been to post performance from optimized builds. In general, I think this is correct. However, I still think it's silly to ask the compiler to optimize code when you in fact do not want that code optimized. It strikes me as being very similar to paying extra for valet parking, but refusing to hand over the keys. In this particular case, I don't want the optimizer running.
Using a slightly modified version of the benchmark (to address the valid point that the original program didn't allocate something on the stack each time through the loop) and compiling without optimizations but linking to release libraries (to address the valid point that we don't want to include any slowdown caused by linking to debug libraries):
#include <cstdio>
#include <chrono>
namespace {
void on_stack()
{
int i;
}
void on_heap()
{
int* i = new int;
delete i;
}
}
int main()
{
auto begin = std::chrono::system_clock::now();
for (int i = 0; i < 1000000000; ++i)
on_stack();
auto end = std::chrono::system_clock::now();
std::printf("on_stack took %f seconds\n", std::chrono::duration<double>(end - begin).count());
begin = std::chrono::system_clock::now();
for (int i = 0; i < 1000000000; ++i)
on_heap();
end = std::chrono::system_clock::now();
std::printf("on_heap took %f seconds\n", std::chrono::duration<double>(end - begin).count());
return 0;
}
displays:
on_stack took 2.070003 seconds
on_heap took 57.980081 seconds
on my system when compiled with the command line cl foo.cc /Od /MT /EHsc
.
You may not agree with my approach to getting a non-optimized build. That's fine: feel free modify the benchmark as much as you want. When I turn on optimization, I get:
on_stack took 0.000000 seconds
on_heap took 51.608723 seconds
Not because stack allocation is actually instantaneous but because any half-decent compiler can notice that on_stack
doesn't do anything useful and can be optimized away. GCC on my Linux laptop also notices that on_heap
doesn't do anything useful, and optimizes it away as well:
on_stack took 0.000003 seconds
on_heap took 0.000002 seconds
"By default, when an application calls DriverManager.getConnection(url, ...)
and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.
Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/** @see http://stackoverflow.com/questions/5225700 */
public class H2MemTest {
public static void main(String[] args) throws Exception {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("create table customer(id integer, name varchar(10))");
st.execute("insert into customer values (1, 'Thomas')");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select name from customer");
while (rset.next()) {
String name = rset.getString(1);
System.out.println(name);
}
}
}
I had similar issue, the problem i faced was i added the selenium-server-standalone-3.141.59.jar under modulepath instead it should be under classpath
so select classpath via (project -> Properties -> Java Bbuild Path -> Libraries) add the downloaded latest jar
After adding it must be something like this
And appropriate driver for browser has to be downloaded for me i checked and downloaded the same version of chrom for chrome driver and added in the C:\Program Files\Java
And following is the code that worked fine for me
public class TestuiAautomation {
public static void main(String[] args) {
System.out.println("Jai Ganesha");
try {
System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Java\\chromedriver.exe");
System.out.println(System.getProperty("webdriver.chrome.driver"));
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("no-sandbox");
chromeOptions.addArguments("--test-type");
chromeOptions.addArguments("disable-extensions");
chromeOptions.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("https://www.google.com");
System.out.println("Google is selected");
} catch (Exception e) {
System.err.println(e);
}
}
}
You can use ng-repeat
with option
like this:
<form>
<select ng-model="yourSelect"
ng-options="option as option for option in ['var1', 'var2', 'var3']"
ng-init="yourSelect='var1'"></select>
<input type="hidden" name="yourSelect" value="{{yourSelect}}" />
</form>
When you submit your form
you can get value of input hidden.
Here is my little utility helper for splitting paths int file, path tokens:
import os
# usage: file, path = splitPath(s)
def splitPath(s):
f = os.path.basename(s)
p = s[:-(len(f))-1]
return f, p
byte b = (byte)0xC8;
int v1 = b; // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)
Most of the time v2 is the way you really need.
Technically, the size of your body
and html
are wider than the screen, so you will have scrolling. You will need to set margin:0;
and padding:0;
to avoid the scrolling behavior, and add some margin/padding to #content
instead.
If the variable table
contains invalid characters (like a space) you should add square brackets around the variable.
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo.[" + table + "]";
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input
You have to increase client_max_body_size in nginx.conf
file. This is the basic step. But if your backend laravel
then you have to do some changes in the php.ini
file as well. It depends on your backend. Below I mentioned file location and condition name.
sudo vim /etc/nginx/nginx.conf.
After open the file adds this into HTTP section.
client_max_body_size 100M;
"Java SE8 for Programmers" claims that the Java will cope with either. (pp. 480, last paragraph). The example claims that:
c:\Program Files\Java\jdk1.6.0_11\demo/jfc
will parse just fine. Take note of the last (Unix-style) separator.
It's tacky, and probably error-prone, but it is what they (Deitel and Deitel) claim.
I think the confusion for people, rather than Java, is reason enough not to use this (mis?)feature.
You could the yolk3k package instead of yolk. yolk3k is a fork from the original yolk and it supports both python2 and 3.
pip install yolk3k
getFragmentManager()
has been deprecated in favor of getParentFragmentManager()
to make it clear that you want to access the fragment manager of the parent instead of any child fragments.
Simply use getParentFragmentManager()
in Java or parentFragmentManager
in Kotlin.
Store IDs of the objects in a hash table mapping to the specific object. Enumerate through all the objects and find their parent if it exists and update its parent pointer accordingly.
class MyObject
{ // The actual object
public int ParentID { get; set; }
public int ID { get; set; }
}
class Node
{
public List<Node> Children = new List<Node>();
public Node Parent { get; set; }
public MyObject AssociatedObject { get; set; }
}
IEnumerable<Node> BuildTreeAndGetRoots(List<MyObject> actualObjects)
{
Dictionary<int, Node> lookup = new Dictionary<int, Node>();
actualObjects.ForEach(x => lookup.Add(x.ID, new Node { AssociatedObject = x }));
foreach (var item in lookup.Values) {
Node proposedParent;
if (lookup.TryGetValue(item.AssociatedObject.ParentID, out proposedParent)) {
item.Parent = proposedParent;
proposedParent.Children.Add(item);
}
}
return lookup.Values.Where(x => x.Parent == null);
}
I haven't tested this on a 500 code, but it works on others like 200, 302 and 404.
response=$(curl --write-out '%{http_code}' --silent --output /dev/null servername)
Note, format provided for --write-out should be quoted.
As suggested by @ibai, add --head
to make a HEAD only request. This will save time when the retrieval is successful since the page contents won't be transmitted.
While
constructs are terminated not with an End While
but with a Wend
.
While counter < 20
counter = counter + 1
Wend
Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.
Also in the VBA help file:
Tip The
Do...Loop
statement provides a more structured and flexible way to perform looping.
I think bad developers find all different uses of null/0/false in there code.
For example, one of the most common mistakes developers make is to return error code in the form of data with a function.
// On error GetChar returns -1
int GetChar()
This is an example of a sugar interface. This is exsplained in the book "Debuging the software development proccess" and also in another book "writing correct code".
The problem with this, is the implication or assumptions made on the char type. On some compilers the char type can be non-signed. So even though you return a -1 the compiler can return 1 instead. These kind of compiler assumptions in C++ or C are hard to spot.
Instead, the best way is not to mix error code with your data. So the following function.
char GetChar()
now becomes
// On success return 1
// on failure return 0
bool GetChar(int &char)
This means no matter how young the developer is in your development shop, he or she will never get this wrong. Though this is not talking about redudancy or dependies in code.
So in general, swapping bool as the first class type in the language is okay and i think joel spoke about it with his recent postcast. But try not to use mix and match bools with your data in your routines and you should be perfectly fine.
Use the str.isspace()
method:
Return
True
if there are only whitespace characters in the string and there is at least one character,False
otherwise.A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.
Combine that with a special case for handling the empty string.
Alternatively, you could use str.strip()
and check if the result is empty.
implementation 'com.treebo:internetavailabilitychecker:1.0.4'
InternetConnectivityListener
.public class MainActivity extends AppCompatActivity implements InternetConnectivityListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InternetAvailabilityChecker.init(this);
mInternetAvailabilityChecker = InternetAvailabilityChecker.getInstance();
mInternetAvailabilityChecker.addInternetConnectivityListener(this);
}
@Override
public void onInternetConnectivityChanged(boolean isConnected) {
if (isConnected) {
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(" internet is connected or not");
alertDialog.setMessage("connected");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
else {
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("internet is connected or not");
alertDialog.setMessage("not connected");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
}
Not directly answering the question but I got a similar question recently where I was asked to count the number of times a sub-string is repeated in a given string. Here is the function I wrote:
def count_substring(string, sub_string):
cnt = 0
len_ss = len(sub_string)
for i in range(len(string) - len_ss + 1):
if string[i:i+len_ss] == sub_string:
cnt += 1
return cnt
The find() function probably returns the index of the fist occurrence only. Storing the index in place of just counting, can give us the distinct set of indices the sub-string gets repeated within the string.
Disclaimer: I am 'extremly' new to Python programming.
Why do you need to attach it to the HTML? Just bind the function with hover
$("div.system_box").hover(function(){ mousin },
function() { mouseout });
If you do insist to have JS references inside the html, which is usualy a bad idea you can use:
onmouseover="yourJavaScriptCode()"
<div class="system_box" data-target="sms_box">
...
$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });
readdir() does that.
Check http://perldoc.perl.org/functions/readdir.html
opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;
That will be possible only if the HTML file is also loaded with the file
protocol from the local user's harddisk.
If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src
attribute with the file://
protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.
As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.
I know it has been a while, but for anyone else interested, there is the Faint project, which has bundled a lot of these features (detection, recognition, etc.) into a nice software package.
russfrisch commented 4 days ago:
I was experiencing this same issue. Changing in the version for grunt-node-inspector to prepend a ">=" instead of a "~" got this to work for me.
Link to github page where I found this solution.
following code works just fine for me.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(movieurl));
startActivity(intent);
Also, could be simple as:
if( typeof foo == "function" )
foo();
window.location.href.split('/');
Will give you an array containing all the URL parts, which you can access like a normal array.
Or an ever more elegant solution suggested by @Dylan, with only the path parts:
window.location.pathname.split('/');
I found this the quick and easy way:
Used: org.json.XML
class from java-json.jar
if (statusCode == 200 && inputStream != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = bufferedReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
jsonObject = XML.toJSONObject(responseStrBuilder.toString());
}
This works for me with php 7.2
sudo apt-get install php7.2-xml
You need to check which jar is giving problem. It must be corrupted. Delete that jar and run mvn spring-boot:run
command again. May be more that one jar has corrupted so every time you need to run that command to delete that jar. In my case mysql, jackson, aspect jars was corrupted mvn spring-boot:run
command 3 times and I figure out this and deleted the jars from .m2
folder. Now the issue has resolved.
The idiomatic way is to say:
if(rsData["usr.ursrdaystime"] != DBNull.Value) {
strLevel = rsData["usr.ursrdaystime"].ToString();
}
This:
rsData = objCmd.ExecuteReader();
rsData.Read();
Makes it look like you're reading exactly one value. Use IDbCommand.ExecuteScalar
instead.
Use limitTo filter to display a limited number of results in ng-repeat.
<ul class="phones">
<li ng-repeat="phone in phones | limitTo:5">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
You can also use insertAdjacentHTML
function:
const select = document.querySelector('select')
const value = 'bmw'
const label = 'BMW'
select.insertAdjacentHTML('beforeend', `
<option value="${value}">${label}</option>
`)
You want
round(new MathContext(0)); // or perhaps another math context with rounding mode HALF_UP
In my case I had curly braces where it should have been parentheses.
const Button = () => {
<button>Hello world</button>
}
Where it should have been:
const Button = () => (
<button>Hello world</button>
)
The reason for this, as explained in the MDN Docs is that an arrow function wrapped by ()
will return the value it wraps, so if I wanted to use curly braces I had to add the return
keyword, like so:
const Button = () => {
return <button>Hello world</button>
}
If not using Word2Vec we have other model to find it using BERT for embed. Below are reference link https://github.com/UKPLab/sentence-transformers
pip install -U sentence-transformers
from sentence_transformers import SentenceTransformer
import scipy.spatial
embedder = SentenceTransformer('bert-base-nli-mean-tokens')
# Corpus with example sentences
corpus = ['A man is eating a food.',
'A man is eating a piece of bread.',
'The girl is carrying a baby.',
'A man is riding a horse.',
'A woman is playing violin.',
'Two men pushed carts through the woods.',
'A man is riding a white horse on an enclosed ground.',
'A monkey is playing drums.',
'A cheetah is running behind its prey.'
]
corpus_embeddings = embedder.encode(corpus)
# Query sentences:
queries = ['A man is eating pasta.', 'Someone in a gorilla costume is playing a set of drums.', 'A cheetah chases prey on across a field.']
query_embeddings = embedder.encode(queries)
# Find the closest 5 sentences of the corpus for each query sentence based on cosine similarity
closest_n = 5
for query, query_embedding in zip(queries, query_embeddings):
distances = scipy.spatial.distance.cdist([query_embedding], corpus_embeddings, "cosine")[0]
results = zip(range(len(distances)), distances)
results = sorted(results, key=lambda x: x[1])
print("\n\n======================\n\n")
print("Query:", query)
print("\nTop 5 most similar sentences in corpus:")
for idx, distance in results[0:closest_n]:
print(corpus[idx].strip(), "(Score: %.4f)" % (1-distance))
Other Link to follow https://github.com/hanxiao/bert-as-service
None of the answers above worked for me, so I just gave my DIV tag a transparent background image instead, that worked perfectly for all browsers.
1 Create login while connecting to the master db (in your databaseclient open a connection to the master db)
CREATE LOGIN 'testUserLogin' WITH password='1231!#ASDF!a';
2 Create a user while connecting to your db (in your db client open a connection to your database)
CREATE USER testUserLoginFROM LOGIN testUserLogin;
Please, note, user name is the same as login. It did not work for me when I had a different username and login.
3 Add required permissions
EXEC sp_addrolemember db_datawriter, 'testUser';
You may want to add 'db_datareader' as well.
list of the roles:
I was inspired by @nthpixel answer, but it did not work for my db client DBeaver.
It did not allow me to run USE [master]
and use [my-db]
statements.
https://azure.microsoft.com/en-us/blog/adding-users-to-your-sql-azure-database/
Run the query bellow in the master database connection.
SELECT A.name as userName, B.name as login, B.Type_desc, default_database_name, B.*
FROM sys.sysusers A
FULL OUTER JOIN sys.sql_logins B
ON A.sid = B.sid
WHERE islogin = 1 and A.sid is not null
Its better to use StringBuilder
instead of String
because String is an immutable class and it cannot be modified once created: in String each concatenation results in creating a new instance of the String class with the modified string.
On Debian/Ubuntu:
aptitude install python-numpy
On Windows, download the installer:
http://sourceforge.net/projects/numpy/files/NumPy/
On other systems, download the tar.gz and run the following:
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
What you are saying is in conflict with what it says in the MSDN library at this location:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
I don't see any mention of the SP1 feature you mention.
$image_name = "this-is.file.name.jpg";
$last_dot_index = strrpos($image_name, ".");
$without_extention = substr($image_name, 0, $last_dot_index);
Output:
this-is.file.name
int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
if you want to find days in this year and present month then this is best
As others have pointed out, this is very probably a problem with the path of the function file not being in Matlab's 'path'.
One easy way to verify this is to open your function in the Editor and press the F5 key. This would make the Editor try to run the file, and in case the file is not in path, it will prompt you with a message box. Choose Add to Path
in that, and you must be fine to go.
One side note: at the end of the above process, Matlab command window will give an error saying arguments missing: obviously, we didn't provide any arguments when we tried to run from the editor. But from now on you can use the function from the command line giving the correct arguments.
I fixed this issue by deleting and inserting new platform-tools folder inside android sdk folder. But it is caused by my Avast anti virus software. Where I can found my adb.exe in Avast chest. You can also solve by restoring it from Avast chest.
You need to use cell-arrays:
names = cell(10,1);
for i=1:10
names{i} = ['Sample Text ' num2str(i)];
end
There is a similar problem.it is a tomcat digital signature.
$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc apache-tomcat-9.0.16-windows-
x64.zip
gpg: Signature made 2019?02? 5? 0:32:50
gpg: using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Can't check signature: No public key
but then I use the RSA key it provided to receive the public key to verify.
$ gpg --receive-keys A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: key 10C01C5A2F6059E7: 38 signatures not checked due to missing keys
gpg: key 10C01C5A2F6059E7: public key "Mark E D Thomas <[email protected]>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg: imported: 1
Then successfully.
$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc
gpg: assuming signed data in 'apache-tomcat-9.0.16-windows-x64.zip'
gpg: Signature made 2019?02? 5? 0:32:50
gpg: using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Good signature from "Mark E D Thomas <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: A9C5 DF4D 22E9 9998 D987 5A51 10C0 1C5A 2F60 59E7
Assembly.LoadFile(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\system.data.dll").FullName
Will result in
System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Tested and working in Angular 9.0
If you're getting the data using API
array: [];
ngOnInit() {
this.service.method()
.subscribe(
data=>
{
this.array = JSON.parse(JSON.stringify(data.object));
}
)
}
You can use that array to print your results from API data in html template.
Like
<p>{{array['something']}}</p>
logical address is address relative to program. It tells how much memory a particular process will take, not tell what will the exact location of the process and this exact location will we generated by using some mapping, and is known as physical address.
Your userPhotos
array is option-typed, you should retrieve the actual underlying object with !
(if you want an error in case the object isn't there) or ?
(if you want to receive nil
in url):
let userPhotos = currentUser?.photos
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
But to preserve safe nil handling, you better use functional approach, for instance, with map
, like this:
let urls = userPhotos?.map{ $0.url }
If injecting multiple script tags in the head like this with mix of local and remote script files a situation may arise where the local scripts that are dependent on external scripts (such as loading jQuery from googleapis) will have errors because the external scripts may not be loaded before the local ones are.
So something like this would have a problem: ("jQuery is not defined" in jquery.some-plugin.js).
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js";
head.appendChild(script);
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "/jquery.some-plugin.js";
head.appendChild(script);
Of course this situation is what the .onload() is for, but if multiple scripts are being loaded that can be cumbersome.
As a resolution to this situation, I put together this function that will keep a queue of scripts to be loaded, loading each subsequent item after the previous finishes, and returns a Promise that resolves when the script (or the last script in the queue if no parameter) is done loading.
load_script = function(src) {
// Initialize scripts queue
if( load_script.scripts === undefined ) {
load_script.scripts = [];
load_script.index = -1;
load_script.loading = false;
load_script.next = function() {
if( load_script.loading ) return;
// Load the next queue item
load_script.loading = true;
var item = load_script.scripts[++load_script.index];
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = item.src;
// When complete, start next item in queue and resolve this item's promise
script.onload = () => {
load_script.loading = false;
if( load_script.index < load_script.scripts.length - 1 ) load_script.next();
item.resolve();
};
head.appendChild(script);
};
};
// Adding a script to the queue
if( src ) {
// Check if already added
for(var i=0; i < load_script.scripts.length; i++) {
if( load_script.scripts[i].src == src ) return load_script.scripts[i].promise;
}
// Add to the queue
var item = { src: src };
item.promise = new Promise(resolve => {item.resolve = resolve;});
load_script.scripts.push(item);
load_script.next();
}
// Return the promise of the last queue item
return load_script.scripts[ load_script.scripts.length - 1 ].promise;
};
With this adding scripts in order ensuring the previous are done before staring the next can be done like...
["https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js",
"/jquery.some-plugin.js",
"/dependant-on-plugin.js",
].forEach(load_script);
Or load the script and use the return Promise to do work when it's complete...
load_script("some-script.js")
.then(function() {
/* some-script.js is done loading */
});
document.getElementById('header').style.width = '50%';
If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.
new StringBuilder().append(str.charAt(0))
.append(str.charAt(10))
.append(str.charAt(20))
.append(str.charAt(30))
.toString();
This way you can get the new string with whatever characters you want.
You can do this:
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
and most of it will work (although MS support will tell you that doing this is not supported because it bypasses RBAC).
I've seen issues with some cmdlets (specifically enable/disable UMmailbox) not working with just the snapin loaded.
In Exchange 2010, they basically don't support using Powershell outside of the the implicit remoting environment of an actual EMS shell.
I just used the following code, which removed all the punctuation:
tokens = nltk.wordpunct_tokenize(raw)
type(tokens)
text = nltk.Text(tokens)
type(text)
words = [w.lower() for w in text if w.isalpha()]
I have researched a lot for cleaning Backstack, and finally see Transaction BackStack and its management. Here is the solution that worked best for me.
// CLEAR BACK STACK.
private void clearBackStack() {
final FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.getBackStackEntryCount() != 0) {
fragmentManager.popBackStackImmediate();
}
}
The above method loops over all the transactions in the backstack and removes them immediately one at a time.
Note: above code sometime not work and i face ANR because of this code,so please do not try this.
Update below method remove all fregment of that "name" from backstack.
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack("name",FragmentManager.POP_BACK_STACK_INCLUSIVE);
One thing that confused me a little bit with this command is that if redis-cli
fails to connect using the passed connection string it will still put you in the redis-cli
shell, i.e:
redis-cli
Could not connect to Redis at 127.0.0.1:6379: Connection refused
not connected>
You'll then need to exit
to get yourself out of the shell. I wasn't paying much attention here and kept passing in new redis-cli
commands wondering why the command wasn't using my passed connection string.
You can make use of the Support Library's NestedScrollView
and it's NestedScrollView.OnScrollChangeListener
interface.
https://developer.android.com/reference/android/support/v4/widget/NestedScrollView.html
Alternatively if your app is targeting API 23 or above, you can make use of the following method on the ScrollView
:
View.setOnScrollChangeListener(OnScrollChangeListener listener)
Then follow the example that @Fustigador described in his answer. Note however that as @Will described, you should consider adding a small buffer in case the user or system isn't able to reach the complete bottom of the list for any reason.
Also worth noting is that the scroll change listener will sometimes be called with negative values or values greater than the view height. Presumably these values represent the 'momentum' of the scroll action. However unless handled appropriately (floor / abs) they can cause problems detecting the scroll direction when the view is scrolled to the top or bottom of the range.
Using a ListView
to make it not scroll is extremely expensive and goes against the whole purpose of ListView
. You should NOT do this. Just use a LinearLayout
instead.
From Linux you can use 'swaks' which is available as an official packages on many distros including Debian/Ubuntu and Redhat/CentOS on EPEL:
swaks -f [email protected] -t [email protected] \
--server mail.example.com
I solved the error by modifying the following property in hibernate.cfg.xml
<property name="hibernate.hbm2ddl.auto">validate</property>
Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.
As far as I know you can also change from validate to update e.g.:
<property name="hibernate.hbm2ddl.auto">update</property>
You can also use a TextView and set the background image to what you wanted in the ImageView
. Furthermore if you were using the ImageView
as a button you can set it to click-able
Here is some basic code for a TextView
that shows an image with text on top of it.
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/your_image"
android:text="your text here" />
If you want to redirect to error pages from your functions (routes) then do following things -
Add general error messages code in your app.js -
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
// render the error page
// you can also serve different error pages
// for example sake, I am just responding with simple error messages
res.status(err.status || 500)
if(err.status === 403){
return res.send('Action forbidden!');
}
if(err.status === 404){
return res.send('Page not found!');
}
// when status is 500, error handler
if(err.status === 500) {
return res.send('Server error occured!');
}
res.render('error')
})
In your function, instead of using a error-page redirect you can use set the error status first and then use next() for the code flow to go through above code -
if(FOUND){
...
}else{
// redirecting to general error page
// any error code can be used (provided you have handled its error response)
res.status(404)
// calling next() will make the control to go call the step 1. error code
// it will return the error response according to the error code given (provided you have handled its error response)
next()
}
Other posters have addressed the question about how contains() works.
An equally important aspect of your question is how to properly implement equals(). And the answer to this is really dependent on what constitutes object equality for this particular class. In the example you provided, if you have two different objects that both have x=5, are they equal? It really depends on what you are trying to do.
If you are only interested in object equality, then the default implementation of .equals() (the one provided by Object) uses identity only (i.e. this == other). If that's what you want, then just don't implement equals() on your class (let it inherit from Object). The code you wrote, while kind of correct if you are going for identity, would never appear in a real class b/c it provides no benefit over using the default Object.equals() implementation.
If you are just getting started with this stuff, I strongly recommend the Effective Java book by Joshua Bloch. It's a great read, and covers this sort of thing (plus how to correctly implement equals() when you are trying to do more than identity based comparisons)
A simple DIY way would be to make the grid yourself:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3], [2,3,4], 'ro')
for xmaj in ax.xaxis.get_majorticklocs():
ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
ax.axvline(x=xmin, ls='--')
for ymaj in ax.yaxis.get_majorticklocs():
ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
ax.axhline(y=ymin, ls='--')
plt.show()
Set the width and height and you're good.
div {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 200px;
height: 200px;
}
If you want the element dimensions to be flexible (and don't care about legacy browsers), go with XwipeoutX's answer.
Gradle is in offline mode, which means that it won't go to the network to resolve dependencies.
Go to Preferences > Gradle and uncheck "Offline work".
Coming across this question,
no answer brought up the possibility of using .setAttribute()
in addition to .value()
document.getElementById('some-input').value="1337";
document.getElementById('some-input').setAttribute("value", "1337");
Though unlikely helpful for the original questioner,
this addendum actually changes the content of the value in the pages source,
which in turn makes the value update form.reset()
-proof.
I hope this may help others.
(Or me in half a year when I've forgotten about js quirks...)
If you are using TOAD, you will need to download the 32-bit version of the Oracle Client Tools.
Since the Client Tools are different on a per-processor architecture basis, you probably need to install versions.
I get this error on Android Studio 4.0.1. Here is my solution: Go your build.gradle(Module: app) file and then update compileSdkVersion and buildToolsVersion.
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
}
String[] is an array of Strings. Such an array is internally a class. Like all classes that don't explicitly extend some other class, it extends Object implicitly. The method toString()
of class Object, by default, gives you the representation you see: the class name, followed by @, followed by the hash code in hex. Since the String[] class doesn't override the toString() method, you get that as a result.
Create some method that outputs the array elements for you. Iterate over the array and use System.out.print()
(not print*ln*) on the elements.
For reference, you can also utilize initWithDictionary
to init the NSMutableDictionary
with a literal one:
NSMutableDictionary buttons = [[NSMutableDictionary alloc] initWithDictionary: @{
@"touch": @0,
@"app": @0,
@"back": @0,
@"volup": @0,
@"voldown": @0
}];
Yes you can do it. Why don't you just try doing that?
Java 8's String.join
provides a tidy way to do this in conjunction with Collections.nCopies
:
// say hello 100 times
System.out.println(String.join("", Collections.nCopies(100, "hello")));
consider the following solution
.disable-anchor-tag {
pointer-events: none;
}
Thanks to @Pax Diablo, @bvmou and @Arachnid for the suggestion of using full datetimes throughout. If I have to accept datetime.time objects from an external source, then this seems to be an alternative add_secs_to_time()
function:
def add_secs_to_time(timeval, secs_to_add):
dummy_date = datetime.date(1, 1, 1)
full_datetime = datetime.datetime.combine(dummy_date, timeval)
added_datetime = full_datetime + datetime.timedelta(seconds=secs_to_add)
return added_datetime.time()
This verbose code can be compressed to this one-liner:
(datetime.datetime.combine(datetime.date(1, 1, 1), timeval) + datetime.timedelta(seconds=secs_to_add)).time()
but I think I'd want to wrap that up in a function for code clarity anyway.
Here's a solution to your problem using dplyr's filter
function.
Although you can pass your data frame as the first argument to any dplyr function, I've used its %>%
operator, which pipes your data frame to one or more dplyr functions (just filter in this case).
Once you are somewhat familiar with dplyr, the cheat sheet is very handy.
> print(df <- data.frame(sub=rep(1:3, each=4), day=1:4))
sub day
1 1 1
2 1 2
3 1 3
4 1 4
5 2 1
6 2 2
7 2 3
8 2 4
9 3 1
10 3 2
11 3 3
12 3 4
> print(df <- df %>% filter(!((sub==1 & day==2) | (sub==3 & day==4))))
sub day
1 1 1
2 1 3
3 1 4
4 2 1
5 2 2
6 2 3
7 2 4
8 3 1
9 3 2
10 3 3
I just created a subclass of UILabel to specially address such use cases. You can add multiple links easily and define different handlers for them. It also supports highlighting the pressed link when you touch down for touch feedback. Please refer to https://github.com/null09264/FRHyperLabel.
In your case, the code may like this:
FRHyperLabel *label = [FRHyperLabel new];
NSString *string = @"This morph was generated with Face Dancer, Click to view in the app store.";
NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};
label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];
[label setLinkForSubstring:@"Face Dancer" withLinkHandler:^(FRHyperLabel *label, NSString *substring){
[[UIApplication sharedApplication] openURL:aURL];
}];
Sample Screenshot (the handler is set to pop an alert instead of open a url in this case)
You can use the bash(1) built-in compgen
compgen -c
will list all the commands you could run.compgen -a
will list all the aliases you could run.compgen -b
will list all the built-ins you could run.compgen -k
will list all the keywords you could run.compgen -A function
will list all the functions you could run.compgen -A function -abck
will list all the above in one go.Check the man page for other completions you can generate.
To directly answer your question:
compgen -ac | grep searchstr
should do what yout want.
You can't call free
on the pointers returned from strsep
. Those are not individually allocated strings, but just pointers into the string s
that you've already allocated. When you're done with s
altogether, you should free it, but you do not have to do that with the return values of strsep
.
Using your code, this is how I would do it. I know an answer was chosen, just giving additional options.
data = json.loads('{"lat":444, "lon":555}')
ret = ''
for j in data:
ret = ret+" "+data[j]
return ret
When you use for in this manor you get the key of the object, not the value, so you can get the value, by using the key as an index.
[Offering a somewhat more descriptive answer than the answer provided by @Ajni.]
This can also be achieved using LINQ fluent syntax:
var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);
Note that each method (Where
, OrderBy
, Take
) that appears in this LINQ statement takes a lambda expression as an argument. Also note that the documentation for Enumerable.Take
begins with:
Returns a specified number of contiguous elements from the start of a sequence.
As explained here, you can use:
function replaceall(str,replace,with_this)
{
var str_hasil ="";
var temp;
for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
{
if (str[i] == replace)
{
temp = with_this;
}
else
{
temp = str[i];
}
str_hasil += temp;
}
return str_hasil;
}
... which you can then call using:
var str = "50.000.000";
alert(replaceall(str,'.',''));
The function will alert "50000000"
There are many ways of doing this (and I encourage you to look them up as they will be more efficient generally) but the simplest way of doing this is to use a non-set operation to define the value of the third column:
SELECT
t1.previous
,t1.present
,(t1.present - t1.previous) as difference
FROM #TEMP1 t1
Note, this style of selection is considered bad practice because it requires the query plan to reselect the value of the first two columns to logically determine the third (a violation of set theory that SQL is based on). Though it is more complicated, if you plan on using this to evaluate more than the values you listed in your example, I would investigate using an APPLY clause. http://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx
I'm loading 50,000 records in 15 or so seconds using Array Binding in ODP.NET
It works by repeatedly invoking a stored procedure you specify (and in which you can do updates/inserts/deletes), but it passes the multiple parameter values from .NET to the database in bulk.
Instead of specifying a single value for each parameter to the stored procedure you specify an array of values for each parameter.
Oracle passes the parameter arrays from .NET to the database in one go, and then repeatedly invokes the stored procedure you specify using the parameter values you specified.
http://www.oracle.com/technetwork/issue-archive/2009/09-sep/o59odpnet-085168.html
/Damian
I found an example from @progress/kendo-data-query
in file filter-descriptor.interface.d.ts
Checker
declare const isCompositeFilterDescriptor: (source: FilterDescriptor | CompositeFilterDescriptor) => source is CompositeFilterDescriptor;
Example usage
const filters: Array<FilterDescriptor | CompositeFilterDescriptor> = filter.filters;
filters.forEach((element: FilterDescriptor | CompositeFilterDescriptor) => {
if (isCompositeFilterDescriptor(element)) {
// element type is CompositeFilterDescriptor
} else {
// element type is FilterDescriptor
}
});
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
it's android:button="@drawable/selector_checkbox"
to make it work
Strings can be joined together using the concatenation operator ".."
this is the same for variables I think
Remove "values" when you're appending a group of rows, and remove the extra parentheses. You can avoid the circular reference by using an alias for avg(CurrencyColumn) (as you did in your example) or by not using an alias at all.
If the column names are the same in both tables, your query would be like this:
INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn) as CurrencyColumn1
FROM Table1
GROUP BY LongIntColumn;
And it would work without an alias:
INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn)
FROM Table1
GROUP BY LongIntColumn;
I had a bit of a dummy moment this morning when I realized what caused this issue for me.
The strange thing is that the request was failing in both Firefox and Chrome, but worked when I tried to access via Fiddler Web Debugger.
For me, the problem was I had mis-typed a character into one of the PHP files in the project. I didn't notice this until I checked Git for changes to the project.
In my case I had: m<?php runMyProgram(); ?>
.
Once I erased the m, it started working again.
Those of you trying to use the following:
window.open('page.html', '_newtab');
should really look at the window.open method.
All you are doing is telling the browser to open a new window NAMED "_newtab" and load page.html into it. Every new page you load will load into that window. However, if a user has their browser set to open new pages in new tabs instead of new windows, it will open a tab. Regardless, it's using the same name for the window or tab.
If you want different pages to open in different windows or tabs you will have to change the NAME of the new window/tab to something different such as:
window.open('page2.html', '_newtab2');
Of course the name for the new window/tab could be any name like page1, page2, page3, etc. instead of _newtab2.
One more thing that might be the problem in a case similar to described - X is not forwarded and $DISPLAY is not set when 'xauth' program is not installed on the remote side. You can see it searches for it when you run "ssh -Xv ip_address", and, if not found, fails, which's not seen unless you turn on verbose mode (a fail IMO). You can usually find 'xauth' in a package with the same name.
I am posting an answer here, since I had the same error message for a different reason.
This error message can happen, for example, if you are using apache httpd to proxy requests from a source on protocol A to target on protocol B.
Here is the example of my situation:
AH01144: No protocol handler was valid for the URL /sockjs-node/info (scheme 'ws').
In the case above, what was happening was simply the following. I had enabled mod proxy to proxy websocket requests to nodejs based on path /sockjs-node.
The problem is that node does not use the path /sockjs-node for websocket requests exclusively. It also uses this path for hosting REST entrypoints that deliver information about websockets.
In this manner, when the application would try to open http://localhost:7001/sockjs-node/info, apache httpd would be trying to route the rest call from HTTP protocol to to a Webscoket endpoint call. Node did not accept this.
This lead to the exception above.
So be mindful that even if you enable the right modules, if you try to do the wrong forwarding, this will end with apache httpd informing you that the protocol you tried to use on the target server is not valid.
I'd rather use more convenient itemSelect
event. With this event you can use org.primefaces.event.SelectEvent
objects in your listener.
<p:selectOneMenu ...>
<p:ajax event="itemSelect"
update="messages"
listener="#{beanMB.onItemSelectedListener}"/>
</p:selectOneMenu>
With such listener:
public void onItemSelectedListener(SelectEvent event){
MyItem selectedItem = (MyItem) event.getObject();
//do something with selected value
}
The value of the match
attribute of the <xsl:template>
instruction must be a match pattern.
Match patterns form a subset of the set of all possible XPath expressions. The first, natural, limitation is that a match pattern must select a set of nodes. There are also other limitations. In particular, reverse axes are not allowed in the location steps (but can be specified within the predicates). Also, no variable or parameter references are allowed in XSLT 1.0, but using these is legal in XSLT 2.x.
/
in XPath denotes the root or document node. In XPath 2.0 (and hence XSLT 2.x) this can also be written as document-node()
.
A match pattern can contain the //
abbreviation.
Examples of match patterns:
<xsl:template match="table">
can be applied on any element named table
.
<xsl:template match="x/y">
can be applied on any element named y
whose parent is an element named x
.
<xsl:template match="*">
can be applied to any element.
<xsl:template match="/*">
can be applied only to the top element of an XML document.
<xsl:template match="@*">
can be applied to any attribute.
<xsl:template match="text()">
can be applied to any text node.
<xsl:template match="comment()">
can be applied to any comment node.
<xsl:template match="processing-instruction()">
can be applied to any processing instruction node.
<xsl:template match="node()">
can be applied to any node: element, text, comment or processing instructon.
Everyone is correct. However, if you're also busy testing your code your own application might still "own" the socket if it starts and stops relatively quickly. Try SO_REUSEADDR as a socket option:
What exactly does SO_REUSEADDR do?
This socket option tells the kernel that even if this port is busy (in the TIME_WAIT state), go ahead and reuse it anyway. If it is busy, but with another state, you will still get an address already in use error. It is useful if your server has been shut down, and then restarted right away while sockets are still active on its port. You should be aware that if any unexpected data comes in, it may confuse your server, but while this is possible, it is not likely.
It has been pointed out that "A socket is a 5 tuple (proto, local addr, local port, remote addr, remote port). SO_REUSEADDR just says that you can reuse local addresses. The 5 tuple still must be unique!" by Michael Hunter ([email protected]). This is true, and this is why it is very unlikely that unexpected data will ever be seen by your server. The danger is that such a 5 tuple is still floating around on the net, and while it is bouncing around, a new connection from the same client, on the same system, happens to get the same remote port. This is explained by Richard Stevens in ``2.7 Please explain the TIME_WAIT state.''.
The garbage collection is the main reason Java# CANNOT be used for real-time systems.
When will the GC happen?
How long will it take?
This is non-deterministic.
To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin()
from the iterator:
ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();
Now you need to check pos
against Names.size()
to see if it is out of bounds or not:
if(pos >= Names.size()) {
//old_name_ not found
}
vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.
Starting with C++11 you can use std::distance
in place of subtraction for both iterators and pointers:
ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));
@Multipart
@POST(Config.UPLOAD_IMAGE)
Observable<Response<String>> uploadPhoto(@Header("Access-Token") String header, @Part MultipartBody.Part imageFile);
And you can call this api like this:
public void uploadImage(File file) {
// create multipart
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// upload
getViewInteractor().showProfileUploadingProgress();
Observable<Response<String>> observable = api.uploadPhoto("",body);
// on Response
subscribeForNetwork(observable, new ApiObserver<Response<String>>() {
@Override
public void onError(Throwable e) {
getViewInteractor().hideProfileUploadingProgress();
}
@Override
public void onResponse(Response<String> response) {
if (response.code() != 200) {
Timber.d("error " + response.code());
return;
}
getViewInteractor().hideProfileUploadingProgress();
getViewInteractor().onProfileImageUploadSuccess(response.body());
}
});
}
Use <td valign="top" style="width: 259px">
instead...
IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.
The multi-framework safe shorthand for ready is:
jQuery(function($, undefined) {
// $ is guaranteed to be short for jQuery in this scope
// undefined is provided because it could have been overwritten elsewhere
});
This is because jQuery isn't the only framework that uses the $
and undefined
variables
You have the Math.Round function that does exactly what you want.
Math.Round(1.1) results with 1
Math.Round(1.8) will result with 2.... and so one.
As stated, there is no non Microsoft / compiler vendor way to do this on the windows platform. However, it is obviously useful to catch these types of exceptions in the normal try { } catch (exception ex) { } way for error reporting and more a graceful exit of your app (as JaredPar says, the app is now probably in trouble). We use _se_translator_function in a simple class wrapper that allows us to catch the following exceptions in a a try handler:
DECLARE_EXCEPTION_CLASS(datatype_misalignment)
DECLARE_EXCEPTION_CLASS(breakpoint)
DECLARE_EXCEPTION_CLASS(single_step)
DECLARE_EXCEPTION_CLASS(array_bounds_exceeded)
DECLARE_EXCEPTION_CLASS(flt_denormal_operand)
DECLARE_EXCEPTION_CLASS(flt_divide_by_zero)
DECLARE_EXCEPTION_CLASS(flt_inexact_result)
DECLARE_EXCEPTION_CLASS(flt_invalid_operation)
DECLARE_EXCEPTION_CLASS(flt_overflow)
DECLARE_EXCEPTION_CLASS(flt_stack_check)
DECLARE_EXCEPTION_CLASS(flt_underflow)
DECLARE_EXCEPTION_CLASS(int_divide_by_zero)
DECLARE_EXCEPTION_CLASS(int_overflow)
DECLARE_EXCEPTION_CLASS(priv_instruction)
DECLARE_EXCEPTION_CLASS(in_page_error)
DECLARE_EXCEPTION_CLASS(illegal_instruction)
DECLARE_EXCEPTION_CLASS(noncontinuable_exception)
DECLARE_EXCEPTION_CLASS(stack_overflow)
DECLARE_EXCEPTION_CLASS(invalid_disposition)
DECLARE_EXCEPTION_CLASS(guard_page)
DECLARE_EXCEPTION_CLASS(invalid_handle)
DECLARE_EXCEPTION_CLASS(microsoft_cpp)
The original class came from this very useful article:
Here's another way to do for multiple Button
(In this case ImageView
)
MainActivity.java
findViewById(R.id.arrowIV).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (strokeWidthIV.getAlpha() == 0f) {
findViewById(R.id.arrowIV).animate().rotationBy(180);
strokeWidthIV.animate().translationXBy(-120 * 4).alpha(1f);
findViewById(R.id.colorChooseIV).animate().translationXBy(-120 * 3).alpha(1f);
findViewById(R.id.saveIV).animate().translationXBy(-120 * 2).alpha(1f);
findViewById(R.id.clearAllIV).animate().translationXBy(-120).alpha(1f);
} else {
findViewById(R.id.arrowIV).animate().rotationBy(180);
strokeWidthIV.animate().translationXBy(120 * 4).alpha(0f);
findViewById(R.id.colorChooseIV).animate().translationXBy(120 * 3).alpha(0f);
findViewById(R.id.saveIV).animate().translationXBy(120 * 2).alpha(0f);
findViewById(R.id.clearAllIV).animate().translationXBy(120).alpha(0f);
}
}
});
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.MainActivity">
<ImageView
android:id="@+id/strokeWidthIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_edit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/colorChooseIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_palette"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/saveIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_save"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/clearAllIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_clear_all"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/arrowIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:contentDescription="Arrow"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_arrow"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
</androidx.constraintlayout.widget.ConstraintLayout>
Maybe you can add a step to the generate-sources phase that moves the folder?
Please DO NOT follow solutions suggesting to use sudo
(sudo adb start-server
)! This run adb as root (administrator) and it is NOT supposed to run like that!!! It's a BAD workaround!
Everything running as root can do anything in your system, if it creates or modify a file can change its permission to be only used by root. Again, DON'T!
The right thing to do is set up your system to make the USER have the permission, check out this guide i wrote on how to do it properly.
You need System.Diagnostics.Process.Start()
.
The simplest example:
Process.Start("notepad.exe", fileName);
More Generic Approach:
Process.Start(fileName);
The second approach is probably a better practice as this will cause the windows Shell to open up your file with it's associated editor. Additionally, if the file specified does not have an association, it'll use the Open With...
dialog from windows.
Note to those in the comments, thankyou for your input. My quick n' dirty answer was slightly off, i've updated the answer to reflect the correct way.
Read the data:
foo <- read.table(text="1 349
1 393
1 392
4 459
3 49
3 32
2 94")
And sort:
foo[order(foo$V1),]
This relies on the fact that order
keeps ties in their original order. See ?order
.
In chrome, if you hover your cursor on Download ZIP it will give you the link at the bottom of the browser
I can give you an ok solution and you can go with it, but before I do I'm going to try to explain why Document is not a DependencyProperty
to begin with.
During the lifetime of a RichTextBox
control, the Document
property generally doesn't change. The RichTextBox
is initialized with a FlowDocument
. That document is displayed, can be edited and mangled in many ways, but the underlying value of the Document
property remains that one instance of the FlowDocument
. Therefore, there is really no reason it should be a DependencyProperty
, ie, Bindable. If you have multiple locations that reference this FlowDocument
, you only need the reference once. Since it is the same instance everywhere, the changes will be accessible to everyone.
I don't think FlowDocument
supports document change notifications, though I am not sure.
That being said, here's a solution. Before you start, since RichTextBox
doesn't implement INotifyPropertyChanged
and Document is not a DependencyProperty
, we have no notifications when the RichTextBox
's Document property changes, so the binding can only be OneWay.
Create a class that will provide the FlowDocument
. Binding requires the existence of a DependencyProperty
, so this class inherits from DependencyObject
.
class HasDocument : DependencyObject
{
public static readonly DependencyProperty DocumentProperty =
DependencyProperty.Register("Document",
typeof(FlowDocument),
typeof(HasDocument),
new PropertyMetadata(new PropertyChangedCallback(DocumentChanged)));
private static void DocumentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine("Document has changed");
}
public FlowDocument Document
{
get { return GetValue(DocumentProperty) as FlowDocument; }
set { SetValue(DocumentProperty, value); }
}
}
Create a Window
with a rich text box in XAML.
<Window x:Class="samples.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Flow Document Binding" Height="300" Width="300"
>
<Grid>
<RichTextBox Name="richTextBox" />
</Grid>
</Window>
Give the Window
a field of type HasDocument
.
HasDocument hasDocument;
Window constructor should create the binding.
hasDocument = new HasDocument();
InitializeComponent();
Binding b = new Binding("Document");
b.Source = richTextBox;
b.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(hasDocument, HasDocument.DocumentProperty, b);
If you want to be able to declare the binding in XAML, you would have to make your HasDocument
class derive from FrameworkElement
so that it can be inserted into the logical tree.
Now, if you were to change the Document
property on HasDocument
, the rich text box's Document
will also change.
FlowDocument d = new FlowDocument();
Paragraph g = new Paragraph();
Run a = new Run();
a.Text = "I showed this using a binding";
g.Inlines.Add(a);
d.Blocks.Add(g);
hasDocument.Document = d;
For that particular case there is file.path
:
File <- file.path("~",
"a",
"very",
"long",
"path",
"here",
"that",
"goes",
"beyond",
"80",
"characters",
"and",
"then",
"some",
"more")
setwd(File)
synchronized should only be used when you want your class to be Thread safe. In fact most of the classes should not use synchronized anyways. synchronized method would only provide a lock on this object and only for the duration of its execution. if you really wanna to make your classes thread safe, you should consider making your variables volatile or synchronize the access.
one of the issues of using synchronized method is that all of the members of the class would use the same lock which will make your program slower. In your case synchronized method and block would execute no different. what I'd would recommend is to use a dedicated lock and use a synchronized block something like this.
public class AClass {
private int x;
private final Object lock = new Object(); //it must be final!
public void setX() {
synchronized(lock) {
x++;
}
}
}
This will solve all gulp problem
sudo npm install gulp && sudo npm install --save del && sudo gulp build
This works perfectly fine for me:
AdapterChart adapterChart = new AdapterChart(getContext(),messageList);
recyclerView.setAdapter(adapterChart);
recyclerView.scrollToPosition(recyclerView.getAdapter().getItemCount()-1);
Don't forget to deploy global.asax
If you're looking to extract the public key for use with OpenSSH, you will need to get the public key a bit differently
$ ssh-keygen -y -f mykey.pem > mykey.pub
This public key format is compatible with OpenSSH. Append the public key to remote:~/.ssh/authorized_keys
and you'll be good to go
docs from SSH-KEYGEN(1)
ssh-keygen -y [-f input_keyfile]
-y This option will read a private OpenSSH format file and print an OpenSSH public key to stdout.
Another option is to update the Microsoft.AspnNet.Mvc NuGet package. Be careful, because NuGet update does not update the Web.Config. You should update all previous version numbers to updated number. For example if you update from asp.net MVC 4.0.0.0 to 5.0.0.0, then this should be replaced in the Web.Config:
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
You need to use Range
and Valu
e functions.
Range
would be the cell where you want the text you want
Value
would be the text that you want in that Cell
Range("A1").Value="whatever text"
JS
$(function () {
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
$("#submit").click(function () {
alert('button clicked');
});
});
html
<input id="submit" type="submit" value="submit" name="submit">
You can do the same with .ix
, like this:
In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))
In [2]: df
Out[2]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 -0.905302 -0.435821 1.934512
3 0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
In [3]: df.ix[df.a>0, ['b','c']] = 0
In [4]: df
Out[4]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 0.000000 0.000000 1.934512
3 0.266113 0.000000 0.000000 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
EDIT
After the extra information, the following will return all columns - where some condition is met - with halved values:
>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)
I hope this helps!
I had the same problem on OSX 10.6.6. But just a simple easy_install mysql-python
on terminal did not solve it as another hiccup followed:
error: command 'gcc-4.2' failed with exit status 1
.
Apparently, this issue arises after upgrading from XCode3 (which is natively shipped with OSX 10.6) to XCode4. This newer ver removes support for building ppc arch. If its the same case, try doing as follows before easy_install mysql-python
sudo bash
export ARCHFLAGS='-arch i386 -arch x86_64'
rm -r build
python setup.py build
python setup.py install
Many thanks to Ned Deily for this solution. Check here
Trying to set background color based on condition:
Consider variable x with some numeric value.
<p [ngStyle]="{ backgroundColor: x > 4 ? 'lightblue' : 'transparent' }">
This is a sample Text
</p>
Click the "Remove all Sessions" button in the toolbar of the "Coverage" view.
You cannot refer non-static members from a static method.
Non-Static members (like your fxn(int y)) can be called only from an instance of your class.
Example:
You can do this:
public class A
{
public int fxn(int y) {
y = 5;
return y;
}
}
class Two {
public static void main(String[] args) {
int x = 0;
A a = new A();
System.out.println("x = " + x);
x = a.fxn(x);
System.out.println("x = " + x);
}
or you can declare you method as static.
int function(){
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
int range;
while(true){
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine(); //Comsume the garbage value
System.out.println("Enter an integer between 1-100:");
}
return range;
}
Project is works in DotNET Core 3.1+ or higher(future)
Add this package:
Microsoft.EntityFrameworkCore.Tools
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.8">
dumpbin
from the Visual Studio command prompt:
dumpbin /exports csp.dll
Example of output:
Microsoft (R) COFF/PE Dumper Version 10.00.30319.01
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file csp.dll
File Type: DLL
Section contains the following exports for CSP.dll
00000000 characteristics
3B1D0B77 time date stamp Tue Jun 05 12:40:23 2001
0.00 version
1 ordinal base
25 number of functions
25 number of names
ordinal hint RVA name
1 0 00001470 CPAcquireContext
2 1 000014B0 CPCreateHash
3 2 00001520 CPDecrypt
4 3 000014B0 CPDeriveKey
5 4 00001590 CPDestroyHash
6 5 00001590 CPDestroyKey
7 6 00001560 CPEncrypt
8 7 00001520 CPExportKey
9 8 00001490 CPGenKey
10 9 000015B0 CPGenRandom
11 A 000014D0 CPGetHashParam
12 B 000014D0 CPGetKeyParam
13 C 00001500 CPGetProvParam
14 D 000015C0 CPGetUserKey
15 E 00001580 CPHashData
16 F 000014F0 CPHashSessionKey
17 10 00001540 CPImportKey
18 11 00001590 CPReleaseContext
19 12 00001580 CPSetHashParam
20 13 00001580 CPSetKeyParam
21 14 000014F0 CPSetProvParam
22 15 00001520 CPSignHash
23 16 000015A0 CPVerifySignature
24 17 00001060 DllRegisterServer
25 18 00001000 DllUnregisterServer
Summary
1000 .data
1000 .rdata
1000 .reloc
1000 .rsrc
1000 .text
The handshake failure could have occurred due to various reasons:
Since, the underlying failure cannot be pinpointed, it is better to switch on the -Djavax.net.debug=all
flag to enable debugging of the SSL connection established. With the debug switched on, you can pinpoint what activity in the handshake has failed.
Update
Based on the details now available, it appears that the problem is due to an incomplete certificate trust path between the certificate issued to the server, and a root CA. In most cases, this is because the root CA's certificate is absent in the trust store, leading to the situation where a certificate trust path cannot exist; the certificate is essentially untrusted by the client. Browsers can present a warning so that users may ignore this, but the same is not the case for SSL clients (like the HttpsURLConnection class, or any HTTP Client library like Apache HttpComponents Client).
Most these client classes/libraries would rely on the trust store used by the JVM for certificate validation. In most cases, this will be the cacerts
file in the JRE_HOME/lib/security directory. If the location of the trust store has been specified using the JVM system property javax.net.ssl.trustStore
, then the store in that path is usually the one used by the client library. If you are in doubt, take a look at your Merchant
class, and figure out the class/library it is using to make the connection.
Adding the server's certificate issuing CA to this trust store ought to resolve the problem. You can refer to my answer on a related question on getting tools for this purpose, but the Java keytool utility is sufficient for this purpose.
Warning: The trust store is essentially the list of all CAs that you trust. If you put in an certificate that does not belong to a CA that you do not trust, then SSL/TLS connections to sites having certificates issued by that entity can be decrypted if the private key is available.
Update #2: Understanding the output of the JSSE trace
The keystore and the truststores used by the JVM are usually listed at the very beginning, somewhat like the following:
keyStore is :
keyStore type is : jks
keyStore provider is :
init keystore
init keymanager of type SunX509
trustStore is: C:\Java\jdk1.6.0_21\jre\lib\security\cacerts
trustStore type is : jks
trustStore provider is :
If the wrong truststore is used, then you'll need to re-import the server's certificate to the right one, or reconfigure the server to use the one listed (not recommended if you have multiple JVMs, and all of them are used for different needs).
If you want to verify if the list of trust certs contains the required certs, then there is a section for the same, that starts as:
adding as trusted cert:
Subject: CN=blah, O=blah, C=blah
Issuer: CN=biggerblah, O=biggerblah, C=biggerblah
Algorithm: RSA; Serial number: yadda
Valid from SomeDate until SomeDate
You'll need to look for if the server's CA is a subject.
The handshake process will have a few salient entries (you'll need to know SSL to understand them in detail, but for the purpose of debugging the current problem, it will suffice to know that a handshake_failure is usually reported in the ServerHello.
1. ClientHello
A series of entries will be reported when the connection is being initialized. The first message sent by the client in a SSL/TLS connection setup is the ClientHello message, usually reported in the logs as:
*** ClientHello, TLSv1
RandomCookie: GMT: 1291302508 bytes = { some byte array }
Session ID: {}
Cipher Suites: [SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_DES_CBC_SHA, SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA]
Compression Methods: { 0 }
***
Note the cipher suites used. This might have to agree with the entry in your merchant.properties file, for the same convention might be employed by the bank's library. If the convention used is different, there is no cause of worry, for the ServerHello will state so, if the cipher suite is incompatible.
2. ServerHello
The server responds with a ServerHello, that will indicate if the connection setup can proceed. Entries in the logs are usually of the following type:
*** ServerHello, TLSv1
RandomCookie: GMT: 1291302499 bytes = { some byte array}
Cipher Suite: SSL_RSA_WITH_RC4_128_SHA
Compression Method: 0
***
Note the cipher suite that it has chosen; this is best suite available to both the server and the client. Usually the cipher suite is not specified if there is an error. The certificate of the server (and optionally the entire chain) is sent by the server, and would be found in the entries as:
*** Certificate chain
chain [0] = [
[
Version: V3
Subject: CN=server, O=server's org, L=server's location, ST =Server's state, C=Server's country
Signature Algorithm: SHA1withRSA, OID = some identifer
.... the rest of the certificate
***
If the verification of the certificate has succeeded, you'll find an entry similar to:
Found trusted certificate:
[
[
Version: V1
Subject: OU=Server's CA, O="Server's CA's company name", C=CA's country
Signature Algorithm: SHA1withRSA, OID = some identifier
One of the above steps would not have succeeded, resulting in the handshake_failure, for the handshake is typically complete at this stage (not really, but the subsequent stages of the handshake typically do not cause a handshake failure). You'll need to figure out which step has failed, and post the appropriate message as an update to the question (unless you've already understood the message, and you know what to do to resolve it).
I have the same issue, and the issue is like this:
dyld: Library not loaded: @rpath/Result.framework/Result Referenced from: /private/var/mobile/Containers/Bundle/Application/74AD1FE2-7095-47D2-B059-520863050EE2/ReactiveCocoaTest.app/Frameworks/ReactiveCocoa.framework/ReactiveCocoa Reason: image not found
My solution is below:
In the TARGET
-> Build Setting
-> Other Linker Flag
-> delete the ReactiveCocoa
framework. If is xxx.framework
, you know, you should delete the xxx
.
delete the ReactiveCocoa
I have faced the problem but found a unique solution.
for me this was the old code
String NOTIFICATION_CHANNEL_ID = "com.codedevtech.emplitrack";
and the working code is
String NOTIFICATION_CHANNEL_ID = "emplitrack_channel";
may be the channel id should not contain dot '.'
This is taken from the Python docs:
Identifiers (also referred to as names) are described by the following lexical definitions:
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
Identifiers are unlimited in length. Case is significant.
That should explain how to name your variables.