Generally and simply it works like this:
<script>_x000D_
$(document).ready(function () {_x000D_
$('i').click(function () {_x000D_
$(this).toggleClass('fa-plus-square fa-minus-square');_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
There are two (mostly used) types of timer function in javascript setTimeout
and setInterval
(other)
Both these methods have same signature. They take a call back function and delay time as parameter.
setTimeout
executes only once after the delay whereas setInterval
keeps on calling the callback function after every delay milisecs.
both these methods returns an integer identifier that can be used to clear them before the timer expires.
clearTimeout
and clearInterval
both these methods take an integer identifier returned from above functions setTimeout
and setInterval
Example:
alert("before setTimeout");
setTimeout(function(){
alert("I am setTimeout");
},1000); //delay is in milliseconds
alert("after setTimeout");
If you run the the above code you will see that it alerts before setTimeout
and then after setTimeout
finally it alerts I am setTimeout
after 1sec (1000ms)
What you can notice from the example is that the setTimeout(...)
is asynchronous which means it doesn't wait for the timer to get elapsed before going to next statement i.e alert("after setTimeout");
Example:
alert("before setInterval"); //called first
var tid = setInterval(function(){
//called 5 times each time after one second
//before getting cleared by below timeout.
alert("I am setInterval");
},1000); //delay is in milliseconds
alert("after setInterval"); //called second
setTimeout(function(){
clearInterval(tid); //clear above interval after 5 seconds
},5000);
If you run the the above code you will see that it alerts before setInterval
and then after setInterval
finally it alerts I am setInterval
5 times after 1sec (1000ms) because the setTimeout clear the timer after 5 seconds or else every 1 second you will get alert I am setInterval
Infinitely.
How browser internally does that?
I will explain in brief.
To understand that you have to know about event queue in javascript. There is a event queue implemented in browser. Whenever an event get triggered in js, all of these events (like click etc.. ) are added to this queue. When your browser has nothing to execute it takes an event from queue and executes them one by one.
Now, when you call setTimeout
or setInterval
your callback get registered to an timer in browser and it gets added to the event queue after the given time expires and eventually javascript takes the event from the queue and executes it.
This happens so, because javascript engine are single threaded and they can execute only one thing at a time. So, they cannot execute other javascript and keep track of your timer. That is why these timers are registered with browser (browser are not single threaded) and it can keep track of timer and add an event in the queue after the timer expires.
same happens for setInterval
only in this case the event is added to the queue again and again after the specified interval until it gets cleared or browser page refreshed.
Note
The delay parameter you pass to these functions is the minimum delay time to execute the callback. This is because after the timer expires the browser adds the event to the queue to be executed by the javascript engine but the execution of the callback depends upon your events position in the queue and as the engine is single threaded it will execute all the events in the queue one by one.
Hence, your callback may sometime take more than the specified delay time to be called specially when your other code blocks the thread and not giving it time to process what's there in the queue.
And as I mentioned javascript is single thread. So, if you block the thread for long.
Like this code
while(true) { //infinite loop
}
Your user may get a message saying page not responding.
I would suggest you use the below css
.showhideoverlay {
width: 100%;
height: 100%;
right: 0px;
top: 0px;
position: fixed;
background: #000;
opacity: 0.75;
}
You can then use a simple toggle function:
$('a.open').click(function() {
$('div.showhideoverlay').toggle("slow");
});
This will display the overlay menu from right to left. Alternatively, you can use the positioning for changing the effect from top or bottom, i.e. use bottom: 0;
instead of top: 0;
- you will see menu sliding from right-bottom corner.
See this: Demo
$('#cat_icon,.panel_title').click(function () {
$('#categories,#cat_icon').stop().slideToggle('slow');
});
Update : To slide from left to right: Demo2
Note: Second one uses jquery-ui also
Here is an example of how to do it with an arrow instead of a +
and -
. This uses jQuery
to change classes on the element, and CSS
to style the arrow.
$(".toggleHide").click(function() {_x000D_
$(".elementToHide").slideToggle("fast");_x000D_
$(this).find("i").toggleClass("down up");_x000D_
});
_x000D_
i {_x000D_
border: solid black;_x000D_
border-width: 0 5px 5px 0;_x000D_
display: inline-block;_x000D_
padding: 5px;_x000D_
-webkit-transition-duration: 1s;_x000D_
/* Safari */_x000D_
transition-duration: 1s;_x000D_
}_x000D_
_x000D_
.up {_x000D_
transform: rotate(-135deg);_x000D_
-webkit-transform: rotate(-135deg);_x000D_
}_x000D_
_x000D_
.down {_x000D_
transform: rotate(45deg);_x000D_
-webkit-transform: rotate(45deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<h3 class="toggleHide"><i class="down"></i></h3>_x000D_
<aside class="elementToHide">_x000D_
Content to hide_x000D_
</aside>
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js</script> <script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
</head>
<body>
<p>Welcome !!!</p>
<button>Toggle between hide() and show()</button>
</body>
</html>
After fixing a performance issue related to the use of .is(":visible"), I would recommend against the above answers and instead use jQuery's code for deciding whether a single element is visible:
$.expr.filters.visible($("#singleElementID")[0]);
What .is does is check whether a set of elements is within another set of elements. So you will looking for your element within the entire set of visible elements on your page. Having 100 elements is pretty normal and might take a few milliseconds to search through the array of visible elements. If you're building a web app you probably have hundreds or possibly thousands. Our app was sometimes taking 100ms for $("#selector").is(":visible") since it was checking if an element was in an array of 5000 other elements.
When I use this method on load page with jquery, I write $('#obj').off('click');
before set the click function, so the bubble not occurs. Works for me.
Try something like:
$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
event.preventDefault();
$(this).next('div').slideToggle(200);
});
Here is the page about that in the jQuery documentation
Yes, just like you did:
select something + somethingElse as onlyOneColumn from someTable
If you queried the database, you would have gotten the right answer.
What happens is you ask for an expression. A very simple expression is just a column name, a more complicated expression can have formulas etc in it.
Just run the main
method which is in the class SampleWebJspApplication
.
Spring Boot will take care of all the rest (starting the embedded tomcat which will host your sample application).
Just to show java 8's stance to remove null values.
String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
...
}
Makes sense if you can use Optional<String>
.
This is a method of the java.awt.Component
class. It is used to set the position and size of a component:
setBounds
public void setBounds(int x, int y, int width, int height)
Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. Parameters:
- x - the new x-coordinate of this component
- y - the new y-coordinate of this component
- width - the new width of this component
- height - the new height of this component
x
and y
as above correspond to the upper left corner in most (all?) cases.
It is a shortcut for setLocation
and setSize
.
This generally only works if the layout/layout manager are non-existent, i.e. null.
If you use
string temp = mystring.Replace("\r\n", "").Replace("\n", "");
then you won't have to worry about where your string is coming from.
$query = mysqli_query('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME IN ("table1","table2","table3") AND TABLE_SCHEMA="yourschema"');
$tablesExists = array();
while( null!==($row=mysqli_fetch_row($query)) ){
$tablesExists[] = $row[0];
}
it's file:///android_asset/... not file:///android_assets/... notice the plural of assets is wrong even if your file name is assets
Resorting to using .htaccess
to rewrite the URLs for static HTML is generally not only unnecessary, but also bad for you website's performance. Enabling .htaccess
is also an unnecessary security vulnerability - turning it off eliminates a significant number of potential issues. The same rules for each .htaccess
file can instead go in a <Directory>
section for that directory, and it will be more performant if you then set AllowOverride None
because it won't need to check each directory for a .htaccess
file, and more secure because an attacker can't change the vhost config without root access.
If you don't need .htaccess
in a VPS environment, you can disable it entirely and get better performance from your web server.
All you need to do is move your individual files from a structure like this:
index.html
about.html
products.html
terms.html
To a structure like this:
index.html
about/index.html
products/index.html
terms/index.html
Your web server will then render the appropriate pages - if you load /about/
, it will treat that as /about/index.html
.
This won't rewrite the URL if anyone visits the old one, though, so it would need redirects to be in place if it was retroactively applied to an existing site.
On Cygwin -mcmodel=medium
is already default and doesn't help. To me adding -Wl,--image-base -Wl,0x10000000
to GCC linker did fixed the error.
A simple question should be followed by a short, simple and clear answer.
When we are getting a value of the property it fires its get{}
part.
When we are setting a value to the property it fires its set{}
part.
PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{}
part.
Example:
var A:Int = 0
var B:Int = 0
var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
B = newValue
}
}
//When we are getting a value of C it fires get{} part of C property
A = C
A //Now A = 1
//When we are setting a value to C it fires set{} part of C property
C = 2
B //Now B = 2
It turns out I was missing the header information. The following works:
url = "http://localhost:8080"
data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
The correct syntax is:
FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
, LCASE( SUBSTRING( NEW.bname, 2 ) ) )
you can do it short like this:
matrix = [["A, B, C, D, E"]*5]
print(matrix)
[['A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E', 'A, B, C, D, E']]
According to the Java Language Specification (specifically §10.7 Array Members) it is a field:
- The
public
final
fieldlength
, which contains the number of components of the array (length may be positive or zero).
Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.
The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:
[...] arrays have a third header field, for the array size.
You need to add JQuery js before adding bootstrap js file, because BootStrap use jqueries function. So make sure to load first jquery js and then bootstap js file.
<!-- JQuery Core JavaScript -->
<script src="app/js/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="app/js/bootstrap.min.js"></script>
This error is probably related to a byte order mark (BOM) prior to the actual XML content. You need to parse the returned String and discard the BOM, so SAXParser can process the document correctly.
You will find a possible solution here.
For mass assignment of values to an ActiveRecord model without saving, use either the assign_attributes
or attributes=
methods. These methods are available in Rails 3 and newer. However, there are minor differences and version-related gotchas to be aware of.
Both methods follow this usage:
@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }
@user.attributes = { model: "Sierra", year: "2012", looks: "Sexy" }
Note that neither method will perform validations or execute callbacks; callbacks and validation will happen when save
is called.
attributes=
differs slightly from assign_attributes
in Rails 3. attributes=
will check that the argument passed to it is a Hash, and returns immediately if it is not; assign_attributes
has no such Hash check. See the ActiveRecord Attribute Assignment API documentation for attributes=
.
The following invalid code will silently fail by simply returning without setting the attributes:
@user.attributes = [ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ]
attributes=
will silently behave as though the assignments were made successfully, when really, they were not.
This invalid code will raise an exception when assign_attributes
tries to stringify the hash keys of the enclosing array:
@user.assign_attributes([ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ])
assign_attributes
will raise a NoMethodError
exception for stringify_keys
, indicating that the first argument is not a Hash. The exception itself is not very informative about the actual cause, but the fact that an exception does occur is very important.
The only difference between these cases is the method used for mass assignment: attributes=
silently succeeds, and assign_attributes
raises an exception to inform that an error has occurred.
These examples may seem contrived, and they are to a degree, but this type of error can easily occur when converting data from an API, or even just using a series of data transformation and forgetting to Hash[]
the results of the final .map
. Maintain some code 50 lines above and 3 functions removed from your attribute assignment, and you've got a recipe for failure.
The lesson with Rails 3 is this: always use assign_attributes
instead of attributes=
.
In Rails 4, attributes=
is simply an alias to assign_attributes
. See the ActiveRecord Attribute Assignment API documentation for attributes=
.
With Rails 4, either method may be used interchangeably. Failure to pass a Hash as the first argument will result in a very helpful exception: ArgumentError: When assigning attributes, you must pass a hash as an argument.
If you're pre-flighting assignments in preparation to a save
, you might be interested in validating before save, as well. You can use the valid?
and invalid?
methods for this. Both return boolean values. valid?
returns true if the unsaved model passes all validations or false if it does not. invalid?
is simply the inverse of valid?
valid?
can be used like this:
@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }.valid?
This will give you the ability to handle any validations issues in advance of calling save
.
null is for database and blank is for fields validation that you want to show on user interface like textfield to get the last name of person. If lastname=models.charfield (blank=true) it didnot ask user to enter last name as this is the optional field now. If lastname=models.charfield (null=true) then it means that if this field doesnot get any value from user then it will store in database as an empty string " ".
Beware that when the mounted
event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.
To really simulate the DOM onload
event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted
:
mounted: function () {
this.$nextTick(function () {
// Will be executed when the DOM is ready
})
}
you can use cURL library for posting data: http://www.php.net/curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);
where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects
After some experimentation I came up with this implementation:
$('.detect-change')
.on('change cut paste', function(e) {
console.log("Change detected.");
contentModified = true;
})
.keypress(function(e) {
if (e.which !== 0 && e.altKey == false && e.ctrlKey == false && e.metaKey == false) {
console.log("Change detected.");
contentModified = true;
}
});
Handles changes to any kind of input and select as well as textareas ignoring arrow keys and things like ctrl, cmd, function keys, etc.
Note: I've only tried this in FF since it's for a FF add-on.
jQuery Ajax loader is not working well when you call two APIs simultaneously. To resolve this problem you have to call the APIs one by one using the isAsync
property in Ajax setting. You also need to make sure that there should not be any error in the setting. Otherwise, the loader will not work. E.g undefined content-type, data-type for POST/PUT/DELETE/GET call.
I would install Microsoft Network Monitor, configure the tool so it would only see HTTP packets (filter the port) and start capturing packets.
You could download it here
I didn't have control over the security configuration for the service I was calling into, but got the same error. I was able to fix my client as follows.
In the config, set up the security mode:
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
In the code, set the proxy class to allow impersonation (I added a reference to a service called customer):
Customer_PortClient proxy = new Customer_PortClient();
proxy.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Impersonation;
if you're using php oop you might need to change to:
public static function cmp($a, $b)
{
return strcmp($a->name, $b->name);
}
//in this case FUNCTION_NAME would be cmp
usort($your_data, array('YOUR_CLASS_NAME','FUNCTION_NAME'));
I wanted the same thing; a delete button on my Details view. I eventually realised I needed to post from that view:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
@Html.ActionLink("Edit", "Edit", new { id = Model.Id }, new { @class = "btn btn-primary", @style="margin-right:30px" })
<input type="submit" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this record?');" />
}
And, in the Controller:
// this action deletes record - called from the Delete button on Details view
[HttpPost]
public ActionResult Details(MainPlus mainPlus)
{
if (mainPlus != null)
{
try
{
using (IDbConnection db = new SqlConnection(PCALConn))
{
var result = db.Execute("DELETE PCAL.Main WHERE Id = @Id", new { Id = mainPlus.Id });
}
return RedirectToAction("Calls");
} etc
If you're interested in making .xlsx (Office 2007 and beyond) files, you're in luck. Office 2007+ uses OpenXML which for lack of a more apt description is XML files inside of a zip named .xlsx
Take an excel file (2007+) and rename it to .zip, you can open it up and take a look. If you're using .NET 3.5 you can use the System.IO.Packaging library to manipulate the relationships & zipfile itself, and linq to xml to play with the xml (or just DOM if you're more comfortable).
Otherwise id reccomend DotNetZip, a powerfull library for manipulation of zipfiles.
OpenXMLDeveloper has lots of resources about OpenXML and you can find more there.
If you want .xls (2003 and below) you're going to have to look into 3rd party libraries or perhaps learn the file format yourself to achieve this without excel installed.
Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
Method from the jquery getJSON method by simply...
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
html
<div class="text-lg-right text-center">
center in xs and right in lg devices
</div>
Improved version of Komang answer (add referer and user agent, check if you can write the file), return true if it's ok, false if there is an error :
public function downloadImage($url,$filename){
if(file_exists($filename)){
@unlink($filename);
}
$fp = fopen($filename,'w');
if($fp){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$result = parse_url($url);
curl_setopt($ch, CURLOPT_REFERER, $result['scheme'].'://'.$result['host']);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0');
$raw=curl_exec($ch);
curl_close ($ch);
if($raw){
fwrite($fp, $raw);
}
fclose($fp);
if(!$raw){
@unlink($filename);
return false;
}
return true;
}
return false;
}
I am building a File-Structure to host up to 2 billion (2^32) files and performed the following tests that show a sharp drop in Navigate + Read Performance at about 250 Files or 120 Directories per NTFS Directory on a Solid State Drive (SSD):
Interestingly the Number of Directories and Files do NOT significantly interfere.
So the Lessons are:
This is the Data (2 Measurements for each File and Directory):
(FOPS = File Operations per Second)
(DOPS = Directory Operations per Second)
#Files lg(#) FOPS FOPS2 DOPS DOPS2
10 1.00 16692 16692 16421 16312
100 2.00 16425 15943 15738 16031
120 2.08 15716 16024 15878 16122
130 2.11 15883 16124 14328 14347
160 2.20 15978 16184 11325 11128
200 2.30 16364 16052 9866 9678
210 2.32 16143 15977 9348 9547
220 2.34 16290 15909 9094 9038
230 2.36 16048 15930 9010 9094
240 2.38 15096 15725 8654 9143
250 2.40 15453 15548 8872 8472
260 2.41 14454 15053 8577 8720
300 2.48 12565 13245 8368 8361
400 2.60 11159 11462 7671 7574
500 2.70 10536 10560 7149 7331
1000 3.00 9092 9509 6569 6693
2000 3.30 8797 8810 6375 6292
10000 4.00 8084 8228 6210 6194
20000 4.30 8049 8343 5536 6100
50000 4.70 7468 7607 5364 5365
And this is the Test Code:
[TestCase(50000, false, Result = 50000)]
[TestCase(50000, true, Result = 50000)]
public static int TestDirPerformance(int numFilesInDir, bool testDirs) {
var files = new List<string>();
var dir = Path.GetTempPath() + "\\Sub\\" + Guid.NewGuid() + "\\";
Directory.CreateDirectory(dir);
Console.WriteLine("prepare...");
const string FILE_NAME = "\\file.txt";
for (int i = 0; i < numFilesInDir; i++) {
string filename = dir + Guid.NewGuid();
if (testDirs) {
var dirName = filename + "D";
Directory.CreateDirectory(dirName);
using (File.Create(dirName + FILE_NAME)) { }
} else {
using (File.Create(filename)) { }
}
files.Add(filename);
}
//Adding 1000 Directories didn't change File Performance
/*for (int i = 0; i < 1000; i++) {
string filename = dir + Guid.NewGuid();
Directory.CreateDirectory(filename + "D");
}*/
Console.WriteLine("measure...");
var r = new Random();
var sw = new Stopwatch();
sw.Start();
int len = 0;
int count = 0;
while (sw.ElapsedMilliseconds < 5000) {
string filename = files[r.Next(files.Count)];
string text = File.ReadAllText(testDirs ? filename + "D" + FILE_NAME : filename);
len += text.Length;
count++;
}
Console.WriteLine("{0} File Ops/sec ", count / 5);
return numFilesInDir;
}
I struggled with this for a few hours today because all of these answers are kind of out of date now what with MDC and the new theming capabilities I just could not see how to override app:titleTextColor
app wide as a style.
The answer is that titleTextColor
is available in the styles.xml is you are overriding something that inherits from Widget.AppCompat.Toolbar
. Today I think the best choice is supposed to be Widget.MaterialComponents.Toolbar
:
<style name="Widget.LL.Toolbar" parent="@style/Widget.MaterialComponents.Toolbar">
<item name="titleTextAppearance">@style/TextAppearance.LL.Toolbar</item>
<item name="titleTextColor">@color/white</item>
<item name="android:background">?attr/colorSecondary</item>
</style>
<style name="TextAppearance.LL.Toolbar" parent="@style/TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textStyle">bold</item>
</style>
And in your app theme, specify the toolbarStyle:
<item name="toolbarStyle">@style/Widget.LL.Toolbar</item>
Now you can leave the xml where you specify the tool bar unchanged. For a long time I thought changing the android:textColor
in the toolbar title text appearance should be working, but for some reason it does not.
Window > Preferences, go to the Run/Debug > Console section >> "Limit console output.>>Console buffer size(characters):" (This option can be seen in Eclipse Indigo ,but it limits buffer size at 1,000,000 )
If it's a Maven project:
The issue should go away.
Security warning: This code is not secure.
working example
define('SALT', 'whateveryouwant');
function encrypt($text)
{
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
function decrypt($text)
{
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
$encryptedmessage = encrypt("your message");
echo decrypt($encryptedmessage);
In the ActionListener Class you can simply add
public void actionPerformed(ActionEvent event) {
if (event.getSource()==textField){
textButton.doClick();
}
else if (event.getSource()==textButton) {
//do something
}
}
I use this method:
var results = this.Database.SqlQuery<yourEntity>("EXEC [ent].[GetNextExportJob] {0}", ProcessorID);
I like it because I just drop in Guids and Datetimes and SqlQuery performs all the formatting for me.
In my case, none of these solutions worked. I had to go to
Tools -> Import and Export Settings -> Reset all settings.
and then debugging started working without any issues.
I copied model code from w3school bootstrap model and added following css. This code provides beautiful animation. You can try it.
.modal.fade .modal-dialog {
-webkit-transform: scale(0.1);
-moz-transform: scale(0.1);
-ms-transform: scale(0.1);
transform: scale(0.1);
top: 300px;
opacity: 0;
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
transition: all 0.3s;
}
.modal.fade.in .modal-dialog {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1);
-webkit-transform: translate3d(0, -300px, 0);
transform: translate3d(0, -300px, 0);
opacity: 1;
}
The webpages on an online server reside in a location which looks somewhat like this: http://www.somerandomsite.com/index.php
Since xampp is Offline, it sets up a local server whose address is like this
http://localhost/
Basically, xampp sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\
folder.
The browser locates the server in localhost and will search through the above folder for any resources available in there.
So create any number of folders inside the "xampp\htdocs\" each folder thus forming a website (as you build it).
Sometimes apache won't even start. This is due to the clashing of ports with some applications. Some of them I commonly encounter is Skype. See to that it is killed completely and restart apache
For preventing the dots in the middle of a word or after a punctuation symbol.
let parseText = function(text, limit){_x000D_
if (text.length > limit){_x000D_
for (let i = limit; i > 0; i--){_x000D_
if(text.charAt(i) === ' ' && (text.charAt(i-1) != ','||text.charAt(i-1) != '.'||text.charAt(i-1) != ';')) {_x000D_
return text.substring(0, i) + '...';_x000D_
}_x000D_
}_x000D_
return text.substring(0, limit) + '...';_x000D_
}_x000D_
else_x000D_
return text;_x000D_
};_x000D_
_x000D_
_x000D_
console.log(parseText("1234567 890",5)) // >> 12345..._x000D_
console.log(parseText("1234567 890",8)) // >> 1234567..._x000D_
console.log(parseText("1234567 890",15)) // >> 1234567 890
_x000D_
An another way is simply :
if($test){
echo "Yes 1";
}
if(!is_null($test)){
echo "Yes 2";
}
$test = "hello";
if($test){
echo "Yes 3";
}
Will return :
"Yes 3"
The best way is to use isset(), otherwise you can have an error like "undefined $test".
You can do it like this :
if( isset($test) && ($test!==null) )
You'll not have any error because the first condition isn't accepted.
There is an option to create virtual environments in Anaconda with required Python version.
conda create -n myenv python=3.4
To activate it :
source activate myenv # (in linux, you can use . as a shortcut for "source")
activate myenv # (in windows - note that you should be in your c:\anaconda2 directory)
UPDATE. I have tested it with Ubuntu 18.04. Now you have to install spyder additionally for the new environment with this command (after the activation of the environment with the command above):
conda install spyder
(I have also tested the installation with pip, but for Python 3.4 or older versions, it breaks with the library dependencies error that requires manual installation.)
And now to run Spyder with Python 3.4 just type:
spyder
EDIT from a reader:
For a normal opening, use "Anaconda Prompt" > activate myenv
> spyder
(then the "Anaconda Prompt" must stay open, you cannot use it for other commands, and a force-close will shut down Spyder). This is of course faster than the long load of "Anaconda Navigator" > switch environment > launch Spyder (@adelriosantiago's answer).
Just put an empty string in the radix place, because parseInt() take two arguments:
parseInt(string, radix);
string The value to parse. If the string argument is not a string, then it is converted to a string (using the ToString abstract operation). Leading whitespace in the string argument is ignored.
radix An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above-mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.
imageIndex = parseInt(id.substring(id.length - 1))-1;
imageIndex = parseInt(id.substring(id.length - 1), '')-1;
There is a system function called ISNUMERIC for SQL 2008 and up. An example:
SELECT myCol
FROM mTable
WHERE ISNUMERIC(myCol)<> 1;
I did a couple of quick tests and also looked further into the docs:
ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.
Which means it is fairly predictable for example
-9879210433
would pass but 987921-0433
does not.
$9879210433
would pass but 9879210$433
does not.
So using this information you can weed out based on the list of valid currency symbols and +
& -
characters.
This is what is did that solved the same problem. I solved it by creating a function that returns the query result thus:
function getUsers(){
$query = $this->db->get('users');
return $query->result();
}
//The above code can go in the user_model or whatever your model is.
This allows me to use one function for the result and number of returned rows.
Use this code below in your contoller where you need the count as well as the result array().
//This gives you the user count using the count function which returns and integer of the exact rows returned from the query.
$this->data['user_count'] = count($this->user_model->getUsers());
//This gives you the returned result array.
$this->data['users'] = $this->user_model->getUsers();
I hope this helps.
I don't think you can round it like that in a single command. Try
ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
list.add(new BigDecimal("100.12"));
list.add(new BigDecimal("100.44"));
list.add(new BigDecimal("100.50"));
list.add(new BigDecimal("100.75"));
for (BigDecimal bd : list){
System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
}
Output:
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00
I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.
An undocumented feature of the formData
field that request
implements is the ability to pass options to the form-data
module it uses:
request({
url: 'http://example.com',
method: 'POST',
formData: {
'regularField': 'someValue',
'regularFile': someFileStream,
'customBufferFile': {
value: fileBufferData,
options: {
filename: 'myfile.bin'
}
}
}
}, handleResponse);
This is useful if you need to avoid calling requestObj.form()
but need to upload a buffer as a file. The form-data
module also accepts contentType
(the MIME type) and knownLength
options.
This change was added in October 2014 (so 2 months after this question was asked), so it should be safe to use now (in 2017+). This equates to version v2.46.0
or above of request
.
If you are only concerned about max limit then just add below line in
android:maxLength="10"
If you need to add min limit then you can do like this way in this case min limit is 7. user is restricted to enter character between min and max limit (in between 8 and 10)
public final static boolean isValidCellPhone(String number){
if (number.length() < 8 || number.length() >10 ) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(number).matches();
}
}
If you also need to restrict user to enter 01 at start then modify if condition like this way
if (!(number.startsWith("01")) || number.length() < 8 || number.length() >10 ) {
.
.
.
}
At the end call method like
....else if (!(Helper.isValidMobilePhone(textMobileNo))){
Helper.setEditTextError(etMobileNo,"Invalid Mobile Number");
}......
The primary committer to node-mongodb-native says:
You open do MongoClient.connect once when your app boots up and reuse the db object. It's not a singleton connection pool each .connect creates a new connection pool.
So, to answer your question directly, reuse the db object that results from MongoClient.connect()
. This gives you pooling, and will provide a noticeable speed increase as compared with opening/closing connections on each db action.
If you want to do this easily from within Android Studio then on the left side, right above your file directory you will see a dropdown with options on how to view your files like:
Project, Android, and Packages, plus a list of Scopes.
If you are on Android it makes it hard to see when you add new folders or assets to your project - BUT if you change the dropdown to PROJECT then the file directory will match the file system on your computer, then go to:
app > src > main > res
From here you can find the conventional Eclipse type files like drawable/drawable-hdpi/drawable-mdpi and so on where you can easily drag and drop files into or import into and instantly see them. As soon as you see your files here they will be available when going to assign image src's and so on.
Good luck Android Warriors in a strange new world!
Try this:
From this question.
In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.
I was getting that behind a corporate proxy.
Solved by:
git config http.sslVerify "false"
To keep the button in the page flow:
<input type="button" value="Click Me" style="margin-left: auto; display: block;" />
(put that style in a .css file, do not use this html inline, for better maintenance)
onmousemove = function(e){console.log("mouse location:", e.clientX, e.clientY)}
Open your console (Ctrl+Shift+J), copy-paste the code above and move your mouse on browser window.
This works well for me, and I'm handling hover and click CSS as well (by changing background color):
HTML (here showing 2 images, image1 on top of image2):
<button class="iconButton" style="background-image: url('image1.png'), url('image2.png')"
onclick="alert('clicked');"></button>
CSS (my images are 32px X 32px, so I gave them 4px for padding and a 5px border rounding):
.iconButton {
width: 36px;
height: 36px;
background-color: #000000;
background-position: center;
background-repeat: no-repeat;
border: none;
border-radius: 5px;
cursor: pointer;
outline: none;
}
.iconButton:hover {
background-color: #303030;
}
.iconButton:active {
background-color: #606060;
}
button::-moz-focus-inner {
border: 0;
}
If you are using SQL Server 2016 or newer, you can also select it as JSON result and display it in JSON Visualizer, it's much easier to read it than in XML and allows you to filter results.
DECLARE @v nvarchar(max) = (SELECT * FROM Suppliers FOR JSON AUTO)
It works great for both known and unknown height elements. Make sure to set the outer div to height: 100%;
and reset the default margin
on body
. See the browser support tables.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
.header, .footer {_x000D_
background: silver;_x000D_
}_x000D_
.content {_x000D_
flex: 1;_x000D_
overflow: auto;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">Header</div>_x000D_
<div class="content">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
<div class="footer">Footer</div>_x000D_
</div>
_x000D_
For both known and unknown height elements. It also works in legacy browsers including IE8.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
display: table;_x000D_
}_x000D_
.header, .content, .footer {_x000D_
display: table-row;_x000D_
}_x000D_
.header, .footer {_x000D_
background: silver;_x000D_
}_x000D_
.inner {_x000D_
display: table-cell;_x000D_
}_x000D_
.content .inner {_x000D_
height: 100%;_x000D_
position: relative;_x000D_
background: pink;_x000D_
}_x000D_
.scrollable {_x000D_
position: absolute;_x000D_
left: 0; right: 0;_x000D_
top: 0; bottom: 0;_x000D_
overflow: auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">_x000D_
<div class="inner">Header</div>_x000D_
</div>_x000D_
<div class="content">_x000D_
<div class="inner">_x000D_
<div class="scrollable">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="footer">_x000D_
<div class="inner">Footer</div>_x000D_
</div>_x000D_
</div>
_x000D_
calc()
If header and footer are fixed height, you can use CSS calc()
.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
height: 50px;_x000D_
background: silver;_x000D_
}_x000D_
.content {_x000D_
height: calc(100% - 100px);_x000D_
overflow: auto;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">Header</div>_x000D_
<div class="content">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
<div class="footer">Footer</div>_x000D_
</div>
_x000D_
If the header and footer are known height, and they are also percentage you can just do the simple math making them together of 100% height.
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
height: 10%;_x000D_
background: silver;_x000D_
}_x000D_
.content {_x000D_
height: 80%;_x000D_
overflow: auto;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="header">Header</div>_x000D_
<div class="content">_x000D_
<div style="height:1000px;">Content</div>_x000D_
</div>_x000D_
<div class="footer">Footer</div>_x000D_
</div>
_x000D_
Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.
If you have created a Java Project in eclipse by using the 'from existing source' option then it should work as it did before. To be more precise File > New Java Project. In the Contents section select 'Create project from existing source' and then select your existing project folder. The wizard will take care of the rest.
If you have a huge number of objects, this can (at times) be much faster:
try:
orgs[0]
# If you get here, it exists...
except IndexError:
# Doesn't exist!
On a project I'm working on with a huge database, not orgs
is 400+ ms and orgs.count()
is 250ms. In my most common use cases (those where there are results), this technique often gets that down to under 20ms. (One case I found, it was 6.)
Could be much longer, of course, depending on how far the database has to look to find a result. Or even faster, if it finds one quickly; YMMV.
EDIT: This will often be slower than orgs.count()
if the result isn't found, particularly if the condition you're filtering on is a rare one; as a result, it's particularly useful in view functions where you need to make sure the view exists or throw Http404. (Where, one would hope, people are asking for URLs that exist more often than not.)
Apple have changed the name of the certificate that is issued. You can now use the same certificate for both development and production. While you can still request a development only certificate you can no longer request a production only certificate.
you have to reason in terms of hased password:
store the password as md5('bob123');
when bob is register to your app
$query = "INSERT INTO users (username,password) VALUES('bob','".md5('bob123')."');
then, when bob is logging-in:
$query = "SELECT * FROM users WHERE username = 'bob' AND password = '".md5('bob123')."';
obvioulsy use variables for username and password, these queries are generated by php and then you can execute them on mysql
Keep in mind that Windows has virtual memory management and the JVM only needs memory that is contiguous in its address space. So, other programs running on the system shouldn't necessarily impact your heap size. What will get in your way are DLL's that get loaded in to your address space. Unfortunately optimizations in Windows that minimize the relocation of DLL's during linking make it more likely you'll have a fragmented address space. Things that are likely to cut in to your address space aside from the usual stuff include security software, CBT software, spyware and other forms of malware. Likely causes of the variances are different security patches, C runtime versions, etc. Device drivers and other kernel bits have their own address space (the other 2GB of the 4GB 32-bit space).
You could try going through your DLL bindings in your JVM process and look at trying to rebase your DLL's in to a more compact address space. Not fun, but if you are desperate...
Alternatively, you can just switch to 64-bit Windows and a 64-bit JVM. Despite what others have suggested, while it will chew up more RAM, you will have much more contiguous virtual address space, and allocating 2GB contiguously would be trivial.
Let's say you have input data x
and you want to classify the data into labels y
. A generative model learns the joint probability distribution p(x,y)
and a discriminative model learns the conditional probability distribution p(y|x)
- which you should read as "the probability of y
given x
".
Here's a really simple example. Suppose you have the following data in the form (x,y)
:
(1,0), (1,0), (2,0), (2, 1)
p(x,y)
is
y=0 y=1
-----------
x=1 | 1/2 0
x=2 | 1/4 1/4
p(y|x)
is
y=0 y=1
-----------
x=1 | 1 0
x=2 | 1/2 1/2
If you take a few minutes to stare at those two matrices, you will understand the difference between the two probability distributions.
The distribution p(y|x)
is the natural distribution for classifying a given example x
into a class y
, which is why algorithms that model this directly are called discriminative algorithms. Generative algorithms model p(x,y)
, which can be transformed into p(y|x)
by applying Bayes rule and then used for classification. However, the distribution p(x,y)
can also be used for other purposes. For example, you could use p(x,y)
to generate likely (x,y)
pairs.
From the description above, you might be thinking that generative models are more generally useful and therefore better, but it's not as simple as that. This paper is a very popular reference on the subject of discriminative vs. generative classifiers, but it's pretty heavy going. The overall gist is that discriminative models generally outperform generative models in classification tasks.
First of all, return
is a keyword and exit
is a function.
That said, here's a simplest of explanations.
return
It returns a value from a function.
exit
It exits out of or abandons the current shell.
when you change a file which is already in the repository, you have to git add
it again if you want it to be staged.
This allows you to commit only a subset of the changes you made since the last commit. For example, let's say you have file a
, file b
and file c
. You modify file a
and file b
but the changes are very different in nature and you don't want all of them to be in one single commit. You issue
git add a
git commit a -m "bugfix, in a"
git add b
git commit b -m "new feature, in b"
As a side note, if you want to commit everything you can just type
git commit -a
Hope it helps.
Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).
When they return look them up by the remember me token and make sure the UserId matches.
if you want to read settings from the DLL's config file but not from the the root applications web.config or app.config use below code to read configuration in the dll.
var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
string dllConfigData = appConfig.AppSettings.Settings["dllConfigData"].Value;
For this type of question Store the orignal array data into a new data and then binary search the first element of the sorted array into the duplicated array and that indice should be stored into a vector or array.
input array=>a
duplicate array=>b
vector=>c(Stores the indices(position) of the orignal array
Syntax:
for(i=0;i<n;i++)
c.push_back(binarysearch(b,n,a[i]));`
Here binarysearch is a function which takes the array,size of array,searching item and would return the position of the searched item
The accepted answer is not ideal, so I decided to add my 2 cents
timeStamp.toLocalDateTime().toLocalDate();
is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.
The good solution is
timestamp.toInstant().atZone(zoneId).toLocalDate()
Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC
The general approach should be
Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.
But more importantly why do you want to read an HTTPOnly
cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly
flag and "secure flag" (which forces the cookie to be sent over https) should always be set.
If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly
flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.
People have too much faith in the HTTPOnly
flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.
One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).
So, take a look here:
car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
# from (irb):11
# from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"
As you can see, requiring json
has magically brought method to_json
to our Hash
.
I was surprised to learn, and so I had to come back here and report, that the excellent and well maintained Interconnect/it SAFE SEARCH AND REPLACE ON DATABASE script has some options for converting tables to utf8 / unicode, and even to convert to innodb. It's a script commonly used to migrate a database driven website (Wordpress, Drupal, Joomla, etc) from one domain to another.
Try this: use "%40" in place of the "@"
Personally, I always use the following:
var x;
if( x === undefined) {
//Do something here
}
else {
//Do something else here
}
The window.undefined property is non-writable in all modern browsers (JavaScript 1.8.5 or later). From Mozilla's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined, I see this: One reason to use typeof() is that it does not throw an error if the variable has not been defined.
I prefer to have the approach of using
x === undefined
because it fails and blows up in my face rather than silently passing/failing if x has not been declared before. This alerts me that x is not declared. I believe all variables used in JavaScript should be declared.
class extends React.Component {
onClickDiv = (column) => {
// do stuff
}
render() {
return <div onClick={() => this.onClickDiv('123')} />
}
}
Bravo JSP Editor (Can't comment on how good it is, i haven't tried it) http://marketplace.eclipse.org/content/bravo-jsp-editor
Today I accidentally solved the issue:
Press finish.
[Optional scenario]: If project(s) and their containing folders have been renamed with the fully qualified package names then simply click on project node parent (where you see project package name instead of project's old name) in Eclipse and rename project with old name. Eclipse will rename folder too.
P.S. Tested on Eclipse Juno.
Edit: Many times have passed since this answer and new Eclipse and Android SDK arrived. They have no much more problems during importing existing projects. The only thing one has to consider before importing is to move project folders(those ones one is willing to import) outside of eclipse workspace dir and then check checkboxes ("copy projects into working sets", "add projects into wokring sets") in import wizard dialog. Also I recommend doing this with latest Android SDK because it no more imports projects with dummy names and does not rename folders as it did in some custom cases.
The main problem is that operator [] is used to insert and read a value into and from the map, so it cannot be const. If the key does not exist, it will create a new entry with a default value in it, incrementing the size of the map, that will contain a new key with an empty string ,in this particular case, as a value if the key does not exist yet. You should avoid operator[] when reading from a map and use, as was mention before, "map.at(key)" to ensure bound checking. This is one of the most common mistakes people often do with maps. You should use "insert" and "at" unless your code is aware of this fact. Check this talk about common bugs Curiously Recurring C++ Bugs at Facebook
Try this
function checkForm($fields){
foreach($fields as $field){
if($field['required'] && strlen($_POST[$field['name']]) <= 0){
$field['value'] = "Some error";
}
}
return $field;
}
If you add the extension .SH
to the environment variable PATHEXT
, you will be able to run shell scripts from PowerShell by only using the script name with arguments:
PS> .\script.sh args
If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:
PS> script args
Note: sh.exe or another *nix shell must be associated with the .sh extension.
This happens when you move your main class location manually because Netbeans doesn't refresh one of its property files. Open nbproject/project.properties and change the value of main.class to the correct package location.
slice()
works like substring()
with a few different behaviors.
Syntax: string.slice(start, stop);
Syntax: string.substring(start, stop);
What they have in common:
start
equals stop
: returns an empty stringstop
is omitted: extracts characters to the end of the stringDistinctions of substring()
:
start > stop
, then substring
will swap those 2 arguments.NaN
, it is treated as if it were 0
.Distinctions of slice()
:
start > stop
, slice()
will return the empty string. (""
)start
is negative: sets char from the end of string, exactly like substr()
in Firefox. This behavior is observed in both Firefox and IE.stop
is negative: sets stop to: string.length – Math.abs(stop)
(original value), except bounded at 0 (thus, Math.max(0, string.length + stop)
) as covered in the ECMA specification.Source: Rudimentary Art of Programming & Development: Javascript: substr() v.s. substring()
Sorting table rows by cell. 1. Little simpler and has some features. 2. Distinguish 'number' and 'string' on sorting 3. Add toggle to sort by ASC, DESC
var index; // cell index
var toggleBool; // sorting asc, desc
function sorting(tbody, index){
this.index = index;
if(toggleBool){
toggleBool = false;
}else{
toggleBool = true;
}
var datas= new Array();
var tbodyLength = tbody.rows.length;
for(var i=0; i<tbodyLength; i++){
datas[i] = tbody.rows[i];
}
// sort by cell[index]
datas.sort(compareCells);
for(var i=0; i<tbody.rows.length; i++){
// rearrange table rows by sorted rows
tbody.appendChild(datas[i]);
}
}
function compareCells(a,b) {
var aVal = a.cells[index].innerText;
var bVal = b.cells[index].innerText;
aVal = aVal.replace(/\,/g, '');
bVal = bVal.replace(/\,/g, '');
if(toggleBool){
var temp = aVal;
aVal = bVal;
bVal = temp;
}
if(aVal.match(/^[0-9]+$/) && bVal.match(/^[0-9]+$/)){
return parseFloat(aVal) - parseFloat(bVal);
}
else{
if (aVal < bVal){
return -1;
}else if (aVal > bVal){
return 1;
}else{
return 0;
}
}
}
below is html sample
<table summary="Pioneer">
<thead>
<tr>
<th scope="col" onclick="sorting(tbody01, 0)">No.</th>
<th scope="col" onclick="sorting(tbody01, 1)">Name</th>
<th scope="col" onclick="sorting(tbody01, 2)">Belong</th>
<th scope="col" onclick="sorting(tbody01, 3)">Current Networth</th>
<th scope="col" onclick="sorting(tbody01, 4)">BirthDay</th>
<th scope="col" onclick="sorting(tbody01, 5)">Just Number</th>
</tr>
</thead>
<tbody id="tbody01">
<tr>
<td>1</td>
<td>Gwanshic Yi</td>
<td>Gwanshic Home</td>
<td>120000</td>
<td>1982-03-20</td>
<td>124,124,523</td>
</tr>
<tr>
<td>2</td>
<td>Steve Jobs</td>
<td>Apple</td>
<td>19000000000</td>
<td>1955-02-24</td>
<td>194,523</td>
</tr>
<tr>
<td>3</td>
<td>Bill Gates</td>
<td>MicroSoft</td>
<td>84300000000</td>
<td>1955-10-28</td>
<td>1,524,124,523</td>
</tr>
<tr>
<td>4</td>
<td>Larry Page</td>
<td>Google</td>
<td>39100000000</td>
<td>1973-03-26</td>
<td>11,124,523</td>
</tr>
</tbody>
</table>
The fastest & best implementation of omitting primes:
def PrimeRanges2(a, b):
arr = range(a, b+1)
up = int(math.sqrt(b)) + 1
for d in range(2, up):
arr = omit_multi(arr, d)
Depends on if the form that the select is contained in has the method set to "get" or "post".
If <form method="get">
then the value of the select will be located in the super global array $_GET['taskOption']
.
If <form method="post">
then the value of the select will be located in the super global array $_POST['taskOption']
.
To store it into a variable you would:
$option = $_POST['taskOption']
A good place for more information would be the PHP manual: http://php.net/manual/en/tutorial.forms.php
According to this post, it's much better now:
// pick out one album
JObject jalbum = albums[0] as JObject;
// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();
Documentation: Convert JSON to a Type
I've used IP*Works SSH and it is great. Easy to setup and use. Plus, their support is top-notch when you run into questions or problems.
If the shell scripts start with #!/bin/bash
, they will always run with bash
from /bin
. If they however start with #!/usr/bin/env bash
, they will search for bash
in $PATH
and then start with the first one they can find.
Why would this be useful? Assume you want to run bash
scripts, that require bash 4.x or newer, yet your system only has bash
3.x installed and currently your distribution doesn't offer a newer version or you are no administrator and cannot change what is installed on that system.
Of course, you can download bash source code and build your own bash from scratch, placing it to ~/bin
for example. And you can also modify your $PATH
variable in your .bash_profile
file to include ~/bin
as the first entry (PATH=$HOME/bin:$PATH
as ~
will not expand in $PATH
). If you now call bash
, the shell will first look for it in $PATH
in order, so it starts with ~/bin
, where it will find your bash
. Same thing happens if scripts search for bash
using #!/usr/bin/env bash
, so these scripts would now be working on your system using your custom bash
build.
One downside is, that this can lead to unexpected behavior, e.g. same script on the same machine may run with different interpreters for different environments or users with different search paths, causing all kind of headaches.
The biggest downside with env
is that some systems will only allow one argument, so you cannot do this #!/usr/bin/env <interpreter> <arg>
, as the systems will see <interpreter> <arg>
as one argument (they will treat it as if the expression was quoted) and thus env
will search for an interpreter named <interpreter> <arg>
. Note that this is not a problem of the env
command itself, which always allowed multiple parameters to be passed through but with the shebang parser of the system that parses this line before even calling env
. Meanwhile this has been fixed on most systems but if your script wants to be ultra portable, you cannot rely that this has been fixed on the system you will be running.
It can even have security implications, e.g. if sudo
was not configured to clean environment or $PATH
was excluded from clean up. Let me demonstrate this:
Usually /bin
is a well protected place, only root
is able to change anything there. Your home directory is not, though, any program you run is able to make changes to it. That means malicious code could place a fake bash
into some hidden directory, modify your .bash_profile
to include that directory in your $PATH
, so all scripts using #!/usr/bin/env bash
will end up running with that fake bash
. If sudo
keeps $PATH
, you are in big trouble.
E.g. consider a tool creates a file ~/.evil/bash
with the following content:
#!/bin/bash
if [ $EUID -eq 0 ]; then
echo "All your base are belong to us..."
# We are root - do whatever you want to do
fi
/bin/bash "$@"
Let's make a simple script sample.sh
:
#!/usr/bin/env bash
echo "Hello World"
Proof of concept (on a system where sudo
keeps $PATH
):
$ ./sample.sh
Hello World
$ sudo ./sample.sh
Hello World
$ export PATH="$HOME/.evil:$PATH"
$ ./sample.sh
Hello World
$ sudo ./sample.sh
All your base are belong to us...
Hello World
Usually the classic shells should all be located in /bin
and if you don't want to place them there for whatever reason, it's really not an issue to place a symlink in /bin
that points to their real locations (or maybe /bin
itself is a symlink), so I would always go with #!/bin/sh
and #!/bin/bash
. There's just too much that would break if these wouldn't work anymore. It's not that POSIX would require these position (POSIX does not standardize path names and thus it doesn't even standardize the shebang feature at all) but they are so common, that even if a system would not offer a /bin/sh
, it would probably still understand #!/bin/sh
and know what to do with it and may it only be for compatibility with existing code.
But for more modern, non standard, optional interpreters like Perl, PHP, Python, or Ruby, it's not really specified anywhere where they should be located. They may be in /usr/bin
but they may as well be in /usr/local/bin
or in a completely different hierarchy branch (/opt/...
, /Applications/...
, etc.). That's why these often use the #!/usr/bin/env xxx
shebang syntax.
here is the complete example of how you can select and upload multiple files in asp.net using file upload control....
write this code in .aspx file..
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<div>
<input type="file" id="myfile" multiple="multiple" name="myfile" runat="server" size="100" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:Label ID="Span1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
after that write this code in .aspx.cs file..
protected void Button1_Click(object sender,EventArgs e) {
string filepath = Server.MapPath("\\Upload");
HttpFileCollection uploadedFiles = Request.Files;
Span1.Text = string.Empty;
for(int i = 0;i < uploadedFiles.Count;i++) {
HttpPostedFile userPostedFile = uploadedFiles[i];
try {
if (userPostedFile.ContentLength > 0) {
Span1.Text += "<u>File #" + (i + 1) + "</u><br>";
Span1.Text += "File Content Type: " + userPostedFile.ContentType + "<br>";
Span1.Text += "File Size: " + userPostedFile.ContentLength + "kb<br>";
Span1.Text += "File Name: " + userPostedFile.FileName + "<br>";
userPostedFile.SaveAs(filepath + "\\" + Path.GetFileName(userPostedFile.FileName));
Span1.Text += "Location where saved: " + filepath + "\\" + Path.GetFileName(userPostedFile.FileName) + "<p>";
}
} catch(Exception Ex) {
Span1.Text += "Error: <br>" + Ex.Message;
}
}
}
}
and here you go...your multiple file upload control is ready..have a happy day.
InputStream is used for reading, OutputStream for writing. They are connected as decorators to one another such that you can read/write all different types of data from all different types of sources.
For example, you can write primitive data to a file:
File file = new File("C:/text.bin");
file.createNewFile();
DataOutputStream stream = new DataOutputStream(new FileOutputStream(file));
stream.writeBoolean(true);
stream.writeInt(1234);
stream.close();
To read the written contents:
File file = new File("C:/text.bin");
DataInputStream stream = new DataInputStream(new FileInputStream(file));
boolean isTrue = stream.readBoolean();
int value = stream.readInt();
stream.close();
System.out.printlin(isTrue + " " + value);
You can use other types of streams to enhance the reading/writing. For example, you can introduce a buffer for efficiency:
DataInputStream stream = new DataInputStream(
new BufferedInputStream(new FileInputStream(file)));
You can write other data such as objects:
MyClass myObject = new MyClass(); // MyClass have to implement Serializable
ObjectOutputStream stream = new ObjectOutputStream(
new FileOutputStream("C:/text.obj"));
stream.writeObject(myObject);
stream.close();
You can read from other different input sources:
byte[] test = new byte[] {0, 0, 1, 0, 0, 0, 1, 1, 8, 9};
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(test));
int value0 = stream.readInt();
int value1 = stream.readInt();
byte value2 = stream.readByte();
byte value3 = stream.readByte();
stream.close();
System.out.println(value0 + " " + value1 + " " + value2 + " " + value3);
For most input streams there is an output stream, also. You can define your own streams to reading/writing special things and there are complex streams for reading complex things (for example there are Streams for reading/writing ZIP format).
The u
prefix means that those strings are unicode rather than 8-bit strings. The best way to not show the u
prefix is to switch to Python 3, where strings are unicode by default. If that's not an option, the str
constructor will convert from unicode to 8-bit, so simply loop recursively over the result and convert unicode
to str
. However, it is probably best just to leave the strings as unicode.
var getMatchingGroups = function(s) {
var r=/\((.*?)\)/g, a=[], m;
while (m = r.exec(s)) {
a.push(m[1]);
}
return a;
};
getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]
In my case it was a problem with a missing init.py file in the module, that I wanted to import in a Python 2.7 environment.
Python 3.3+ has Implicit Namespace Packages that allow it to create a packages without an init.py file.
Somehow the accepted answer is only talking about including css file from bootstrap.
But I think this question is related to the one here - Bootstrap Dropdown not working in React
There are couple of answers that can help -
Twine is an open-source tool for telling interactive, nonlinear stories. It generates a single html with multiples pages. Maybe it is not the right tool for you but it could be useful for someone else looking for something similar.
This was happening to me with mariadb because I made a varchar(255)
column a unique key
.. guess that's too heavy for a unique, as the insert was timing out.
You can chnage font size by ctrl + mousewheel.
OR
tools --> options --> environment --> font and color.
Detail with screenshot is mentonied here
As MadScientist pointed out, you can export individual variables with:
export MY_VAR = foo # Available for all targets
Or export variables for a specific target (target-specific variables):
my-target: export MY_VAR_1 = foo
my-target: export MY_VAR_2 = bar
my-target: export MY_VAR_3 = baz
my-target: dependency_1 dependency_2
echo do something
You can also specify the .EXPORT_ALL_VARIABLES
target to—you guessed it!—EXPORT ALL THE THINGS!!!:
.EXPORT_ALL_VARIABLES:
MY_VAR_1 = foo
MY_VAR_2 = bar
MY_VAR_3 = baz
test:
@echo $$MY_VAR_1 $$MY_VAR_2 $$MY_VAR_3
For completeness:
https://developer.chrome.com/multidevice/android/installtohomescreen
Does Add to homescreen work on Chrome for iOS?
No.
Doing it the mathy way...
nums = [1, 2, 3, 4, 5]
min_combo = (min(nums), max(nums))
Unless, of course, you have negatives in there. In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. And double negatives would break it.
This is what I do when I need to add months or years and don't want to import more libraries. Just create a datetime.date() object, call add_month(date) to add a month and add_year(date) to add a year.
import datetime
__author__ = 'Daniel Margarido'
# Check if the int given year is a leap year
# return true if leap year or false otherwise
def is_leap_year(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False
THIRTY_DAYS_MONTHS = [4, 6, 9, 11]
THIRTYONE_DAYS_MONTHS = [1, 3, 5, 7, 8, 10, 12]
# Inputs -> month, year Booth integers
# Return the number of days of the given month
def get_month_days(month, year):
if month in THIRTY_DAYS_MONTHS: # April, June, September, November
return 30
elif month in THIRTYONE_DAYS_MONTHS: # January, March, May, July, August, October, December
return 31
else: # February
if is_leap_year(year):
return 29
else:
return 28
# Checks the month of the given date
# Selects the number of days it needs to add one month
# return the date with one month added
def add_month(date):
current_month_days = get_month_days(date.month, date.year)
next_month_days = get_month_days(date.month + 1, date.year)
delta = datetime.timedelta(days=current_month_days)
if date.day > next_month_days:
delta = delta - datetime.timedelta(days=(date.day - next_month_days) - 1)
return date + delta
def add_year(date):
if is_leap_year(date.year):
delta = datetime.timedelta(days=366)
else:
delta = datetime.timedelta(days=365)
return date + delta
# Validates if the expected_value is equal to the given value
def test_equal(expected_value, value):
if expected_value == value:
print "Test Passed"
return True
print "Test Failed : " + str(expected_value) + " is not equal to " str(value)
return False
# Test leap year
print "---------- Test leap year ----------"
test_equal(True, is_leap_year(2012))
test_equal(True, is_leap_year(2000))
test_equal(False, is_leap_year(1900))
test_equal(False, is_leap_year(2002))
test_equal(False, is_leap_year(2100))
test_equal(True, is_leap_year(2400))
test_equal(True, is_leap_year(2016))
# Test add month
print "---------- Test add month ----------"
test_equal(datetime.date(2016, 2, 1), add_month(datetime.date(2016, 1, 1)))
test_equal(datetime.date(2016, 6, 16), add_month(datetime.date(2016, 5, 16)))
test_equal(datetime.date(2016, 3, 15), add_month(datetime.date(2016, 2, 15)))
test_equal(datetime.date(2017, 1, 12), add_month(datetime.date(2016, 12, 12)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 31)))
test_equal(datetime.date(2015, 3, 1), add_month(datetime.date(2015, 1, 31)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 30)))
test_equal(datetime.date(2016, 4, 30), add_month(datetime.date(2016, 3, 30)))
test_equal(datetime.date(2016, 5, 1), add_month(datetime.date(2016, 3, 31)))
# Test add year
print "---------- Test add year ----------"
test_equal(datetime.date(2016, 2, 2), add_year(datetime.date(2015, 2, 2)))
test_equal(datetime.date(2001, 2, 2), add_year(datetime.date(2000, 2, 2)))
test_equal(datetime.date(2100, 2, 2), add_year(datetime.date(2099, 2, 2)))
test_equal(datetime.date(2101, 2, 2), add_year(datetime.date(2100, 2, 2)))
test_equal(datetime.date(2401, 2, 2), add_year(datetime.date(2400, 2, 2)))
Not sure if this is what you were looking for, but this worked for me:
$query = query("DESC YourTable");
$col_names = array_column($query, 'Field');
That returns a simple array of the column names / variable names in your table or array as strings, which is what I needed to dynamically build MySQL queries. My frustration was that I simply don't know how to index arrays in PHP very well, so I wasn't sure what to do with the results from DESC or SHOW. Hope my answer is helpful to beginners like myself!
To check result: print_r($col_names);
The only reason to have a return in a void function would be to exit early due to some conditional statement:
void foo(int y)
{
if(y == 0) return;
// do stuff with y
}
As unwind said: when the code ends, it ends. No need for an explicit return at the end.
Since $http.get
returns a 'promise' with the extra convenience methods success
and error
(which just wrap the result of then
) you should be able to use (regardless of your Angular version):
$http.get('/someUrl')
.then(function success(response) {
console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
}, function error(response) {
console.log('failed', response); // supposed to have: data, status, headers, config, statusText
})
Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments
, even if you don't know the appropriate method signature:
$http.get('/someUrl')
.success(function(data, foo, bar) {
console.log(arguments); // includes data, status, etc including unlisted ones if present
})
.error(function(baz, foo, bar, idontknow) {
console.log(arguments); // includes data, status, etc including unlisted ones if present
});
Then, based on whatever you find, you can 'fix' the function arguments to match.
The best - and simplest - solution might be this:
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
finishAndRemoveTask();
Documentation for finishAndRemoveTask()
:
Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.
Is that what you're looking for?
ENum stands for "Enumerated Type". It is a data type having a fixed set of constants which you define yourself.
On my website, to check if registering people is 18 years old, I simply used the following :
$legalAge = date('Y-m-d', strtotime('-18 year'));
After, only compare the the two dates.
Hope it could help someone.
In Selenium Python it is:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
def get_selected_value_from_drop_down(self):
try:
select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
return select.first_selected_option.get_attribute("value")
except NoSuchElementException, e:
print "Element not found "
print e
Edit: Garth's answer is probably better.
My old answer text is preserved below.
To convert a string to a stream, you can use a paused through stream:
through().pause().queue('your string').end()
Example:
var through = require('through')
// Create a paused stream and buffer some data into it:
var stream = through().pause().queue('your string').end()
// Pass stream around:
callback(null, stream)
// Now that a consumer has attached, remember to resume the stream:
stream.resume()
@Test(expected = Exception.class)
Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.
For
@Test
Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.
Lambdas are actually very powerful constructs that stem from ideas in functional programming, and it is something that by no means will be easily revised, redefined or removed in the near future of Python. They help you write code that is more powerful as it allows you to pass functions as parameters, thus the idea of functions as first-class citizens.
Lambdas do tend to get confusing, but once a solid understanding is obtained, you can write clean elegant code like this:
squared = map(lambda x: x*x, [1, 2, 3, 4, 5])
The above line of code returns a list of the squares of the numbers in the list. Ofcourse, you could also do it like:
def square(x):
return x*x
squared = map(square, [1, 2, 3, 4, 5])
It is obvious the former code is shorter, and this is especially true if you intend to use the map function (or any similar function that takes a function as a parameter) in only one place. This also makes the code more intuitive and elegant.
Also, as @David Zaslavsky mentioned in his answer, list comprehensions are not always the way to go especially if your list has to get values from some obscure mathematical way.
From a more practical standpoint, one of the biggest advantages of lambdas for me recently has been in GUI and event-driven programming. If you take a look at callbacks in Tkinter, all they take as arguments are the event that triggered them. E.g.
def define_bindings(widget):
widget.bind("<Button-1>", do-something-cool)
def do-something-cool(event):
#Your code to execute on the event trigger
Now what if you had some arguments to pass? Something as simple as passing 2 arguments to store the coordinates of a mouse-click. You can easily do it like this:
def main():
# define widgets and other imp stuff
x, y = None, None
widget.bind("<Button-1>", lambda event: do-something-cool(x, y))
def do-something-cool(event, x, y):
x = event.x
y = event.y
#Do other cool stuff
Now you can argue that this can be done using global variables, but do you really want to bang your head worrying about memory management and leakage especially if the global variable will just be used in one particular place? That would be just poor programming style.
In short, lambdas are awesome and should never be underestimated. Python lambdas are not the same as LISP lambdas though (which are more powerful), but you can really do a lot of magical stuff with them.
DEFAULT
is the value that will be inserted in the absence of an explicit value in an insert / update statement. Lets assume, your DDL did not have the NOT NULL
constraint:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT 'MyDefault'
Then you could issue these statements
-- 1. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B) VALUES (NULL, NULL);
-- 2. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, DEFAULT);
-- 3. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) DEFAULT VALUES;
-- 4. This will insert NULL into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, NULL);
Alternatively, you can also use DEFAULT
in UPDATE
statements, according to the SQL-1992 standard:
-- 5. This will update 'MyDefault' into tbl.col
UPDATE tbl SET col = DEFAULT;
-- 6. This will update NULL into tbl.col
UPDATE tbl SET col = NULL;
Note, not all databases support all of these SQL standard syntaxes. Adding the NOT NULL
constraint will cause an error with statements 4, 6
, while 1-3, 5
are still valid statements. So to answer your question: No, they're not redundant.
Cookies:
Local Storage:
The problem here seems to be that you're reassigning $today
by assigning a string to it:
$today = $dd+'/'+$mm+'/'+$yyyy;
Strings don't have getDate
.
Also, $today.getDate()-1
just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:
$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.
Then just apply the formatting code you wrote:
var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!
var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;
Because of the last statement, $yesterday
is now a String
(not a Date
) containing the formatted date.
Currently (Swift 2.1) you can check it using 3 ways:
Using '?' answered by @Sulthan
And using as?
operator:
if let delegateMe = self.delegate as? YourCustomViewController
{
delegateMe.onSuccess()
}
Basically it depends on what you are trying to achieve:
Assume your original xml is:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:drawable="@drawable/tick_img" />
<item android:state_checked="false"
android:drawable="@drawable/untick_img" />
</selector>
then simply remove android:button="@drawable/xml_above"
in your checkbox xml, and do drawable scaling programmatically in java (decrease the 150
big size to your desired dp):
CheckBox tickRememberPasswd = findViewById(R.id.remember_tick);
//custom selector size
Drawable drawableTick = ContextCompat.getDrawable(this, R.drawable.tick_img);
Drawable drawableUntick = ContextCompat.getDrawable(this, R.drawable.untick_img);
Bitmap bitmapTick = null;
if (drawableTick != null && drawableUntick != null) {
int desiredPixels = Math.round(convertDpToPixel(150, this));
bitmapTick = ((BitmapDrawable) drawableTick).getBitmap();
Drawable dTick = new BitmapDrawable(getResources()
, Bitmap.createScaledBitmap(bitmapTick, desiredPixels, desiredPixels, true));
Bitmap bitmapUntick = ((BitmapDrawable) drawableUntick).getBitmap();
Drawable dUntick = new BitmapDrawable(getResources()
, Bitmap.createScaledBitmap(bitmapUntick, desiredPixels, desiredPixels, true));
final StateListDrawable statesTick = new StateListDrawable();
statesTick.addState(new int[] {android.R.attr.state_checked},
dTick);
statesTick.addState(new int[] { }, //else state_checked false
dUntick);
tickRememberPasswd.setButtonDrawable(statesTick);
}
the convertDpToPixel
method:
public static float convertDpToPixel(float dp, Context context) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return px;
}
C programmers use the static attribute to hide variable and function declarations inside modules, much as you would use public and private declarations in Java and C++. C source files play the role of modules. Any global variable or function declared with the static attribute is private to that module. Similarly, any global variable or function declared without the static attribute is public and can be accessed by any other module. It is good programming practice to protect your variables and functions with the static attribute wherever possible.
I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.
The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.
SHORT ANSWER (should be similar for MinGW too but I haven't tried it):
LONG ANSWER:
Below are the detailed steps that solved this issue for me:
Uninstall/delete the previous version of Cygwin (MinGW in your case)
Make sure that CLion is up-to-date
Run Cygwin setup (x64 for my 64-bit OS)
Install at least the following packages for Cygwin:
gcc
g++
make
Cmake
gdb
Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).
Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows
[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']
Add the 'bin' folder to the Path variable. For Cygwin, I added:
D:\cygwin64\bin
Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings
Select 'Build, Execution, Deployment' and then click on 'Toolchains'
Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)
For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)
'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]
Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'
See screenshot: Check all paths to the compiler, make and gdb
See screenshot: Check the configuration to run the project
There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active
Build your project and then run the project. You should see the output in the terminal window
Hope this helps! Good luck and enjoy CLion.
If fptr
is NULL
, then you don't have an open file. Therefore, you can't freopen
it, you should just fopen
it.
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
fptr = fopen("scores.dat", "wb");
}
note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.
int main()
{
FILE *fptr;
char there_was_error = 0;
char opened_in_read = 1;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("scores.dat", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
}
We can do this by the following way.
<link href="{{ asset('/css/style.css') }}" rel="stylesheet">
{{ HTML::style('css/style.css', array('media' => 'print')) }}
It will search the style file in the public folder of Laravel and then will render it.
I do not know why the answer of @user1010160 got rating of 0. I would have given it +1 if I had enough reputations.
Since my app is designed for API less than 14 and I did not want to add code to my program I did not find a solution until I read his answer. What he said was that even though you have done what is needed in the Application styles it will not work unless you add a style to your activity and there you set textAllCaps to false.
It is not enough to have a style for the activity (my activity had a style), because the style might defaults to the AllCaps property. You have to set explicitly, in the activity too, that property to false.
I now have it both in the Application and in the Activity parts of the manifest file.
let data = [
{
'name': 'Amir',
'surname': 'Rahnama'
},
{
'name': 'Amir',
'surname': 'Stevens'
}
];
let non_duplicated_data = _.uniqBy(data, 'name');
location.href = location.href + "¶meter=" + value;
It's not possible to do directly in JavaScript. You'll need to embed a short WAV file in the HTML, and then play that via code.
An Example:
<script>
function PlaySound(soundObj) {
var sound = document.getElementById(soundObj);
sound.Play();
}
</script>
<embed src="success.wav" autostart="false" width="0" height="0" id="sound1"
enablejavascript="true">
You would then call it from JavaScript code as such:
PlaySound("sound1");
This should do exactly what you want - you'll just need to find/create the beep sound yourself, which should be trivial.
I wanted to do the same thing from a script using a variable and achieved it by putting quotes around the $variable to separate the variable name from the p:
sed -n "$first","$count"p imagelist.txt >"$imageblock"
I wanted to split a list into separate folders and found the initial question and answer a useful step. (split command not an option on the old os I have to port code to).
The other answers here didn't work for me, but I found a pretty simple solution that did work.
I made the default one the last one listed, and I gave it ServerAlias *
.
For example:
NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.secondwebsite.com
ServerAlias secondwebsite.com *.secondwebsite.com
DocumentRoot /home/secondwebsite/web
</VirtualHost>
<VirtualHost *:80>
ServerName www.defaultwebsite.com
ServerAlias *
DocumentRoot /home/defaultwebsite/web
</VirtualHost>
If the visitor didn't explicitly choose to go to something ending in secondwebsite.com
, they get the default website.
Try this : https://code.google.com/p/oracle-gui/
Haven't used it yet, but looks good though.
Another solution I've just found here How to render a scaled SVG to a QImage?
from PySide.QtSvg import *
from PySide.QtGui import *
def convertSvgToPng(svgFilepath,pngFilepath,width):
r=QSvgRenderer(svgFilepath)
height=r.defaultSize().height()*width/r.defaultSize().width()
i=QImage(width,height,QImage.Format_ARGB32)
p=QPainter(i)
r.render(p)
i.save(pngFilepath)
p.end()
PySide is easily installed from a binary package in Windows (and I use it for other things so is easy for me).
However, I noticed a few problems when converting country flags from Wikimedia, so perhaps not the most robust svg parser/renderer.
There is a workaround for your problem. You can use reflection to achieve it.
First, create an interface for your target class Calculatons
:
package mypackage;
public interface CalculationsInterface {
int Calculate(int contextId);
double GetProgress(int contextId);
}
Next, make your target class implements that interface:
public class Calculations implements mypackage.CalculationsInterface {
@Override
native public int Calculate(int contextId);
@Override
native public double GetProgress(int contextId);
static {
System.loadLibrary("Calc");
}
}
Finally, use reflection to create an instance of Calculations
class and assign it to a variable of type CalculationsInterface
:
Class<?> calcClass = Class.forName("Calculations");
CalculationsInterface api = (CalculationsInterface)calcClass.newInstance();
// Use it
double res = api.GetProgress(10);
Video Tutorial: Accessing the Camera with HTML5 & appMobi API will be helpful for you.
Also, you may try the getUserMedia
method (supported by Opera 12)
Take a look at https://github.com/greenrobot/EventBus or http://square.github.io/otto/
or even ... http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/
Download the file and from the same directory run docker build -t nodebb .
This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb
(you can change nodebb to your own name).
for(<first part>; <second part>; <third part>)
{
DoStuff();
}
This code is evaluated like this:
So for your example:
for (int i = 0; i < 8; i++)
{
DoStuff();
}
So the loop runs one time with i set to each value from 0 to 7. Note that i is incremented to 8, but then the loop ends immediately afterwards; it does not run with i set to 8.
You cannot delete an managed object in C# . That's why is called MANAGED language. So you don't have to troble yourself with delete (just like in c++).
It is true that you can set it's instance to null. But that is not going to help you that much because you have no control of your GC (Garbage collector) to delete some objects apart from Collect. And this is not what you want because this will delete all your collection from a generation.
So how is it done then ? So : GC searches periodically objects that are not used anymore and it deletes the object with an internal mechanism that should not concern you.
When you set an instance to null you just notify that your object has no referene anymore ant that could help CG to collect it faster !!!
List
dict = {'Neetu':22,'Shiny':21,'Poonam':23}
print sorted(dict.items())
sv = sorted(dict.values())
print sv
Dictionary
d = []
l = len(sv)
while l != 0 :
d.append(sv[l - 1])
l = l - 1
print d`
This is just an example based on Ned Batchelder's explanation.
__getattr__
example:
class Foo(object):
def __getattr__(self, attr):
print "looking up", attr
value = 42
self.__dict__[attr] = value
return value
f = Foo()
print f.x
#output >>> looking up x 42
f.x = 3
print f.x
#output >>> 3
print ('__getattr__ sets a default value if undefeined OR __getattr__ to define how to handle attributes that are not found')
And if same example is used with __getattribute__
You would get >>> RuntimeError: maximum recursion depth exceeded while calling a Python object
if you use bootstrap 3 , just add img-responsive class in your img tag
<img class="img-responsive" src="...">
if you use bootstrap 4, add img-fluid class in your img tag
<img class="img-fluid" src="...">
which does the staff: max-width: 100%, height: auto, and display:block to the image
or //div[@id='id-74385'][@class='guest clearfix']
opacity
on parent element sets it for the whole sub DOM treeYou can't really set opacity for certain element that wouldn't cascade to descendants as well. That's not how CSS opacity
works I'm afraid.
What you can do is to have two sibling elements in one container and set transparent one's positioning:
<div id="container">
<div id="transparent"></div>
<div id="content"></div>
</div>
then you have to set transparent position: absolute/relative
so its content sibling will be rendered over it.
rgba
can do background transparency of coloured backgroundsrgba
colour setting on element's background-color
will of course work, but it will limit you to only use colour as background. No images I'm afraid. You can of course use CSS3 gradients though if you provide gradient stop colours in rgba
. That works as well.
But be advised that rgba
may not be supported by your required browsers.
But if you're after some kind of masking the whole page, this is usually done by adding a separate div
with this set of styles:
position: fixed;
width: 100%;
height: 100%;
z-index: 1000; /* some high enough value so it will render on top */
opacity: .5;
filter: alpha(opacity=50);
Then when you display the content it should have a higher z-index
. But these two elements are not related in terms of siblings or anything. They're just displayed as they should be. One over the other.
Paste this line in folder path url in file explore: C:\Windows\SysWOW64\SQLServerManager11.msc then press enter.
For arbitrary levels of nestedness:
In [2]: def nested_dict():
...: return collections.defaultdict(nested_dict)
...:
In [3]: a = nested_dict()
In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})
In [5]: a['a']['b']['c'] = 1
In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
{'a': defaultdict(<function __main__.nested_dict>,
{'b': defaultdict(<function __main__.nested_dict>,
{'c': 1})})})
The full paramiko distribution ships with a lot of good demos.
In the demos subdirectory, demo.py
and interactive.py
have full interactive TTY examples which would probably be overkill for your situation.
In your example above ssh_stdin
acts like a standard Python file object, so ssh_stdin.write
should work so long as the channel is still open.
I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write
method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command
method is implemented for all the gory details.
Could always do:
db.foo.find().forEach(function(f){print(tojson(f, '', true));});
To get that compact view.
Also, I find it very useful to limit the fields returned by the find so:
db.foo.find({},{name:1}).forEach(function(f){print(tojson(f, '', true));});
which would return only the _id and name field from foo.
You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy read excel file to DataTable and you can import excel file to sql server database (use SqlBulkCopy). ExcelDataReader reads very fast. On my machine 10000 records less 3 sec and 60000 less 8 sec.
Read to DataTable example:
class Program
{
static void Main(string[] args)
{
var dt = new DataTable();
using (var reader = new ExcelDataReader(@"data.xlsx"))
dt.Load(reader);
Console.WriteLine("done: " + dt.Rows.Count);
Console.ReadKey();
}
}
You are really asking a couple of questions here:
1) Why does the price of SSL certificates vary so much
2) Where can I get good, cheap SSL certificates?
The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).
You can read more on this subject here
For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.
INADDR_ANY is a constant, that contain 0 in value . this will used only when you want connect from all active ports you don't care about ip-add . so if you want connect any particular ip you should mention like as my_sockaddress.sin_addr.s_addr = inet_addr("192.168.78.2")
make -k
(or --keep-going
on gnumake) will do what you are asking for, I think.
You really ought to find the del or rm line that is failing and add a -f
to it to keep that error from happening to others though.
Use this code on xml . i hope it will be work
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<stroke android:width="3dp"
android:color="#4799E8"/>
<corners android:radius="5dp" />
<gradient
android:startColor="#C8C8C8"
android:endColor="#FFFFFF"
android:type="linear"
android:angle="270"/>
</shape>
Structure your code so that all your temporary objects are located inside closures instead of global namespace / global object properties and go out of scope when you've done with them. GC will take care of the rest.
Take a look at this JQuery plugin:
It adds vertical (fixed header row) or horizontal (fixed first column) scrolling to an existing HTML table. There is a demo you can check for both cases of scrolling.
Way late, but I threw this together to be able to do String comparisons using SQL Like style wildcards:
public static class StringLikeExtensions
{
/// <summary>
/// Tests a string to be Like another string containing SQL Like style wildcards
/// </summary>
/// <param name="value">string to be searched</param>
/// <param name="searchString">the search string containing wildcards</param>
/// <returns>value.Like(searchString)</returns>
/// <example>value.Like("a")</example>
/// <example>value.Like("a%")</example>
/// <example>value.Like("%b")</example>
/// <example>value.Like("a%b")</example>
/// <example>value.Like("a%b%c")</example>
/// <remarks>base author -- Ruard van Elburg from StackOverflow, modifications by dvn</remarks>
/// <remarks>converted to a String extension by sja</remarks>
/// <seealso cref="https://stackoverflow.com/questions/1040380/wildcard-search-for-linq"/>
public static bool Like(this String value, string searchString)
{
bool result = false;
var likeParts = searchString.Split(new char[] { '%' });
for (int i = 0; i < likeParts.Length; i++)
{
if (likeParts[i] == String.Empty)
{
continue; // "a%"
}
if (i == 0)
{
if (likeParts.Length == 1) // "a"
{
result = value.Equals(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
else // "a%" or "a%b"
{
result = value.StartsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
}
else if (i == likeParts.Length - 1) // "a%b" or "%b"
{
result &= value.EndsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
else // "a%b%c"
{
int current = value.IndexOf(likeParts[i], StringComparison.OrdinalIgnoreCase);
int previous = value.IndexOf(likeParts[i - 1], StringComparison.OrdinalIgnoreCase);
result &= previous < current;
}
}
return result;
}
/// <summary>
/// Tests a string containing SQL Like style wildcards to be ReverseLike another string
/// </summary>
/// <param name="value">search string containing wildcards</param>
/// <param name="compareString">string to be compared</param>
/// <returns>value.ReverseLike(compareString)</returns>
/// <example>value.ReverseLike("a")</example>
/// <example>value.ReverseLike("abc")</example>
/// <example>value.ReverseLike("ab")</example>
/// <example>value.ReverseLike("axb")</example>
/// <example>value.ReverseLike("axbyc")</example>
/// <remarks>reversed logic of Like String extension</remarks>
public static bool ReverseLike(this String value, string compareString)
{
bool result = false;
var likeParts = value.Split(new char[] {'%'});
for (int i = 0; i < likeParts.Length; i++)
{
if (likeParts[i] == String.Empty)
{
continue; // "a%"
}
if (i == 0)
{
if (likeParts.Length == 1) // "a"
{
result = compareString.Equals(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
else // "a%" or "a%b"
{
result = compareString.StartsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
}
else if (i == likeParts.Length - 1) // "a%b" or "%b"
{
result &= compareString.EndsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
}
else // "a%b%c"
{
int current = compareString.IndexOf(likeParts[i], StringComparison.OrdinalIgnoreCase);
int previous = compareString.IndexOf(likeParts[i - 1], StringComparison.OrdinalIgnoreCase);
result &= previous < current;
}
}
return result;
}
}
There are a couple of things to check:
proceedToSecond
" into the FireBug console to see if the function gets definedscript
tag: it should be <script type="text/javascript">
instead of <script type = "text/javascript">
YES (for non-integer keys).
Most Browsers iterate object properties as:
Some older browsers combine categories #1 and #2, iterating all keys in insertion order. If your keys might parse as integers, it's best not to rely on any specific iteration order.
Current Language Spec (since ES2015) insertion order is preserved, except in the case of keys that parse as integers (eg "7" or "99"), where behavior varies between browsers. For example, Chrome/V8 does not respect insertion order when the keys are parse as numeric.
Old Language Spec (before ES2015): Iteration order was technically undefined, but all major browsers complied with the ES2015 behavior.
Note that the ES2015 behavior was a good example of the language spec being driven by existing behavior, and not the other way round. To get a deeper sense of that backwards-compatibility mindset, see http://code.google.com/p/v8/issues/detail?id=164, a Chrome bug that covers in detail the design decisions behind Chrome's iteration order behavior. Per one of the (rather opinionated) comments on that bug report:
Standards always follow implementations, that's where XHR came from, and Google does the same thing by implementing Gears and then embracing equivalent HTML5 functionality. The right fix is to have ECMA formally incorporate the de-facto standard behavior into the next rev of the spec.
How are you setting up the SqlParameter
? You should set the SqlDbType
property to SqlDbType.DateTime
and then pass the DateTime
directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).
You should be able to get the value into the DB. If not, here is a very simple example of how to do it:
static void Main(string[] args)
{
// Create the connection.
using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
{
// Open the connection.
connection.Open();
// Create the command.
using (SqlCommand command = new SqlCommand("xsp_Test", connection))
{
// Set the command type.
command.CommandType = System.Data.CommandType.StoredProcedure;
// Add the parameter.
SqlParameter parameter = command.Parameters.Add("@dt",
System.Data.SqlDbType.DateTime);
// Set the value.
parameter.Value = DateTime.Now;
// Make the call.
command.ExecuteNonQuery();
}
}
}
I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.
If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the DateTime
, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the DateTime
struct will easily do).
All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the ToUniversalTime
method, not by converting to a string) to the stored procedure.
And when you get the value back, call the ToLocalTime
method to get the time in the local time zone.
You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?
Given your description, you want: ha='right'
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]
fig, axs = plt.subplots(1,3, figsize=(12,3))
ha = ['right', 'center', 'left']
for n, ax in enumerate(axs):
ax.plot(x,y, 'o-')
ax.set_title(ha[n])
ax.set_xticks(x)
ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])
Here are some macros I use:
SET_FLAG(Status, Flag) ((Status) |= (Flag))
CLEAR_FLAG(Status, Flag) ((Status) &= ~(Flag))
INVALID_FLAGS(ulFlags, ulAllowed) ((ulFlags) & ~(ulAllowed))
TEST_FLAGS(t,ulMask, ulBit) (((t)&(ulMask)) == (ulBit))
IS_FLAG_SET(t,ulMask) TEST_FLAGS(t,ulMask,ulMask)
IS_FLAG_CLEAR(t,ulMask) TEST_FLAGS(t,ulMask,0)
In addition to the above, WAMP supports 64 bit PHP on Windows systems while XAMPP only offers 32 bit versions. This actually made me switch to WAMP on my Windows machine since you need 64 bit PHP 7 to get bigint numbers correctly from MySQL
To Solve this Error in Webview Android,
First Check the Permissions in Manifest.xml,
if not define there,then define as like this.
<uses-permission android:name="android.permission.INTERNET"/>
If you use a TFS online(Cloud version) and you want to transform the App.Config in a project, you can do the following without installing any extra tools. From VS => Unload the project => Edit project file => Go to the bottom of the file and add the following:
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterBuild" Condition="Exists('App.$(Configuration).config')">
<TransformXml Source="App.config" Transform="App.$(Configuration).config" Destination="$(OutDir)\$(AssemblyName).dll.config" />
AssemblyFile and Destination works for local use and TFS online(Cloud) server.
Another easy way of doing this. Make a "input type file" tag in html and hide it. Then click a button and format it according to need. After this use javascript/jquery to programmatically click the input tag when the button is clicked.
HTML :-
<input id="file" type="file" style="display: none;">
<button id="button">Add file</button>
JavaScript :-
document.getElementById('button').addEventListener("click", function() {
document.getElementById('file').click();
});
jQuery :-
$('#button').click(function(){
$('#file').click();
});
CSS :-
#button
{
background-color: blue;
color: white;
}
Here is a working JS fiddle for the same :- http://jsfiddle.net/32na3/
It's better to do this.
Navigate to the folder structure you require
Use the command
jar -xvf 'Path_to_ur_Jar_file'
You absolutely can, I use this approach a lot w/ both JavaScript and PHP.
Field definition:
<input type="hidden" name="foo" value="<?php echo $var;?>" />
Access w/ PHP:
$_GET['foo'] or $_POST['foo']
Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php
Cheers!
MultiBinding friendly version...
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
BindingOperations.GetBindingExpressionBase((ComboBox)sender, ComboBox.ItemsSourceProperty).UpdateTarget();
}
If you're working within a single method (or even in a single class or assembly in some cases) and no one outside is going to see what you're doing, use the fullness of a List. But if you're interacting with outside code, like when you're returning a list from a method, then you only want to declare the interface without necessarily tying yourself to a specific implementation, especially if you have no control over who compiles against your code afterward. If you started with a concrete type and you decided to change to another one, even if it uses the same interface, you're going to break someone else's code unless you started off with an interface or abstract base type.
System.Diagnostics.Process.Start("Exe Name");
^
used at the beginning of a character range, or negative lookahead/lookbehind assertions.
>>> re.match('[^f]', 'foo')
>>> re.match('[^f]', 'bar')
<_sre.SRE_Match object at 0x7f8b102ad6b0>
>>> re.match('(?!foo)...', 'foo')
>>> re.match('(?!foo)...', 'bar')
<_sre.SRE_Match object at 0x7f8b0fe70780>
In response to your postscript, that depends on what you would like.
You are getting (possible) multiple rows for each row in your left table because there are multiple matches for the join condition. If you want your total results to have the same number of rows as there is in the left part of the query you need to make sure your join conditions cause a 1-to-1 match.
Alternatively, depending on what you actually want you can use aggregate functions (if for example you just want a string from the right part you could generate a column that is a comma delimited string of the right side results for that left row.
If you are only looking at 1 or 2 columns from the outer join you might consider using a scalar subquery since you will be guaranteed 1 result.
I was facing the same issue while publishing my 1'st web services. I resolved it by simply doing this:
Open IIS
Click on Application Pools
Right Click on DefaultAppPool => Set Application Pool Default => Change .Net Version to V 4.0. (You can also change .Net Framework Version of your application specifically)
Hope, it'll work.
Or you can put in the CSS,
<style>
div#img {
background-image: url(“file.png");
color:yellow (this part doesn't matter;
height:100%;
width:100%;
}
</style>
Though I am using kotlin, the following code answered your question. This return selected item:
val item = myListView.adapter.getItem(i).toString()
The following is the whole selecteditem Listener
myListView.setOnItemClickListener(object : OnItemClickListener {
override fun onItemClick(parent: AdapterView<*>, view: View, i: Int,
id: Long) {
val item = myListView.adapter.getItem(i).toString()
}
})
The code returns the item clicked by its index i as shown in the code
In case you need the []
syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:
[routerLink]="['edit', business._id]"
As for an "about page" with no parameters like yours,
[routerLink]="/about"
or
[routerLink]=['about']
will do the trick.
In the case it is not possibile to use the new Blob
solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way:
function download() {
var fileContents=JSON.stringify(jsonObject, null, 2);
var fileName= "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {download()}, 500);
$('#download').on("click", function() {_x000D_
function download() {_x000D_
var jsonObject = {_x000D_
"name": "John",_x000D_
"age": 31,_x000D_
"city": "New York"_x000D_
};_x000D_
var fileContents = JSON.stringify(jsonObject, null, 2);_x000D_
var fileName = "data.json";_x000D_
_x000D_
var pp = document.createElement('a');_x000D_
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));_x000D_
pp.setAttribute('download', fileName);_x000D_
pp.click();_x000D_
}_x000D_
setTimeout(function() {_x000D_
download()_x000D_
}, 500);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="download">Download me</button>
_x000D_
There is no C portable way to do this. Although various cursor manipulation libraries like curses are relatively portable. conio.h is portable between OS/2 DOS and Windows, but not to *nix variants.
The entire notion of a "console" is a concept outside of the scope of standard C.
If you are looking for a pure Win32 API solution, There is no single call in the Windows console API to do this. One way is to FillConsoleOutputCharacter of a sufficiently large number of characters. Or WriteConsoleOutput You can use GetConsoleScreenBufferInfo to find out how many characters will be enough.
You can also create an entirely new Console Screen Buffer and make the current one.
Not sure from what version, but I use 1.3.14 and you can just use:
window.location.href = '/employee/1';
No need to inject $location
or $window
in the controller and no need to get the current host address.
use DateTime.ParseExact
string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)
null
will use the current culture, which is somewhat dangerous. Try to supply a specific culture
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)
I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.
(function() {
var lastText = '';
$('#MyTextBox'), {
source: MyData
})
.on('autocompleteselect autocompletefocus', function(ev, ui) {
lastText = ui.item.label;
jqTag.data('autocomplete-item', ui.item);
})
.keyup(function(ev) {
if (lastText != jqTag.val()) {
// Clear when they stop typing
jqTag.data('autocomplete-item', null);
// Pass the event on as autocompleteclear so callers can listen for select/clear
var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
return jqTag.trigger(clearEv);
});
})();
With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.
To download the SDK over command line, the link has changed slightly than previously mentioned:
wget --quiet --output-document=/tmp/sdk-tools-linux.zip https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_SDK_TOOLS}.zip
Latest version listed on the downloads page.
Here are shortcuts for the IPython Notebook.
Ctrl-m i
interrupts the kernel. (that is, the sole letter i after Ctrl-m
)
According to this answer, I
twice works as well.
In my case. I had the error because I forgot to make a commit after create a repository on github into an existing project. So I solved:
git add .
git commit -m"commentary"
Then I was able to type:
git push -u origin master
Basically this happened with me, when i tried to change the package name of the app.
So, in emulator, same app was installed before. When i tried to install app after changing package name, it said, authority already used by older application in device.
Simply after uninstalling the application, it solved my problem.
Also, Authority name should always be : your.package.name.UNIQUENAME
;
example :
<provider
android:name="com.aviary.android.feather.cds.AviaryCdsProvider"
android:authorities="your.package.name.AviaryCdsProvider"
/>
In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction()
but instead wrap your code in DB::beginTransaction
and DB::commit
/DB::rollback()
:
DB::beginTransaction();
try {
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit();
// all good
} catch (\Exception $e) {
DB::rollback();
// something went wrong
}
See the transaction docs.
The following converts decimal to Hexa Decimal with Time Complexity : O(n) Linear Time with out any java inbuilt function
private static String decimalToHexaDecimal(int N) {
char hexaDecimals[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
StringBuilder builder = new StringBuilder();
int base= 16;
while (N != 0) {
int reminder = N % base;
builder.append(hexaDecimals[reminder]);
N = N / base;
}
return builder.reverse().toString();
}
I expanded Magoos answer to get both desired strings:
@ECHO OFF
SETLOCAL enabledelayedexpansion
SET "string=string1 by string2.txt"
SET "s2=%string:* by =%"
set "s1=!string: by %s2%=!"
set "s2=%s2:.txt=%"
ECHO +%s1%+%s2%+
EDIT: just to prove, my solution also works with the additional requirements:
@ECHO OFF
SETLOCAL enabledelayedexpansion
SET "string=string&1 more words by string&2 with spaces.txt"
SET "s2=%string:* by =%"
set "s1=!string: by %s2%=!"
set "s2=%s2:.txt=%"
ECHO "+%s1%+%s2%+"
set s1
set s2
Output:
"+string&1 more words+string&2 with spaces+"
s1=string&1 more words
s2=string&2 with spaces
Use wildcards:
cp /home/ankur/folder/* /home/ankur/dest
If you don't want to copy all the files, you can use braces to select files:
cp /home/ankur/folder/{file{1,2},xyz,abc} /home/ankur/dest
This will copy file1
, file2
, xyz
, and abc
.
You should read the sections of the bash
man page on Brace Expansion and Pathname Expansion for all the ways you can simplify this.
Another thing you can do is cd /home/ankur/folder
. Then you can type just the filenames rather than the full pathnames, and you can use filename completion by typing Tab.
Changing the cell property such as the cell's background colors shouldn't be done on the UICollectionViewController itself, it should be done inside you CollectionViewCell class. Don't use didSelect and didDeselect, just use this:
class MyCollectionViewCell: UICollectionViewCell
{
override var isSelected: Bool
{
didSet
{
// Your code
}
}
}
Create a method to recursively iterate through nested lists. If the current element is an instance of list, then call the same method again. If not, print the current element. Here's an example:
data = [1,2,3,[4,[5,6,7,[8,9]]]]
def print_list(the_list):
for each_item in the_list:
if isinstance(each_item, list):
print_list(each_item)
else:
print(each_item)
print_list(data)
This should work:
ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")
In order to reference an external library in a project File -> Settings -> Project -> Project structure -> select the folder and mark as a source
You can get the name value from an input field using name element in jQuery by:
var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD_x000D_
var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ _x000D_
console.log(firstname);_x000D_
console.log(lastname);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form name="form1" id="form1">_x000D_
<input type="text" name="firstname" value="ABCD"/>_x000D_
<input type="text" name="lastname" value="XYZ"/>_x000D_
</form>
_x000D_
You can use my code here
//Print Button Event Handeler
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += PrintPage;
//here to select the printer attached to user PC
PrintDialog printDialog1 = new PrintDialog();
printDialog1.Document = pd;
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
pd.Print();//this will trigger the Print Event handeler PrintPage
}
}
//The Print Event handeler
private void PrintPage(object o, PrintPageEventArgs e)
{
try
{
if (File.Exists(this.ImagePath))
{
//Load the image from the file
System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\myimage.jpg");
//Adjust the size of the image to the page to print the full image without loosing any part of it
Rectangle m = e.MarginBounds;
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}
}
catch (Exception)
{
}
}
alloca () is nice and efficient... but it is also deeply broken.
In most cases you can replace it using local variables and majorant size. If it's used for large objects, putting them on the heap is usually a safer idea.
If you really need it C you can use VLA (no vla in C++, too bad). They are much better than alloca() regarding scope behavior and consistency. As I see it VLA are a kind of alloca() made right.
Of course a local structure or array using a majorant of the needed space is still better, and if you don't have such majorant heap allocation using plain malloc() is probably sane. I see no sane use case where you really really need either alloca() or VLA.
tl;dr
cp -R "/src/project 1/App" "/src/project 2"
Explanation:
Using quotes will cater for spaces in the directory names
cp -R "/src/project 1/App" "/src/project 2"
If the App directory is specified in the destination directory:
cp -R "/src/project 1/App" "/src/project 2/App"
and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"
Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.
Inside a bash script:
cp -R "${1}/App" "${2}"
You can use a regular expression for that pretty easily…
Allowing spaces around the word (but not keeping them):
str.match(/< ?([^>]+) ?>\Z/)[1]
Or without the spaces allowed:
str.match(/<([^>]+)>\Z/)[1]
Use format
with no parameters:
var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"
To me this is just one of many idiosyncracies (emphasis on the idio(t) ) of typescript that causes people to pull out their hair and curse the developers. Maybe they could work on coming up with more understandable error messages.
The optional key
parameter to sort
/sorted
is a function. The function is called for each item and the return values determine the ordering of the sort
>>> lst = [['John', 2], ['Jim', 9], ['Jason', 1]]
>>> def my_key_func(item):
... print("The key for {} is {}".format(item, item[1]))
... return item[1]
...
>>> sorted(lst, key=my_key_func)
The key for ['John', 2] is 2
The key for ['Jim', 9] is 9
The key for ['Jason', 1] is 1
[['Jason', 1], ['John', 2], ['Jim', 9]]
taking the print
out of the function leaves
>>> def my_key_func(item):
... return item[1]
This function is simple enough to write "inline" as a lambda function
>>> sorted(lst, key=lambda item: item[1])
[['Jason', 1], ['John', 2], ['Jim', 9]]