Can I increase the heap memory to 75% of physical memory(6GB Heap).
Yes you can. In fact, you can increase to more than the amount of physical memory, if you want to.
Whether it is a good idea to do this depends on how much else is running on your system. In particular, if the "working set" of the applications and services that are currently running significantly exceeds the available physical memory, your system is liable to "thrash", spending a lot of time moving virtual memory pages to and from disk. The net effect is that the system gets horribly slow.
To remove all array elements irrespective of any given id, use this:
collection.update(
{ },
{ $pull: { 'contact.phone': { number: '+1786543589455' } } }
);
The answers here are outdated. Now you can easily use a CSS3 transform without hardcoding a margin. This works on all elements, including elements with no width or dynamic width.
Horizontal center:
left: 50%;
transform: translateX(-50%);
Vertical center:
top: 50%;
transform: translateY(-50%);
Both horizontal and vertical:
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
Compatibility is not an issue: http://caniuse.com/#feat=transforms2d
We need to implement two layouts. One to hold listview and another to hold row item of listview. Implement your own custom adapter. Idea is to include one textview and one imageview.
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View single_row = inflater.inflate(R.layout.list_row, null,
true);
TextView textView = (TextView) single_row.findViewById(R.id.textView);
ImageView imageView = (ImageView) single_row.findViewById(R.id.imageView);
textView.setText(color_names[position]);
imageView.setImageResource(image_id[position]);
return single_row;
}
Next we implement functionality in main activity to include images and text data dynamically during runtime. You can pass dynamically created text array and image id array to the constructor of custom adapter.
Customlistadapter adapter = new Customlistadapter(this, image_id, text_name);
Make the background image transparent/semi-transparent. If it's a solid coloured background just create a 1px by 1px image in fireworks or whatever and adjust its opacity...
All you have to do is apply the format you want in the html helper call, ie.
@Html.TextBoxFor(m => m.RegistrationDate, "{0:dd/MM/yyyy}")
You don't need to provide the date format in the model class.
First one is for Javadoc you define on the top of classes, interfaces, methods etc. You can use Javadoc as the name suggest to document your code on what the class does or what method does etc and generate report on it.
Second one is code block comment. Say for example you have some code block which you do not want compiler to interpret then you use code block comment.
another one is // this you use on statement level to specify what the proceeding lines of codes are supposed to do.
There are some other also like //TODO, this will mark that you want to do something later on that place
//FIXME you can use when you have some temporary solution but you want to visit later and make it better.
Hope this helps
One more thing i would like to add-
Union:- Result set is sorted in ascending order.
Union All:- Result set is not sorted. two Query output just gets appended.
As of 2016 (ES6) we may use for…of
for array iteration, as John Slegers already noticed.
I would just like to add this simple demonstration code, to make things clearer:
Array.prototype.foo = 1;
var arr = [];
arr[5] = "xyz";
console.log("for...of:");
var count = 0;
for (var item of arr) {
console.log(count + ":", item);
count++;
}
console.log("for...in:");
count = 0;
for (var item in arr) {
console.log(count + ":", item);
count++;
}
The console shows:
for...of:
0: undefined
1: undefined
2: undefined
3: undefined
4: undefined
5: xyz
for...in:
0: 5
1: foo
In other words:
for...of
counts from 0 to 5, and also ignores Array.prototype.foo
. It shows array values.
for...in
lists only the 5
, ignoring undefined array indexes, but adding foo
. It shows array property names.
I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:
<p>
Hello {
<span>World</span>
}!
</p>
or
<p>
Hello {}
<span>World</span>
{} again!
</p>
Each of these produces clean html without additional
or other extraneous markup. It creates fewer text nodes than using {' '}
, and allows using of html entities where {' hello & goodbye '}
does not.
Place it in the Dockerfile
above the ENV
.
# make the "en_US.UTF-8" locale so postgres will be utf-8 enabled by default
RUN apt-get update && apt-get install -y locales && rm -rf /var/lib/apt/lists/* \
&& localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8
ENV LANG en_US.UTF-8
I too had this problem. But apparently there is an issue of the order of method calls. You must call:
[self.picker selectRow:2 inComponent:0 animated:YES];
after calling
[self.view addSubview:self.picker];
CASE AlarmEventTransactions.DeviceID
should just be CASE
.
You are mixing the 2 forms of the CASE
expression.
Using a decorator for measuring execution time for functions can be handy. There is an example at http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods.
Below I've shamelessly pasted the code from the site mentioned above so that the example exists at SO in case the site is wiped off the net.
import time
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '%r (%r, %r) %2.2f sec' % \
(method.__name__, args, kw, te-ts)
return result
return timed
class Foo(object):
@timeit
def foo(self, a=2, b=3):
time.sleep(0.2)
@timeit
def f1():
time.sleep(1)
print 'f1'
@timeit
def f2(a):
time.sleep(2)
print 'f2',a
@timeit
def f3(a, *args, **kw):
time.sleep(0.3)
print 'f3', args, kw
f1()
f2(42)
f3(42, 43, foo=2)
Foo().foo()
// John
html
<input class='all' type='checkbox'> All
<input class='item' type='checkbox' value='1'> 1
<input class='item' type='checkbox' value='2'> 2
<input class='item' type='checkbox' value='3'> 3
javascript
$(':checkbox.all').change(function(){
$(':checkbox.item').prop('checked', this.checked);
});
In Access VBA I've used this to turn off all the dialogs when running a bunch of updates:
DoCmd.SetWarnings False
After running all the updates, the last step in my VBA script is:
DoCmd.SetWarnings True
Hope this helps.
Implement Activity with View.OnClickListener
like below.
public class MyActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_options);
Button button = findViewById(R.id.button);
Button button2 = findViewById(R.id.button2);
button.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.button:
// Write your code here first button
break;
case R.id.button2:
// Write your code here for second button
break;
}
}
}
Another way to do this is to create a custom template tag which can let you fish values out of the settings.
@register.tag
def value_from_settings(parser, token):
try:
# split_contents() knows not to split quoted strings.
tag_name, var = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
return ValueFromSettings(var)
class ValueFromSettings(template.Node):
def __init__(self, var):
self.arg = template.Variable(var)
def render(self, context):
return settings.__getattr__(str(self.arg))
You can then use:
{% value_from_settings "FQDN" %}
to print it on any page, without jumping through context-processor hoops.
What we have in our table:-
Primary Key
Event type (e.g. "UPDATED", "APPROVED")
Description ("Frisbar was added to blong")
User Id
User Id of second authoriser
Amount
Date/time
Generic Id
Table Name
The generic id points at a row in the table that was updated and the table name is the name of that table as a string. Not a good DB design, but very usable. All our tables have a single surrogate key column so this works well.
You can also use XPath's text()
node test to get the text nodes only. For example
var target = document.querySelector('div.title');
var iter = document.evaluate('text()', target, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);
var node;
var want = '';
while (node = iter.iterateNext()) {
want += node.data;
}
Using combining anonymous functions and Array.map
for a cleaner; more streamlined look.
var write=function(str){document.body.innerHTML=JSON.stringify(str,null,' ');};_x000D_
_x000D_
function hexToRgb(hex, asObj) {_x000D_
return (function(res) {_x000D_
return res == null ? null : (function(parts) {_x000D_
return !asObj ? parts : { r : parts[0], g : parts[1], b : parts[2] }_x000D_
}(res.slice(1,4).map(function(val) { return parseInt(val, 16); })));_x000D_
}(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)));_x000D_
}_x000D_
_x000D_
function rgbToHex(r, g, b) {_x000D_
return (function(values) {_x000D_
return '#' + values.map(function(intVal) {_x000D_
return (function(hexVal) {_x000D_
return hexVal.length == 1 ? "0" + hexVal : hexVal;_x000D_
}(intVal.toString(16)));_x000D_
}).join('');_x000D_
}(arguments.length === 1 ? Array.isArray(r) ? r : [r.r, r.g, r.b] : [r, g, b]))_x000D_
}_x000D_
_x000D_
// Prints: { r: 255, g: 127, b: 92 }_x000D_
write(hexToRgb(rgbToHex(hexToRgb(rgbToHex(255, 127, 92), true)), true));
_x000D_
body{font-family:monospace;white-space:pre}
_x000D_
You can use $.browser to detect the browser name. possible values are :
or get a boolean flag: $.browser.msie will be true if the browser is MSIE.
as for the version number, if you are only interested in the major release number - you can use parseInt($.browser.version, 10). no need to parse the $.browser.version string yourself.
Anyway, The $.support property is available for detection of support for particular features rather than relying on $.browser.
The error happens when you have compiled with higher version of Java and it is been tried to run with lower version of JRE. Even with minor version mismatch you would have this issue
I had issue compiling with JDK 1.8.0_31 and it was run with jdk1.8.0_25 and was displaying the same error. Once either the target is updated to higher version or compiled with same or lesser version would resolve the issue
Static Methods:
Benefits of Static Methods:
More convenient to import versus module-level functions since each method does not have to be specially imported
@staticmethod
def some_static_method(*args, **kwds):
pass
Class Methods:
These are created with classmethod in-built function.
@classmethod
def some_class_method(cls, *args, **kwds):
pass
I don't think there is a way to print array for you in printf. "printf" function has no idea how long your array is.
Answering the question at hand...
No it's not enough to have these attributes, to be able to autoplay a media with audio you need to have an user-gesture registered on your document.
But, this limitation is very weak: if you did receive this user-gesture on the parent document, and your video got loaded from an iframe, then you could play it...
So take for instance this fiddle, which is only
<video src="myvidwithsound.webm" autoplay=""></video>
At first load, and if you don't click anywhere, it will not run, because we don't have any event registered yet.
But once you click the "Run" button, then the parent document (jsfiddle.net) did receive an user-gesture, and now the video plays, even though it is technically loaded in a different document.
But the following snippet, since it requires you to actually click the Run code snippet button, will autoplay.
<video src="https://upload.wikimedia.org/wikipedia/commons/transcoded/2/22/Volcano_Lava_Sample.webm/Volcano_Lava_Sample.webm.360p.webm" autoplay=""></video>
_x000D_
This means that your ad was probably able to play because you did provide an user-gesture to the main page.
Now, note that Safari and Mobile Chrome have stricter rules than that, and will require you to actually trigger at least once the play()
method programmatically on the <video>
or <audio>
element from the user-event handler itself.
btn.onclick = e => {_x000D_
// mark our MediaElement as user-approved_x000D_
vid.play().then(()=>vid.pause());_x000D_
// now we can do whatever we want at any time with this MediaElement_x000D_
setTimeout(()=> vid.play(), 3000);_x000D_
};
_x000D_
<button id="btn">play in 3s</button>_x000D_
<video_x000D_
src="https://upload.wikimedia.org/wikipedia/commons/transcoded/2/22/Volcano_Lava_Sample.webm/Volcano_Lava_Sample.webm.360p.webm" id="vid"></video>
_x000D_
And if you don't need the audio, then simply don't attach it to your media, a video with only a video track is also allowed to autoplay, and will reduce your user's bandwidth usage.
In case if anyone wants to create there own exponential function using recursion, below is for your reference.
public static double power(double value, double p) {
if (p <= 0)
return 1;
return value * power(value, p - 1);
}
Since coffeescript is rarely used on it's own, you can use global
variable supplied by either node.js or browserify (and any descendants like coffeeify, gulp build scripts, etc).
In node.js global
is global namespace.
In browserify global
is equal to window
.
So, just:
somefunc = ->
global.variable = 123
There is also an 'E' status
E = File existed before update
This can happen if you have manually created a folder that would have been created by performing an update.
You can indeed match all those characters, but it's safer to escape the -
so that it is clear that it be taken literally.
If you are using a POSIX variant you can opt to use:
([[:alnum:]\-_]+)
But a since you are including the underscore I would simply use:
([\w\-]+)
(works in all variants)
z
means (un)z_ip.x
means ex_tract files from the archive.v
means print the filenames v_erbosely.f
means the following argument is a f_ilename.For more details, see tar
's man page.
Use JavaScript (screen.width
and screen.height
IIRC, but I may be wrong, haven't done JS in a while). PHP cannot do it.
It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:
public class ImageHandler : IHttpHandler
{
byte[] bytes;
public void ProcessRequest(HttpContext context)
{
int param;
if (int.TryParse(context.Request.QueryString["id"], out param))
{
using (var db = new MusicLibContext())
{
if (param == -1)
{
bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));
context.Response.ContentType = "image/png";
}
else
{
var data = (from x in db.Images
where x.ImageID == (short)param
select x).FirstOrDefault();
bytes = data.ImageData;
context.Response.ContentType = "image/" + data.ImageFileType;
}
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
}
else
{
//image not found
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
In the view, i added the ID of the photo to the query string of the handler.
Thank you so much to @Code in another answer. I can read any JSON file thanks to your code. Now, I'm trying to organize all the elements by levels, for could use them!
I was working with Android reading a JSON from an URL and the only I had to change was the lines
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
for
Iterator<?> iterator = jsonObject.keys();
I share my implementation, to help someone:
public void parseJson(JSONObject jsonObject) throws ParseException, JSONException {
Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String obj = iterator.next().toString();
if (jsonObject.get(obj) instanceof JSONArray) {
//Toast.makeText(MainActivity.this, "Objeto: JSONArray", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString());
TextView txtView = new TextView(this);
txtView.setText(obj.toString());
layoutIzq.addView(txtView);
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
//Toast.makeText(MainActivity.this, "Objeto: JSONObject", Toast.LENGTH_SHORT).show();
parseJson((JSONObject) jsonObject.get(obj));
} else {
//Toast.makeText(MainActivity.this, "Objeto: Value", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString() + "\t"+ jsonObject.get(obj));
TextView txtView = new TextView(this);
txtView.setText(obj.toString() + "\t"+ jsonObject.get(obj));
layoutIzq.addView(txtView);
}
}
}
}
one way;
var = count("find me", Range("A1:A100"))
function count(find as string, lookin as range) As Long
dim cell As Range
for each cell in lookin
if (cell.Value = find) then count = count + 1 '//case sens
next
end function
With -Raw
you should get what you expect
You can use recursion to do this. I haven't verified the following, but it should give you the right idea:
MergeListOfDf = function( data , ... )
{
if ( length( data ) == 2 )
{
return( merge( data[[ 1 ]] , data[[ 2 ]] , ... ) )
}
return( merge( MergeListOfDf( data[ -1 ] , ... ) , data[[ 1 ]] , ... ) )
}
Another option is to use placeholders.
Html:
<body>
<div id="root">
<asp:PlaceHolder ID="iframeDiv" runat="server"/>
</div>
</body>
C#:
iframeDiv.Controls.Add(new LiteralControl("<iframe src=\"" + whatever.com + "\"></iframe><br />"));
What you're looking for is:
if($variable === NULL) {...}
Note the ===
.
When use ==
, as you did, PHP treats NULL, false, 0, the empty string, and empty arrays as equal.
It's even simpler than that. Just did this (on Windows, but it should work on other OS):
Git just sees you added a directory and renamed a bunch of files. No biggie.
Encapsulation is a way to achieve "information hiding" so, following your example, you don't "need to know the internal working of the mobile phone to operate" with it. You have an interface to use the device behaviour without knowing implementation details.
Abstraction on the other side, can be explained as the capability to use the same interface for different objects. Different implementations of the same interface can exist. Details are hidden by encapsulation.
On input, if you want to filter out other characters and only show numbers in the input field, you could replace the value of the field on keyup:
var yourInput = jQuery('#input-field');
yourInput.keyup(function() {
yourInput.val((yourInput.val().replace(/[^\d]/g,'')))
})
Delete package-lock.json
it works for me
then npm install
You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Be sure that the LocationListener you're implementing is from the google api, that is import this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
and it should work just fine.
It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html
You've almost done it. However setting flex: 0 0 <basis>
declaration to the columns would prevent them from growing/shrinking; And the <basis>
parameter would define the width of columns.
In addition, you could use CSS3 calc()
expression to specify the height
of columns with the respect to the height of the header.
#productShowcaseTitle {
flex: 0 0 100%; /* Let it fill the entire space horizontally */
height: 100px;
}
#productShowcaseDetail,
#productShowcaseThumbnailContainer {
height: calc(100% - 100px); /* excluding the height of the header */
}
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
flex: 0 0 100%; /* Let it fill the entire space horizontally */_x000D_
height: 100px;_x000D_
background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
flex: 0 0 66%; /* ~ 2 * 33.33% */_x000D_
height: calc(100% - 100px); /* excluding the height of the header */_x000D_
background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
flex: 0 0 34%; /* ~ 33.33% */_x000D_
height: calc(100% - 100px); /* excluding the height of the header */_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle"></div>_x000D_
<div id="productShowcaseDetail"></div>_x000D_
<div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>
_x000D_
(Vendor prefixes omitted due to brevity)
Alternatively, if you could change your markup e.g. wrapping the columns by an additional <div>
element, it would be achieved without using calc()
as follows:
<div class="contentContainer"> <!-- Added wrapper -->
<div id="productShowcaseDetail"></div>
<div id="productShowcaseThumbnailContainer"></div>
</div>
#productShowcaseContainer {
display: flex;
flex-direction: column;
height: 600px; width: 580px;
}
.contentContainer { display: flex; flex: 1; }
#productShowcaseDetail { flex: 3; }
#productShowcaseThumbnailContainer { flex: 2; }
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.contentContainer {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
height: 100px;_x000D_
background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
flex: 3;_x000D_
background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle"></div>_x000D_
_x000D_
<div class="contentContainer"> <!-- Added wrapper -->_x000D_
<div id="productShowcaseDetail"></div>_x000D_
<div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
(Vendor prefixes omitted due to brevity)
You can't. Variables defined inside a method are local to that method.
If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Looks like you're using instance methods instead of static ones.
If you don't want to create an object, you should declare all your methods static, so something like
private static void methodName(Argument args...)
If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.
private static int[][] array = new int[3][5];
Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.
Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.
Here's a final (shortened) example of what your code should be like:
public class Test3 {
//Use this array in your methods
private static int[][] scores = new int[3][5];
/* Rather than just "Scores" name it so people know what
* to expect
*/
private static void createScores() {
//Code...
}
//Other methods...
/* Since you're now using static methods, you don't
* have to initialise an object and call its methods.
*/
public static void main(String[] args){
createScores();
MD(); //Don't know what these do
sumD(); //so I'll leave them.
}
}
Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.
Most of the times there has been a problem with building the cache of the IDE, or something related.
Most probably, File -> Invalidate Caches / Restart
, will resolve this problem, just let the IDE finalize it's caching.
I believe this will work:
TextArea.Text = "Line 1" & vbCrLf & "Line 2"
System.Environment.NewLine could be used in place of vbCrLf if you wanted to be a little less VB6 about it.
I disagree with this kind of path
GET /companies/{companyId}/departments
If you want to get departments, I think it's better to use a /departments resource
GET /departments?companyId=123
I suppose you have a companies
table and a departments
table then classes to map them in the programming language you use. I also assume that departments could be attached to other entities than companies, so a /departments resource is straightforward, it's convenient to have resources mapped to tables and also you don't need as many endpoints since you can reuse
GET /departments?companyId=123
for any kind of search, for instance
GET /departments?name=xxx
GET /departments?companyId=123&name=xxx
etc.
If you want to create a department, the
POST /departments
resource should be used and the request body should contain the company ID (if the department can be linked to only one company).
It is not possible for javascript to "click" on an element (u can trigger the attached onclick
event, but you can't literally click it)
To view all the items in the list, make the list a multiple
list and increase its size, like such:
<select id="countries" multiple="multiple" size="10">
<option value="1">Country</option>
</select>
Though Excel format conditions will only display 1 of 3 conditions related to number size (they code it as "positive; negative; zero; text" but I prefer to see it as : if isnumber and true; elseif isnumber and false; elseif number; elseif is text )
so to me the best answer is David's as well as Grastveit's comment for other regional format.
Here are the ones I use depending on reports I make.
[<1000000]#,##0.00," KB";[<1000000000]#,##0.00,," MB";#,##0.00,,," GB"
[>999999999999]#,##0.00,,,," TB";[>999999999]#,##0.00,,," GB";#.##0.00,," MB"
[<1000000]# ##0,00 " KB";[<1000000000]# ##0,00 " MB";# ##0,00 " GB"
[>999999999999]# ##0,00 " TB";[>999999999]# ##0,00 " GB";# ##0,00 " MB"
Take your pick!
If RAND_MAX
is 32767, you can double the number of bits easily.
int BigRand()
{
assert(INT_MAX/(RAND_MAX+1) > RAND_MAX);
return rand() * (RAND_MAX+1) + rand();
}
In the official getting started example (https://docs.docker.com/compose/gettingstarted/) with the following docker-compose.yml
:
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
After you start this with docker-compose up
, you can easily shell into either your redis
container or your web
container with:
docker-compose exec redis sh
docker-compose exec web sh
Update: created a js fiddle here to see it live: http://jsfiddle.net/HFMvX/
I went through tons of google searches and didn't find anything satisfying. i like how passpack have done it so essentially reverse-engineered their approach, here we go:
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /\d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /\W/.test(pass),
}
var variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
Good passwords start to score around 60 or so, here's function to translate that in words:
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "strong";
if (score > 60)
return "good";
if (score >= 30)
return "weak";
return "";
}
you might want to tune this a bit but i found it working for me nicely
You should map from classes to a row in your confusion matrix.
Here the mapping is trivial:
def row_of_class(classe):
return {1: 0, 2: 1}[classe]
In your loop, compute expected_row
, correct_row
, and increment conf_arr[expected_row][correct_row]
. You'll even have less code than what you started with.
after generating XML you can just Replace your XML <Marks>... content here </Marks>
tags with <SubjectMarks>... content here </SubjectMarks>tag
. and pass updated XML to your DB.
Edit: I here explain complete process here.
Your XML Generate Like as below.
<NewDataSet>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>80</Marks>
</StudentMarks>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>79</Marks>
</StudentMarks>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>88</Marks>
</StudentMarks>
</NewDataSet>
Here you can assign XML to string variable like as
string strXML = DataSet.GetXML();
strXML = strXML.Replace ("<Marks>","<SubjectMarks>");
strXML = strXML.Replace ("<Marks/>","<SubjectMarks/>");
and now pass strXML To your DB. Hope it will help for you.
Now we can add a picture to Excel directly and easely. Just follow these instructions:
If you have multiple images, you can select and insert all the images at once (as shown in step 4).
You can also resize images by selecting it and dragging the edges. In the case of logos or product images, you may want to keep the aspect ratio of the image intact. To keep the aspect ratio intact, use the corners of an image to resize it.
When you place an image within a cell using the steps above, it will not stick with the cell in case you resize, filter, or hide the cells. If you want the image to stick to the cell, you need to lock the image to the cell it’s placed n.
To do this, you need to follow the additional steps as shown below.
Now you can move cells, filter it, or hide it, and the picture will also move/filter/hide.
NOTE:
This answer was taken from this link: Insert Picture into a Cell in Excel.
It's fine, the continue
statement relates to the enclosing loop, and your code should be equivalent to (avoiding such jump statements):
while (something = get_something()) {
if (something == A || something == B)
do_something();
}
But if you expect break
to exit the loop, as your comment suggest (it always tries again with another something, until it evaluates to false), you'll need a different structure.
For example:
do {
something = get_something();
} while (!(something == A || something == B));
do_something();
all answers are 100% correct and well explained, but i did something good and very simple to make it responsive.
here the element will take 100% height of view port but when it comes to mobile view it don't look good specially on portrait view ( mobile ), so when view port is getting smaller the element will collapse and overlap on each other. so to make it little responsive here is code. hope someone will get help from this.
<style>
.img_wrap{
width:100%;
background: #777;
}
.img_wrap img{
display: block;
width: 100px;
height: 100px;
padding: 50px 0px;
margin: 0 auto;
}
.img_wrap img:nth-child(2){
padding-top: 0;
}
</style>
<div class="img_wrap">
<img src="https://i.pinimg.com/originals/71/84/fc/7184fc63db0516a00e7d86900d957925.jpg" alt="">
<img src="https://i.pinimg.com/originals/71/84/fc/7184fc63db0516a00e7d86900d957925.jpg" alt="">
</div>
<script>
var windowHeight = $(window).height();
var elementHeight = $('.img_wrap').height();
if( elementHeight > windowHeight ){
$('.img_wrap').css({height:elementHeight});
}else{
$('.img_wrap').css({height:windowHeight});
}
</script>
here is JSfiddle Demo.
For further readers/searchers:
As Rene Pot points out on this topic,
By adding the attribute
readonly
(orreadonly="readonly"
) to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it.
With this method, you can avoid popping up the "soft" Keyboard and still launch click events / fill the input by any on-screen keyboard.
This solution also works fine with date-time-pickers which generally already implement controls.
Here's what I had to do. (And I probably forgot an important aspect of my problem, which is that this wasn't set up as a Python project originally, but a Java project, with some python files in them.)
Project Settings -> Modules -> Plus button (add a module) -> Python
Then, click the "..." button next to Python Interpreter.
In the "Configure SDK" dialog that pops up, click the "+" button. Select "Python SDK", then select the default "Python" shortcut that appears in my finder dialog
Wait about 5 minutes. Read some productivity tips. :)
Click Ok
Wait for the system to rebuild some indexes.
Hooray! Code hinting is back for my modules!
Use the method that accepts a Comparator
when you want to sort in something other than natural order.
If some beginner, like me, has followed multiple Python tutorials now possible has multiple Python versions and/or multiple versions of pip/virtualenv/pipenv...
In that case, answers listed, while many correct, might not help.
The first thing I would try in your place is uninstall and reinstall Python and go from there.
You can set the style using jQuery's css
method:
$('something:visible').css('display', 'none');
an array does not contain index when elements are associative. An array in php can contain mixed values like this:
$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");
print_r($var);
Gives you:
Array
(
[0] => apple
[1] => banana
[foo] => grape
[2] => carrot
[bar] => donkey
)
What are you trying to achieve since you need the index value in an associative array?
Profiler is hands-down your best option.
You might need to copy a set of statements from profiler due to the prepare + execute steps involved.
Complete sample:
public class CharacterCounter
{
public static int countOccurrences(String find, String string)
{
int count = 0;
int indexOf = 0;
while (indexOf > -1)
{
indexOf = string.indexOf(find, indexOf + 1);
if (indexOf > -1)
count++;
}
return count;
}
}
Call:
int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
System.out.println(occurrences); // 3
import json
myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}]}
myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}
I think, the reason of the error from JDBC driver, you should get suitable JDBC driver for your Oracle db. You can get it from
http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html
When you need the probabilities as well... The following gets the AUC value and plots it all in one shot.
from sklearn.metrics import plot_roc_curve
plot_roc_curve(m,xs,y)
When you have the probabilities... you can't get the auc value and plots in one shot. Do the following:
from sklearn.metrics import roc_curve
fpr,tpr,_ = roc_curve(y,y_probas)
plt.plot(fpr,tpr, label='AUC = ' + str(round(roc_auc_score(y,m.oob_decision_function_[:,1]), 2)))
plt.legend(loc='lower right')
Hashtable
and ConcurrentHashMap
do not allow null
keys or null
values.
Collections.synchronizedMap(Map)
synchronizes all operations (get
, put
, size
, etc).
ConcurrentHashMap
supports full concurrency of retrievals, and adjustable expected concurrency for updates.
As usual, there are concurrency--overhead--speed tradeoffs involved. You really need to consider the detailed concurrency requirements of your application to make a decision, and then test your code to see if it's good enough.
in /etc/my.cnf
:
[mysqld]
...
performance_schema = 0
table_cache = 0
table_definition_cache = 0
max-connect-errors = 10000
query_cache_size = 0
query_cache_limit = 0
...
Good work on server with 256MB Memory.
Set min-width: inherit /* Reset the min-width */
Try this. It will work.
What I do in these cases is:
In the server, move the cursor back to the last known good commit:
git push -f origin <last_known_good_commit>:<branch_name>
Locally, do the same:
git reset --hard <last_known_good_commit>
# ^^^^^^
# optional
See a full example on a branch my_new_branch
that I created for this purpose:
$ git branch
my_new_branch
This is the recent history after adding some stuff to myfile.py
:
$ git log
commit 80143bcaaca77963a47c211a9cbe664d5448d546
Author: me
Date: Wed Mar 23 12:48:03 2016 +0100
Adding new stuff in myfile.py
commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date: Tue Mar 18 12:46:59 2016 +0100
Initial commit
I want to get rid of the last commit, which was already pushed, so I run:
$ git push -f origin b4zad078237fa48746a4feb6517fa409f6bf238e:my_new_branch
Total 0 (delta 0), reused 0 (delta 0)
To [email protected]:me/myrepo.git
+ 80143bc...b4zad07 b4zad078237fa48746a4feb6517fa409f6bf238e -> my_new_branch (forced update)
Nice! Now I see the file that was changed on that commit (myfile.py
) shows in "not staged for commit":
$ git status
On branch my_new_branch
Your branch is up-to-date with 'origin/my_new_branch'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: myfile.py
no changes added to commit (use "git add" and/or "git commit -a")
Since I don't want these changes, I just move the cursor back locally as well:
$ git reset --hard b4zad078237fa48746a4feb6517fa409f6bf238e
HEAD is now at b4zad07 Initial commit
So now HEAD is in the previous commit, both in local and remote:
$ git log
commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date: Tue Mar 18 12:46:59 2016 +0100
Initial commit
You can simply use:
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(string.Join(",", items));
Happy coding!
They pretty much got it there... just like a checkbox, all you have to do is add the attribute checked="checked" like so:
<input type="radio" checked="checked">
...and you got it.
Cheers!
This answer is pretty similar to Oz.'s, using <chrono>
for C++ -- I didn't grab it from Oz. though...
I picked up the original snippet at the bottom of this page, and slightly modified it to be a complete console app. I love using this lil' ol' thing. It's fantastic if you do a lot of scripting and need a reliable tool in Windows to get the epoch in actual milliseconds without resorting to using VB, or some less modern, less reader-friendly code.
#include <chrono>
#include <iostream>
int main() {
unsigned __int64 now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
std::cout << now << std::endl;
return 0;
}
each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.
For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.
http:..../somelink?componentId=123
would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123
The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.
Using regular expressions to check for nested patterns is very easy.
'/(\((?>[^()]+|(?1))*\))/'
##Unique Approach
##App.getRes().getString(R.string.some_id)
This will work everywhere in app. (Util class, Dialog, Fragment or any class in your app)
(1) Create or Edit (if already exist) your Application
class.
import android.app.Application;
import android.content.res.Resources;
public class App extends Application {
private static App mInstance;
private static Resources res;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
res = getResources();
}
public static App getInstance() {
return mInstance;
}
public static Resources getRes() {
return res;
}
}
(2) Add name field to your manifest.xml
<application
tag.
<application
android:name=".App"
...
>
...
</application>
Now you are good to go. Use App.getRes().getString(R.string.some_id)
anywhere in app.
You could default the parameter to null
or false
.
This way, it would be shorter to test if a value has been passed as parameter.
@mixin clearfix($width: null) {
@if not ($width) {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
This was a developer mistake - a misplaced ending brace, which made the above function a nested function.
I see a lot of questions related to the undefined function error in SO. Let me note down this as an answer, in case someone else have the same issue with function scope.
Things I tried to troubleshoot first:
It was difficult to trace the braces, since the functions were very long - problem with legacy systems. Further steps to troubleshoot were this:
Identified this as some scope issue.
Used the Netbeans collapse (code fold) feature to check the function just above this one. So, the 1000 lines function above just collapsed along with this one, making this a nested function.
Once the problem identified, cut-pasted the function to the end of file, which solved the issue.
Try using TempData
:
public ActionResult Create(FormCollection collection) {
...
TempData["notice"] = "Successfully registered";
return RedirectToAction("Index");
...
}
Then, in your Index view, or master page, etc., you can do this:
<% if (TempData["notice"] != null) { %>
<p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>
Or, in a Razor view:
@if (TempData["notice"] != null) {
<p>@TempData["notice"]</p>
}
Quote from MSDN (page no longer exists as of 2014, archived copy here):
An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.
If your drive letter is C, you should be able to use
scp -r \desktop\myfolder\deployments\ user@host:/path/to/whereyouwant/thefile
without drive letter and backslashes instead of forward slashes.
You are using putty, so you can use pscp. It is better adapted to Windows.
You can use Ramda JS flatten
var arr = [[1,2], [3], [4,5]];_x000D_
var flattenedArray = R.flatten(arr); _x000D_
_x000D_
console.log(flattenedArray)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
_x000D_
For Swift 4.2+ and iOS 9+
let appURL = URL(string: "mailto:[email protected]")!
if #available(iOS 10.0, *) {
UIApplication.shared.open(appURL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(appURL)
}
Replace [email protected] with your desired email address.
You should stop the task that you have scheduled on the timer: Your timer:
Timer t = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
//do something
};
}
t.schedule(tt,1000,1000);
In order to stop:
tt.cancel();
t.cancel(); //In order to gracefully terminate the timer thread
Notice that just cancelling the timer will not terminate ongoing timertasks.
public static void main(String[] args) {
int[] arr = {0,12,74,56,2,63,45};
int f1 = 1, f2 = 0, temp = 0;
int num = 0;
for (int i = 0; i < arr.length; i++){
num = arr[i];
if (f1 < num) {
temp = f1;
f1 = num;
num = temp;
}
if (f2 < num) {
temp = f2;
f2 = num;
num = temp;
}
}
System.out.println("First Highest " + f1 + " Second Highest " + f2 + " Third " + num);
}
It is technically possible to put a caption on an ImageButton
if you really want to do it. Just put a TextView
over the ImageButton
using FrameLayout
. Just remember to not make the Textview
clickable.
Example:
<FrameLayout>
<ImageButton
android:id="@+id/button_x"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@null"
android:scaleType="fitXY"
android:src="@drawable/button_graphic" >
</ImageButton>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:text="TEST TEST" >
</TextView>
</FrameLayout>
I have used this before:
$('input[type=checkbox]').prop('checked', false);
seems that .attr and .removeAttr doesn't work for some situations.
edit: Note that in jQuery v1.6 and higher, you should be using .prop('checked', false)
instead for greater cross-browser compatibility - see https://api.jquery.com/prop
Comment here: How to reset all checkboxes using jQuery or pure JS?
On Firefox for Ubuntu, just using
input[type='number'] {
-moz-appearance:textfield;
}
did the trick for me.
Adding
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
Would lead me to
Unknown pseudo-class or pseudo-element ‘-webkit-outer-spin-button’. Ruleset ignored due to bad selector.
everytime I tried. Same for the inner spin button.
You can access the array index directly:
var csv = 'zero,one,two,three';
csv.split(',')[0]; //result: zero
csv.split(',')[3]; //result: three
In order to change the attribute of the class conditionally,
var css_val = $(".handle").css('left');
if(css_val == '336px')
{
$(".handle").css('left','300px');
}
If id is given as following,
<a id="handle" class="handle" href="#" style="left: 336px;"></a>
Here is an alternative solution:
var css_val = $("#handle").css('left');
if(css_val == '336px')
{
$("#handle").css('left','300px');
}
I recommend to uninstall typescript first with the command:
npm uninstall -g typescript
then use the chocolatey package in order to run:
choco install typescript
in PowerShell.
One way with sed
:
echo "$(echo "$foo" | sed 's/.*/\u&/')"
Prints:
Bar
How about something like this?
<html>
<head>
<script type="text/javascript">
var HoverListener = {
addElem: function( elem, callback, delay )
{
if ( delay === undefined )
{
delay = 1000;
}
var hoverTimer;
addEvent( elem, 'mouseover', function()
{
hoverTimer = setTimeout( callback, delay );
} );
addEvent( elem, 'mouseout', function()
{
clearTimeout( hoverTimer );
} );
}
}
function tester()
{
alert( 'hi' );
}
// Generic event abstractor
function addEvent( obj, evt, fn )
{
if ( 'undefined' != typeof obj.addEventListener )
{
obj.addEventListener( evt, fn, false );
}
else if ( 'undefined' != typeof obj.attachEvent )
{
obj.attachEvent( "on" + evt, fn );
}
}
addEvent( window, 'load', function()
{
HoverListener.addElem(
document.getElementById( 'test' )
, tester
);
HoverListener.addElem(
document.getElementById( 'test2' )
, function()
{
alert( 'Hello World!' );
}
, 2300
);
} );
</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>
Everything you need is in the npm-folders
documentation. I don't want to start my Win notebook now so I cannot verify it, but you should only change prefix
to C:\Program Files\nodejs
in your config file. If you want to change it globally for all users, edit the C:\Program Files\nodejs\npmrc
file, otherwise create/edit C:\Users\{username}\.npmrc
.
But this change will probably have some side effects, so read this discussion first. I don't think it's a good idea.
You can convert a number to a string with n decimal places using the SPRINTF command:
>> x = 1.23; >> sprintf('%0.6f', x) ans = 1.230000 >> x = 1.23456789; >> sprintf('%0.6f', x) ans = 1.234568
Just bind to the hidden
property
[hidden]="!myVar"
See also
issues
hidden
has some issues though because it can conflict with CSS for the display
property.
See how some
in Plunker example doesn't get hidden because it has a style
:host {display: block;}
set. (This might behave differently in other browsers - I tested with Chrome 50)
workaround
You can fix it by adding
[hidden] { display: none !important;}
To a global style in index.html
.
another pitfall
hidden="false"
hidden="{{false}}"
hidden="{{isHidden}}" // isHidden = false;
are the same as
hidden="true"
and will not show the element.
hidden="false"
will assign the string "false"
which is considered truthy.
Only the value false
or removing the attribute will actually make the element
visible.
Using {{}}
also converts the expression to a string and won't work as expected.
Only binding with []
will work as expected because this false
is assigned as false
instead of "false"
.
*ngIf
vs [hidden]
*ngIf
effectively removes its content from the DOM while [hidden]
modifies the display
property and only instructs the browser to not show the content but the DOM still contains it.
Depends on your requirment, but the most effective way to create is:
Product obj = new Product
{
ID = 21,
Price = 200,
Category = "XY",
Name = "SKR",
};
I recommend you should clarify port that postgres. In my case I didn't know which port postgres was running on.
lsof -i | grep 'post'
then you can know which port is listening.
psql -U postgres -p "port_in_use"
with port option, might be answer. you can use psql.
What I did to make the Date (e.g December 01, 2016) as header. I used the StickyHeaderListView library
https://github.com/emilsjolander/StickyListHeaders
Convert the date to long in millis [do not include the time] and make it as the header Id.
@Override
public long getHeaderId(int position) {
return <date in millis>;
}
script1.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170
This error happens due to a security measure which won't let scripts be executed on your system without you having approved of it. You can do so by opening up a powershell with administrative rights (search for powershell in the main menu and select Run as administrator from the context menu) and entering:
set-executionpolicy remotesigned
I had a similar problem. I was attempting to have a file written every time a user visits a website.
The problem ended up being twofold.
1: the permissions were not set correctly
2: I attempted to use
f = open(r"newfile.txt","w+")
(Wrong)
After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+")
(Right)
You can use GetExitCodeProcess
. It will return STILL_ACTIVE
(259) if the process is still running (or if it happened to exit with that exit code :( ).
numberOfLines
parameter on a Text
component:<Text numberOfLines={1}>long long long long text<Text>
Will produce:
long long long…
(Assuming you have short width container.)
ellipsizeMode
parameter to move the ellipsis to the head
or middle
. tail
is the default value.<Text numberOfLines={1} ellipsizeMode='head'>long long long long text<Text>
Will produce:
…long long text
NOTE: The Text
component should also include style={{ flex: 1 }}
when the ellipsis needs to be applied relative to the size of its container. Useful for row layouts, etc.
As You're getting values from textfield as jTextField3.getText();
.
As it is a textField
it will return you string format as its format says:
String getText()
Returns the text contained in this TextComponent.
So, convert your String
to Integer
as:
int jml = Integer.parseInt(jTextField3.getText());
instead of directly setting
int jml = jTextField3.getText();
Use [ngClass]
and conditionally apply class based on the id
.
In your HTML file:
<li>
<img [ngClass]="{'this-is-a-class': id === 1 }" id="1"
src="../../assets/images/1.jpg" (click)="addClass(id=1)"/>
</li>
<li>
<img [ngClass]="{'this-is-a-class': id === 2 }" id="2"
src="../../assets/images/2.png" (click)="addClass(id=2)"/>
</li>
In your TypeScript file:
addClass(id: any) {
this.id = id;
}
The alert() function can't output an object in a read-friendly manner. Try using console.log(object) instead, and fire up your browser's console to debug.
The following answer is based on answers by M. Turnhout and Jerry Birchler to this question but with the following improvements:
sys.fn_varbintohexsubstring
, fn_varbintohexstr
) with CONVERT()
for binary stylesCAST('' as xml).value('xs:hexBinary())
) with CONVERT()
for binary stylesfn_ConvertIpAddressToBinary
(as pointed out by C.Plock)The code has been tested in SQL Server 2014 and SQL Server 2016 (see test cases at the end)
Converts 4 bytes values to IPV4 and 16 byte values to IPV6 string representations. Note that this function does not shorten addresses.
ALTER FUNCTION dbo.IPAddressVarbinaryToString
(
@varbinaryValue VARBINARY( 16 )
)
RETURNS VARCHAR(39)
AS
BEGIN
IF @varbinaryValue IS NULL
RETURN NULL;
ELSE IF DATALENGTH( @varbinaryValue ) = 4
RETURN
CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 1, 1 ))) + '.' +
CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 2, 1 ))) + '.' +
CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 3, 1 ))) + '.' +
CONVERT( VARCHAR(3), CONVERT(TINYINT, SUBSTRING( @varbinaryValue, 4, 1 )));
ELSE IF DATALENGTH( @varbinaryValue ) = 16
RETURN
CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 1, 2 ), 2 ) + ':' +
CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 3, 2 ), 2 ) + ':' +
CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 5, 2 ), 2 ) + ':' +
CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 7, 2 ), 2 ) + ':' +
CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 9, 2 ), 2 ) + ':' +
CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 11, 2 ), 2 ) + ':' +
CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 13, 2 ), 2 ) + ':' +
CONVERT( VARCHAR(4), SUBSTRING( @varbinaryValue, 15, 2 ), 2 );
RETURN 'Invalid';
END
SELECT dbo.IPAddressVarbinaryToString(0x00000000000000000000000000000000) -- 0000:0000:0000:0000:0000:0000:0000:0000 (no address shortening)
SELECT dbo.IPAddressVarbinaryToString(0x00010002000300400500060070000089) -- 0001:0002:0003:0040:0500:0600:7000:0089
SELECT dbo.IPAddressVarbinaryToString(0xC0A80148) -- 255.168.1.72
SELECT dbo.IPAddressVarbinaryToString(0x7F000001) -- 127.0.0.1 (no address shortening)
SELECT dbo.IPAddressVarbinaryToString(NULL) -- NULL
Converts IPV4 and IPV6 string representations to 4 byte and 16 bytes binary values respectively. Note that this function is able to parse most (all of the commonly used) of shorthand address representations (e.g. 127...1 and 2001:db8::1319:370:7348). To force this function to always return 16 byte binary values uncomment leading 0s concatenation at the end of the function.
ALTER FUNCTION [dbo].[IPAddressStringToVarbinary]
(
@IPAddress VARCHAR( 39 )
)
RETURNS VARBINARY(16) AS
BEGIN
IF @ipAddress IS NULL
RETURN NULL;
DECLARE @bytes VARBINARY(16), @token VARCHAR(4),
@vbytes VARBINARY(16) = 0x, @vbzone VARBINARY(2),
@tIPAddress VARCHAR( 40 ),
@colIndex TINYINT,
@delim CHAR(1) = '.',
@prevColIndex TINYINT = 0,
@parts TINYINT = 0, @limit TINYINT = 4;
-- Get position if IPV4 delimiter
SET @colIndex = CHARINDEX( @delim, @ipAddress );
-- If not IPV4, then assume IPV6
IF @colIndex = 0
BEGIN
SELECT @delim = ':', @limit = 8, @colIndex = CHARINDEX( @delim, @ipAddress );
-- Get number of parts (delimiters)
WHILE @colIndex > 0
SELECT @parts += 1, @colIndex = CHARINDEX( @delim, @ipAddress, @colIndex + 1 );
SET @colIndex = CHARINDEX( @delim, @ipAddress );
IF @colIndex = 0
RETURN NULL;
END
-- Add trailing delimiter (need new variable of larger size)
SET @tIPAddress = @IPAddress + @delim;
WHILE @colIndex > 0
BEGIN
SET @token = SUBSTRING( @tIPAddress, @prevColIndex + 1, @Colindex - @prevColIndex - 1 );
IF @delim = ':'
BEGIN
SELECT @vbzone = CONVERT( VARBINARY(2), RIGHT( '0000' + @token, 4 ), 2 ), @vbytes += @vbzone;
-- Handles consecutive sections of zeros representation rule (i.e. ::)(https://en.wikipedia.org/wiki/IPv6#Address_representation)
IF @token = ''
WHILE @parts + 1 < @limit
SELECT @vbytes += @vbzone, @parts += 1;
END
ELSE
BEGIN
SELECT @vbzone = CONVERT( VARBINARY(1), CONVERT( TINYINT, @token )), @vbytes += @vbzone
END
SELECT @prevColIndex = @colIndex, @colIndex = CHARINDEX( @delim, @tIPAddress, @colIndex + 1 )
END
SET @bytes =
CASE @delim
WHEN ':' THEN @vbytes
ELSE /*0x000000000000000000000000 +*/ @vbytes -- Return IPV4 addresses as 4 byte binary (uncomment leading 0s section to force 16 byte binary)
END
RETURN @bytes
END
Valid cases
SELECT dbo.IPAddressStringToVarbinary( '0000:0000:0000:0000:0000:0000:0000:0001' ) -- 0x0000000000000000000000000001 (check bug fix)
SELECT dbo.IPAddressStringToVarbinary( '0001:0002:0003:0040:0500:0600:7000:0089' ) -- 0x00010002000300400500060070000089
SELECT dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319::370:7348' ) -- 0x20010DB885A308D31319000003707348 (check short hand)
SELECT dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319:0000:370:7348' ) -- 0x20010DB885A308D31319000003707348
SELECT dbo.IPAddressStringToVarbinary( '192.168.1.72' ) -- 0xC0A80148
SELECT dbo.IPAddressStringToVarbinary( '127...1' ) -- 0x7F000001 (check short hand)
SELECT dbo.IPAddressStringToVarbinary( NULL ) -- NULL
SELECT dbo.IPAddressStringToVarbinary( '' ) -- NULL
-- Check that conversions return original address
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '0001:0002:0003:0040:0500:0600:7000:0089' )) -- '0001:0002:0003:0040:0500:0600:7000:0089'
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '127...1' )) -- 127.0.0.1
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '192.168.1.72' )) -- 192.168.1.72
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1319::370:7348' )) -- 2001:0db8:85a3:08d3:1319:0000:0370:7348
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3:1314:0000:370:7348' )) -- 2001:0db8:85a3:08d3:1319:0000:0370:7348
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8:85a3:8d3::370:7348' )) -- 2001:0DB8:85A3:08D3:0000:0000:0370:7348
-- This is technically an invalid IPV6 (according to Wikipedia) but it parses correctly
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8::1319::370:7348' )) -- 2001:0DB8:0000:0000:1319:0000:0370:7348
Invalid cases
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '2001:db8::1319::7348' )) -- 2001:0DB8:0000:0000:0000:1319:0000:7348 (ambiguous address)
SELECT dbo.IPAddressStringToVarbinary( '127.1' ) -- 127.0.0.1 (not supported short-hand)
SELECT dbo.IPAddressVarbinaryToString( dbo.IPAddressStringToVarbinary( '127.1' )) -- 127.0.0.1 (not supported short-hand)
SELECT dbo.IPAddressStringToVarbinary( '0300.0000.0002.0353' ) -- octal byte values
SELECT dbo.IPAddressStringToVarbinary( '0xC0.0x00.0x02.0xEB' ) -- hex values
SELECT dbo.IPAddressStringToVarbinary( 'C0.00.02.EB' ) -- hex values
I would suggest you to don't modify web.config from your, because every time when change, it will restart your application.
However you can read web.config using System.Configuration.ConfigurationManager.AppSettings
I'd recommend using some work queue using, for example, the excellent Gearman, which will provide you with a great way to dispatch background jobs, and asynchronously get their result once they're processed.
The advantage of this, used heavily at Digg (among many others) is that it provides a strong, scalable and robust way to make workers in any language to speak with clients in any language.
Instead of ((t[1])/length) * t[1] += string
, you should use string += ((t[1])/length) * t[1]
. (The other syntax issue - int is not iterable
- will be your exercise to figure out.)
Here's a more optimized version of Mike's answer above that gets the websites Content-Type properly, supports POST and GET request, and uses your browsers User-Agent so websites can identify your proxy as a browser. You can just simply set the URL by changing url =
and it will automatically set HTTP and HTTPS stuff without manually doing it.
var express = require('express')
var app = express()
var https = require('https');
var http = require('http');
const { response } = require('express');
app.use('/', function(clientRequest, clientResponse) {
var url;
url = 'https://www.google.com'
var parsedHost = url.split('/').splice(2).splice(0, 1).join('/')
var parsedPort;
var parsedSSL;
if (url.startsWith('https://')) {
parsedPort = 443
parsedSSL = https
} else if (url.startsWith('http://')) {
parsedPort = 80
parsedSSL = http
}
var options = {
hostname: parsedHost,
port: parsedPort,
path: clientRequest.url,
method: clientRequest.method,
headers: {
'User-Agent': clientRequest.headers['user-agent']
}
};
var serverRequest = parsedSSL.request(options, function(serverResponse) {
var body = '';
if (String(serverResponse.headers['content-type']).indexOf('text/html') !== -1) {
serverResponse.on('data', function(chunk) {
body += chunk;
});
serverResponse.on('end', function() {
// Make changes to HTML files when they're done being read.
body = body.replace(`example`, `Cat!` );
clientResponse.writeHead(serverResponse.statusCode, serverResponse.headers);
clientResponse.end(body);
});
}
else {
serverResponse.pipe(clientResponse, {
end: true
});
clientResponse.contentType(serverResponse.headers['content-type'])
}
});
serverRequest.end();
});
app.listen(3000)
console.log('Running on 0.0.0.0:3000')
For me this error ocurred after trying to use audioplayers flutter library. To solve i got tools.jar of the folder:
C:\Program Files\Android\Android Studio\jre\lib
and pasted on
C:\Program Files\Java\jre1.8.0_181\lib.
After this the build worked fine.
You could use regular expressions to count for you.
String subject = "First Line\n Second Line\nThird Line";
Matcher wordM = Pattern.compile("\\b\\S+?\\b").matcher(subject); //matches a word
Matcher charM = Pattern.compile(".").matcher(subject); //matches a character
Matcher newLineM = Pattern.compile("\\r?\\n").matcher(subject); //matches a linebreak
int words=0,chars=0,newLines=1; //newLines is initially 1 because the first line has no corresponding linebreak
while(wordM.find()) words++;
while(charM.find()) chars++;
while(newLineM.find()) newLines++;
System.out.println("Words: "+words);
System.out.println("Chars: "+chars);
System.out.println("Lines: "+newLines);
To get the lines that contain the texts 8768
, 9875
or 2353
, use:
^.*(8768|9875|2353).*$
What it means:
^ from the beginning of the line
.* get any character except \n (0 or more times)
(8768|9875|2353) if the line contains the string '8768' OR '9875' OR '2353'
.* and get any character except \n (0 or more times)
$ until the end of the line
If you do want the literal *
char, you'd have to escape it:
^.*(\*8768|\*9875|\*2353).*$
1 - disable fork
option in /etc/mongodb.conf
if enabled
2 - Repair your database
mongod --repair --dbpath DBPATH
3 - kill current mongod process
Find mongo processes
ps -ef | grep mongo
you'll get mongod PID
mongodb PID 1 0 06:26 ? 00:00:00 /usr/bin/mongod --config /etc/mongodb.conf
Stop current mongod process
kill -9 PID
4 - start mongoDB service
service mongodb start
Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.
Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).
So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...
I just bumped into this problem, tried all above suggestions but still failed. Without repeat what have been suggested above, here are the things I (you) may be missing: In case you are using maven, likely you'll state the dependencies i.e:
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.10.1.1</version>
Please be careful with the version. It must be compatible with the server instance you are running.
I solved my case by giving up on what maven dependencies provided and manually adding external jar from "%JAVA_HOME%\db\lib", the same source of my running server. In this case I'm testing using my Local.
So if you're testing with remote server instance, look for the derbyclient.jar that come with server package.
Problem was solved by simply:
node_modules
folder npm install
to get all packages with correct versionsIn my case, the problem occurred after changing Git branches, where a new branch was using a different set of node modules. The old branch was using TypeScript v1.8, the new one v2.0
Take care with some of the examples; $0 may include some leading path as well as the name of the program. Eg save this two line script as ./mytry.sh and the execute it.
#!/bin/bash
echo "parameter 0 --> $0" ; exit 0
Output:
parameter 0 --> ./mytry.sh
This is on a current (year 2016) version of Bash, via Slackware 14.2
For better understand how it works!
int n = JOptionPane.showConfirmDialog(null, "Yes No Cancel", "YesNoCancel", JOptionPane.YES_NO_CANCEL_OPTION);
if(n == 0)
{
JOptionPane.showConfirmDialog(null, "You pressed YES\n"+"Pressed value is = "+n);
}
else if(n == 1)
{
JOptionPane.showConfirmDialog(null, "You pressed NO\n"+"Pressed value is = "+n);
}
else if (n == 2)
{
JOptionPane.showConfirmDialog(null, "You pressed CANCEL\n"+"Pressed value is = "+n);
}
else if (n == -1)
{
JOptionPane.showConfirmDialog(null, "You pressed X\n"+"Pressed value is = "+n);
}
OR
int n = JOptionPane.showConfirmDialog(null, "Yes No Cancel", "YesNoCancel", JOptionPane.YES_NO_CANCEL_OPTION);
switch (n) {
case 0:
JOptionPane.showConfirmDialog(null, "You pressed YES\n"+"Pressed value is = "+n);
break;
case 1:
JOptionPane.showConfirmDialog(null, "You pressed NO\n"+"Pressed value is = "+n);
break;
case 2:
JOptionPane.showConfirmDialog(null, "You pressed CANCEL\n"+"Pressed value is = "+n);
break;
case -1:
JOptionPane.showConfirmDialog(null, "You pressed X\n"+"Pressed value is = "+n);
break;
default:
break;
}
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
This is what you have to do
var fileVariable =document.getElementsById('fileId').files[0];
If you want to check for image file types then
if(fileVariable.type.match('image.*'))
{
alert('its an image');
}
I like to use the following. Reading the lines immediately.
contents = []
for line in open(filepath, 'r').readlines():
contents.append(line.strip())
Or using list comprehension:
contents = [line.strip() for line in open(filepath, 'r').readlines()]
function display_c(){
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh)
}
function display_ct() {
var strcount
var currentdate = new Date();
document.getElementById('ct').innerHTML = currentdate.toDateString() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
tt = display_c();
}
id = 'ct' // Replace in Your id
onload = "display_ct();" // Type inside a Body Tag
#include <iostream>
using namespace std;
int main()
{
int n1 ;
cout <<"Please enter five digits number: ";
cin >> n1;
cout << n1 / 10000 % 10 << " ";
cout << n1 / 1000 % 10 << " ";
cout << n1 / 100 % 10 << " ";
cout << n1 / 10 % 10 << " ";
cout << n1 % 10 << " :)";
cout << endl;
return 0;
}
'\r' = carriage return and '\n' = line feed.
In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.
Get simple name instead of path.
String onlyClassName = this.getLocalClassName();
call above method in onCreate
I do believe this is an issue connected to a general problem. When HTML was born no one could foresee its widespread use. Another technology which almost collapsed under the weight of its own success. When HTML pages were written in vi on a green text terminal a TABLE was all that was needed to present data to the visitors of the page, and it mostly was data that made sense in a tabular form.
We all know how things evolved. TABLEs went out of fashion comparatively recently, but there are lots of reasons to prefer DIVs and CSS based layouts (accessibility not the last of them). Of course I can't write a CSS to save my life :-) and I think a graphical design expert should always be at hand.
That said... there are lots of data that should be presented in a table even in a modern web site.
I'm using Visual Studio Code 1.8, and this feature is available. But it's a little tricky to understand at first, and (at the time of writing) the docs don't explain clearly how to use it, so here's how it works, step by step:
Invoke Replace in Files (under the Edit menu, or with shortcut Ctrl+Shift+H)
You'll see a standard Find/Replace input replacing the files pane on the left:
Enter your search string and the replace string, then press enter. It may churn for a second searching all files, then it'll show the proposed changes in all your project files -- but note, these changes haven't been made yet! Here's what it looks like:
Now you need to make the changes (and even after that, you have to save the modified files.)
You can make those changes in various ways:
Click the replace icon next to your replace string (note: you'll get a dialog to confirm this bulk action.)
Click the replace icon next to the filename (note: the icon only shows up when you hover over the filename row)
Click the replace icon next to the individual change: (note: the icon only shows up when you hover over the change row)
All those files are now modified in the editor and not yet saved to disk.
Use File -> Save All (or Ctrl+Alt+S)
Update: I'm not sure when this was added, but if you click the "Replace all" button and see this dialog, clicking "Replace" will change and save all files in one click:
With the non-null assertion operator we can tell the compiler explicitly that an expression has value other than null
or undefined
. This is can be useful when the compiler cannot infer the type with certainty but we more information than the compiler.
TS code
function simpleExample(nullableArg: number | undefined | null) {
const normal: number = nullableArg;
// Compile err:
// Type 'number | null | undefined' is not assignable to type 'number'.
// Type 'undefined' is not assignable to type 'number'.(2322)
const operatorApplied: number = nullableArg!;
// compiles fine because we tell compiler that null | undefined are excluded
}
Compiled JS code
Note that the JS does not know the concept of the Non-null assertion operator since this is a TS feature
"use strict";
function simpleExample(nullableArg) {
const normal = nullableArg;
const operatorApplied = nullableArg;
}
_x000D_
You can use some online websites to beautify JSON, such as: JSON Formatter, and then paste the beautified result to WIKI
You can also try what is suggested here: https://www.stkent.com/2017/08/10/update-your-path-for-the-new-android-emulator-location.html
For short, run the emulator from the sdk/emulator
folder
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
In addition to the Javascript solutions above, you can also use an HTML 5 solution by marking the radio buttons as required in the markup. This will eliminate the need for any Javascript and let the browser do the work for you.
See HTML5: How to use the "required" attribute with a "radio" input field for more information on how to do this well.
You're trying to use key functions with lambda functions.
Python and other languages like C# or F# use lambda functions.
Also, when it comes to key functions and according to the documentation
Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.
...
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
So, key functions have a parameter key and it can indeed receive a lambda function.
In Real Python there's a nice example of its usage. Let's say you have the following list
ids = ['id1', 'id100', 'id2', 'id22', 'id3', 'id30']
and want to sort through its "integers". Then, you'd do something like
sorted_ids = sorted(ids, key=lambda x: int(x[2:])) # Integer sort
and printing it would give
['id1', 'id2', 'id3', 'id22', 'id30', 'id100']
In your particular case, you're only missing to write key=
before lambda. So, you'd want to use the following
a = sorted(a, key=lambda x: x.modified, reverse=True)
CollectionViews are very powerful, and they come at a price. Lots, and lots of options. As omz said:
there are multiple ways you could change the number of columns
I'd suggest implementing the <UICollectionViewDelegateFlowLayout>
Protocol, giving you access to the following methods in which you can have greater control over the layout of your UICollectionView
, without the need for subclassing it:
collectionView:layout:insetForSectionAtIndex:
collectionView:layout:minimumInteritemSpacingForSectionAtIndex:
collectionView:layout:minimumLineSpacingForSectionAtIndex:
collectionView:layout:referenceSizeForFooterInSection:
collectionView:layout:referenceSizeForHeaderInSection:
collectionView:layout:sizeForItemAtIndexPath:
Also, implementing the following method will force your UICollectionView to update it's layout on an orientation change: (say you wanted to re-size the cells for landscape and make them stretch)
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration{
[self.myCollectionView.collectionViewLayout invalidateLayout];
}
Additionally, here are 2 really good tutorials on UICollectionViews
:
http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12
Content inside a <div class='html-content'>....</div>
can be downloaded as pdf with styles using jspdf & html2canvas.
You need to refer both js libraries,
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
Then call below function,
//Create PDf from HTML...
function CreatePDFfromHTML() {
var HTML_Width = $(".html-content").width();
var HTML_Height = $(".html-content").height();
var top_left_margin = 15;
var PDF_Width = HTML_Width + (top_left_margin * 2);
var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
var canvas_image_width = HTML_Width;
var canvas_image_height = HTML_Height;
var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
html2canvas($(".html-content")[0]).then(function (canvas) {
var imgData = canvas.toDataURL("image/jpeg", 1.0);
var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
for (var i = 1; i <= totalPDFPages; i++) {
pdf.addPage(PDF_Width, PDF_Height);
pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
}
pdf.save("Your_PDF_Name.pdf");
$(".html-content").hide();
});
}
Ref: pdf genration from html canvas and jspdf.
May be this will help someone.
$('elemId').length
doesn't work for me.
You need to put #
before element id:
$('#elemId').length
---^
With vanilla JavaScript, you don't need the hash (#
) e.g. document.getElementById('id_here')
, however when using jQuery, you do need to put hash to target elements based on id
just like CSS.
using pywin32:
from win32com.client import Dispatch
session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\nUserName');
msg = session.Outbox.Messages.Add('Hello', 'This is a test')
msg.Recipients.Add('Corey', 'SMTP:[email protected]')
msg.Send()
session.Logoff()
Use:
function remove-HSsoftware{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,
ValuefromPipeline = $true,
HelpMessage="IdentifyingNumber can be retrieved with `"get-wmiobject -class win32_product`"")]
[ValidatePattern('{[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}}')]
[string[]]$ids,
[parameter(Mandatory=$false,
ValuefromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
HelpMessage="Computer name or IP adress to query via WMI")]
[Alias('hostname,CN,computername')]
[string[]]$computers
)
begin {}
process{
if($computers -eq $null){
$computers = Get-ADComputer -Filter * | Select dnshostname |%{$_.dnshostname}
}
foreach($computer in $computers){
foreach($id in $ids){
write-host "Trying to uninstall sofware with ID ", "$id", "from computer ", "$computer"
$app = Get-WmiObject -class Win32_Product -Computername "$computer" -Filter "IdentifyingNumber = '$id'"
$app | Remove-WmiObject
}
}
}
end{}}
remove-hssoftware -ids "{8C299CF3-E529-414E-AKD8-68C23BA4CBE8}","{5A9C53A5-FF48-497D-AB86-1F6418B569B9}","{62092246-CFA2-4452-BEDB-62AC4BCE6C26}"
It's not fully tested, but it ran under PowerShell 4.
I've run the PS1 file as it is seen here. Letting it retrieve all the Systems from the AD and trying to uninstall multiple applications on all systems.
I've used the IdentifyingNumber to search for the Software cause of David Stetlers input.
Not tested:
What it does not:
I wasn't able to use uninstall(). Trying that I got an error telling me that calling a method for an expression that has a value of NULL is not possible. Instead I used Remove-WmiObject, which seems to accomplish the same.
CAUTION: Without a computer name given it removes the software from ALL systems in the Active Directory.
i was looking for the same. and found this solution.
Use negative regex assertion:
location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) {
.... # your stuff
}
Source Negated Regular Expressions in location
Explanation of Regex :
If URL does not match any of the following path
example.com/favicon.ico
example.com/resources
example.com/robots.txt
Then it will go inside that location block and will process it.
Another way to do it is to use np.prod
shown below:
def factorial(n):
if n == 0:
return 1
else:
return np.prod(np.arange(1,n+1))
date_part(text, timestamp)
e.g.
date_part('month', timestamp '2001-02-16 20:38:40'),
date_part('year', timestamp '2001-02-16 20:38:40')
http://www.postgresql.org/docs/8.0/interactive/functions-datetime.html
You can use CSS:
p.capitalize {text-transform:capitalize;}
Based on Kamal Reddy's comment:
document.getElementById("myP").style.textTransform = "capitalize";
For .NET 2.0 you could implement a class which inherits from Dictionary
and implements ICloneable
.
public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue> where TValue : ICloneable
{
public IDictionary<TKey, TValue> Clone()
{
CloneableDictionary<TKey, TValue> clone = new CloneableDictionary<TKey, TValue>();
foreach (KeyValuePair<TKey, TValue> pair in this)
{
clone.Add(pair.Key, (TValue)pair.Value.Clone());
}
return clone;
}
}
You can then clone the dictionary simply by calling the Clone
method. Of course this implementation requires that the value type of the dictionary implements ICloneable
, but otherwise a generic implementation isn't practical at all.
In my case, I was updating the server-sided datatable twice and it gives me this error. Hope it helps someone.
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value)
no add(value)
.
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
There is an alternative way of just killing the daemon process by calling
kill -TERM PID
where PID
is the value stored in the file mysqld.pid
or the mysqld process id which can be obtained by issuing the command ps -a | grep mysqld
.
Try using the verbatim operator "@
" before your message:
message.Body =
@"
FirstLine
SecondLine
"
Consider that also the distance of the text from the left margin affects on the real distance from the email body left margin..
Just for completion, the best solution here is often to require a factory function argument:
T GetObject<T>(Func<T> factory)
{ return factory(); }
and call it something like this:
string s = GetObject(() => "result");
You can use that to require or make use of available parameters, if needed.
more example
I have configus.yml with flows files
"pattern":
- _(\d{14})_
"datetime_string":
- "%m%d%Y%H%M%f"
in python code I use
data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)
In my case I did it like this:
int cursor = 0;
do {
if (integer.equals(remove))
integerList.remove(cursor);
else cursor++;
} while (cursor != integerList.size());
first, check its offset every time you scroll the page
$(document).scroll(function() {
checkOffset();
});
and make its position absolute if it has been downed under 10px before the footer.
function checkOffset() {
if($('#social-float').offset().top + $('#social-float').height()
>= $('#footer').offset().top - 10)
$('#social-float').css('position', 'absolute');
if($(document).scrollTop() + window.innerHeight < $('#footer').offset().top)
$('#social-float').css('position', 'fixed'); // restore when you scroll up
}
notice that #social-float
's parent should be sibling of the footer
<div class="social-float-parent">
<div id="social-float">
something...
</div>
</div>
<div id="footer">
</div>
good luck :)
add list using
<asp:ListItem Value="United States" Text="Canada"></asp:ListItem>
and then try
DropDownList1.SelectedItem.Text
I found your mistake.
<asp:ListItem>United States</asp:ListItem>
change this to
<asp:ListItem>United States1</asp:ListItem>
Then you will got the actual value.
What was the issue is, there are two same values in your dropdown, when page postback, it take first value as selected and give the result accordingly. if you noticed when after postback United State Value is selected
cpuguru, if your applet has been compiled with javac 1.3 (or less), your best option is to use Jad.
Unfortunately, the last JDK supported by JAD 1.5.8 (Apr 14, 2001) is JDK 1.3.
If your applet has been compiled with a more recent compiler, you could try JD-GUI : this decompiler is under development, nevertheless, it generates correct Java sources, most of time, for classes compiled with the JDKs 1.4, 1.5 or 1.6.
DarenW, thank you for your post. JD-GUI is not the best decompiler yet ... but I'm working on :)
You can replace
document.getElementById(this.state.baction).addPrecent(10);
with
this.refs[this.state.baction].addPrecent(10);
<Progressbar completed={25} ref="Progress1" id="Progress1"/>
@Bill Karwin describes three inheritance models in his SQL Antipatterns book, when proposing solutions to the SQL Entity-Attribute-Value antipattern. This is a brief overview:
Using a single table as in your first option is probably the simplest design. As you mentioned, many attributes that are subtype-specific will have to be given a NULL
value on rows where these attributes do not apply. With this model, you would have one policies table, which would look something like this:
+------+---------------------+----------+----------------+------------------+
| id | date_issued | type | vehicle_reg_no | property_address |
+------+---------------------+----------+----------------+------------------+
| 1 | 2010-08-20 12:00:00 | MOTOR | 01-A-04004 | NULL |
| 2 | 2010-08-20 13:00:00 | MOTOR | 02-B-01010 | NULL |
| 3 | 2010-08-20 14:00:00 | PROPERTY | NULL | Oxford Street |
| 4 | 2010-08-20 15:00:00 | MOTOR | 03-C-02020 | NULL |
+------+---------------------+----------+----------------+------------------+
\------ COMMON FIELDS -------/ \----- SUBTYPE SPECIFIC FIELDS -----/
Keeping the design simple is a plus, but the main problems with this approach are the following:
When it comes to adding new subtypes, you would have to alter the table to accommodate the attributes that describe these new objects. This can quickly become problematic when you have many subtypes, or if you plan to add subtypes on a regular basis.
The database will not be able to enforce which attributes apply and which don't, since there is no metadata to define which attributes belong to which subtypes.
You also cannot enforce NOT NULL
on attributes of a subtype that should be mandatory. You would have to handle this in your application, which in general is not ideal.
Another approach to tackle inheritance is to create a new table for each subtype, repeating all the common attributes in each table. For example:
--// Table: policies_motor
+------+---------------------+----------------+
| id | date_issued | vehicle_reg_no |
+------+---------------------+----------------+
| 1 | 2010-08-20 12:00:00 | 01-A-04004 |
| 2 | 2010-08-20 13:00:00 | 02-B-01010 |
| 3 | 2010-08-20 15:00:00 | 03-C-02020 |
+------+---------------------+----------------+
--// Table: policies_property
+------+---------------------+------------------+
| id | date_issued | property_address |
+------+---------------------+------------------+
| 1 | 2010-08-20 14:00:00 | Oxford Street |
+------+---------------------+------------------+
This design will basically solve the problems identified for the single table method:
Mandatory attributes can now be enforced with NOT NULL
.
Adding a new subtype requires adding a new table instead of adding columns to an existing one.
There is also no risk that an inappropriate attribute is set for a particular subtype, such as the vehicle_reg_no
field for a property policy.
There is no need for the type
attribute as in the single table method. The type is now defined by the metadata: the table name.
However this model also comes with a few disadvantages:
The common attributes are mixed with the subtype specific attributes, and there is no easy way to identify them. The database will not know either.
When defining the tables, you would have to repeat the common attributes for each subtype table. That's definitely not DRY.
Searching for all the policies regardless of the subtype becomes difficult, and would require a bunch of UNION
s.
This is how you would have to query all the policies regardless of the type:
SELECT date_issued, other_common_fields, 'MOTOR' AS type
FROM policies_motor
UNION ALL
SELECT date_issued, other_common_fields, 'PROPERTY' AS type
FROM policies_property;
Note how adding new subtypes would require the above query to be modified with an additional UNION ALL
for each subtype. This can easily lead to bugs in your application if this operation is forgotten.
This is the solution that @David mentions in the other answer. You create a single table for your base class, which includes all the common attributes. Then you would create specific tables for each subtype, whose primary key also serves as a foreign key to the base table. Example:
CREATE TABLE policies (
policy_id int,
date_issued datetime,
-- // other common attributes ...
);
CREATE TABLE policy_motor (
policy_id int,
vehicle_reg_no varchar(20),
-- // other attributes specific to motor insurance ...
FOREIGN KEY (policy_id) REFERENCES policies (policy_id)
);
CREATE TABLE policy_property (
policy_id int,
property_address varchar(20),
-- // other attributes specific to property insurance ...
FOREIGN KEY (policy_id) REFERENCES policies (policy_id)
);
This solution solves the problems identified in the other two designs:
Mandatory attributes can be enforced with NOT NULL
.
Adding a new subtype requires adding a new table instead of adding columns to an existing one.
No risk that an inappropriate attribute is set for a particular subtype.
No need for the type
attribute.
Now the common attributes are not mixed with the subtype specific attributes anymore.
We can stay DRY, finally. There is no need to repeat the common attributes for each subtype table when creating the tables.
Managing an auto incrementing id
for the policies becomes easier, because this can be handled by the base table, instead of each subtype table generating them independently.
Searching for all the policies regardless of the subtype now becomes very easy: No UNION
s needed - just a SELECT * FROM policies
.
I consider the class table approach as the most suitable in most situations.
The names of these three models come from Martin Fowler's book Patterns of Enterprise Application Architecture.
FFmpeg does not write to a specific log file, but rather sends its output to standard error. To capture that, you need to either
Example for std error redirection:
ffmpeg -i myinput.avi {a-bunch-of-important-params} out.flv 2> /path/to/out.txt
Once the process is done, you can inspect out.txt
.
It's a bit trickier to do the first option, but it is possible. (I've done it myself. So have others. Have a look around SO and the net for details.)
Based on this answer i write my own loader.
With Loading effect and Appear effect :
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.InputStream;
/**
* Created by Sergey Shustikov ([email protected]) at 2015.
*/
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
public static final int ANIMATION_DURATION = 250;
private final ImageView mDestination, mFakeForError;
private final String mUrl;
private final ProgressBar mProgressBar;
private Animation.AnimationListener mOutAnimationListener = new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
}
@Override
public void onAnimationEnd(Animation animation)
{
mProgressBar.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
};
private Animation.AnimationListener mInAnimationListener = new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
if (isBitmapSet)
mDestination.setVisibility(View.VISIBLE);
else
mFakeForError.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animation animation)
{
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
};
private boolean isBitmapSet;
public DownloadImageTask(Context context, ImageView destination, String url)
{
mDestination = destination;
mUrl = url;
ViewGroup parent = (ViewGroup) destination.getParent();
mFakeForError = new ImageView(context);
destination.setVisibility(View.GONE);
FrameLayout layout = new FrameLayout(context);
mProgressBar = new ProgressBar(context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mProgressBar.setLayoutParams(params);
FrameLayout.LayoutParams copy = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
copy.gravity = Gravity.CENTER;
copy.width = dpToPx(48);
copy.height = dpToPx(48);
mFakeForError.setLayoutParams(copy);
mFakeForError.setVisibility(View.GONE);
mFakeForError.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
layout.addView(mProgressBar);
layout.addView(mFakeForError);
mProgressBar.setIndeterminate(true);
parent.addView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
protected Bitmap doInBackground(String... urls)
{
String urlDisplay = mUrl;
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(urlDisplay).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap result)
{
AlphaAnimation in = new AlphaAnimation(0f, 1f);
AlphaAnimation out = new AlphaAnimation(1f, 0f);
in.setDuration(ANIMATION_DURATION * 2);
out.setDuration(ANIMATION_DURATION);
out.setAnimationListener(mOutAnimationListener);
in.setAnimationListener(mInAnimationListener);
in.setStartOffset(ANIMATION_DURATION);
if (result != null) {
mDestination.setImageBitmap(result);
isBitmapSet = true;
mDestination.startAnimation(in);
} else {
mFakeForError.startAnimation(in);
}
mProgressBar.startAnimation(out);
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = mDestination.getContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
}
Add permission
<uses-permission android:name="android.permission.INTERNET"/>
And execute :
new DownloadImageTask(context, imageViewToLoad, urlToImage).execute();
Tools as pure JavaScript code for handling Selectbox:
Graphical Understanding:
Image - A
Image - B
Image - C
Updated - 25-June-2019 | Fiddler DEMO
JavaScript Code:
/**
* Empty Select Box
* @param eid Element ID
* @param value text
* @param text text
* @author Neeraj.Singh
*/
function emptySelectBoxById(eid, value, text) {
document.getElementById(eid).innerHTML = "<option value='" + value + "'>" + text + "</option>";
}
/**
* Reset Select Box
* @param eid Element ID
*/
function resetSelectBoxById(eid) {
document.getElementById(eid).options[0].selected = 'selected';
}
/**
* Set Select Box Selection By Index
* @param eid Element ID
* @param eindx Element Index
*/
function setSelectBoxByIndex(eid, eindx) {
document.getElementById(eid).getElementsByTagName('option')[eindx].selected = 'selected';
//or
document.getElementById(eid).options[eindx].selected = 'selected';
}
/**
* Set Select Box Selection By Value
* @param eid Element ID
* @param eval Element Index
*/
function setSelectBoxByValue(eid, eval) {
document.getElementById(eid).value = eval;
}
/**
* Set Select Box Selection By Text
* @param eid Element ID
* @param eval Element Index
*/
function setSelectBoxByText(eid, etxt) {
var eid = document.getElementById(eid);
for (var i = 0; i < eid.options.length; ++i) {
if (eid.options[i].text === etxt)
eid.options[i].selected = true;
}
}
/**
* Get Select Box Text By ID
* @param eid Element ID
* @return string
*/
function getSelectBoxText(eid) {
return document.getElementById(eid).options[document.getElementById(eid).selectedIndex].text;
}
/**
* Get Select Box Value By ID
* @param eid Element ID
* @return string
*/
function getSelectBoxValue(id) {
return document.getElementById(id).options[document.getElementById(id).selectedIndex].value;
}
I have a sample app where I prepare the intent and just pass the CITY_NAME in the intent to the maps marker activity which eventually calculates longitude and latitude by Geocoder using CITY_NAME.
Below is the code snippet of starting the maps marker activity and the complete MapsMarkerActivity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.action_refresh) {
Log.d(APP_TAG, "onOptionsItemSelected Refresh selected");
new MainActivityFragment.FetchWeatherTask().execute(CITY, FORECAS_DAYS);
return true;
} else if (id == R.id.action_map) {
Log.d(APP_TAG, "onOptionsItemSelected Map selected");
Intent intent = new Intent(this, MapsMarkerActivity.class);
intent.putExtra("CITY_NAME", CITY);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public class MapsMarkerActivity extends AppCompatActivity
implements OnMapReadyCallback {
private String cityName = "";
private double longitude;
private double latitude;
static final int numberOptions = 10;
String [] optionArray = new String[numberOptions];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_map);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Test whether geocoder is present on platform
if(Geocoder.isPresent()){
cityName = getIntent().getStringExtra("CITY_NAME");
geocodeLocation(cityName);
} else {
String noGoGeo = "FAILURE: No Geocoder on this platform.";
Toast.makeText(this, noGoGeo, Toast.LENGTH_LONG).show();
return;
}
}
/**
* Manipulates the map when it's available.
* The API invokes this callback when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user receives a prompt to install
* Play services inside the SupportMapFragment. The API invokes this method after the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(latitude, longitude);
// If cityName is not available then use
// Default Location.
String markerDisplay = "Default Location";
if (cityName != null
&& cityName.length() > 0) {
markerDisplay = "Marker in " + cityName;
}
googleMap.addMarker(new MarkerOptions().position(sydney)
.title(markerDisplay));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
/**
* Method to geocode location passed as string (e.g., "Pentagon"), which
* places the corresponding latitude and longitude in the variables lat and lon.
*
* @param placeName
*/
private void geocodeLocation(String placeName){
// Following adapted from Conder and Darcey, pp.321 ff.
Geocoder gcoder = new Geocoder(this);
// Note that the Geocoder uses synchronous network access, so in a serious application
// it would be best to put it on a background thread to prevent blocking the main UI if network
// access is slow. Here we are just giving an example of how to use it so, for simplicity, we
// don't put it on a separate thread. See the class RouteMapper in this package for an example
// of making a network access on a background thread. Geocoding is implemented by a backend
// that is not part of the core Android framework, so we use the static method
// Geocoder.isPresent() to test for presence of the required backend on the given platform.
try{
List<Address> results = null;
if(Geocoder.isPresent()){
results = gcoder.getFromLocationName(placeName, numberOptions);
} else {
Log.i(MainActivity.APP_TAG, "No Geocoder found");
return;
}
Iterator<Address> locations = results.iterator();
String raw = "\nRaw String:\n";
String country;
int opCount = 0;
while(locations.hasNext()){
Address location = locations.next();
if(opCount == 0 && location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
country = location.getCountryName();
if(country == null) {
country = "";
} else {
country = ", " + country;
}
raw += location+"\n";
optionArray[opCount] = location.getAddressLine(0)+", "
+location.getAddressLine(1)+country+"\n";
opCount ++;
}
// Log the returned data
Log.d(MainActivity.APP_TAG, raw);
Log.d(MainActivity.APP_TAG, "\nOptions:\n");
for(int i=0; i<opCount; i++){
Log.i(MainActivity.APP_TAG, "("+(i+1)+") "+optionArray[i]);
}
Log.d(MainActivity.APP_TAG, "latitude=" + latitude + ";longitude=" + longitude);
} catch (Exception e){
Log.d(MainActivity.APP_TAG, "I/O Failure; do you have a network connection?",e);
}
}
}
Links expire so i have pasted complete code above but just in case if you would like to see complete code then its available at : https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753
There is another possibility - standalone VALUES()
:
VALUES ('Hello World');
Output:
column1
Hello World
It is useful when you need to specify multiple values in compact way:
VALUES (1, 'a'), (2, 'b'), (3, 'c');
Output:
column1 column2
1 a
2 b
3 c
This syntax is supported by SQLite/PostgreSQL/DB LUW/MariaDB 10.3.
This solution is being used for converting multiple string like ("22 44 112 2 34") to an integer list and you can access to the values in a list.
n = input("") # Like : "22 343 455 54445 22332"
if n[:-1] != " ":
n += " "
char = ""
list = []
for i in n :
if i != " ":
char += i
elif i == " ":
list.append(int(char))
char = ""
print(list) # Be happy :))))
If you need the index in the forEach then this provides a way.
public class IndexedValue {
private final int index;
private final Object value;
public IndexedValue(final int index, final Object value) {
this.index = index;
this.value = value;
}
public int getIndex() {
return index;
}
public Object getValue() {
return value;
}
}
Then use it as follows.
@Test
public void withIndex() {
final List<String> list = Arrays.asList("a", "b");
IntStream.range(0, list.size())
.mapToObj(index -> new IndexedValue(index, list.get(index)))
.forEach(indexValue -> {
System.out.println(String.format("%d, %s",
indexValue.getIndex(),
indexValue.getValue().toString()));
});
}
My JDK is installed at C:\Program Files\Java\jdk1.8.0_144\
.
I had set JAVA_HOME= C:\Program Files\Java\jdk1.8.0_144\
,
and I was getting this error:
The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE
When I changed the JAVA_HOME
to C:\Program Files\Java\jdk1.8.0_144\jre
, the issue got fixed.
I am not sure how.
$("#select1").change(function() {_x000D_
if ($(this).data('options') === undefined) {_x000D_
/*Taking an array of all options-2 and kind of embedding it on the select1*/_x000D_
$(this).data('options', $('#select2 option').clone());_x000D_
}_x000D_
var id = $(this).val();_x000D_
var options = $(this).data('options').filter('[value=' + id + ']');_x000D_
$('#select2').html(options);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<select name="select1" id="select1">_x000D_
<option value="1">Fruit</option>_x000D_
<option value="2">Animal</option>_x000D_
<option value="3">Bird</option>_x000D_
<option value="4">Car</option>_x000D_
</select>_x000D_
_x000D_
_x000D_
<select name="select2" id="select2">_x000D_
<option value="1">Banana</option>_x000D_
<option value="1">Apple</option>_x000D_
<option value="1">Orange</option>_x000D_
<option value="2">Wolf</option>_x000D_
<option value="2">Fox</option>_x000D_
<option value="2">Bear</option>_x000D_
<option value="3">Eagle</option>_x000D_
<option value="3">Hawk</option>_x000D_
<option value="4">BWM<option>_x000D_
</select>
_x000D_
Using jQuery data() to store data
I guess hiding elements doesn't work cross-browser(2012), I have'nt tested it myself.
sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
sudo ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin
sudo service apache2 restart
Run above commands issue will be resolved.
I had a similar issue with Datagrip and none of these solutions worked.
Once I restarted the Datagrip Client it was no longer an issue and I could drop tables again.
You can add a method in Float Class, I learnt this from stackoverflow:
class Float
def precision(p)
# Make sure the precision level is actually an integer and > 0
raise ArgumentError, "#{p} is an invalid precision level. Valid ranges are integers > 0." unless p.class == Fixnum or p < 0
# Special case for 0 precision so it returns a Fixnum and thus doesn't have a trailing .0
return self.round if p == 0
# Standard case
return (self * 10**p).round.to_f / 10**p
end
end
I had the app with multiple subdomains and session cookie was the problem between those. Clearing the cookies resolved my problem.
Also, try setting the SESSION_DOMAIN
in .env file. Use the exact subdomain you are browsing.
None of these options worked for me on Ubuntu 12.10 (yeah, I need to upgrade). However, I found an easy solution. Download the source from here: https://github.com/miracle2k/android-platform_sdk/blob/master/emulator/mksdcard/mksdcard.c. Then simply compile with "gcc mksdcard.c -o mksdcard". Backup mksdcard in the SDK tools subfolder and replace with the newly compiled one. Android Studio will now be happy with your SDK.
Yes, scripts can access properties of other windows in the same domain that they have a handle on (typically gained through window.open/opener and window.frames/parent). It is usually more manageable to call functions defined on the other window rather than fiddle with variables directly.
However, windows can die or move on, and browsers deal with it differently when they do. Check that a window (a) is still open (!window.closed) and (b) has the function you expect available, before you try to call it.
Simple values like strings are fine, but generally it isn't a good idea to pass complex objects such as functions, DOM elements and closures between windows. If a child window stores an object from its opener, then the opener closes, that object can become 'dead' (in some browsers such as IE), or cause a memory leak. Weird errors can ensue.
Just use the "vh" unit instead of "px", which means view-port height.
height: 100vh;
You can use below command if you want to print entire line and file name if the occurrence of particular word in current directory you are searching.
grep -m 1 -r "Not caching" * | head -1
I always use this in jQuery for disabling links
$("form a").attr("disabled", "disabled");
In my first encounter with this error my user had rights to "write" to the file but not the containing directory. Check the permissions of the directory containing the file.
In my case, I was going nuts since there wasn't any issues with the string to be decoded, since I could successfully decode it on online tools.
Until I found out that you first have to decodeURIComponent
what you are decoding, like so:
atob(decodeURIComponent(dataToBeDecoded));
Two issues I can see here:
The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.
The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_EXTERNAL_STORAGE: {
if (grantResults.length > 0) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Denied
} else {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// To what you want
} else {
// Bob never checked click
}
}
}
}
}
}
you can declare a Numpy array dynamically for 1 dimension as shown below:
import numpy as np
n = 2
new_table = np.empty(shape=[n,1])
new_table[0,0] = 2
new_table[1,0] = 3
print(new_table)
The above example assumes we know we need to have 1 column but we want to allocate the number of rows dynamically (in this case the number or rows required is equal to 2)
output is shown below:
[[2.] [3.]]
It'll have the same behavior as the underlying recv libc call see the man page for an official description of behavior (or read a more general description of the sockets api).
input.name()
needs to be inside a function; classes contain declarations, not random code.
You could try a formatter like this
They will always be limited because they don't (and can't) know what user defined functions you may have defined in your database (or which built-in functions you have or don't have access to).
You could also look at ANTLR (but that would be an offline solution)
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
You should define source code encoding, add this to the top of your script:
# -*- coding: utf-8 -*-
The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:
import sys
print sys.getdefaultencoding()
Also see:
i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.
label1.Text = DateTime.Now.Month.ToString();
and
label2.Text = DateTime.Now.Year.ToString();
Might be, more safe alternative to "_ORACLE_SCRIPT"=true
is to change "_common_user_prefix"
from C##
to an empty string. When it's null - any name can be used for common user. Found there.
During changing that value you may face another issue - ORA-02095 - parameter cannot be modified, that can be fixed in a several ways, based on your configuration (source).
So for me worked that:
alter system set _common_user_prefix = ''; scope=spfile;
Looks like a server issue (i.e. a "GitHub" issue).
If you look at this thread, it can happen when the git-http-backend
gets a corrupted heap.(and since they just put in place a smart http support...)
But whatever the actual cause is, it may also be related with recent sporadic disruption in one of the GitHub fileserver.
Do you still see this error message? Because if you do:
Note: the Smart HTTP Support is a big deal for those of us behind an authenticated-based enterprise firewall proxy!
From now on, if you clone a repository over the
http://
url and you are using a Git client version 1.6.6 or greater, Git will automatically use the newer, better transport mechanism.
Even more amazing, however, is that you can now push over that protocol and clone private repositories as well. If you access a private repository, or you are a collaborator and want push access, you can put your username in the URL and Git will prompt you for the password when you try to access it.Older clients will also fall back to the older, less efficient way, so nothing should break - just newer clients should work better.
So again, make sure to upgrade your Git client first.
For those who are getting the error as:
I/O error on POST request for "anothermachine:31112/url/path";: class path
resource [fileName.csv] cannot be resolved to URL because it does not exist.
It can be resolved by using the
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(file));
If the file is not present in the classpath, and an absolute path is required.
You could also write up your own user functions to handle dates in the format you choose. SQLite has a fairly simple method for writing your own user functions. For example, I wrote a few to add time durations together.
The following is about disabling the close and Maximize/Minimize buttons, it does not actually remove the buttons (but it does remove the menu items!). The buttons on the title bar are drawn in a disabled/grayed state. (I'm not quite ready to take over all the functionality myself ^^)
This is slightly different than Virgoss solution in that it removes the menu items (and the trailing separator, if needed) instead of just disabling them. It differs from Joe Whites solution as it does not disable the entire system menu and so, in my case, I can keep around the Minimize button and icon.
The follow code also supports disabling the Maximize/Minimize buttons as, unlike the Close button, removing the entries from the menu does not cause the system to render the buttons "disabled" even though removing the menu entries does disable the functionality of the buttons.
It works for me. YMMV.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Window = System.Windows.Window;
using WindowInteropHelper = System.Windows.Interop.WindowInteropHelper;
using Win32Exception = System.ComponentModel.Win32Exception;
namespace Channelmatter.Guppy
{
public class WindowUtil
{
const int MF_BYCOMMAND = 0x0000;
const int MF_BYPOSITION = 0x0400;
const uint MFT_SEPARATOR = 0x0800;
const uint MIIM_FTYPE = 0x0100;
[DllImport("user32", SetLastError=true)]
private static extern uint RemoveMenu(IntPtr hMenu, uint nPosition, uint wFlags);
[DllImport("user32", SetLastError=true)]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32", SetLastError=true)]
private static extern int GetMenuItemCount(IntPtr hWnd);
[StructLayout(LayoutKind.Sequential)]
public struct MenuItemInfo {
public uint cbSize;
public uint fMask;
public uint fType;
public uint fState;
public uint wID;
public IntPtr hSubMenu;
public IntPtr hbmpChecked;
public IntPtr hbmpUnchecked;
public IntPtr dwItemData; // ULONG_PTR
public IntPtr dwTypeData;
public uint cch;
public IntPtr hbmpItem;
};
[DllImport("user32", SetLastError=true)]
private static extern int GetMenuItemInfo(
IntPtr hMenu, uint uItem,
bool fByPosition, ref MenuItemInfo itemInfo);
public enum MenuCommand : uint
{
SC_CLOSE = 0xF060,
SC_MAXIMIZE = 0xF030,
}
public static void WithSystemMenu (Window win, Action<IntPtr> action) {
var interop = new WindowInteropHelper(win);
IntPtr hMenu = GetSystemMenu(interop.Handle, false);
if (hMenu == IntPtr.Zero) {
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Failed to get system menu");
} else {
action(hMenu);
}
}
// Removes the menu item for the specific command.
// This will disable and gray the Close button and disable the
// functionality behind the Maximize/Minimuze buttons, but it won't
// gray out the Maximize/Minimize buttons. It will also not stop
// the default Alt+F4 behavior.
public static void RemoveMenuItem (Window win, MenuCommand command) {
WithSystemMenu(win, (hMenu) => {
if (RemoveMenu(hMenu, (uint)command, MF_BYCOMMAND) == 0) {
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Failed to remove menu item");
}
});
}
public static bool RemoveTrailingSeparator (Window win) {
bool result = false; // Func<...> not in .NET3 :-/
WithSystemMenu(win, (hMenu) => {
result = RemoveTrailingSeparator(hMenu);
});
return result;
}
// Removes the final trailing separator of a menu if it exists.
// Returns true if a separator is removed.
public static bool RemoveTrailingSeparator (IntPtr hMenu) {
int menuItemCount = GetMenuItemCount(hMenu);
if (menuItemCount < 0) {
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Failed to get menu item count");
}
if (menuItemCount == 0) {
return false;
} else {
uint index = (uint)(menuItemCount - 1);
MenuItemInfo itemInfo = new MenuItemInfo {
cbSize = (uint)Marshal.SizeOf(typeof(MenuItemInfo)),
fMask = MIIM_FTYPE,
};
if (GetMenuItemInfo(hMenu, index, true, ref itemInfo) == 0) {
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Failed to get menu item info");
}
if (itemInfo.fType == MFT_SEPARATOR) {
if (RemoveMenu(hMenu, index, MF_BYPOSITION) == 0) {
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Failed to remove menu item");
}
return true;
} else {
return false;
}
}
}
private const int GWL_STYLE = -16;
[Flags]
public enum WindowStyle : int
{
WS_MINIMIZEBOX = 0x00020000,
WS_MAXIMIZEBOX = 0x00010000,
}
// Don't use this version for dealing with pointers
[DllImport("user32", SetLastError=true)]
private static extern int SetWindowLong (IntPtr hWnd, int nIndex, int dwNewLong);
// Don't use this version for dealing with pointers
[DllImport("user32", SetLastError=true)]
private static extern int GetWindowLong (IntPtr hWnd, int nIndex);
public static int AlterWindowStyle (Window win,
WindowStyle orFlags, WindowStyle andNotFlags)
{
var interop = new WindowInteropHelper(win);
int prevStyle = GetWindowLong(interop.Handle, GWL_STYLE);
if (prevStyle == 0) {
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Failed to get window style");
}
int newStyle = (prevStyle | (int)orFlags) & ~((int)andNotFlags);
if (SetWindowLong(interop.Handle, GWL_STYLE, newStyle) == 0) {
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Failed to set window style");
}
return prevStyle;
}
public static int DisableMaximizeButton (Window win) {
return AlterWindowStyle(win, 0, WindowStyle.WS_MAXIMIZEBOX);
}
}
}
Usage: This must be done AFTER the source is initialized. A good place is to use the SourceInitialized event of the Window:
Window win = ...; /* the Window :-) */
WindowUtil.DisableMaximizeButton(win);
WindowUtil.RemoveMenuItem(win, WindowUtil.MenuCommand.SC_MAXIMIZE);
WindowUtil.RemoveMenuItem(win, WindowUtil.MenuCommand.SC_CLOSE);
while (WindowUtil.RemoveTrailingSeparator(win))
{
//do it here
}
To disable the Alt+F4 functionality the easy method is just to wire up the Canceling event and use set a flag for when you really do want to close the window.
Here's how you do it using only PIL (install with: pip install Pillow
):
import glob
from PIL import Image
# filepaths
fp_in = "/path/to/image_*.png"
fp_out = "/path/to/image.gif"
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=200, loop=0)
See docs: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
One way to fix an overflow of a Text Widget within a row if for example a chat message can be one really long line. You can create a Container and a BoxConstraint with a maxWidth in it.
Container(
constraints: BoxConstraints(maxWidth: 200),
child: Text(
(chatName == null) ? " ": chatName,
style: TextStyle(
fontWeight: FontWeight.w400,
color: Colors.black87,
fontSize: 17.0),
)
),