You can use the storage_path();
function to get storage folder path.
storage_path(); // Return path like: laravel_app\storage
Suppose you want to save your logfile mylog.log
inside Log folder of storage folder. You have to write something like
storage_path() . '/LogFolder/mylog.log'
I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.
EDIT: As others have pointed out there is indeed a difference between the two.
Instead of calling ipython directly, it is loaded using Python such as
$ python "full path to ipython.exe"
As Ryan says, the tsc compiler has a switch --declaration
which generates a .d.ts
file from a .ts
file. Also note that (barring bugs) TypeScript is supposed to be able to compile Javascript, so you can pass existing javascript code to the tsc compiler.
Suppose I have the following table T
:
a b
--------
1 abc
1 def
1 ghi
2 jkl
2 mno
2 pqr
And I do the following query:
SELECT a, b
FROM T
GROUP BY a
The output should have two rows, one row where a=1
and a second row where a=2
.
But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.
This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).
Fixing it might look like this:
SELECT a, MAX(b) AS x
FROM T
GROUP BY a
Now it's clear that you want the following result:
a x
--------
1 ghi
2 pqr
Without Using ANY Drop down Using your Drop Down ICON
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item>
<shape>
<gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear" /><!--For gradient background-->
<stroke android:width="1dp" android:color="#FFF" /><!--For Border background-->
<corners android:radius="0dp" /><!--For background corner-->
<padding android:bottom="3dp" android:left="3dp" android:right="6dp" android:top="3dp" /><!--For padding for all sides-->
</shape>
</item>
<item>
<bitmap android:gravity="center|right" android:src="@drawable/ic_down_arrow" /> // Replace with your Icon
</item>
</layer-list>
</item>
Something important to add: When using INSERT IGNORE and you do have key violations, MySQL does NOT raise a warning!
If you try for instance to insert 100 records at a time, with one faulty one, you would get in interactive mode:
Query OK, 99 rows affected (0.04 sec)
Records: 100 Duplicates: 1 Warnings: 0
As you see: No Warnings! This behavior is even wrongly described in the official Mysql Documentation.
If your script needs to be informed, if some records have not been added (due to key violations) you have to call mysql_info() and parse it for the "Duplicates" value.
I don't know about php but i belive the problem is from this :
echo '<script language="javascript>';
echo 'alery("message successfully sent")';
echo '</script>';
Try to change this with :
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
Some of the answers of this post are valid, but using TypeToken, the Gson library generates a Tree objects whit unreal types for your application.
To get it I had to read the array and convert one by one the objects inside the array. Of course this method is not the fastest and I don't recommend to use it if you have the array is too big, but it worked for me.
It is necessary to include the Json library in the project. If you are developing on Android, it is included:
/**
* Convert JSON string to a list of objects
* @param sJson String sJson to be converted
* @param tClass Class
* @return List<T> list of objects generated or null if there was an error
*/
public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){
try{
Gson gson = new Gson();
List<T> listObjects = new ArrayList<>();
//read each object of array with Json library
JSONArray jsonArray = new JSONArray(sJson);
for(int i=0; i<jsonArray.length(); i++){
//get the object
JSONObject jsonObject = jsonArray.getJSONObject(i);
//get string of object from Json library to convert it to real object with Gson library
listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
}
//return list with all generated objects
return listObjects;
}catch(Exception e){
e.printStackTrace();
}
//error: return null
return null;
}
Personally, I'd append the element to the form instead of hacking the serialized data, e.g.
moredata = 'your custom data here';
// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);
// append to the form
$('#myForm').append($input);
// then..
data: $('#myForm').serialize()
That way, you don't have to worry about ?
or &
I got a lot of these errors just now. What happened is that I split a header-file-only class into a header file and a cpp file. However, I didn't update my build system, so the cpp file didn't get compiled. Among simply having undefined references to the functions declared in the header but not implemented, I got a lot of these typeinfo errors.
The solution was to re-run the build system to compile and link the new cpp file.
C# 7.1 (perhaps earlier?) makes this as easy and nice-looking as it should be, with string interpolation:
var jackpot = 1000000;
var niceNumberString = $"Jackpot is {jackpot:n}";
var niceMoneyString = $"Jackpot is {jackpot:C}";
I would consider using a quadtree if you have a large number of balls. For deciding the direction of bounce, just use simple conservation of energy formulas based on the collision normal. Elasticity, weight, and velocity would make it a bit more realistic.
This helped me: just wait about a minute or two.
Wait a few minutes, then retry your operation.
I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur
to convert numbers or string to Curency formats. CCur(number)
or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "")
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
It's really not an 'either/or' situation. AJAX stands for Asynchronous JavaScript and XML, and JQuery is a JavaScript library that takes the pain out of writing common JavaScript routines.
It's the difference between a thing (jQuery) and a process (AJAX). To compare them would be to compare apples and oranges.
I think you should consider using the shelve
module which provides persistent file-backed dictionary-like objects. It's easy to use in place of a "real" dictionary because it almost transparently provides your program with something that can be used just like a dictionary, without the need to explicitly convert it to a string and then write to a file (or vice-versa).
The main difference is needing to initially open()
it before first use and then close()
it when you're done (and possibly sync()
ing it, depending on the writeback
option being used). Any "shelf" file objects create can contain regular dictionaries as values, allowing them to be logically nested.
Here's a trivial example:
import shelve
shelf = shelve.open('mydata') # open for reading and writing, creating if nec
shelf.update({'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }})
shelf.close()
shelf = shelve.open('mydata')
print shelf
shelf.close()
Output:
{'three': {'three.1': 3.1, 'three.2': 3.2}, 'two': 2, 'one': 1}
If you were asking how to do it in vue2 and make options to insert and delete it, please, have a look an js fiddle
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
finds: [] _x000D_
},_x000D_
methods: {_x000D_
addFind: function () {_x000D_
this.finds.push({ value: 'def' });_x000D_
},_x000D_
deleteFind: function (index) {_x000D_
console.log(index);_x000D_
console.log(this.finds);_x000D_
this.finds.splice(index, 1);_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
<h1>Finds</h1>_x000D_
<div v-for="(find, index) in finds">_x000D_
<input v-model="find.value">_x000D_
<button @click="deleteFind(index)">_x000D_
delete_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<button @click="addFind">_x000D_
New Find_x000D_
</button>_x000D_
_x000D_
<pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
Just read the whole file into a StringBuilder, then split the String by dot following a space. You will get a String array.
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt"));
StringBuilder sb = new Stringbuilder();
while(inFile1.hasNext()) {
sb.append(inFile1.nextLine());
}
String[] yourArray = sb.toString().split(", ");
onclick
may not be the best event to attach that action to. Anytime anyone clicks anywhere in the form, it will open the window.
<form action="..." ...
onsubmit="window.open('google.html', '_blank', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');return true;">
Objects have methods and attributes(variables) which are derived from classes, in order to specify which methods and variables belong to a particular object the this
reserved word is used. in the case of instance variables, it is important to understand the difference between implicit and explicit parameters. Take a look at the fillTank
call for the audi
object.
Car audi= new Car();
audi.fillTank(5); // 5 is the explicit parameter and the car object is the implicit parameter
The value in the parenthesis is the implicit parameter and the object itself is the explicit parameter, methods that don't have explicit parameters, use implicit parameters, the fillTank
method has both an explicit and an implicit parameter.
Lets take a closer look at the fillTank
method in the Car
class
public class Car()
{
private double tank;
public Car()
{
tank = 0;
}
public void fillTank(double gallons)
{
tank = tank + gallons;
}
}
In this class we have an instance variable "tank". There could be many objects that use the tank instance variable, in order to specify that the instance variable "tank" is used for a particular object, in our case the "audi" object we constructed earlier, we use the this
reserved keyword. for instance variables the use of 'this' in a method indicates that the instance variable, in our case "tank", is instance variable of the implicit parameter.
The java compiler automatically adds the this
reserved word so you don't have to add it, it's a matter of preference. You can not use this
without a dot(.) because those are the rules of java ( the syntax).
In summary.
this
on an instance variable in a method indicates that, the instance variable belongs to the implicit parameter, or that it is an instance variable of the implicit parameter. this
cannot be used without a dot(.) this is syntactically invalidthis
can also be used to distinguish between local variables and global variables that have the same namethis
reserve word also applies to methods, to indicate a method belongs to a particular object. Turns out that Evan Larsen has the best answer. Please upvote his answer (and/or select it as the correct answer) - it's brilliant.
Using Evan's trick, you can instantiate all tooltips with one line of code:
$('[data-toggle="tooltip"]').tooltip({'placement': 'top'});
You will see that all tooltips in your long paragraph have working tooltips with just that one line.
In the jsFiddle example (link above), I also added a situation where one tooltip (by the Sign-In button) is ON by default. Also, the tooltip code is ADDED to the button in jQuery, not in the HTML markup.
Popovers do work the same as the tooltips:
$('[data-toggle="popover"]').popover({trigger: 'hover','placement': 'top'});
And there you have it! Success at last.
One of the biggest problems in figuring this stuff out was making bootstrap work with jsFiddle... Here's what you must do:
NOW you are ready to go.
(a) wwww.somewebsite.com/a.txt
isn't a 'file URL'. It isn't a URL at all. If you put http://
on the front of it it would be an HTTP URL, which is clearly what you intend here.
(b) FileInputStream
is for files, not URLs.
(c) The way to get an input stream from any URL is via URL.openStream(),
or URL.getConnection().getInputStream(),
which is equivalent but you might have other reasons to get the URLConnection
and play with it first.
Here is a really elegant solution from Chris Thielen ui-router-extras: $previousState
var previous = $previousState.get(); //Gets a reference to the previous state.
previous
is an object that looks like: { state: fromState, params: fromParams }
where fromState is the previous state and fromParams is
the previous state parameters.
I suggest wrapping your call to requestAnimationFrame
in a setTimeout
:
const fps = 25;
function animate() {
// perform some animation task here
setTimeout(() => {
requestAnimationFrame(animate);
}, 1000 / fps);
}
animate();
You need to call requestAnimationFrame
from within setTimeout
, rather than the other way around, because requestAnimationFrame
schedules your function to run right before the next repaint, and if you delay your update further using setTimeout
you will have missed that time window. However, doing the reverse is sound, since you’re simply waiting a period of time before making the request.
Under the windows feature list, make sure to check the IIS Management Console You also need to check additional check boxes as shown below:
This is re-post for insert code also. This example included: - One object list - Each object hast child list. Ex:
var list1 = {
name: "Role A",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
I'll 3 list like above and i'll add to a one object list
newArr.push(list1);
newArr.push(list2);
newArr.push(list3);
Then i'll do how to show checkbox with multiple group:
$scope.toggleAll = function(item) {
var toogleStatus = !item.name_selected;
console.log(toogleStatus);
angular.forEach(item, function() {
angular.forEach(item.subs, function(sub) {
sub.selected = toogleStatus;
});
});
};
$scope.optionToggled = function(item, subs) {
item.name_selected = subs.every(function(itm) {
return itm.selected;
})
$scope.txtRet = item.name_selected;
}
HTML:
<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
<div>
<ul>
<input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)"><span>{{item.name}}</span>
<div>
<li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
<input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
</li>
</div>
</ul>
</div>
<span>{{txtRet}}</span>
</li>
Fiddle: example
You can do this:
DB::transaction(function() {
//
});
Everything inside the Closure executes within a transaction. If an exception occurs it will rollback automatically.
Using WinRAR command line interface, you can copy the file names and/or file types to an archive. Then you can extract that archive to whatever location you like. This preserves the original file structure.
I needed to add missing album picture files to my mobile phone without having to recopy the music itself. Fortunately the directory structure was the same on my computer and mobile!
I used:
rar a -r C:\Downloads\music.rar X:\music\Folder.jpg
This created an archive with all the Folder.jpg files in the proper subdirectories.
This technique can be used to copy file types as well. If the files all had different names, you could choose to extract all files to a single directory. Additional command line parameters can archive multiple file types.
More information in this very helpful link http://cects.com/using-the-winrar-command-line-tools-in-windows/
array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.
It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)
if (isset($a['element']) || array_key_exists('element', $a)) {
//the element exists in the array. write your code here.
}
The benchmarking comparison: (extracted from below blog posts).
array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms
See http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/ and http://thinkofdev.com/php-isset-and-multi-dimentional-array/
for detailed discussion.
I always use method 2 as well. The only benefit of using each is if you're just reading (rather than re-assigning) the value of the hash entry, you're not constantly de-referencing the hash.
See this question: Converting data.frame to xts order.by requires an appropriate time-based object, which suggests looking at argument to order.by,
Currently acceptable classes include: ‘Date’, ‘POSIXct’, ‘timeDate’, as well as ‘yearmon’ and ‘yearqtr’ where the index values remain unique.
And further suggests an explicit conversion using order.by = as.POSIXct,
df$Date <- as.POSIXct(strptime(df$Date,format),tz="UTC")
xts(df[, -1], order.by=as.POSIXct(df$Date))
Where your format is assigned elswhere,
format <- "%m/%d/%Y" #see strptime for details
if you have a hive setup you can put the local dataset directly using Hive load command in hdfs/s3.
You will need to use "Local" keyword when writing your load command.
Syntax for hiveload command
LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)]
Refer below link for more detailed information. https://cwiki.apache.org/confluence/display/Hive/LanguageManual%20DML#LanguageManualDML-Loadingfilesintotables
It should be $_COOKIE['name']
, not $_COOKIE('name')
$_COOKIE
is an array, not a function.
using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( http://www.php.net/manual/en/function.json-decode.php ) to parse it in php. And then you can use it as an array.
There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.
For functions with return types, there is Func<> and for functions without return types there is Action<>.
Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).
So you can declare your Diff function to take a Func:
public double Diff(double x, Func<double, double> f) {
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:
double result = Diff(myValue, Function);
You can even write the function in-line with lambda syntax:
double result = Diff(myValue, d => Math.Sqrt(d * 3.14));
Take a look at this post: http://praveenbattula.blogspot.com/2009/09/access-iframe-content-using-jquery.html
$("#iframeID").contents().find("[tokenid=" + token + "]").html();
Place your selector in the find method.
This may not be possible however if the iframe is not coming from your server. Other posts talk about permission denied errors.
exec
is often used in conjunction with fork
, which I saw that you also asked about, so I will discuss this with that in mind.
exec
turns the current process into another program. If you ever watched Doctor Who, then this is like when he regenerates -- his old body is replaced with a new body.
The way that this happens with your program and exec
is that a lot of the resources that the OS kernel checks to see if the file you are passing to exec
as the program argument (first argument) is executable by the current user (user id of the process making the exec
call) and if so it replaces the virtual memory mapping of the current process with a virtual memory the new process and copies the argv
and envp
data that were passed in the exec
call into an area of this new virtual memory map. Several other things may also happen here, but the files that were open for the program that called exec
will still be open for the new program and they will share the same process ID, but the program that called exec
will cease (unless exec failed).
The reason that this is done this way is that by separating running a new program into two steps like this you can do some things between the two steps. The most common thing to do is to make sure that the new program has certain files opened as certain file descriptors. (remember here that file descriptors are not the same as FILE *
, but are int
values that the kernel knows about). Doing this you can:
int X = open("./output_file.txt", O_WRONLY);
pid_t fk = fork();
if (!fk) { /* in child */
dup2(X, 1); /* fd 1 is standard output,
so this makes standard out refer to the same file as X */
close(X);
/* I'm using execl here rather than exec because
it's easier to type the arguments. */
execl("/bin/echo", "/bin/echo", "hello world");
_exit(127); /* should not get here */
} else if (fk == -1) {
/* An error happened and you should do something about it. */
perror("fork"); /* print an error message */
}
close(X); /* The parent doesn't need this anymore */
This accomplishes running:
/bin/echo "hello world" > ./output_file.txt
from the command shell.
"Correct" is a dangerous word in Ruby. There's usually more than one way to do anything. If you know you'll always want that default value for that column on that table, setting them in a DB migration file is the easiest way:
class SetDefault < ActiveRecord::Migration
def self.up
change_column :people, :last_name, :type, :default => "Doe"
end
def self.down
# You can't currently remove default values in Rails
raise ActiveRecord::IrreversibleMigration, "Can't remove the default"
end
end
Because ActiveRecord autodiscovers your table and column properties, this will cause the same default to be set in any model using it in any standard Rails app.
However, if you only want default values set in specific cases -- say, it's an inherited model that shares a table with some others -- then another elegant way is do it directly in your Rails code when the model object is created:
class GenericPerson < Person
def initialize(attributes=nil)
attr_with_defaults = {:last_name => "Doe"}.merge(attributes)
super(attr_with_defaults)
end
end
Then, when you do a GenericPerson.new()
, it'll always trickle the "Doe" attribute up to Person.new()
unless you override it with something else.
You need to join the two tables:
select p.id, p.first, p.middle, p.last, p.age,
a.id as address_id, a.street, a.city, a.state, a.zip
from Person p inner join Address a on p.id = a.person_id
where a.zip = '97229';
This will select all of the columns from both tables. You could of course limit that by choosing different columns in the select
clause.
Your question is: are these not modules capable of declaring variables at global scope?
Answer: YES, they are "capable"
The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1
, e.g.)
References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).
For instance, place in Sheet1 code
Public glob_sh1 As String
Sub test_sh1()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
place in ThisWorkbook code
Public glob_this As String
Sub test_this()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
and in a Standard Module code
Public glob_mod As String
Sub test_mod()
glob_mod = "glob_mod"
ThisWorkbook.glob_this = "glob_this"
Sheet1.glob_sh1 = "glob_sh1"
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
All three subs work fine.
PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).
PS2: Your line Debug.Print ("Hello")
will give you the compile error Invalid outside procedure
.
PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.
PS4: Check also Put Excel-VBA code in module or sheet?.
PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.
PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.
1.save your file name as hey.py with the below given hello world script
#! /usr/bin/python
print('Hello, world!')
2.open the terminal in that directory
$ python hey.py
or if you are using python3 then
$ python3 hey.py
On the Admin panel in the footer you should see the words "Wordpress x.x" where x.x is your version number :)
Alternatively you can echo out the WP_VERSION constant in your script, it's up to you. The former is a lot quicker and easier.
How the hash is computed does usually not depend on the hashtable, but on the items added to it. In frameworks/base class libraries such as .net and Java, each object has a GetHashCode() (or similar) method returning a hash code for this object. The ideal hash code algorithm and the exact implementation depends on the data represented by in the object.
I taken from this thread decision Implement an input with a mask and adapted it for IE10, and added setter- and getter- functions.
BUT I TESTED FOR PHONE-mask ONLY
$(document).ready(function(){
var el_arr = document.querySelectorAll("[placeholder][data-slots]");
for (var el_ind=0; el_ind < el_arr.length; el_ind++ ){
var el = el_arr[el_ind];
var pattern = el.getAttribute("placeholder"),
slots = new Set(el.getAttribute("data-slots") || "_"),
prev = function(j){return Array.from(pattern, function(c,i){ return slots.has(c)? j=i+1: j;});}(0),
first = pattern.split('').findIndex(function(c){return slots.has(c);} ),
accept = new RegExp(el.getAttribute("data-accept") || "\\d", "g"),
clean = function(input){input = input.match(accept) || [];return Array.from(pattern, function(c){return input[0] === c || slots.has(c) ? input.shift() || c : c;});},
format = function(){
var elem = this;
var i_j_arr = [el.selectionStart, el.selectionEnd].map(function(i){
i = clean(el.value.slice(0, i)).findIndex(function(c){ return slots.has(c);});
return i<0? prev[prev.length-1]: elem.back? prev[i-1] || first: i;
});
el.value = clean(el.value).join('');
el.setSelectionRange(i_j_arr[0], i_j_arr[1]);
this.back = false;
},
// sdo added
get_masked_value = function(){
var input = this.value;
var ret=[];
for(var k in pattern){
if ( !input[k] )break;
if( slots.has(pattern[k]) && input[k]!=pattern[k]){
ret.push(input[k]);
}
}
return ret.join('');
},
set_masked_value = function(input){
var ret=[];
var index_in_value = 0;
for(var k in pattern){
if( slots.has(pattern[k]) && input[index_in_value]){
ret.push(input[index_in_value]);
index_in_value++;
}
else{
ret.push(pattern[k]);
}
}
this.value = ret.join('');
}
;
el.get_masked_value = get_masked_value;
el.set_masked_value = set_masked_value;
el.back = false;
el.addEventListener("keydown", function(event){ this.back = event.key === "Backspace";});
el.addEventListener("input", format);
el.addEventListener("focus", format);
el.addEventListener("blur", function() { return el.value === pattern && (el.value=""); });
}
});
Here is the simplest logic for beginners to get prime numbers:
p=[]
for n in range(2,50):
for k in range(2,50):
if n%k ==0 and n !=k:
break
else:
for t in p:
if n%t ==0:
break
else:
p.append(n)
print p
I ran into this problem today. Based on the solutions above, this worked for me:
<div style="width:100%;">
<div style="float:left;">Content left div</div>
<div style="float:right;">Content right div</div>
</div>
Simply make the parent div span the full width and float the divs contained within.
there are two columns in the a table ID and name where names are repeating with different IDs so for that you may use this query: . .
DELETE FROM dbo.tbl1
WHERE id NOT IN (
Select MIN(Id) AS namecount FROM tbl1
GROUP BY Name
)
I think Django docs explicitly mention that if the intent is to start from an empty DB again (which seems to be OP's intent), then just drop and re-create the database and re-run migrate
(instead of using flush
):
If you would rather start from an empty database and re-run all migrations, you should drop and recreate the database and then run migrate instead.
So for OP's case, we just need to:
python manage.py migrate
You may try:
settings = s.merge_environment_settings(prepped.url, None, None, None, None)
You can read more here: http://docs.python-requests.org/en/master/user/advanced/
The closest thing to "for each" is probably MySQL Procedure using Cursor and LOOP.
"this" is also useful when calling one constructor from another:
public class MyClass {
public MyClass(String foo) {
this(foo, null);
}
public MyClass(String foo, String bar) {
...
}
}
Well in my case, my project A had a dependency on another, say X(A was using some of the classes defined in X). So when I added X as a reference project in the build path of A , I got this error. However when I removed X as the referenced project and included X's jar as one of the libraries, the problem was solved.
Here's an alternative that works well for readability if you have the Binding in the middle of the string or multiple bindings:
<TextBlock>
<Run Text="Temperature is "/>
<Run Text="{Binding CelsiusTemp}"/>
<Run Text="°C"/>
</TextBlock>
<!-- displays: 0°C (32°F)-->
<TextBlock>
<Run Text="{Binding CelsiusTemp}"/>
<Run Text="°C"/>
<Run Text=" ("/>
<Run Text="{Binding Fahrenheit}"/>
<Run Text="°F)"/>
</TextBlock>
I had this same problem and I was able to solve it by implementing the IValidatableObject interface in my view model.
public class RegisterViewModel : IValidatableObject
{
/// <summary>
/// Error message for Minimum password
/// </summary>
public static string PasswordLengthErrorMessage => $"The password must be at least {PasswordMinimumLength} characters";
/// <summary>
/// Minimum acceptable password length
/// </summary>
public const int PasswordMinimumLength = 8;
/// <summary>
/// Gets or sets the password provided by the user.
/// </summary>
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
/// <summary>
/// Only need to validate the minimum length
/// </summary>
/// <param name="validationContext">ValidationContext, ignored</param>
/// <returns>List of validation errors</returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var errorList = new List<ValidationResult>();
if ((Password?.Length ?? 0 ) < PasswordMinimumLength)
{
errorList.Add(new ValidationResult(PasswordLengthErrorMessage, new List<string>() {"Password"}));
}
return errorList;
}
}
The markup in the Razor is then...
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control input-lg" }
<div class="password-helper">Must contain: 8 characters, 1 upper-case, 1 lower-case
</div>
@Html.ValidationMessagesFor(m => m.Password, new { @class = "text-danger" })
</div>
This works really well. If I attempt to use [StringLength] instead then the rendered HTML is just not correct. The validation should render as:
<span class="text-danger field-validation-invalid field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true"><span id="Password-error" class="">The Password should be a minimum of 8 characters long.</span></span>
With the StringLengthAttribute the rendered HTML shows as a ValidationSummary which is not correct. The funny thing is that when the validator fails the submit is still blocked!
As mentioned in the github issue originally linked by @peter in the comments:
const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);
Aspx
<ajax:ModalPopupExtender runat="server" ID="modalPop"
PopupControlID="pnlpopup"
TargetControlID="btnGo"
BackgroundCssClass="modalBackground"
DropShadow="true"
CancelControlID="btnCancel" X="470" Y="300" />
//Codebehind
protected void OkButton_Clicked(object sender, EventArgs e)
{
modalPop.Hide();
//Do something in codebehind
}
And don't set the OK button as OkControlID.
You've tried alot. And I feel for you. Here is an idea. I kinda followed everything you tried. The mental note I have in my head goes like this: "When Sql Server won't connect when you've tried everything, wire up your firewall rules by the program, not the port"
I know you said you disabled the firewall. But something is telling me to give this a try anyways.
I think you have to open the firewall "by program", and not by port.
http://technet.microsoft.com/en-us/library/cc646023.aspx
To add a program exception to the firewall using the Windows Firewall item in Control Panel.
On the Exceptions tab of the Windows Firewall item in Control Panel, click Add a program.
Browse to the location of the instance of SQL Server that you want to allow through the firewall, for example C:\Program Files\Microsoft SQL Server\MSSQL11.<instance_name>\MSSQL\Binn, select sqlservr.exe, and then click Open.
Click OK.
EDIT..........
http://msdn.microsoft.com/en-us/library/ms190479.aspx
I'm a little cloudy on which "program" you're trying to use on SQLB?
Is it SSMS on SQLB? Or a client program on SQLB ?
EDIT...........
No idea if this will help. But I use this to ping "ports" ... and something that is outside of the SSMS world.
http://www.microsoft.com/en-us/download/details.aspx?id=24009
Upgraded from Angular 5 / Rxjs 5 to Angular 6 / Rxjs 6?
You must change your imports and your instantiation. Check out Damien's blog post
Tl;dr:
import { Observable, fromEvent, of } from 'rxjs';
const yourResult = Observable
.create(of(yourObservable))
.startWith(null)
.map(x => x.someStringProperty.toLowerCase());
//subscribe to keyup event on input element
Observable
.create(fromEvent(yourInputElement, 'keyup'))
.debounceTime(5000)
.distinctUntilChanged()
.subscribe((event) => {
yourEventHandler(event);
});
What about overriding the method with
void f(int value)
{
f((byte)value);
}
this will allow for f(0)
The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.
Below is a batch file that will run corflags.exe
against all dlls
and exes
in the current working directory and all sub-directories, parse the results and display the target architecture of each.
Depending on the version of corflags.exe
that is used, the line items in the output will either include 32BIT
, or 32BITREQ
(and 32BITPREF
). Whichever of these two is included in the output is the critical line item that must be checked to differentiate between Any CPU
and x86
. If you are using an older version of corflags.exe
(pre Windows SDK v8.0A), then only the 32BIT
line item will be present in the output, as others have indicated in past answers. Otherwise 32BITREQ
and 32BITPREF
replace it.
This assumes corflags.exe
is in the %PATH%
. The simplest way to ensure this is to use a Developer Command Prompt
. Alternatively you could copy it from it's default location.
If the batch file below is run against an unmanaged dll
or exe
, it will incorrectly display it as x86
, since the actual output from Corflags.exe
will be an error message similar to:
corflags : error CF008 : The specified file does not have a valid managed header
@echo off
echo.
echo Target architecture for all exes and dlls:
echo.
REM For each exe and dll in this directory and all subdirectories...
for %%a in (.exe, .dll) do forfiles /s /m *%%a /c "cmd /c echo @relpath" > testfiles.txt
for /f %%b in (testfiles.txt) do (
REM Dump corflags results to a text file
corflags /nologo %%b > corflagsdeets.txt
REM Parse the corflags results to look for key markers
findstr /C:"PE32+">nul .\corflagsdeets.txt && (
REM `PE32+` indicates x64
echo %%~b = x64
) || (
REM pre-v8 Windows SDK listed only "32BIT" line item,
REM newer versions list "32BITREQ" and "32BITPREF" line items
findstr /C:"32BITREQ : 0">nul /C:"32BIT : 0" .\corflagsdeets.txt && (
REM `PE32` and NOT 32bit required indicates Any CPU
echo %%~b = Any CPU
) || (
REM `PE32` and 32bit required indicates x86
echo %%~b = x86
)
)
del corflagsdeets.txt
)
del testfiles.txt
echo.
You should stop the submit procedure by returning false on the onsubmit callback.
<script>
function checkRegistration(){
if(!form_valid){
alert('Given data is not correct');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()"...
Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:
<script>
function checkRegistration(){
var form_valid = (document.getElementById('some_input').value == 'google');
if(!form_valid){
alert('Given data is incorrect');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
Write google to go to google...<br/>
<input type="text" id="some_input" value=""/>
<input type="submit" value="google it"/>
</form>
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
Like this:
{% if age > 18 %}
{% with patient as p %}
<my html here>
{% endwith %}
{% else %}
{% with patient.parent as p %}
<my html here>
{% endwith %}
{% endif %}
If the html is too big and you don't want to repeat it, then the logic would better be placed in the view. You set this variable and pass it to the template's context:
p = (age > 18 && patient) or patient.parent
and then just use {{ p }} in the template.
using PhpMyAdmin version 4.5.4.1deb2ubuntu2, you can set the variables in /etc/phpmyadmin/config-db.php
so set $dbserver
to your server name, e.g. $dbserver='mysql.example.com';
<?php
##
## database access settings in php format
## automatically generated from /etc/dbconfig-common/phpmyadmin.conf
## by /usr/sbin/dbconfig-generate-include
##
## by default this file is managed via ucf, so you shouldn't have to
## worry about manual changes being silently discarded. *however*,
## you'll probably also want to edit the configuration file mentioned
## above too.
##
$dbuser='phpmyadmin';
$dbpass='P@55w0rd';
$basepath='';
$dbname='phpmyadmin';
$dbserver='localhost';
$dbport='';
$dbtype='mysql';
You define an enumeration to restrict the possible values of elements of the type to a limited set. This restriction is to be enforced at compile time.
When forward declaring the fact that you will use a 'limited set' later on doesn't add any value: subsequent code needs to know the possible values in order to benefit from it.
Although the compiler is concerned about the size of the enumerated type, the intent of the enumeration gets lost when you forward declare it.
You probably need to update the remote URL since github puts your username in it. You can take a look at the original URL by typing
git config --get remote.origin.url
Or just go to the repository page on Github and get the new URL. Then use
git remote set-url origin https://{new url with username replaced}
to update the URL with your new username.
For clear frame, first need to destroy all widgets inside the frame,. it will clear frame.
import tkinter as tk
from tkinter import *
root = tk.Tk()
frame = Frame(root)
frame.pack(side="top", expand=True, fill="both")
lab = Label(frame, text="hiiii")
lab.grid(row=0, column=0, padx=10, pady=5)
def clearFrame():
# destroy all widgets from frame
for widget in frame.winfo_children():
widget.destroy()
# this will clear frame and frame will be empty
# if you want to hide the empty panel then
frame.pack_forget()
frame.but = Button(frame, text="clear frame", command=clearFrame)
frame.but.grid(row=0, column=1, padx=10, pady=5)
# then whenever you add data in frame then you can show that frame
lab2 = Label(frame, text="hiiii")
lab2.grid(row=1, column=0, padx=10, pady=5)
frame.pack()
root.mainloop()
I've used this process to attach a 3rd party Jar to an Android project in IDEA.
The library should now be recognised.
It is OK, but at the same time can cause some browsers to become slow.
http://webdesignfan.com/yslow-tutorial-part-2-of-3-reducing-server-calls/
My advice is use <a href="#"></a>
If you're using JQuery remember to also use:
.click(function(event){
event.preventDefault();
// Click code here...
});
You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.
According to the page:
This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.
Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.
It depends on what keeps your users happy. For example, Gmail takes quite a while to open at first, but users wait because it is worth waiting for.
A kernel is the part of the operating system that mediates access to system resources. It's responsible for enabling multiple applications to effectively share the hardware by controlling access to CPU, memory, disk I/O, and networking.
An operating system is the kernel plus applications that enable users to get something done (i.e compiler, text editor, window manager, etc).
Hopefully a simple explanation : -
onStart() -> called when the activity becomes visible, but might not be in the foreground (e.g. an AlertFragment is on top or any other possible use case).
onResume() -> called when the activity is in the foreground, or the user can interact with the Activity.
I guess an img tag is needed as a child of an a tag, the following way:
<a download="YourFileName.jpeg" href="data:image/jpeg;base64,iVBO...CYII=">
<img src="data:image/jpeg;base64,iVBO...CYII="></img>
</a>
or
<a download="YourFileName.jpeg" href="/path/to/OtherFile.jpg">
<img src="/path/to/OtherFile.jpg"></img>
</a>
Only using the a tag as explained in #15 didn't worked for me with the latest version of Firefox and Chrome, but putting the same image data in both a.href and img.src tags worked for me.
From JavaScript it could be generated like this:
var data = canvas.toDataURL("image/jpeg");
var img = document.createElement('img');
img.src = data;
var a = document.createElement('a');
a.setAttribute("download", "YourFileName.jpeg");
a.setAttribute("href", data);
a.appendChild(img);
var w = open();
w.document.title = 'Export Image';
w.document.body.innerHTML = 'Left-click on the image to save it.';
w.document.body.appendChild(a);
Similar to colMeans
, colSums
, etc, you could write a column maximum function, colMax
, and a column sort function, colSort
.
colMax <- function(data) sapply(data, max, na.rm = TRUE)
colSort <- function(data, ...) sapply(data, sort, ...)
I use ...
in the second function in hopes of sparking your intrigue.
Get your data:
dat <- read.table(h=T, text = "Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
3 12 149 12.6 74 5 3
4 18 313 11.5 62 5 4
5 NA NA 14.3 56 5 5
6 28 NA 14.9 66 5 6
7 23 299 8.6 65 5 7
8 19 99 13.8 59 5 8
9 8 19 20.1 61 5 9")
Use colMax
function on sample data:
colMax(dat)
# Ozone Solar.R Wind Temp Month Day
# 41.0 313.0 20.1 74.0 5.0 9.0
To do the sorting on a single column,
sort(dat$Solar.R, decreasing = TRUE)
# [1] 313 299 190 149 118 99 19
and over all columns use our colSort
function,
colSort(dat, decreasing = TRUE) ## compare with '...' above
Assume n=2. Then we have 2-1 = 1 on the left side and 2*1/2 = 1 on the right side.
Denote f(n) = (n-1)+(n-2)+(n-3)+...+1
Now assume we have tested up to n=k. Then we have to test for n=k+1.
on the left side we have k+(k-1)+(k-2)+...+1, so it's f(k)+k
On the right side we then have (k+1)*k/2 = (k^2+k)/2 = (k^2 +2k - k)/2 = k+(k-1)k/2 = kf(k)
So this have to hold for every k, and this concludes the proof.
on debian :
apt list --upgradable
gives the list with package, version to be upgraded, and actual version of the package.
result :
base-files/stable 8+deb8u8 amd64 [upgradable from: 8+deb8u7]
bind9-host/stable 1:9.9.5.dfsg-9+deb8u11 amd64 [upgradable from: 1:9.9.5.dfsg-9+deb8u9]
ca-certificates/stable 20141019+deb8u3 all [upgradable from: 20141019+deb8u2]
certbot/jessie-backports 0.10.2-1~bpo8+1 all [upgradable from: 0.8.1-2~bpo8+1]
dnsutils/stable 1:9.9.5.dfsg-9+deb8u11 amd64 [upgradable from: 1:9.9.5.dfsg-9+deb8u9]
No, you can't achieve that without setting a fixed height (or using a script).
Here are 2 answers of mine, showing how to use a script to achieve something like that:
Answer updated for 2020:
Both <object>
and <embed>
are included in the WHAT-WG HTML Living Standard (Sept 2020).
<object>
The object element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a child browsing context, or as an external resource to be processed by a plugin.
<embed>
The embed element provides an integration point for an external (typically non-HTML) application or interactive content.
Are there advantages/disadvantages to using one tag vs. the other?
The opinion of Mozilla Developer Network (MDN) appears (albeit fairly subtly) to very marginally favour <object>
over <embed>
but overwhelmingly, MDN, wants to recommend that wherever you can, you avoid embedding external content entirely.
[...] you are unlikely to use these elements very much — Applets haven't been used for years, Flash is no longer very popular, due to a number of reasons (see The case against plugins, below), PDFs tend to be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. Plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects.
Once upon a time, plugins were indispensable on the Web. Remember the days when you had to install Adobe Flash Player just to watch a movie online? And then you constantly got annoying alerts about updating Flash Player and your Java Runtime Environment. Web technologies have since grown much more robust, and those days are over. For virtually all applications, it's time to stop delivering content that depends on plugins and start taking advantage of Web technologies instead.
Use get_the_category()
function.
$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories);
Here are a couple of complete working examples that build on the @bendewey & @dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:
//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ1
{
static void Main( )
{
//Load xml
XDocument xdoc = XDocument.Load(@"c:\\data.xml"); //you'll have to edit your path
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new
{
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
StringBuilder result = new StringBuilder(); //had to add this to make the result work
//Loop through results
foreach (var lv1 in lv1s)
{
result.AppendLine(" " + lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result.ToString()); //added this so you could see the output on the console
}
}
And next:
//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ
{
static void Main( )
{
XElement rootElement = XElement.Load(@"c:\\data.xml"); //you'll have to edit your path
Console.WriteLine(GetOutline(0, rootElement));
}
static private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
}
These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.
EDIT: added @eglasius' example as well since it became useful to me:
//@eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
class loadXMLToLINQ2
{
static void Main( )
{
StringBuilder result = new StringBuilder(); //needed for result below
XDocument xdoc = XDocument.Load(@"c:\\deg\\data.xml"); //you'll have to edit your path
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Console.WriteLine(result);//added this so you could see the result
}
}
You can quote the entire path as in windows or you can escape the spaces like in:
/foo\ folder\ with\ space/foo.sh -help
Both ways will work!
opt
is new for ruby 1.9. The various options are documented in IO.new
: www.ruby-doc.org/core/IO.html
I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)
There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):
The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.
API is really nice and easy to learn. Example how to capture single image and save it to PNG file:
Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
Update for transposition:
You should use cvTranspose()
or cv::transpose()
because (as you rightly pointed out) it's more efficient. Again, I recommend upgrading to OpenCV2.0 since most of the cvXXX
functions just convert IplImage*
structures to Mat
objects (no deep copies). If you stored the image in a Mat
object, Mat.t()
would return the transpose.
Any rotation:
You should use cvWarpAffine by defining the rotation matrix in the general framework of the transformation matrix. I would highly recommend upgrading to OpenCV2.0 which has several features as well as a Mat
class which encapsulates matrices and images. With 2.0 you can use warpAffine to the above.
Read the documentation:
with open('names.txt', 'r') as f:
myNames = f.readlines()
The others already provided answers how to get rid of the newline character.
Update:
Fred Larson provides a nice solution in his comment:
with open('names.txt', 'r') as f:
myNames = [line.strip() for line in f]
Alternatively there's the application called LiveReload...
The object where Oracle stores the name of the identifiers (e.g. the table names of the user are stored in the table named as USER_TABLES and the column names of the user are stored in the table named as USER_TAB_COLUMNS), have the NAME columns (e.g. TABLE_NAME in USER_TABLES) of size Varchar2(30)...and it's uniform through all system tables of objects or identifiers --
DBA_ALL_TABLES ALL_ALL_TABLES USER_ALL_TABLES
DBA_PARTIAL_DROP_TABS ALL_PARTIAL_DROP_TABS USER_PARTIAL_DROP_TABS
DBA_PART_TABLES ALL_PART_TABLES USER_PART_TABLES
DBA_TABLES ALL_TABLES USER_TABLES
DBA_TABLESPACES USER_TABLESPACES TAB
DBA_TAB_COLUMNS ALL_TAB_COLUMNS USER_TAB_COLUMNS
DBA_TAB_COLS ALL_TAB_COLS USER_TAB_COLS
DBA_TAB_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS
DBA_TAB_HISTOGRAMS ALL_TAB_HISTOGRAMS USER_TAB_HISTOGRAMS
DBA_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS
DBA_TAB_PARTITIONS ALL_TAB_PARTITIONS USER_TAB_PARTITIONS
Here is a cool feature I discovered recently, I tried this on the console and it seems to work:
var text = "border-bottom-left-radius";
var newText = text.replace(/-/g,function(match, index){
return " " + index + " ";
});
Which returned: "border 6 bottom 13 left 18 radius"
So this seems to be what you are looking for.
In my case, it wasn't working because I had added only one folder of the monorepo to the project, even though I had the package.json
and the extension configured. I worked only when I added the whole project (which contained the package.json
file) to the VS Code.
DONT: This is not a solution!
My first approach was:
public int longToInt(long theLongOne) {
return Long.valueOf(theLongOne).intValue();
}
But that merely just casts the long to an int, potentially creating new Long
instances or retrieving them from the Long pool.
The drawbacks
Long.valueOf
creates a new Long
instance if the number is not within Long
's pool range [-128, 127].
The intValue
implementation does nothing more than:
return (int)value;
So this can be considered even worse than just casting the long
to int
.
For secure HTTPS
<meta property="og:image:secure_url" content="https://image.path.png" />
EDIT (removed wrong solution). EDIT (to add this other option):
Another way to use it would be subclass QThread since it has protected *sleep methods.
QThread::usleep(unsigned long microseconds);
QThread::msleep(unsigned long milliseconds);
QThread::sleep(unsigned long second);
Here's the code to create your own *sleep method.
#include <QThread>
class Sleeper : public QThread
{
public:
static void usleep(unsigned long usecs){QThread::usleep(usecs);}
static void msleep(unsigned long msecs){QThread::msleep(msecs);}
static void sleep(unsigned long secs){QThread::sleep(secs);}
};
and you call it by doing this:
Sleeper::usleep(10);
Sleeper::msleep(10);
Sleeper::sleep(10);
This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.
Step by step instructions:
I'm assuming you're using express
, given the logs you have in your question. The key is to set the timeout
property on server (the following sets the timeout to one second, use whatever value you want):
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;
If you're not using express and are only working with vanilla node, the principle is the same. The following will not return data:
var http = require('http');
var server = http.createServer(function (req, res) {
setTimeout(function() {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}, 200);
}).listen(1337, '127.0.0.1');
server.timeout = 20;
console.log('Server running at http://127.0.0.1:1337/');
Now Junit5 provides a way to assert the exceptions
You can test both general exceptions and customized exceptions
A general exception scenario:
ExpectGeneralException.java
public void validateParameters(Integer param ) {
if (param == null) {
throw new NullPointerException("Null parameters are not allowed");
}
}
ExpectGeneralExceptionTest.java
@Test
@DisplayName("Test assert NullPointerException")
void testGeneralException(TestInfo testInfo) {
final ExpectGeneralException generalEx = new ExpectGeneralException();
NullPointerException exception = assertThrows(NullPointerException.class, () -> {
generalEx.validateParameters(null);
});
assertEquals("Null parameters are not allowed", exception.getMessage());
}
You can find a sample to test CustomException here : assert exception code sample
ExpectCustomException.java
public String constructErrorMessage(String... args) throws InvalidParameterCountException {
if(args.length!=3) {
throw new InvalidParameterCountException("Invalid parametercount: expected=3, passed="+args.length);
}else {
String message = "";
for(String arg: args) {
message += arg;
}
return message;
}
}
ExpectCustomExceptionTest.java
@Test
@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
final ExpectCustomException expectEx = new ExpectCustomException();
InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
expectEx.constructErrorMessage("sample ","error");
});
assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
}
To convert your object
in JSON with Jackson:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
You can use BETWEEN
:
DELETE FROM table
where id between 163 and 265
You can use xp_dirtree
It takes three parameters:
Path of a Root Directory, Depth up to which you want to get files and folders and the last one is for showing folders only or both folders and files.
EXAMPLE: EXEC xp_dirtree 'C:\', 2, 1
In my case the problem was the line with default instructions in switch block:
handlePageChange = ({ btnType}) => {
let { page } = this.state;
switch (btnType) {
case 'next':
this.updatePage(page + 1);
break;
case 'prev':
this.updatePage(page - 1);
break;
default: null;
}
}
Instead of
default: null;
The line
default: ;
worked for me.
int i = 0;
while(rs.next()) {
i++;
}
If you are looking for a one-size-fits-all, I'd suggest DECIMAL(19, 4)
is a popular choice (a quick Google bears this out). I think this originates from the old VBA/Access/Jet Currency data type, being the first fixed point decimal type in the language; Decimal
only came in 'version 1.0' style (i.e. not fully implemented) in VB6/VBA6/Jet 4.0.
The rule of thumb for storage of fixed point decimal values is to store at least one more decimal place than you actually require to allow for rounding. One of the reasons for mapping the old Currency
type in the front end to DECIMAL(19, 4)
type in the back end was that Currency
exhibited bankers' rounding by nature, whereas DECIMAL(p, s)
rounded by truncation.
An extra decimal place in storage for DECIMAL
allows a custom rounding algorithm to be implemented rather than taking the vendor's default (and bankers' rounding is alarming, to say the least, for a designer expecting all values ending in .5 to round away from zero).
Yes, DECIMAL(24, 8)
sounds like overkill to me. Most currencies are quoted to four or five decimal places. I know of situations where a decimal scale of 8 (or more) is required but this is where a 'normal' monetary amount (say four decimal places) has been pro rata'd, implying the decimal precision should be reduced accordingly (also consider a floating point type in such circumstances). And no one has that much money nowadays to require a decimal precision of 24 :)
However, rather than a one-size-fits-all approach, some research may be in order. Ask your designer or domain expert about accounting rules which may be applicable: GAAP, EU, etc. I vaguely recall some EU intra-state transfers with explicit rules for rounding to five decimal places, therefore using DECIMAL(p, 6)
for storage. Accountants generally seem to favour four decimal places.
PS Avoid SQL Server's MONEY
data type because it has serious issues with accuracy when rounding, among other considerations such as portability etc. See Aaron Bertrand's blog.
Microsoft and language designers chose banker's rounding because hardware designers chose it [citation?]. It is enshrined in the Institute of Electrical and Electronics Engineers (IEEE) standards, for example. And hardware designers chose it because mathematicians prefer it. See Wikipedia; to paraphrase: The 1906 edition of Probability and Theory of Errors called this 'the computer's rule' ("computers" meaning humans who perform computations).
I liked the "START /W" answer, though for my situation I found something even more basic. My processes were console applications. And in my ignorance I thought I would need something special in BAT syntax to make sure that the 1st one completed before the 2nd one started. However BAT appears to make a distinction between console apps and windows apps, and it executes them a little differently. The OP shows that window apps will get launched as an asynchronous call from BAT. But for console apps, that are invoked synchronously, inside the same command window as the BAT itself is running in.
For me it was actually better not to use "START /W", because everything could run inside one command window. The annoying thing about "START /W" is that it will spawn a new command window to execute your console application in.
It seems that your project is written in Python < 3. This is because the file()
builtin function is removed in Python 3. Try using Python 2to3 tool or edit the erroneous file yourself.
EDIT: BTW, the project page clearly mentions that
Gunicorn requires Python 2.x >= 2.5. Python 3.x support is planned.
Query all users and filter by the list from your text file:
$Users = Get-Content 'C:\scripts\Users.txt'
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users -contains $_.SamAccountName } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
Get-ADUser -Filter '*'
returns all AD user accounts. This stream of user objects is then piped into a Where-Object
filter, which checks for each object if its SamAccountName
property is contained in the user list from your input file ($Users
). Only objects with a matching account name are passed forward to the next step of the pipeline. The output can be limited by selecting the relevant properties before exporting the data.
You can further optimize the code by replacing the -contains
operator with hashtable lookups:
$Users = @{}
Get-Content 'C:\scripts\Users.txt' | ForEach-Object { $Users[$_] = $true }
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users.ContainsKey($_.SamAccountName) } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
viewDidLoad()
—Called when the view controller’s content view (the top of its view hierarchy) is created and loaded from a storyboard. … Use this method to perform any additional setup required by your view controller.
viewWillAppear()
—Called just before the view controller’s content view is added to the app’s view hierarchy. Use this method to trigger any operations that need to occur before the content view is presented onscreen
viewDidAppear()
—Called just after the view controller’s content view has been added to the app’s view hierarchy. Use this method to trigger any operations that need to occur as soon as the view is presented onscreen, such as fetching data or showing an animation.
viewWillDisappear()
—Called just before the view controller’s content view is removed from the app’s view hierarchy. Use this method to perform cleanup tasks like committing changes or resigning the first responder status.
viewDidDisappear()
—Called just after the view controller’s content view has been removed from the app’s view hierarchy. Use this method to perform additional teardown activities.
If you have a budget for your IDE, you should give Wingware Professional a try, see wingware.com .
There is no BI project in Visual Studio. Youll need to download SSDT. SSDT 2017 works fine :)
https://docs.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt
Let me reiterate what @Chase recommended: Use XLConnect.
The reasons for using XLConnect are, in my opinion:
XLConnect is somewhat new compared to other solutions so it is less frequently mentioned in blog posts and reference docs. For me it's been very useful.
The way to approach this is to tell the tableView to remove and add rows and sections with the
insertRowsAtIndexPaths:withRowAnimation:
,
deleteRowsAtIndexPaths:withRowAnimation:
,
insertSections:withRowAnimation:
and
deleteSections:withRowAnimation:
methods of UITableView.
When you call these methods, the table will animate in/out the items you requested, then call reloadData on itself so you can update the state after this animation. This part is important - if you animate away everything but don't change the data returned by the table's dataSource, the rows will appear again after the animation completes.
So, your application flow would be:
[self setTableIsInSecondState:YES];
[myTable deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:YES]];
As long as your table's dataSource methods return the correct new set of sections and rows by checking [self tableIsInSecondState]
(or whatever), this will achieve the effect you're looking for.
Use the tee
command:
echo "hello" | tee logfile.txt
-f is the correct flag, but for the test operator, not rm
[ -f "$THEFILE" ] && rm "$THEFILE"
this ensures that the file exists and is a regular file (not a directory, device node etc...)
Directly using scanf(3)
and its variants poses a number of problems. Typically, users and non-interactive use cases are defined in terms of lines of input. It's rare to see a case where, if enough objects are not found, more lines will solve the problem, yet that's the default mode for scanf. (If a user didn't know to enter a number on the first line, a second and third line will probably not help.)
At least if you fgets(3)
you know how many input lines your program will need, and you won't have any buffer overflows...
You can refer to event modifiers in vuejs to prevent form submission on enter
key.
It is a very common need to call
event.preventDefault()
orevent.stopPropagation()
inside event handlers.Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.
To address this problem, Vue provides event modifiers for
v-on
. Recall that modifiers are directive postfixes denoted by a dot.
<form v-on:submit.prevent="<method>">
...
</form>
As the documentation states, this is syntactical sugar for e.preventDefault()
and will stop the unwanted form submission on press of enter key.
Here is a working fiddle.
new Vue({_x000D_
el: '#myApp',_x000D_
data: {_x000D_
emailAddress: '',_x000D_
log: ''_x000D_
},_x000D_
methods: {_x000D_
validateEmailAddress: function(e) {_x000D_
if (e.keyCode === 13) {_x000D_
alert('Enter was pressed');_x000D_
} else if (e.keyCode === 50) {_x000D_
alert('@ was pressed');_x000D_
} _x000D_
this.log += e.key;_x000D_
},_x000D_
_x000D_
postEmailAddress: function() {_x000D_
this.log += '\n\nPosting';_x000D_
},_x000D_
noop () {_x000D_
// do nothing ?_x000D_
}_x000D_
}_x000D_
})
_x000D_
html, body, #editor {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
<form v-on:submit.prevent="noop">_x000D_
<input type="text" v-model="emailAddress" v-on:keyup="validateEmailAddress" />_x000D_
<button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
<br /><br />_x000D_
_x000D_
<textarea v-model="log" rows="4"></textarea> _x000D_
</form>_x000D_
</div>
_x000D_
Check the following Function for date comparison first of all create two NSDate objects and pass to the function: Add the bellow lines of code in viewDidload or according to your scenario.
-(void)testDateComaparFunc{
NSString *getTokon_Time1 = @"2016-05-31 03:19:05 +0000";
NSString *getTokon_Time2 = @"2016-05-31 03:18:05 +0000";
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate *tokonExpireDate1=[dateFormatter dateFromString:getTokon_Time1];
NSDate *tokonExpireDate2=[dateFormatter dateFromString:getTokon_Time2];
BOOL isTokonValid = [self dateComparision:tokonExpireDate1 andDate2:tokonExpireDate2];}
here is the function
-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{
BOOL isTokonValid;
if ([date1 compare:date2] == NSOrderedDescending) {
//"date1 is later than date2
isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
//date1 is earlier than date2
isTokonValid = NO;
} else {
//dates are the same
isTokonValid = NO;
}
return isTokonValid;}
Simply change the date and test above function :)
drawnonward's code is very close, but collides with UIKit's namespace and could be made easier to use.
@interface KeyboardStateListener : NSObject {
BOOL _isVisible;
}
+ (KeyboardStateListener *)sharedInstance;
@property (nonatomic, readonly, getter=isVisible) BOOL visible;
@end
static KeyboardStateListener *sharedInstance;
@implementation KeyboardStateListener
+ (KeyboardStateListener *)sharedInstance
{
return sharedInstance;
}
+ (void)load
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
sharedInstance = [[self alloc] init];
[pool release];
}
- (BOOL)isVisible
{
return _isVisible;
}
- (void)didShow
{
_isVisible = YES;
}
- (void)didHide
{
_isVisible = NO;
}
- (id)init
{
if ((self = [super init])) {
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(didShow) name:UIKeyboardDidShowNotification object:nil];
[center addObserver:self selector:@selector(didHide) name:UIKeyboardWillHideNotification object:nil];
}
return self;
}
@end
You need install Queuelib
either via the Python Package Index (PyPI)
or from source.
To install using pip:-
$ pip install queuelib
To install using easy_install:-
$ easy_install queuelib
If you have downloaded a source tarball you can install it by running the following (as root):-
python setup.py install
It would be best to have a TIMESTAMP
column that defaults to CURRENT_TIMESTAMP
.. it is the only true predictive behavior you can find here.
The second-best thing you can do is ORDER BY ID DESC LIMIT 1
and hope the newest ID is the largest value.
Try this below code it is also works well in angular 2
<span>{{current_date | date: 'yyyy-MM-dd'}}</span>
None of the above answers worked for me in ansible 2.3.0.0, but the following does:
when: variable1 | search("value")
In ansible 2.9 this is deprecated in favor of using ~ concatenation for variable replacement:
when: "variable1.find('v=' ~ value) == -1"
http://jinja.pocoo.org/docs/dev/templates/#other-operators
Other options:
when: "inventory_hostname in groups[sync_source]"
Are you sure you are in bash? Works for me, all four ways:
echo -e "Hello\nworld"
echo -e 'Hello\nworld'
echo Hello$'\n'world
echo Hello ; echo world
Solution:
ul {
font-size: 0;
}
ul li {
font-size: 14px;
display: inline-block;
}
You must set parent font size to 0
I've gotten same problem. The servers logs showed:
DEBUG: <-- origin: null
I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine
I am new to AJAX and I have tried this and it works well.
function q1mrks(country,m) {
// alert("hellow");
if (country.length==0) {
//alert("hellow");
document.getElementById("q1mrks").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("q1mrks").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../location/cal_marks.php?q1mrks="+country+"&marks="+m,true);
//mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
xmlhttp.send();
}
>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True
So it doesn't matter, they are all the same value.
The only reason all three modules provide a pi
value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.
To dump a database into an SQL file use the following command.
mysqldump -u username -p database_name > database_name.sql
To import an SQL file into a database (make sure you are in the same directory as the SQL file or supply the full path to the file), do:
mysql -u username -p database_name < database_name.sql
Open Source: CMU Sphinx
Shareware: http://www.e-speaking.com/ (Windows)
Commercial: Dragon NaturallySpeaking (Windows)
first, check that the array actually exists, you could try something like
if (isset($votes)) {
// Do bad things to the votes array
}
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:
All the results were as expected.
Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.
My example files follow:
EXTERNAL JS:
var global = 0;
function f1()
{
alert('fired: f1');
global = 1;
alert('global changed to 1');
}
function f2()
{
alert('fired f2');
alert('value of global: '+global);
}
HTML 1:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
HTML 2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
Assuming the file exists and you just need to update the timestamp.
type test.c > test.c.bkp && type test.c.bkp > test.c && del test.c.bkp
You've got several options how to do this, either:
urlencode()
or rawurlencode()
- functions designed to encode URLs for http protocolstr_replace()
- "heavy machinery" string replacestrtr()
- would have better performance than str_replace()
when replacing multiple characterspreg_replace()
use regular expressions (perl compatible)strtr()
Assuming that you want to replace "\t"
and " "
with "%20"
:
$replace_pairs = array(
"\t" => '%20',
" " => '%20',
);
return strtr( $text, $replace_pairs)
preg_replace()
You've got few options here, either replacing just space ~ ~
, again replacing space and tab ~[ \t]~
or all kinds of spaces ~\s~
:
return preg_replace( '~\s~', '%20', $text);
Or when you need to replace string like this "\t \t \t \t"
with just one %20
:
return preg_replace( '~\s+~', '%20', $text);
I assumed that you really want to use manual string replacement and handle more types of whitespaces such as non breakable space (
)
A list
is immutable
by Default
, you can use ArrayList
instead. like this :
val orders = arrayListOf<String>()
then you can add/delete
items from this like below:
orders.add("Item 1")
orders.add("Item 2")
by default
ArrayList
ismutable
so you can perform the operations on it.
Well, you need to look at the answers above, but you'll find that the manager app requires you to have a user with the role 'manager', I believe, so you'll probably want to add the following to your tomcat-users.xml file:
<role rolename="manager"/>
<user username="youruser" password="yourpass" roles="manager"/>
This might seem simplistic, but it's just a simple implementation that you can extend / replace with other authentication mechanisms.
Struggled with this - Have both openstreet map and google street map and wanted to project an external graphic image
var map = new OpenLayers.Map({
div:"map-id",
allOverlays: true
});
var osm = new OpenLayers.Layer.OSM("OpenStreeMao");
var gmap = new OpenLayers.Layer.Google("Google Streets", {visibility: false});
map.addLayers([osm,gmap]);
var vectorLayer = new OpenLayers.Layer.Vector("IconLayer");
var lonlatObject = new OpenLayers.LonLat(24.938622,60.170421).transform(
new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()
);
console.log(lonlatObject);
var point = new OpenLayers.Geometry.Point(lonlatObject.lon, lonlatObject.lat);
console.log(point);
var point2 = new OpenLayers.Geometry.Point(lonlatObject.x, lonlatObject.y);
console.log(point2);
var feature = new OpenLayers.Feature.Vector(point, null, {
externalGraphic: "http://cdn1.iconfinder.com/data/icons/SUPERVISTA/networking/png/72/antenna.png",
graphicWidth: 72,
graphicHeight: 72,
fillOpacity: 1
});
vectorLayer.addFeatures(feature);
map.addLayer(vectorLayer);
map.setCenter(
new OpenLayers.LonLat(24.938622,60.170421).transform(
new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()
),
12);
map.addControl(new OpenLayers.Control.LayerSwitcher());
The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)
So, listening to popstate
event and sending a popstate
event when using history.pushState()
should be enough to take action on href
change:
window.addEventListener('popstate', listener);
const pushUrl = (href) => {
history.pushState({}, '', href);
window.dispatchEvent(new Event('popstate'));
};
You can either use javascript url form with
<form action="javascript:handleClick()">
Or use onSubmit event handler
<form onSubmit="return handleClick()">
In the later form, if you return false from the handleClick it will prevent the normal submision procedure. Return true if you want the browser to follow normal submision procedure.
Your onSubmit event handler in the button also fails because of the Javascript:
part
EDIT: I just tried this code and it works:
<html>
<head>
<script type="text/javascript">
function handleIt() {
alert("hello");
}
</script>
</head>
<body>
<form name="myform" action="javascript:handleIt()">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>
Cocos2d-x within uikit tutorial http://jpsarda.tumblr.com/post/24983791554/mixing-cocos2d-x-uikit
i made a little change to this code to save entry of a radio button but unable to save the text which appears in text box after selecting the radio button.
the code is below:-
<!DOCTYPE html>
<html>
<head>
<style>
form * {
display: block;
margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="name" value="test.txt">
<textarea rows=3 cols=50 name="text">PLEASE WRITE ANSWER HERE. </textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
<input type="submit" value="SAVE">
</form>
</body>
</html>
I do not like referring to the number, the sybolic name is much more expressive and avoid having to add a comment that could become obsolete over time.
So I'd rather do:
#pylint: disable-msg=too-many-arguments
And I would also recommend to not leave it dangling there: it will stay active until the file ends or it is disabled, whichever comes first.
So better doing:
#pylint: disable-msg=too-many-arguments
code_which_would_trigger_the_msg
#pylint: enable-msg=too-many-arguments
I would also recommend enabling/disabling one single warning/error per line.
Before, this could be downloaded with streamlink but YouTube changed HLS rewinding with DASH. Therefore the way to do it below (that Prashant Adlinge commented) no longer works for YouTube:
streamlink --hls-live-restart STREAMURL best
More info here
The problem with SQL injection is, that a user input is used as part of the SQL statement. By using prepared statements you can force the user input to be handled as the content of a parameter (and not as a part of the SQL command).
But if you don't use the user input as a parameter for your prepared statement but instead build your SQL command by joining strings together, you are still vulnerable to SQL injections even when using prepared statements.
BEGIN
-END
blocks are the building blocks of PL/SQL, and each PL/SQL unit is contained within at least one such block. Nesting BEGIN
-END
blocks within PL/SQL blocks is usually done to trap certain exceptions and handle that special exception and then raise unrelated exceptions. Nevertheless, in PL/SQL you (the client) must always issue a commit or rollback for the transaction.
If you wish to have atomic transactions within a PL/SQL containing transaction, you need to declare a PRAGMA AUTONOMOUS_TRANSACTION
in the declaration block. This will ensure that any DML within that block can be committed or rolledback independently of the containing transaction.
However, you cannot declare this pragma for nested blocks. You can only declare this for:
Reference: Oracle
In that example, e
is just a parameter for that function, but it's the event
object that gets passed in through it.
func.__code__.co_argcount
gives you number of any arguments BEFORE *args
func.__kwdefaults__
gives you a dict of the keyword arguments AFTER *args
func.__code__.co_kwonlyargcount
is equal to len(func.__kwdefaults__)
func.__defaults__
gives you the values of optional arguments that appear before *args
Here is the simple illustration:
>>> def a(b, c, d, e, f=1, g=3, h=None, *i, j=2, k=3, **L):
pass
>>> a.__code__.co_argcount
7
>>> a.__defaults__
(1, 3, None)
>>> len(a.__defaults__)
3
>>>
>>>
>>> a.__kwdefaults__
{'j': 2, 'k': 3}
>>> len(a.__kwdefaults__)
2
>>> a.__code__.co_kwonlyargcount
2
To reference an element by id, you need to use the #
qualifier.
Try:
alert($("#link1").text());
To replace it, you could use:
$("#link1").text('New text');
The .html()
function would work in this case too.
Since NumPy version 1.16, for more details see GitHub ticket 12251.
from sys import maxsize
from numpy import set_printoptions
set_printoptions(threshold=maxsize)
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
Have you tried changing the wrapper height to vh instead of %?
#wrapper {
width:300px;
height:100vh;
}
That worked great for me when I wanted to fill my page with a gradient background for instance...
PDB is an abbreviation for Program Data Base. As the name suggests, it is a repository (persistent storage such as databases) to maintain information required to run your program in debug mode. It contains many important relevant information required while you debug your code (in Visual Studio), for e.g. at what points you have inserted break points where you expect the debugger to break in Visual Studio.
This is the reason why many times Visual Studio fails to hit the break points if you remove the *.pdb
files from your debug folders. Visual Studio debugger is also able to tell you the precise line number of code file at which an exception occurred in a stack trace with the help of *.pdb
files. So effectively pdb files are really a boon to developers while debugging a program.
Generally it is not recommended to exclude the generation of *.pdb
files. From production release stand-point what you should be doing is create the pdb files but don't ship them to customer site in product installer. Preserve all the generated PDB files on to a symbol server from where it can be used/referenced in future if required. Specially for cases when you debug issues like process crash. When you start analysing the crash dump files and if your original *.pdb
files created during the build process are not preserved then Visual Studio will not be able to make out the exact line of code which is causing crash.
If you still want to disable generation of *.pdb
files altogether for any release then go to properties of the project -> Build Tab -> Click on Advanced button -> Choose none
from "Debug Info" drop-down box -> press OK as shown in the snapshot below.
Note: This setting will have to be done separately for "Debug" and "Release" build configurations.
So for example:
$ docker build -t <your username>/node-web-app .
It's a bit hidden, but if you pay attention to the .
at the end...
Use log4j in your java program instead. Then you can output to multiple media, create rolling logs, etc. and include timestamps, class names and line numbers.
Commands
git fetch --all
git checkout -b <ur_new_local_branch_name> origin/<Remote_Branch_Name>
are equal to
git fetch --all
and then
git checkout -b fixes_for_dev origin/development
Both will create a latest fixes_for_dev
from development
I found a easy solution: make the tag " li "be inside the tag " a ":
<a href="#"><li>Something1</li></a>
Oct. 2008:
I would recommend to cache it in a static variable:
public static final class OsUtils
{
private static String OS = null;
public static String getOsName()
{
if(OS == null) { OS = System.getProperty("os.name"); }
return OS;
}
public static boolean isWindows()
{
return getOsName().startsWith("Windows");
}
public static boolean isUnix() // and so on
}
That way, every time you ask for the Os, you do not fetch the property more than once in the lifetime of your application.
February 2016: 7+ years later:
There is a bug with Windows 10 (which did not exist at the time of the original answer).
See "Java's “os.name” for Windows 10?"
I had this annoying issue since I upgraded my VS 2019 to 16.4.3 and caused me a lot of headache.
Finally I solved the problem this way:
1. Stop Debugging
2. Select the solution from "Solution Explorer"
3. In the Properties window change the "Active config" Property From "Release|Any CPU" To "Debug|Any CPU"
4. In Debug > Options > General Check the Edit and Continue checkbox
That worked for me, and hope it works for you too.
From this thread:
import os
os.system("import -window root temp.png")
Hi you can download using boto3. In python
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Table')
response = table.scan()
items = response['Items']
while 'LastEvaluatedKey' in response:
print(response['LastEvaluatedKey'])
response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
items.extend(response['Items'])
1. Inspect the page with the svg on.
2. Click on the link that displays the imagine in full resolution.
3. Do CMD/CTRL+S
4. You are done!
This is my way to setup Servlet as welcome page.
I share for whom concern.
web.xml
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Demo</servlet-name>
<servlet-class>servlet.Demo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
Servlet class
@WebServlet(name = "/demo")
public class Demo extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
}
}
You can also use str.partition
:
>>> text = "123mango abcd mango kiwi peach"
>>> text.partition("mango")
('123', 'mango', ' abcd mango kiwi peach')
>>> text.partition("mango")[-1]
' abcd mango kiwi peach'
>>> text.partition("mango")[-1].lstrip() # if whitespace strip-ing is needed
'abcd mango kiwi peach'
The advantage of using str.partition
is that it's always gonna return a tuple in the form:
(<pre>, <separator>, <post>)
So this makes unpacking the output really flexible as there's always going to be 3 elements in the resulting tuple.
I know this is old, but I have to add this in here..
And while this is not a full answer, it is an 'IN ADDITION TO'
The address bar will not disappear if you're NOT using https.
ALSO
If you are using https and the address bar still won't hide, you might have some https errors in your webpage (such as certain images being served from a non-https location.)
Hope this helps..
You will need InternetExplorer driver executable on your system. So download it from the hinted source (http://www.seleniumhq.org/download/) unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe
Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:
File file = new File("C:/Selenium/iexploredriver.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();
Basically, you have to set this property before you initialize driver
You can use the File.deleteOnExit()
method
https://developer.android.com/reference/java/io/File.html#deleteOnExit()
It is referenced here https://developer.android.com/reference/java/io/File.html#createTempFile(java.lang.String, java.lang.String, java.io.File)
var defaultSettings = {
ajaxsettings: {},
uisettings: {}
};
Take a look at this site: http://www.json.org/
Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.
A checksum comparison will most likely be slower than a byte-by-byte comparison.
In order to generate a checksum, you'll need to load each byte of the file, and perform processing on it. You'll then have to do this on the second file. The processing will almost definitely be slower than the comparison check.
As for generating a checksum: You can do this easily with the cryptography classes. Here's a short example of generating an MD5 checksum with C#.
However, a checksum may be faster and make more sense if you can pre-compute the checksum of the "test" or "base" case. If you have an existing file, and you're checking to see if a new file is the same as the existing one, pre-computing the checksum on your "existing" file would mean only needing to do the DiskIO one time, on the new file. This would likely be faster than a byte-by-byte comparison.
Collection<Map<Item, Integer>> itemCollection = basket.values();
Iterator<Map<Item, Integer>> itemIterator = itemCollection.stream().sorted(new TestComparator()).collect(Collectors.toList()).iterator();
package com.ie.util;
import com.ie.item.Item;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TestComparator implements Comparator<Map<Item, Integer>> {
// comparator is used to sort the Items based on the price
@Override
public int compare(Map<Item, Integer> o1, Map<Item, Integer> o2) {
// System.out.println("*** compare method will be called *****");
Item item1 = null;
Item item2 = null;
Set<Item> itemSet1 = o1.keySet();
Iterator<Item> itemIterator1 = itemSet1.iterator();
if(itemIterator1.hasNext()){
item1 = itemIterator1.next();
}
Set<Item> itemSet2 = o2.keySet();
Iterator<Item> itemIterator2 = itemSet2.iterator();
if(itemIterator2.hasNext()){
item2 = itemIterator2.next();
}
return -item1.getPrice().compareTo(item2.getPrice());
}
}
**** this is helpful to sort the nested map objects like Map> here i sorted based on the Item object price .
Manually resolving instances involves using the IServiceProvider
interface:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMyService, MyService>();
var serviceProvider = services.BuildServiceProvider();
var service = serviceProvider.GetService<IMyService>();
}
public void Configure(
IApplicationBuilder application,
IServiceProvider serviceProvider)
{
// By type.
var service1 = (MyService)serviceProvider.GetService(typeof(MyService));
// Using extension method.
var service2 = serviceProvider.GetService<MyService>();
// ...
}
public void Configure(
IApplicationBuilder application,
IWebHostEnvironment webHostEnvironment)
{
application.ApplicationServices.GetService<MyService>();
}
Some types can be injected as method parameters:
public class Startup
{
public Startup(
IHostingEnvironment hostingEnvironment,
ILoggerFactory loggerFactory)
{
}
public void ConfigureServices(
IServiceCollection services)
{
}
public void Configure(
IApplicationBuilder application,
IHostingEnvironment hostingEnvironment,
IServiceProvider serviceProvider,
ILoggerFactory loggerfactory,
IApplicationLifetime applicationLifetime)
{
}
}
[HttpGet("/some-action")]
public string SomeAction([FromServices] IMyService myService) => "Hello";
# This keeps all separators in result
##########################################################################
import re
st="%%(c+dd+e+f-1523)%%7"
sh=re.compile('[\+\-//\*\<\>\%\(\)]')
def splitStringFull(sh, st):
ls=sh.split(st)
lo=[]
start=0
for l in ls:
if not l : continue
k=st.find(l)
llen=len(l)
if k> start:
tmp= st[start:k]
lo.append(tmp)
lo.append(l)
start = k + llen
else:
lo.append(l)
start =llen
return lo
#############################
li= splitStringFull(sh , st)
['%%(', 'c', '+', 'dd', '+', 'e', '+', 'f', '-', '1523', ')%%', '7']
What your looking for is Reverse Geo Coding. Have a look at this example here. https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
For exporting html to csv try following this example. More details and examples are available at the author's website.
Create a html2csv.js file and put the following code in it.
jQuery.fn.table2CSV = function(options) {
var options = jQuery.extend({
separator: ',',
header: [],
delivery: 'popup' // popup, value
},
options);
var csvData = [];
var headerArr = [];
var el = this;
//header
var numCols = options.header.length;
var tmpRow = []; // construct header avalible array
if (numCols > 0) {
for (var i = 0; i < numCols; i++) {
tmpRow[tmpRow.length] = formatData(options.header[i]);
}
} else {
$(el).filter(':visible').find('th').each(function() {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
}
row2CSV(tmpRow);
// actual data
$(el).find('tr').each(function() {
var tmpRow = [];
$(this).filter(':visible').find('td').each(function() {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
row2CSV(tmpRow);
});
if (options.delivery == 'popup') {
var mydata = csvData.join('\n');
return popup(mydata);
} else {
var mydata = csvData.join('\n');
return mydata;
}
function row2CSV(tmpRow) {
var tmp = tmpRow.join('') // to remove any blank rows
// alert(tmp);
if (tmpRow.length > 0 && tmp != '') {
var mystr = tmpRow.join(options.separator);
csvData[csvData.length] = mystr;
}
}
function formatData(input) {
// replace " with “
var regexp = new RegExp(/["]/g);
var output = input.replace(regexp, "“");
//HTML
var regexp = new RegExp(/\<[^\<]+\>/g);
var output = output.replace(regexp, "");
if (output == "") return '';
return '"' + output + '"';
}
function popup(data) {
var generator = window.open('', 'csv', 'height=400,width=600');
generator.document.write('<html><head><title>CSV</title>');
generator.document.write('</head><body >');
generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
generator.document.write(data);
generator.document.write('</textArea>');
generator.document.write('</body></html>');
generator.document.close();
return true;
}
};
include the js files into the html page like this:
<script type="text/javascript" src="jquery-1.3.2.js" ></script>
<script type="text/javascript" src="html2CSV.js" ></script>
TABLE:
<table id="example1" border="1" style="background-color:#FFFFCC" width="0%" cellpadding="3" cellspacing="3">
<tr>
<th>Title</th>
<th>Name</th>
<th>Phone</th>
</tr>
<tr>
<td>Mr.</td>
<td>John</td>
<td>07868785831</td>
</tr>
<tr>
<td>Miss</td>
<td><i>Linda</i></td>
<td>0141-2244-5566</td>
</tr>
<tr>
<td>Master</td>
<td>Jack</td>
<td>0142-1212-1234</td>
</tr>
<tr>
<td>Mr.</td>
<td>Bush</td>
<td>911-911-911</td>
</tr>
</table>
EXPORT BUTTON:
<input value="Export as CSV 2" type="button" onclick="$('#example1').table2CSV({header:['prefix','Employee Name','Contact']})">
I didn't really like any of the solutions here for my particular use case, so I figured I'd post what I did because I didn't see it here.
I simply wanted to use a controller more like a directive, within a ng-repeat loop:
<div ng-repeat="objParameter in [{id:'a'},{id:'b'},{id:'c'}]">
<div ng-controller="DirectiveLikeController as ctrl"></div>
</div>
Now, in order to access the objParameter
on creation within each DirectiveLikeController (or to get the up-to-date objParameter at ANY time), all I need to do is inject $scope and call $scope.$eval('objParameter')
:
var app = angular.module('myapp', []);
app.controller('DirectiveLikeController',['$scope'], function($scope) {
//print 'a' for the 1st instance, 'b' for the 2nd instance, and 'c' for the 3rd.
console.log($scope.$eval('objParameter').id);
});
The only real downside that I see is that it requires the parent controller to know that the parameter is named objParameter
.
I would try to map a drive to the remote system (using 'net use' or WshNetwork.MapNetworkDrive, both methods support credentials) and then use copy-item.
The powerful command installs and replaces the last package.
I had a similar problem. I fixed it.
npm install -g @angular/cli@latest
and
npm install --save-dev @angular/cli@latest
public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button) findViewById(R.id.uploadButton);
messageText = (TextView) findViewById(R.id.messageText);
messageText.setText("Uploading file path :- '/mnt/sdcard/"
+ uploadFileName + "'");
/************* Php script path ****************/
upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";
uploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
uploadFile(uploadFilePath + "" + uploadFileName);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection connection = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
+ uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ uploadFilePath + "" + uploadFileName);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // Allow Inputs
connection.setDoOutput(true); // Allow Outputs
connection.setUseCaches(false); // Don't use a Cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
// dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
// + fileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ URLEncoder.encode(fileName, "UTF-8") + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " http://www.androidexample.com/media/uploads/"
+ uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
PHP FILE
<?php
$target_path = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Any of LinearLayout.LayoutParams
and TableLayout.LayoutParams
worked for me, for buttons the right one is TableRow.LayoutParams
. That is:
TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT, 1f);
About using MATCH_PARENT
or WRAP_CONTENT
be the same.
I encountered this error recently and after some brief investigation, found the cause to be that we were running out of space on the disk holding the database (less than 1GB).
As soon as I moved out the database files (.mdf and .ldf) to another disk on the same server (with lots more space), the same page (running the query) that had timed-out loaded within three seconds.
One other thing to investigate, while trying to resolve this error, is the size of the database log files. Your log files just might need to be shrunk.
10 minutes ago i had the same problem of place label above input
then i got a small ugly resolution
<form>
<h4><label for="male">Male</label></h4>
<input type="radio" name="sex" id="male" value="male">
</form>
The disadvantage is that there is a big blank space between the label and input, of course you can adjust the css
Demo at: http://jsfiddle.net/bqkawjs5/
This Worked for me
In Web.config add below script
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="WebDAVModule"/>
</modules>
<handlers accessPolicy="Read, Execute, Script">
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*."
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
_x000D_
Also in RouteConfig.cs
Change
settings.AutoRedirectMode = RedirectMode.Permanent;
To
settings.AutoRedirectMode = RedirectMode.Off;
Hope it helps you or some one :)
As mentioned above,
show procedure status;
Will indeed show a list of procedures, but shows all of them, server-wide.
If you want to see just the ones in a single database, try this:
SHOW PROCEDURE STATUS WHERE Db = 'databasename';
Below in Kotlin worked well for me:
(fromNumber.rangeTo(toNumber)).random()
Range of the numbers starts with variable fromNumber
and ends with variable toNumber
. fromNumber
and toNumber
will also be included in the random numbers generated out of this.
If you encounter the problem with missing MS VC 14 Build tools while trying pip install mysqlclient
a possible solution for this may be https://stackoverflow.com/a/51811349/1552410
Keep in mind that you have to wait until adapter will added to list, then you can try to getting view by position
final int i = 0;
recyclerView.setAdapter(adapter);
recyclerView.post(new Runnable() {
@Override
public void run() {
View view = recyclerView.getLayoutManager().findViewByPosition(i);
}
});
Well id
isn't really the root node: Login
is.
It should just be a case of specifying the attributes (not tags, btw) using XmlElement.SetAttribute
. You haven't specified how you're creating the file though - whether you're using XmlWriter, the DOM, or any other XML API.
If you could give an example of the code you've got which isn't working, that would help a lot. In the meantime, here's some code which creates the file you described:
using System;
using System.Xml;
class Test
{
static void Main()
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Login");
XmlElement id = doc.CreateElement("id");
id.SetAttribute("userName", "Tushar");
id.SetAttribute("passWord", "Tushar");
XmlElement name = doc.CreateElement("Name");
name.InnerText = "Tushar";
XmlElement age = doc.CreateElement("Age");
age.InnerText = "24";
id.AppendChild(name);
id.AppendChild(age);
root.AppendChild(id);
doc.AppendChild(root);
doc.Save("test.xml");
}
}
CodeIgniter returns result rows as objects, not arrays. From the user guide:
result()
This function returns the query result as an array of objects, or an empty array on failure.
You'll have to access the fields using the following notation:
foreach ($getvidids->result() as $row) {
$vidid = $row->videoid;
}
A slightly more robust method I needed to use recently:
- (void) dismissKeyboard {
NSArray *windows = [UIApplication sharedApplication].windows;
for(UIWindow *window in windows) [window endEditing:true];
// Or if you're only working with one UIWindow:
[[UIApplication sharedApplication].keyWindow endEditing:true];
}
I found some of the other "global" methods didn't work (for example, UIWebView
& WKWebView
refused to resign).
None of posted answers did work for me. I came with my own solution:
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
boolean keepOriginal = true;
StringBuilder sb = new StringBuilder(end - start);
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (isCharAllowed(c)) // put your condition here
sb.append(c);
else
keepOriginal = false;
}
if (keepOriginal)
return null;
else {
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(sb);
TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
return sp;
} else {
return sb;
}
}
}
private boolean isCharAllowed(char c) {
return Character.isLetterOrDigit(c) || Character.isSpaceChar(c);
}
}
editText.setFilters(new InputFilter[] { filter });
You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.
dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);
Check this
EDIT
As per the comment posted by Frank and Mat, you can also enable it with Null
exec dbms_output.enable(NULL);
buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
I'm answering because the previous answers have stopped working with the latest version of jQuery. I don't know when it stopped working, but the documentation says that .prop() has been the preferred method to get/set properties since jQuery 1.6.
This is how I got it to work (with jQuery 3.2.1):
$('select option:nth-child(1)').prop("selected", true);
I am using knockoutjs and the change bindings weren't firing with the above code, so I added .change() to the end.
Here's what I needed for my solution:
$('select option:nth-child(1)').prop("selected", true).change();
See .prop() notes in the documentation here: http://api.jquery.com/prop/
You need to use IFS
instead of -d
:
while IFS=, read -r col1 col2
do
echo "I got:$col1|$col2"
done < myfile.csv
Note that for general purpose CSV parsing you should use a specialized tool which can handle quoted fields with internal commas, among other issues that Bash can't handle by itself. Examples of such tools are cvstool
and csvkit
.
Simply You can do it
import time
delay=60*15 ###for 15 minutes delay
close_time=time.time()+delay
while True:
##bla bla
###bla bla
if time.time()>close_time
break
In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj)
in your ModelForm.save
override, as ModelForm.save
later populates your m2m from self.cleaned_data['my_m2m']
which overwrites your changes. Instead call:
my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms
(It is fine to convert the incoming QuerySet to a list - the ManyToManyField
does that anyway.)
If you add text-align: center
to the declarations for .columns-container
then they align centrally:
.columns-container {
display: table-cell;
height: 100%;
width:600px;
text-align: center;
}
/*************************_x000D_
* Sticky footer hack_x000D_
* Source: http://pixelsvsbytes.com/blog/2011/09/sticky-css-footers-the-flexible-way/_x000D_
************************/_x000D_
_x000D_
/* Stretching all container's parents to full height */_x000D_
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
/* Setting the container to be a table with maximum width and height */_x000D_
_x000D_
#container {_x000D_
display: table;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
/* All sections (container's children) should be table rows with minimal height */_x000D_
_x000D_
.section {_x000D_
display: table-row;_x000D_
height: 1px;_x000D_
}_x000D_
/* The last-but-one section should be stretched to automatic height */_x000D_
_x000D_
.section.expand {_x000D_
height: auto;_x000D_
}_x000D_
/*************************_x000D_
* Full height columns_x000D_
************************/_x000D_
_x000D_
/* We need one extra container, setting it to full width */_x000D_
_x000D_
.columns-container {_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
width:600px;_x000D_
text-align: center;_x000D_
}_x000D_
/* Creating columns */_x000D_
_x000D_
.column {_x000D_
/* The float:left won't work for Chrome for some reason, so inline-block */_x000D_
display: inline-block;_x000D_
/* for this to work, the .column elements should have NO SPACE BETWEEN THEM */_x000D_
vertical-align: top;_x000D_
height: 100%;_x000D_
width: 100px;_x000D_
}_x000D_
/****************************************************************_x000D_
* Just some coloring so that we're able to see height of columns_x000D_
****************************************************************/_x000D_
_x000D_
header {_x000D_
background-color: yellow;_x000D_
}_x000D_
#a {_x000D_
background-color: pink;_x000D_
}_x000D_
#b {_x000D_
background-color: lightgreen;_x000D_
}_x000D_
#c {_x000D_
background-color: lightblue;_x000D_
}_x000D_
footer {_x000D_
background-color: purple;_x000D_
}
_x000D_
<div id="container">_x000D_
<header class="section">_x000D_
foo_x000D_
</header>_x000D_
_x000D_
<div class="section expand">_x000D_
<div class="columns-container">_x000D_
<div class="column" id="a">_x000D_
<p>Contents A</p>_x000D_
</div>_x000D_
<div class="column" id="b">_x000D_
<p>Contents B</p>_x000D_
</div>_x000D_
<div class="column" id="c">_x000D_
<p>Contents C</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<footer class="section">_x000D_
bar_x000D_
</footer>_x000D_
</div>
_x000D_
This does, though, require that you reset the .column
elements to text-align: left
(assuming you want them left-aligned, obviously (JS Fiddle demo).
getDerivedStateFromProps is used whenever you want to update state before render and update with the condition of props
GetDerivedStateFromPropd updating the stats value with the help of props value