Pass multiple parameter for VB.NET 3.5
Public Class MyWork
Public Structure thread_Data
Dim TCPIPAddr As String
Dim TCPIPPort As Integer
End Structure
Dim STthread_Data As thread_Data
STthread_Data.TCPIPAddr = "192.168.2.2"
STthread_Data.TCPIPPort = 80
Dim multiThread As Thread = New Thread(AddressOf testthread)
multiThread.SetApartmentState(ApartmentState.MTA)
multiThread.Start(STthread_Data)
Private Function testthread(ByVal STthread_Data As thread_Data)
Dim IPaddr as string = STthread_Data.TCPIPAddr
Dim IPport as integer = STthread_Data.TCPIPPort
'Your work'
End Function
End Class
maybe you are looking for
JSON.stringify(JSON.stringify(obj))
"{\"id\":30}"
You can try to do json.loads()
, which will throw a ValueError
if the string you pass can't be decoded as JSON.
In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.
The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:
function getMachine(color, qty) {
var returnValue = null;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
returnValue = thisArray[3];
return false; // this breaks out of the each
}
});
return returnValue;
}
var retval = getMachine(color, qty);
For a partial match, do the following:
getDriver().findElement(By.cssSelector("<tag name>[id*='id pattern to look for']")).click();
Lists are mutable; tuples are not.
From docs.python.org/2/tutorial/datastructures.html
Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
For copy directory use following command
cp -r source Destination
For example
cp -r /home/hasan /opt
For copy file use command without -r
cp /home/file /home/hasan/
If you have a list of contacts the you can go for this:
((Spinner) view.findViewById(R.id.mobile)).setSelection(spinnerContactPersonDesignationAdapter.getPosition(schoolContact.get(i).getCONT_DESIGNATION()));
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
You can use single line comments:
-- this is a comment
# this is also a comment
Or a multiline comment:
/*
multiline
comment
*/
Example using std::vector
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
int main()
{
/// Initilaize vector using intitializer list ( requires C++11 )
std::vector<std::string> names = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
// Sort names using std::sort
std::sort(names.begin(), names.end() );
// Print using range-based and const auto& for ( both requires C++11 )
for(const auto& currentName : names)
{
std::cout << currentName << std::endl;
}
//... or by using your orignal for loop ( vector support [] the same way as plain arrays )
for(int y = 0; y < names.size(); y++)
{
std:: cout << names[y] << std::endl; // you were outputting name[z], but only increasing y, thereby only outputting element z ( 14 )
}
return 0;
}
This completely avoids using plain arrays, and lets you use the std::sort function. You might need to update you compiler to use the = {...}
You can instead add them by using vector.push_back("name")
As shaishab roy says, in the cheat sheet you can find the answer.
But in his answer, the given response was :
{path: '/home/...', name: 'Home', component: HomeComponent} {path: '/', redirectTo: ['Home']}, {path: '/user/...', name: 'User', component: UserComponent}, {path: '/404', name: 'NotFound', component: NotFoundComponent}, {path: '/*path', redirectTo: ['NotFound']}
For some reasons, it doesn't works on my side, so I tried instead :
{path: '/**', redirectTo: ['NotFound']}
and it works. Be careful and don't forget that you need to put it at the end, or else you will often have the 404 error page ;).
"mm" means the "minutes" fragment of a date. For the "months" part, use "MM".
So, try to change the code to:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = df.parse(startDateString);
Edit: A DateFormat object contains a date formatting definition, not a Date object, which contains only the date without concerning about formatting. When talking about formatting, we are talking about create a String representation of a Date in a specific format. See this example:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws Exception {
String startDateString = "06/27/2007";
// This object can interpret strings representing dates in the format MM/dd/yyyy
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
// Convert from String to Date
Date startDate = df.parse(startDateString);
// Print the date, with the default formatting.
// Here, the important thing to note is that the parts of the date
// were correctly interpreted, such as day, month, year etc.
System.out.println("Date, with the default formatting: " + startDate);
// Once converted to a Date object, you can convert
// back to a String using any desired format.
String startDateString1 = df.format(startDate);
System.out.println("Date in format MM/dd/yyyy: " + startDateString1);
// Converting to String again, using an alternative format
DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
String startDateString2 = df2.format(startDate);
System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
}
}
Output:
Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007
For VS 2015 & VS 2017: Right-click the IIS Express system tray icon (when running the application), and select "Show all applications":
Then, select the relevant application and click the applicationhost.config file path:
Apply a css-reset to reset all the margins and paddings like this
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126 License: none (public domain) */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
You can use various css-resets as you need, normal and use in css
html
{
margin: 0px;
padding: 0px;
}
body
{
margin: 0px;
padding: 0px;
}
In HTML5 better use this:
{
//...
canvas.width = img.naturalWidth; //img.width;
canvas.height = img.naturalHeight; //img.height;
//...
}
You may also want to make sure that your code localizes correctly, or make sure the users are used to the "international" notation. For example, "1,112" actually means different numbers across different countries. In Germany it means the number a little over one, instead of one thousand and something.
Corresponding Wikipedia article is at http://en.wikipedia.org/wiki/Decimal_mark. It seems to be poorly written at this time though. For example as a Chinese I'm not sure where does these description about thousand separator in China come from.
suppose you're posting a html form with this:
<input type="text" name="username">
If using raw cgi:
import cgi
form = cgi.FieldStorage()
print form["username"]
If using Django, Pylons, Flask or Pyramid:
print request.GET['username'] # for GET form method
print request.POST['username'] # for POST form method
Using Turbogears, Cherrypy:
from cherrypy import request
print request.params['username']
form = web.input()
print form.username
print request.form['username']
If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:
def index(self, username):
print username
class SomeHandler(webapp2.RequestHandler):
def post(self):
name = self.request.get('username') # this will get the value from the field named username
self.response.write(name) # this will write on the document
So you really will have to choose one of those frameworks.
timeout
is now supported by call()
and communicate()
in the subprocess module (as of Python3.3):
import subprocess
subprocess.call("command", timeout=20, shell=True)
This will call the command and raise the exception
subprocess.TimeoutExpired
if the command doesn't finish after 20 seconds.
You can then handle the exception to continue your code, something like:
try:
subprocess.call("command", timeout=20, shell=True)
except subprocess.TimeoutExpired:
# insert code here
Hope this helps.
In C# 6 and above you can simply use the syntax:
public object Foo { get; set; } = bar;
Note that to have a readonly
property simply omit the set, as so:
public object Foo { get; } = bar;
You can also assign readonly
auto-properties from the constructor.
Prior to this I responded as below.
I'd avoid adding a default to the constructor; leave that for dynamic assignments and avoid having two points at which the variable is assigned (i.e. the type default and in the constructor). Typically I'd simply write a normal property in such cases.
One other option is to do what ASP.Net does and define defaults via an attribute:
http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
From your stack trace, EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
occurred because dispatch_group_t
was released while it was still locking (waiting for dispatch_group_leave
).
According to what you found, this was what happened :
dispatch_group_t group
was created. group
's retain count = 1.-[self webservice:onCompletion:]
captured the group
. group
's retain count = 2.dispatch_async(...., ^{ dispatch_group_wait(group, ...) ... });
captured the group
again. group
's retain count = 3.group
was released. group
's retain count = 2.dispatch_group_leave
was never called.dispatch_group_wait
was timeout. The dispatch_async
block was completed. group
was released. group
's retain count = 1.-[self webservice:onCompletion:]
was called again, the old onCompletion
block was replaced with the new one. So, the old group
was released. group
's retain count = 0. group
was deallocated. That resulted to EXC_BAD_INSTRUCTION
.To fix this, I suggest you should find out why -[self webservice:onCompletion:]
didn't call onCompletion
block, and fix it. Then make sure the next call to the method will happen after the previous call did finish.
In case you allow the method to be called many times whether the previous calls did finish or not, you might find someone to hold group
for you :
DISPATCH_TIME_FOREVER
or a reasonable amount of time that all -[self webservice:onCompletion]
should call their onCompletion
blocks by the time. So that the block in dispatch_async(...)
will hold it for you.group
into a collection, such as NSMutableArray
.I think it is the best approach to create a dedicate class for this action. When you want to make calls to webservice, you then create an object of the class, call the method on it with the completion block passing to it that will release the object. In the class, there is an ivar of dispatch_group_t
or dispatch_semaphore_t
.
Simple ASP.NET MVC subscription form with email textbox would be implemented like that:
The data from the form is mapped to this model
public class SubscribeModel
{
[Required]
public string Email { get; set; }
}
View name should match controller method name.
@model App.Models.SubscribeModel
@using (Html.BeginForm("Subscribe", "Home", FormMethod.Post))
{
@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
<button type="submit">Subscribe</button>
}
Controller is responsible for request processing and returning proper response view.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Subscribe(SubscribeModel model)
{
if (ModelState.IsValid)
{
//TODO: SubscribeUser(model.Email);
}
return View("Index", model);
}
}
Here is my project structure. Please notice, "Home" views folder matches HomeController name.
Apparently random.sample
was introduced in python 2.3
so for version under that, we can use shuffle (example for 4 items):
myRange = range(0,len(mylist))
shuffle(myRange)
coupons = [ bestCoupons[i] for i in sorted(myRange[:4]) ]
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w
covers a-zA-Z and some other word characters. It all depends on what you need specifically.
If you want just to test a cross domain application in which the browser blocks your request, then you can just open your browser in unsafe mode and test your application without changing your code and without making your code unsafe. From MAC OS you can do this from the terminal line:
open -a Google\ Chrome --args --disable-web-security --user-data-dir
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(new Date (currentDate));
currentDate = currentDate.addDays(1);
}
return dateArray;
}
Here is a functional demo http://jsfiddle.net/jfhartsock/cM3ZU/
If using WORD for mac enable 'use maths autocorrect rules outside maths regions' Type \therefore
The ^
negates a character class:
SELECT * FROM mytable WHERE REGEXP_LIKE(column_1, '[^A-Za-z]')
Here is a solid, modern solution. (Short a sweet )
document.addEventListener("visibilitychange", () => {
console.log( document.hasFocus() )
})
This will setup a listener to trigger when any visibility event is fired which could be a focus or blur.
You have to escape each \
to be \\
:
var ttt = "aa ///\\\\\\";
Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.
because you had to show a message to user that user can't give a name which has (\) character.
I think the scenario is like:
var user_input_name = document.getElementById('the_name').value;
Then the asker wants to check if user_input_name
contains any [\
]. If so, then alert the user.
If user enters [aa ///\
] in HTML input box, then if you alert(user_input_name)
, you will see [aaa ///\
]. You don't need to escape, i.e. replace [\
] to be [\\
] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.
I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:
var ttt = "aa ///\";
Hence, we assume the asker having problem with escaping.
If you want to simulate, you code must be valid at first place.
var ttt = "aa ///\\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.
alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?
Now, you only need to do is
var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
do_something_else();
}
Edit: I used []
to quote text to be shown, so it would be less confused than using ""
.
You can use MarkerWithLabel with SVG icons.
Update: The Google Maps Javascript API v3 now natively supports multiple characters in the MarkerLabel
proof of concept fiddle (you didn't provide your icon, so I made one up)
Note: there is an issue with labels on overlapping markers that is addressed by this fix, credit to robd who brought it up in the comments.
code snippet:
function initMap() {_x000D_
var latLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
zoom: 12,_x000D_
center: latLng,_x000D_
mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
});_x000D_
_x000D_
var marker = new MarkerWithLabel({_x000D_
position: homeLatLng,_x000D_
map: map,_x000D_
draggable: true,_x000D_
raiseOnDrag: true,_x000D_
labelContent: "ABCD",_x000D_
labelAnchor: new google.maps.Point(15, 65),_x000D_
labelClass: "labels", // the CSS class for the label_x000D_
labelInBackground: false,_x000D_
icon: pinSymbol('red')_x000D_
});_x000D_
_x000D_
var iw = new google.maps.InfoWindow({_x000D_
content: "Home For Sale"_x000D_
});_x000D_
google.maps.event.addListener(marker, "click", function(e) {_x000D_
iw.open(map, this);_x000D_
});_x000D_
}_x000D_
_x000D_
function pinSymbol(color) {_x000D_
return {_x000D_
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',_x000D_
fillColor: color,_x000D_
fillOpacity: 1,_x000D_
strokeColor: '#000',_x000D_
strokeWeight: 2,_x000D_
scale: 2_x000D_
};_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initMap);
_x000D_
html,_x000D_
body,_x000D_
#map_canvas {_x000D_
height: 500px;_x000D_
width: 500px;_x000D_
margin: 0px;_x000D_
padding: 0px_x000D_
}_x000D_
.labels {_x000D_
color: white;_x000D_
background-color: red;_x000D_
font-family: "Lucida Grande", "Arial", sans-serif;_x000D_
font-size: 10px;_x000D_
text-align: center;_x000D_
width: 30px;_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>_x000D_
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerwithlabel/src/markerwithlabel.js"></script>_x000D_
<div id="map_canvas" style="height: 400px; width: 100%;"></div>
_x000D_
null
is null
. false
is false
. Sad but true.
there's not much consistency in PHP (though it is improving on latest releases, there's too much backward compatibility). Despite the design wishing some consistency (outlined in the selected answer here), it all get confusing when you consider method returns that use false
/null
in not-so-easy to reason ways.
You will often see null being used when they are already using false for something. e.g. filter_input(). They return false if the variable fails the filter, and null if the variable does not exists (does not existing means it also failed the filter?)
Methods returning false/null/string/etc interchangeably is a hack when the author care about the type of failure, for example, with filter_input()
you can check for ===false
or ===null
if you care why the validation failed. But if you don't it might be a pitfall as one might forget to add the check for ===null
if they only remembered to write the test case for ===false
. And most php unit test/coverage tools will not call your attention for the missing, untested code path!
Lastly, here's some fun with type juggling. not even including arrays or objects.
var_dump( 0<0 ); #bool(false)
var_dump( 1<0 ); #bool(false)
var_dump( -1<0 ); #bool(true)
var_dump( false<0 ); #bool(false)
var_dump( null<0 ); #bool(false)
var_dump( ''<0 ); #bool(false)
var_dump( 'a'<0 ); #bool(false)
echo "\n";
var_dump( !0 ); #bool(true)
var_dump( !1 ); #bool(false)
var_dump( !-1 ); #bool(false)
var_dump( !false ); #bool(true)
var_dump( !null ); #bool(true)
var_dump( !'' ); #bool(true)
var_dump( !'a' ); #bool(false)
echo "\n";
var_dump( false == 0 ); #bool(true)
var_dump( false == 1 ); #bool(false)
var_dump( false == -1 ); #bool(false)
var_dump( false == false ); #bool(true)
var_dump( false == null ); #bool(true)
var_dump( false == '' ); #bool(true)
var_dump( false == 'a' ); #bool(false)
echo "\n";
var_dump( null == 0 ); #bool(true)
var_dump( null == 1 ); #bool(false)
var_dump( null == -1 ); #bool(false)
var_dump( null == false ); #bool(true)
var_dump( null == null ); #bool(true)
var_dump( null == '' ); #bool(true)
var_dump( null == 'a' ); #bool(false)
echo "\n";
$a=0; var_dump( empty($a) ); #bool(true)
$a=1; var_dump( empty($a) ); #bool(false)
$a=-1; var_dump( empty($a) ); #bool(false)
$a=false; var_dump( empty($a) ); #bool(true)
$a=null; var_dump( empty($a) ); #bool(true)
$a=''; var_dump( empty($a) ); #bool(true)
$a='a'; var_dump( empty($a)); # bool(false)
echo "\n"; #new block suggested by @thehpi
var_dump( null < -1 ); #bool(true)
var_dump( null < 0 ); #bool(false)
var_dump( null < 1 ); #bool(true)
var_dump( -1 > true ); #bool(false)
var_dump( 0 > true ); #bool(false)
var_dump( 1 > true ); #bool(true)
var_dump( -1 > false ); #bool(true)
var_dump( 0 > false ); #bool(false)
var_dump( 1 > true ); #bool(true)
Make sure you have downloaded the latest 'Command Line Tools' package and run this from a terminal (command line):
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
For some information on Catalina, see Can't compile a C program on a Mac after upgrading to Catalina 10.15.
Extracting a semi-coherent answer from rather extensive comments…
Very often, xcode-select --install
has been the correct solution, but it does not seem to help this time. Have you tried running the main Xcode GUI interface? It may install some extra software for you and clean up. I did that after installing Xcode 10.0, but a week or more ago, long before upgrading to Mojave.
I observe that if your GCC is installed in /usr/local/bin
, you probably aren't using the GCC from Xcode; that's normally installed in /usr/bin
.
I too have updated to macOS 10.14 Mojave and Xcode 10.0. However, both the system /usr/bin/gcc
and system /usr/bin/clang
are working for me (Apple LLVM version 10.0.0 (clang-1000.11.45.2) Target: x86_64-apple-darwin18.0.0
for both.) I have a problem with my home-built GCC 8.2.0 not finding headers in /usr/include
, which is parallel to your problem with /usr/local/bin/gcc
not finding headers either.
I've done a bit of comparison, and my Mojave machine has no /usr/include
at all, yet /usr/bin/clang
is able to compile OK. A header (_stdio.h
, with leading underscore) was in my old /usr/include
; it is missing now (hence my problem with GCC 8.2.0). I ran xcode-select --install
and it said "xcode-select: note: install requested for command line developer tools
" and then ran a GUI installer which showed me a licence which I agreed to, and it downloaded and installed the command line tools — or so it claimed.
I then ran Xcode GUI (command-space, Xcode, return) and it said it needed to install some more software, but still no /usr/include
. But I can compile with /usr/bin/clang
and /usr/bin/gcc
— and the -v
option suggests they're using
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
I've found a way. If we are using Xcode 10, you will notice that if you navigate to the
/usr
in the Finder, you will not see a folder called 'include' any more, which is why the terminal complains of the absence of the header files which is contained inside the 'include' folder. In the Xcode 10.0 Release Notes, it says there is a package:/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
and you should install that package to have the
/usr/include
folder installed. Then you should be good to go.
When all else fails, read the manual or, in this case, the release notes. I'm not dreadfully surprised to find Apple wanting to turn their backs on their Unix heritage, but I am disappointed. If they're careful, they could drive me away. Thank you for the information.
Having installed the package using the following command at the command line, I have /usr/include
again, and my GCC 8.2.0 works once more.
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
As Vesal points out in a valuable comment, you need to download the Command Line Tools package for Xcode 10.1 on Mojave 10.14, and you can do so from:
You need to login with an Apple ID to be able to get the download. When you've done the download, install the Command Line Tools package. Then install the headers as described in the section 'Working Solution'.
This worked for me on Mojave 10.14.1. I must have downloaded this before, but I'd forgotten by the time I was answering this question.
On or about 2019-05-17, I updated to Mojave 10.14.4, and the Xcode 10.2 command line tools were also upgraded (or Xcode 10.1 command line tools were upgraded to 10.2). The open
command shown above fixed the missing headers. There may still be adventures to come with upgrading the main Xcode to 10.2 and then re-reinstalling the command line tools and the headers package.
On 2019-07-22, I got notice via the App Store that the upgrade to Xcode 10.3 is available and that it includes SDKs for iOS 12.4, tvOS 12.4, watchOS 5.3 and macOS Mojave 10.14.6. I installed it one of my 10.14.5 machines, and ran it, and installed extra components as it suggested, and it seems to have left /usr/include
intact.
Later the same day, I discovered that macOS Mojave 10.14.6 was available too (System Preferences ? Software Update), along with a Command Line Utilities package IIRC (it was downloaded and installed automatically). Installing the o/s update did, once more, wipe out /usr/include
, but the open
command at the top of the answer reinstated it again. The date I had on the file for the open
command was 2019-07-15.
The upgrade to XCode 11.0 ("includes Swift 5.1 and SDKs for iOS 13, tvOS 13, watchOS 6 and macOS Catalina 10.15") was released 2019-09-21. I was notified of 'updates available', and downloaded and installed it onto machines running macOS Mojave 10.14.6 via the App Store app (updates tab) without problems, and without having to futz with /usr/include
. Immediately after installation (before having run the application itself), I tried a recompilation and was told:
Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” and then retry this command.
Running that (sudo xcodebuild -license
) allowed me to run the compiler. Since then, I've run the application to install extra components it needs; still no problem. It remains to be seen what happens when I upgrade to Catalina itself — but my macOS Mojave 10.14.6 machines are both OK at the moment (2019-09-24).
Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =
I have improved user2638929 answer and now it can preserves column type, primary key, default value etc.
public static void dropColumns(SQLiteDatabase database, String tableName, Collection<String> columnsToRemove){
List<String> columnNames = new ArrayList<>();
List<String> columnNamesWithType = new ArrayList<>();
List<String> primaryKeys = new ArrayList<>();
String query = "pragma table_info(" + tableName + ");";
Cursor cursor = database.rawQuery(query,null);
while (cursor.moveToNext()){
String columnName = cursor.getString(cursor.getColumnIndex("name"));
if (columnsToRemove.contains(columnName)){
continue;
}
String columnType = cursor.getString(cursor.getColumnIndex("type"));
boolean isNotNull = cursor.getInt(cursor.getColumnIndex("notnull")) == 1;
boolean isPk = cursor.getInt(cursor.getColumnIndex("pk")) == 1;
columnNames.add(columnName);
String tmp = "`" + columnName + "` " + columnType + " ";
if (isNotNull){
tmp += " NOT NULL ";
}
int defaultValueType = cursor.getType(cursor.getColumnIndex("dflt_value"));
if (defaultValueType == Cursor.FIELD_TYPE_STRING){
tmp += " DEFAULT " + "\"" + cursor.getString(cursor.getColumnIndex("dflt_value")) + "\" ";
}else if(defaultValueType == Cursor.FIELD_TYPE_INTEGER){
tmp += " DEFAULT " + cursor.getInt(cursor.getColumnIndex("dflt_value")) + " ";
}else if (defaultValueType == Cursor.FIELD_TYPE_FLOAT){
tmp += " DEFAULT " + cursor.getFloat(cursor.getColumnIndex("dflt_value")) + " ";
}
columnNamesWithType.add(tmp);
if (isPk){
primaryKeys.add("`" + columnName + "`");
}
}
cursor.close();
String columnNamesSeparated = TextUtils.join(", ", columnNames);
if (primaryKeys.size() > 0){
columnNamesWithType.add("PRIMARY KEY("+ TextUtils.join(", ", primaryKeys) +")");
}
String columnNamesWithTypeSeparated = TextUtils.join(", ", columnNamesWithType);
database.beginTransaction();
try {
database.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");
database.execSQL("CREATE TABLE " + tableName + " (" + columnNamesWithTypeSeparated + ");");
database.execSQL("INSERT INTO " + tableName + " (" + columnNamesSeparated + ") SELECT "
+ columnNamesSeparated + " FROM " + tableName + "_old;");
database.execSQL("DROP TABLE " + tableName + "_old;");
database.setTransactionSuccessful();
}finally {
database.endTransaction();
}
}
PS. I used here android.arch.persistence.db.SupportSQLiteDatabase
, but you can easyly modify it for use android.database.sqlite.SQLiteDatabase
I am not sure if something has changed, but I just tried the other answers regarding entries in "eclipse.ini" for Eclipse Galileo SR2 (Windows XP SR3) and none worked. Java is jdk1.6.0_18 and is the default Windows install. Things improved when I dropped "\javaw.exe" from the path.
Also, I can't thank enough the mention that -vm
needs to be first line in the ini file. I believe that really helped me out.
Thus my eclipse.ini file starts with:
-vm
C:\Program Files\Java\jdk1.6.0_18\bin
FYI, my particular need to specify launching Eclipse with a JDK arose from my wanting to work with the m2eclipse plugin.
You can just run:
git stash pop
and it will unstash your changes.
If you want to preserve the state of files (staged vs. working), use
git stash apply --index
Use
$(window).scrollTop()
It'll scroll the window to the item.
var scrollPos = $("#branch1").offset().top;
$(window).scrollTop(scrollPos);
I just created a local connection by breaking my head for hours. So thought of helping you guys.
Step 1: Check your file name listener.ora located at
C:\app\\product\12.1.0\dbhome_3\NETWORK\ADMIN
Check your HOSTNAME, PORT AND SERVICE and give the same while creating new database connection.
Step 2: if this doesnt work, try these combinations give PORT:1521
and SID: orcl
give PORT: and
SID: orcl
give PORT:1521
and SID: pdborcl
give PORT:1521
and
SID: admin
If you get the error as "wrong username and password" :
Make sure you are giving correct username and password
if still it doesnt work try this: Username :system Password: .
Hope it helps!!!!
I had the same issue, and by Running "exec sp_updatestats" the issue solved and works now
It's work!
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitDay;
NSInteger value = 1;
NSDate *today = [NSDate date];
NSDate *tomorrow = [calendar dateByAddingUnit:unit value:value toDate:today options:NSCalendarMatchStrictly];
Google Reflections seems to be much faster than Spring. Found this feature request that adresses this difference: http://www.opensaga.org/jira/browse/OS-738
This is a reason to use Reflections as startup time of my application is really important during development. Reflections seems also to be very easy to use for my use case (find all implementers of an interface).
=IF(ISNA(INDEX(B:B,MATCH(C2,A:A,0))),"",INDEX(B:B,MATCH(C2,A:A,0)))
Will return the answer you want and also remove the #N/A
result that would appear if you couldn't find a result due to it not appearing in your lookup list.
Ross
When we are using normal text at that time we want <p>
tag.when we are using normal text with some effects at that time we want <span>
tag
Might be a bit redundant but the cleanest way i found which builds on some of the answers here:
const params: {
key1: 'value1',
key2: 'value2',
key3: 'value3',
}
const esc = encodeURIComponent;
const query = Object.keys(params)
.map(k => esc(k) + '=' + esc(params[k]))
.join('&');
return fetch('my-url', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: query,
})
I liked @Brad's answer from this thread, but wanted a way to save the results for further processing (MySql 8):
-- May need to adjust the recursion depth first
SET @@cte_max_recursion_depth = 10000 ; -- permit deeper recursion
-- Some boundaries
set @startDate = '2015-01-01'
, @endDate = '2020-12-31' ;
-- Save it to a table for later use
drop table if exists tmpDates ;
create temporary table tmpDates as -- this has to go _before_ the "with", Duh-oh!
WITH RECURSIVE t as (
select @startDate as dt
UNION
SELECT DATE_ADD(t.dt, INTERVAL 1 DAY) FROM t WHERE DATE_ADD(t.dt, INTERVAL 1 DAY) <= @endDate
)
select * FROM t -- need this to get the "with"'s results as a "result set", into the "create"
;
-- Exists?
select * from tmpDates ;
Which produces:
dt |
----------|
2015-01-01|
2015-01-02|
2015-01-03|
2015-01-04|
2015-01-05|
2015-01-06|
OTRS, Cerberus
JavaScript Code
//this function is used to fire click event
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
function showPdf(){
eventFire(document.getElementById('picToClick'), 'click');
}
HTML Code
<img id="picToClick" data-toggle="modal" data-target="#pdfModal" src="img/Adobe-icon.png" ng-hide="1===1">
<button onclick="showPdf()">Click me</button>
Use the stopPropagation method:
event.stopPropagation();
I'd make a comparator using Guava's ComparisonChain
:
public class ReportComparator implements Comparator<Report> {
public int compare(Report r1, Report r2) {
return ComparisonChain.start()
.compare(r1.getReportKey(), r2.getReportKey())
.compare(r1.getStudentNumber(), r2.getStudentNumber())
.compare(r1.getSchool(), r2.getSchool())
.result();
}
}
you can simply do like that in the html part:
<span>Heading Text</span>
and in the css you can make it as an h1 block using display:
span{
display:block;
font-size:20px;
}
you will get it as a h1 without bold ,
if you want it bold just add this to the css:
font-weight:bold;
By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.
In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.
If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.
Here are some examples to illustrate it (my local time offset is UTC+3 during DST):
>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
If you want the date-time string interpreted as UTC, you should be explicit about it:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc()
and include the format string as a second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
To go the other way around and convert a UTC date to a local date, you can use the local()
method, as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"
I found solution. The call:
-(void) someMethod{
UIButton * but;
but.tag = 1;//some id button that you choice
[but addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
}
And here the method called:
-(void) buttonPressed : (id) sender{
UIButton *clicked = (UIButton *) sender;
NSLog(@"%d",clicked.tag);//Here you know which button has pressed
}
If some other portion of your layout is influencing the div
width you can set width:auto
and the div
(which is a block element) will fill the space
<div style="width:auto">
<div style="margin-left:45px;width:auto">
<asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
</div>
</div>
If that's still not working we may need to see more of your layout HTML/CSS
Once, this happens to me as well. and when I googled the matter, I got to know that this happens when the permissions on the file is wrongfully set to 000 (which means that no one can read, write, or execute that file). Then I just changed my file permission privilege into Read & Write and it's worked for me.
To change file permission settings on mac: Right click on the particular file and click on Get info from dropdown menu and refer to the sharing and permissions panel and change privilege settings into Read & Write
Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...
http://www.jetbrains.com/idea/features/editions_comparison_matrix.html
it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.
I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.
Anyway this tells that story too... http://www.jetbrains.com/products.html
…another lambda
copying a new string from the original, but leaving out the character that is to delete
String text = "removing a special character from a string";
int delete = 'e';
int[] arr = text.codePoints().filter( c -> c != delete ).toArray();
String rslt = new String( arr, 0, arr.length );
gives: rmoving a spcial charactr from a string
You need:
record = record[:-1]
before the for
loop.
This will set record
to the current record
list but without the last item. You may, depending on your needs, want to ensure the list isn't empty before doing this.
do it simply
public class Test{
public Test(){
design();
}//end Test()
public void design(){
JFame f = new JFrame();
f.setSize(int w, int h);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
JPanel p = new JPanel();
f.getContentPane().add(p);
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
try{
new Test();
}catch(Exception e){
e.printStackTrace();
}
}
);
}
}
I am also new to MVC and I received the same error and found that it is not passing proper routeValues
in the Index
view or whatever view is present to view the all data.
It was as below
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
I changed it to the as show below and started to work properly.
<td>
@Html.ActionLink("Edit", "Edit", new { EmployeeID=item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
Basically this error can also come because of improper navigation also.
Related to this I had to find a fix where animated gifs were used as a background image to ensure styling was kept to the stylesheet. A similar fix worked for me there too... my script went something like this (I'm using jQuery to make it easier to get the computed background style - how to do that without jQuery is a topic for another post):
var spinner = <give me a spinner element>
window.onbeforeunload = function() {
bg_image = $(spinner).css('background-image');
spinner.style.backgroundImage = 'none';
spinner.style.backgroundImage = bg_image;
}
[EDIT] With a bit more testing I've just realised that this doesn't work with background images in IE8. I've been trying everything I can think of to get IE8 to render a gif animation wile loading a page, but it doesn't look possible at this time.
All of these answers are simple and good. However, I always like to add an interactive mode to these scripts so that I can find false positives.
if [[ -n $inInteractiveMode ]]
then
echo -e -n "$oldFileName => $newFileName\nDo you want to do this change? [Y/n]: "
read run[[ -z $run || "$run" == "y" || "$run" == "Y" ]] && mv "$oldFileName" "$newFileName"
fi
Or make interactive mode the default and add a force flag (-f | --force) for automated scripts or if you're feeling daring. And this doesn't slow you down too much: the default response is "yes, I do want to rename" so you can just hit the enter key at each prompt (because of the ``-z $run\
test.
You have to loop through the list and fill your String[]
.
String[] array = new String[lst.size()];
int index = 0;
for (Object value : lst) {
array[index] = (String) value;
index++;
}
If the list would be of String
values, List then this would be as simple as calling lst.toArray(new String[0])
;
Works on Azure, doesn't require stored procs.
SELECT t.name, s.row_count from sys.tables t
JOIN sys.dm_db_partition_stats s
ON t.object_id = s.object_id
AND t.type_desc = 'USER_TABLE'
AND t.name not like '%dss%'
AND s.index_id IN (0,1)
If you're using this for currency, and also want the value to be seperated by ,
's you can use
$ {:,.f2}.format(currency_value)
.
e.g.:
currency_value = 1234.50
$ {:,.f2}.format(currency_value)
-->
$ 1,234.50
Here is a bit of code I wrote some time ago:
print("> At the end of year " + year_string + " total paid is \t$ {:,.2f}".format(total_paid))
> At the end of year 1 total paid is $ 43,806.36
> At the end of year 2 total paid is $ 87,612.72
> At the end of year 3 total paid is $ 131,419.08
> At the end of year 4 total paid is $ 175,225.44
> At the end of year 5 total paid is $ 219,031.80 <-- Note .80 and not .8
> At the end of year 6 total paid is $ 262,838.16
> At the end of year 7 total paid is $ 306,644.52
> At the end of year 8 total paid is $ 350,450.88
> At the end of year 9 total paid is $ 394,257.24
> At the end of year 10 total paid is $ 438,063.60 <-- Note .60 and not .6
> At the end of year 11 total paid is $ 481,869.96
> At the end of year 12 total paid is $ 525,676.32
> At the end of year 13 total paid is $ 569,482.68
> At the end of year 14 total paid is $ 613,289.04
> At the end of year 15 total paid is $ 657,095.40 <-- Note .40 and not .4
> At the end of year 16 total paid is $ 700,901.76
> At the end of year 17 total paid is $ 744,708.12
> At the end of year 18 total paid is $ 788,514.48
> At the end of year 19 total paid is $ 832,320.84
> At the end of year 20 total paid is $ 876,127.20 <-- Note .20 and not .2
Use this to solve the problem in hive while making connection with MySQL
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:mysql://localhost/metastore?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false</value>
<description>metadata is stored in a MySQL server</description>
</property>
All have highlighted almost all major differences between numpy array and python list, I will just brief them out here:
Numpy arrays have a fixed size at creation, unlike python lists (which can grow dynamically). Changing the size of ndarray will create a new array and delete the original.
The elements in a Numpy array are all required to be of the same data type (we can have the heterogeneous type as well but that will not gonna permit you mathematical operations) and thus will be the same size in memory
Numpy arrays are facilitated advances mathematical and other types of operations on large numbers of data. Typically such operations are executed more efficiently and with less code than is possible using pythons build in sequences
You need to add a name
attribute.
Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3
.
In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]
) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.
Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs
For PHP you can use:
<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
The ZT Process Executor library is an alternative to Apache Commons Exec. It has functionality to run commands, capturing their output, setting timeouts, etc.
I have not used it yet, but it looks reasonably well-documented.
An example from the documentation: Executing a command, pumping the stderr to a logger, returning the output as UTF8 string.
String output = new ProcessExecutor().command("java", "-version")
.redirectError(Slf4jStream.of(getClass()).asInfo())
.readOutput(true).execute()
.outputUTF8();
Its documentation lists the following advantages over Commons Exec:
A small/hidden iframe can work for this purpose.
That way you don't have to worry about closing the pop up.
If you have Apache2.4 check 000-default.conf
- remove DocumentRoot
and add
Redirect permanent / https://[your-domain]/
The IntelliJ debugger has a very handy feature called "Evaluate Expression", that is by far better than eclipses pendant. It has full code-completion and i concider it to be generally "more useful".
If you didn't commit the transaction yet, try rollback
. If you have already committed the transaction (by commit
or by exiting the command line client), you must restore the data from your last backup.
I appreciate this is a very old question but I thought I would add another answer for future users as all the answers to date use some form of Assembly.GetTypes
.
Whilst GetTypes() will indeed return all types, it does not necessarily mean you could activate them and could thus potentially throw a ReflectionTypeLoadException
.
A classic example for not being able to activate a type would be when the type returned is derived
from base
but base
is defined in a different assembly from that of derived
, an assembly that the calling assembly does not reference.
So say we have:
Class A // in AssemblyA
Class B : Class A, IMyInterface // in AssemblyB
Class C // in AssemblyC which references AssemblyB but not AssemblyA
If in ClassC
which is in AssemblyC
we then do something as per accepted answer:
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
Then it will throw a ReflectionTypeLoadException
.
This is because without a reference to AssemblyA
in AssemblyC
you would not be able to:
var bType = typeof(ClassB);
var bClass = (ClassB)Activator.CreateInstance(bType);
In other words ClassB
is not loadable which is something that the call to GetTypes checks and throws on.
So to safely qualify the result set for loadable types then as per this Phil Haacked article Get All Types in an Assembly and Jon Skeet code you would instead do something like:
public static class TypeLoaderExtensions {
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) {
if (assembly == null) throw new ArgumentNullException("assembly");
try {
return assembly.GetTypes();
} catch (ReflectionTypeLoadException e) {
return e.Types.Where(t => t != null);
}
}
}
And then:
private IEnumerable<Type> GetTypesWithInterface(Assembly asm) {
var it = typeof (IMyInterface);
return asm.GetLoadableTypes().Where(it.IsAssignableFrom).ToList();
}
package all.is.well;_x000D_
import java.io.IOException;_x000D_
import java.io.RandomAccessFile;_x000D_
import java.util.concurrent.ExecutorService;_x000D_
import java.util.concurrent.Executors;_x000D_
import junit.framework.TestCase;_x000D_
_x000D_
/**_x000D_
* @author Naresh Bhabat_x000D_
* _x000D_
Following implementation helps to deal with extra large files in java._x000D_
This program is tested for dealing with 2GB input file._x000D_
There are some points where extra logic can be added in future._x000D_
_x000D_
_x000D_
Pleasenote: if we want to deal with binary input file, then instead of reading line,we need to read bytes from read file object._x000D_
_x000D_
_x000D_
_x000D_
It uses random access file,which is almost like streaming API._x000D_
_x000D_
_x000D_
* ****************************************_x000D_
Notes regarding executor framework and its readings._x000D_
Please note :ExecutorService executor = Executors.newFixedThreadPool(10);_x000D_
_x000D_
* for 10 threads:Total time required for reading and writing the text in_x000D_
* :seconds 349.317_x000D_
* _x000D_
* For 100:Total time required for reading the text and writing : seconds 464.042_x000D_
* _x000D_
* For 1000 : Total time required for reading and writing text :466.538 _x000D_
* For 10000 Total time required for reading and writing in seconds 479.701_x000D_
*_x000D_
* _x000D_
*/_x000D_
public class DealWithHugeRecordsinFile extends TestCase {_x000D_
_x000D_
static final String FILEPATH = "C:\\springbatch\\bigfile1.txt.txt";_x000D_
static final String FILEPATH_WRITE = "C:\\springbatch\\writinghere.txt";_x000D_
static volatile RandomAccessFile fileToWrite;_x000D_
static volatile RandomAccessFile file;_x000D_
static volatile String fileContentsIter;_x000D_
static volatile int position = 0;_x000D_
_x000D_
public static void main(String[] args) throws IOException, InterruptedException {_x000D_
long currentTimeMillis = System.currentTimeMillis();_x000D_
_x000D_
try {_x000D_
fileToWrite = new RandomAccessFile(FILEPATH_WRITE, "rw");//for random write,independent of thread obstacles _x000D_
file = new RandomAccessFile(FILEPATH, "r");//for random read,independent of thread obstacles _x000D_
seriouslyReadProcessAndWriteAsynch();_x000D_
_x000D_
} catch (IOException e) {_x000D_
// TODO Auto-generated catch block_x000D_
e.printStackTrace();_x000D_
}_x000D_
Thread currentThread = Thread.currentThread();_x000D_
System.out.println(currentThread.getName());_x000D_
long currentTimeMillis2 = System.currentTimeMillis();_x000D_
double time_seconds = (currentTimeMillis2 - currentTimeMillis) / 1000.0;_x000D_
System.out.println("Total time required for reading the text in seconds " + time_seconds);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* @throws IOException_x000D_
* Something asynchronously serious_x000D_
*/_x000D_
public static void seriouslyReadProcessAndWriteAsynch() throws IOException {_x000D_
ExecutorService executor = Executors.newFixedThreadPool(10);//pls see for explanation in comments section of the class_x000D_
while (true) {_x000D_
String readLine = file.readLine();_x000D_
if (readLine == null) {_x000D_
break;_x000D_
}_x000D_
Runnable genuineWorker = new Runnable() {_x000D_
@Override_x000D_
public void run() {_x000D_
// do hard processing here in this thread,i have consumed_x000D_
// some time and ignore some exception in write method._x000D_
writeToFile(FILEPATH_WRITE, readLine);_x000D_
// System.out.println(" :" +_x000D_
// Thread.currentThread().getName());_x000D_
_x000D_
}_x000D_
};_x000D_
executor.execute(genuineWorker);_x000D_
}_x000D_
executor.shutdown();_x000D_
while (!executor.isTerminated()) {_x000D_
}_x000D_
System.out.println("Finished all threads");_x000D_
file.close();_x000D_
fileToWrite.close();_x000D_
}_x000D_
_x000D_
/**_x000D_
* @param filePath_x000D_
* @param data_x000D_
* @param position_x000D_
*/_x000D_
private static void writeToFile(String filePath, String data) {_x000D_
try {_x000D_
// fileToWrite.seek(position);_x000D_
data = "\n" + data;_x000D_
if (!data.contains("Randomization")) {_x000D_
return;_x000D_
}_x000D_
System.out.println("Let us do something time consuming to make this thread busy"+(position++) + " :" + data);_x000D_
System.out.println("Lets consume through this loop");_x000D_
int i=1000;_x000D_
while(i>0){_x000D_
_x000D_
i--;_x000D_
}_x000D_
fileToWrite.write(data.getBytes());_x000D_
throw new Exception();_x000D_
} catch (Exception exception) {_x000D_
System.out.println("exception was thrown but still we are able to proceeed further"_x000D_
+ " \n This can be used for marking failure of the records");_x000D_
//exception.printStackTrace();_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
}
_x000D_
You can also type "top" and look at the list of running processes.
#fullDiv {
height: 100%;
width: 100%;
left: 0;
top: 0;
overflow: hidden;
position: fixed;
}
One of the most used tool in the scientific community to that purpose is DummyNet. Once you have installed the ipfw
kernel module, in order to introduce 50ms propagation delay between 2 machines simply run these commands:
./ipfw pipe 1 config delay 50ms
./ipfw add 1000 pipe 1 ip from $IP_MACHINE_1 to $IP_MACHINE_2
In order to also introduce 50% of packet losses you have to run:
./ipfw pipe 1 config plr 0.5
Here more details.
I can imagine following advantages of having a class method defined as static one:
remaining advantages are probably marginal if present at all:
As above mentioned, there is no special command to do it. However, if all those connection are inactive, using 'flush tables;' is able to release all those connection which are not active.
If you want to use SimpleDateFormat
, you could write:
private final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
{ sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }
private long parseTimeToMillis(final String time) throws ParseException
{ return sdf.parse("1970-01-01 " + time).getTime(); }
But a custom method would be much more efficient. SimpleDateFormat
, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)
Also, SimpleDateFormat
is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)
Personally, I'd probably write a custom method.
sample text:
"this is a test sentence; to prove this regex; that is g;iven below"
If for example we have the sample text above, the regex /(.*?\;)/
will give you everything until the first occurence of semicolon (;
), including the semicolon: "this is a test sentence;"
FWIW, since regular languages (aka rational languages) are closed under complementation, it's always possible to find a regular expression (aka rational expression) that negates another expression. But not many tools implement this.
Vcsn supports this operator (which it denotes {c}
, postfix).
You first define the type of your expressions: labels are letter (lal_char
) to pick from a
to z
for instance (defining the alphabet when working with complementation is, of course, very important), and the "value" computed for each word is just a Boolean: true
the word is accepted, false
, rejected.
In Python:
In [5]: import vcsn
c = vcsn.context('lal_char(a-z), b')
c
Out[5]: {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z} ?
then you enter your expression:
In [6]: e = c.expression('(hede){c}'); e
Out[6]: (hede)^c
convert this expression to an automaton:
In [7]: a = e.automaton(); a
finally, convert this automaton back to a simple expression.
In [8]: print(a.expression())
\e+h(\e+e(\e+d))+([^h]+h([^e]+e([^d]+d([^e]+e[^]))))[^]*
where +
is usually denoted |
, \e
denotes the empty word, and [^]
is usually written .
(any character). So, with a bit of rewriting ()|h(ed?)?|([^h]|h([^e]|e([^d]|d([^e]|e.)))).*
.
Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:
with open('Path/to/file', 'r') as content_file:
content_list = content_file.read().strip().split("\n")
As can be seen, one needs to add the concatenated methods .strip().split("\n")
to the main answer in this thread.
Here, .strip()
just removes whitespace and newline characters at the endings of the entire file string,
and .split("\n")
produces the actual list via splitting the entire file string at every newline character \n.
Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.
Its a late answer, but as I can see most of the people mentioned about "refresh" method to redirect a webpage. As per W3C, we should not use "refresh" to redirect. Because it could break the "back" button. Imagine that the user presses the "back" button, the refresh would work again, and the user would bounce forward. The user will most likely get very annoyed, and close the window, which is probably not what you, as the author of this page, want.
Use HTTP redirects instead. One can refer the complete documentation here: W3C document
For OS X use this command:
sudo chown -R www:www /www/folder_name
You can do it programmatically:
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select", "NA"));
Or add it in markup as:
<asp:DropDownList .. AppendDataBoundItems="true">
<Items>
<asp:ListItem Text="Select" Value="" />
</Items>
</asp:DropDownList>
It could be something like:
var qry = from t in db.Lasttraces
group t by t.AccountId into g
orderby t.Date
select new { g.AccountId, Date = g.Max(e => e.Date) };
One can also do this :
<xsl:text disable-output-escaping="yes"><![CDATA[ ]]></xsl:text>
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
I messed with my css for hours, changing the positioning and z-index of just about every element on the page. I deleted every other element from the DOM except for the one with the cursor: pointer on hover, and it STILL didn't work.
For me, on Mac OSX El Captain V 10.11, the issue had to do with some sort of interference with Photoshop CC. Once I closed photoshop, the cursor started working again.
Solution for me: Close and reopen photoshop
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'Category';
$join_str[0]['join_table_id'] = 'Category.cat_id';
$join_str[0]['from_table_id'] = 'Album.cat_id';
$join_str[0]['join_type'] = 'left';
$join_str[1]['table'] = 'Soundtrack';
$join_str[1]['join_table_id'] = 'Soundtrack.album_id';
$join_str[1]['from_table_id'] = 'Album.album_id';
$join_str[1]['join_type'] = 'left';
$selected = "Album.*,Category.cat_name,Category.cat_title,Soundtrack.track_title,Soundtrack.track_url";
$albumData= $this->common->select_data_by_condition('Album', array('Soundtrack.album_id' => $album_id), $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}
Use the correct call: strptime
is a classmethod of the datetime.datetime
class, it's not a function in the datetime
module.
self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")
As mentioned by Jon Clements in the comments, some people do from datetime import datetime
, which would bind the datetime
name to the datetime
class, and make your initial code work.
To identify which case you're facing (in the future), look at your import statements
import datetime
: that's the module (that's what you have right now).from datetime import datetime
: that's the class.The difference between 'exec' and 'system' is that exec replaces your current program with 'command' and NEVER returns to your program. system, on the other hand, forks and runs 'command' and returns you the exit status of 'command' when it is done running. The back tick runs 'command' and then returns a string representing its standard out (whatever it would have printed to the screen)
You can also use popen to run shell commands and I think that there is a shell module - 'use shell' that gives you transparent access to typical shell commands.
Hope that clarifies it for you.
For me the code:
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
throws error, but I added name attribute to input:
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
and it started to work.
You can use any
:
print any(df.column == 07311954)
True #true if it contains the number, false otherwise
If you rather want to see how many times '07311954' occurs in a column you can use:
df.column[df.column == 07311954].count()
One (good, IMO) difference between Scala and other languages is that it lets you name your methods with almost any character.
What you enumerate is not "punctuation" but plain and simple methods, and as such their behavior vary from one object to the other (though there are some conventions).
For example, check the Scaladoc documentation for List, and you'll see some of the methods you mentioned here.
Some things to keep in mind:
Most of the times the A operator+equal B
combination translates to A = A operator B
, like in the ||=
or ++=
examples.
Methods that end in :
are right associative, this means that A :: B
is actually B.::(A)
.
You'll find most answers by browsing the Scala documentation. Keeping a reference here would duplicate efforts, and it would fall behind quickly :)
In case you just need one (first) value to retrieve from xml:
public static String getTagValue(String xml, String tagName){
return xml.split("<"+tagName+">")[1].split("</"+tagName+">")[0];
}
In case you want to parse whole xml document use JSoup:
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
for (Element e : doc.select("Request")) {
System.out.println(e);
}
Quick solution in NetBeans 6.8.
In the Projects window right-click on the name of the project that lacks library -> Properties -> The Project Properties window opens. In Categories tree select "Libraries" node -> On the right side of the Project Properties window press button "Add JAR/Folder" -> Select jars you need.
You also can see my short Video How-To.
Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).
json_encode($array,JSON_UNESCAPED_SLASHES);
Windows 10 uwp
application.
Try this:
webview.Navigate(new Uri("ms-appx-web:///index.html"));
For now, it seems that I could get over that by adding a ?
after the URL.
I recommend the method given by doofledorfer.
If you really want to do it via a direct API call, then look at the OpenSCManager function. Below are sample functions to take a machine name and service, and stop or start them.
function ServiceStart(sMachine, sService : string) : boolean; //start service, return TRUE if successful
var schm, schs : SC_Handle;
ss : TServiceStatus;
psTemp : PChar;
dwChkP : DWord;
begin
ss.dwCurrentState := 0;
schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT); //connect to the service control manager
if(schm > 0)then begin // if successful...
schs := OpenService( schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS); // open service handle, start and query status
if(schs > 0)then begin // if successful...
psTemp := nil;
if (StartService(schs,0,psTemp)) and (QueryServiceStatus(schs,ss)) then
while(SERVICE_RUNNING <> ss.dwCurrentState)do begin
dwChkP := ss.dwCheckPoint; //dwCheckPoint contains a value incremented periodically to report progress of a long operation. Store it.
Sleep(ss.dwWaitHint); //Sleep for recommended time before checking status again
if(not QueryServiceStatus(schs,ss))then
break; //couldn't check status
if(ss.dwCheckPoint < dwChkP)then
Break; //if QueryServiceStatus didn't work for some reason, avoid infinite loop
end; //while not running
CloseServiceHandle(schs);
end; //if able to get service handle
CloseServiceHandle(schm);
end; //if able to get svc mgr handle
Result := SERVICE_RUNNING = ss.dwCurrentState; //if we were able to start it, return true
end;
function ServiceStop(sMachine, sService : string) : boolean; //stop service, return TRUE if successful
var schm, schs : SC_Handle;
ss : TServiceStatus;
dwChkP : DWord;
begin
schm := OpenSCManager(PChar(sMachine),nil,SC_MANAGER_CONNECT);
if(schm > 0)then begin
schs := OpenService(schm,PChar(sService),SERVICE_STOP or SERVICE_QUERY_STATUS);
if(schs > 0)then begin
if (ControlService(schs,SERVICE_CONTROL_STOP,ss)) and (QueryServiceStatus(schs,ss)) then
while(SERVICE_STOPPED <> ss.dwCurrentState) do begin
dwChkP := ss.dwCheckPoint;
Sleep(ss.dwWaitHint);
if(not QueryServiceStatus(schs,ss))then
Break;
if(ss.dwCheckPoint < dwChkP)then
Break;
end; //while
CloseServiceHandle(schs);
end; //if able to get svc handle
CloseServiceHandle(schm);
end; //if able to get svc mgr handle
Result := SERVICE_STOPPED = ss.dwCurrentState;
end;
You should follow the guidelines on Add a secondary horizontal axis:
To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.
Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Layout tab, in the Axes group, click Axes.
Click Secondary Horizontal Axis, and then click the display option that you want.
You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.
In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:
Click the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.
On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.
Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.
On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.
A secondary vertical axis is displayed in the chart.
To change the display of the secondary vertical axis, do the following:
On the Layout tab, in the Axes group, click Axes.
Click Secondary Vertical Axis, and then click the display option that you want.
To change the axis options of the secondary vertical axis, do the following:
Right-click the secondary vertical axis, and then click Format Axis.
Under Axis Options, select the options that you want to use.
Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).
I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:
sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF
In order to select an element by attribute having a specific characteristic you may create a new selector like in the following snippet using a regex pattern. The usage of regex is intended to make flexible the new selector as much as possible:
jQuery.extend(jQuery.expr[':'], {
nameMatch: function (ele, idx, selector) {
var rpStr = (selector[3] || '').replace(/^\/(.*)\/$/, '$1');
return (new RegExp(rpStr)).test(ele.name);
}
});
//
// use of selector
//
$('input:nameMatch(/^pages_title\\[\\d\\]$/)').each(function(idx, ele) {
console.log(ele.outerHTML);
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">
<input type="text" value="1" name="pages_title[]">
_x000D_
Another solution can be based on:
[name^=”value”]: selects elements that have the specified attribute with a value beginning exactly with a given string.
.filter(): reduce the set of matched elements to those that match the selector or pass the function's test.
var selectedEle = $(':input[name^="pages_title"]').filter(function(idx, ele) {
//
// test if the name attribute matches the pattern.....
//
return /^pages_title\[\d\]$/.test(ele.name);
});
selectedEle.each(function(idx, ele) {
console.log(ele.outerHTML);
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="2" name="pages_title[1]">
<input type="text" value="1" name="pages_title[2]">
<input type="text" value="1" name="pages_title[]">
_x000D_
An understanding of the Iterator pattern will be helpful for you. I recommend reading the same.
At a high level the iterator pattern can be used to provide a standard way of iterating through collections of any type. We have 3 participants in the iterator pattern, the actual collection (client), the aggregator and the iterator. The aggregate is an interface/abstract class that has a method that returns an iterator. Iterator is an interface/abstract class that has methods allowing us to iterate through a collection.
In order to implement the pattern we first need to implement an iterator to produce a concrete that can iterate over the concerned collection (client) Then the collection (client) implements the aggregator to return an instance of the above iterator.
So basically in c#, IEnumerable is the abstract aggregate and IEnumerator is the abstract Iterator. IEnumerable has a single method GetEnumerator that is responsible for creating an instance of IEnumerator of the desired type. Collections like Lists implement the IEnumerable.
Example.
Lets suppose that we have a method getPermutations(inputString)
that returns all the permutations of a string and that the method returns an instance of IEnumerable<string>
In order to count the number of permutations we could do something like the below.
int count = 0;
var permutations = perm.getPermutations(inputString);
foreach (string permutation in permutations)
{
count++;
}
The c# compiler more or less converts the above to
using (var permutationIterator = perm.getPermutations(input).GetEnumerator())
{
while (permutationIterator.MoveNext())
{
count++;
}
}
If you have any questions please don't hesitate to ask.
Not least important is why these symbols occur in url. See https://www.php.net/manual/en/function.parse-str.php#76792, specifically:
parse_str('foo[]=1&foo[]=2&foo[]=3', $bar);
the above produces:
$bar = ['foo' => ['1', '2', '3'] ];
and what is THE method to separate query vars in arrays (in php, at least).
Getting the Text of ComboBox when the item is changed
self.ui.comboBox.activated.connect(self.pass_Net_Adap)
def pass_Net_Adap(self):
print str(self.ui.comboBox.currentText())
Or, similar to erikkallen's idea, make the background of the A tag black, and make the image semitransparent on mouseover. That way you won't have to create additional divs.
Source for the CSS-based solution:
a.darken {
display: inline-block;
background: black;
padding: 0;
}
a.darken img {
display: block;
-webkit-transition: all 0.5s linear;
-moz-transition: all 0.5s linear;
-ms-transition: all 0.5s linear;
-o-transition: all 0.5s linear;
transition: all 0.5s linear;
}
a.darken:hover img {
opacity: 0.7;
}
And the image:
<a href="http://google.com" class="darken">
<img src="http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg" width="200">
</a>
I used a global action filter to remove Accept: application/xml
when the User-Agent
header contains "Chrome":
internal class RemoveXmlForGoogleChromeFilter : IActionFilter
{
public bool AllowMultiple
{
get { return false; }
}
public async Task<HttpResponseMessage> ExecuteActionFilterAsync(
HttpActionContext actionContext,
CancellationToken cancellationToken,
Func<Task<HttpResponseMessage>> continuation)
{
var userAgent = actionContext.Request.Headers.UserAgent.ToString();
if (userAgent.Contains("Chrome"))
{
var acceptHeaders = actionContext.Request.Headers.Accept;
var header =
acceptHeaders.SingleOrDefault(
x => x.MediaType.Contains("application/xml"));
acceptHeaders.Remove(header);
}
return await continuation();
}
}
Seems to work.
Update:
_.find would be better as it breaks out of the loop when the element is found:
var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){
count = count +1;
if(arrEl.id === 1 ){
return arrEl;
}
});
console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1
** Old **
If you want to conditionally break out of a loop, use _.filter api instead of _.each. Here is a code snippet
var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){
if(arrEl.id === 1 ){
return arrEl;
}
});
console.log(filteredEl);
//output: {id:1,text:"foo"}
It's a matter of scope. In short, global variables should be avoided so:
You either need to pass it as a parameter:
$data = 'My data';
function menugen($data)
{
echo $data;
}
Or have it in a class and access it
class MyClass
{
private $data = "";
function menugen()
{
echo this->data;
}
}
See @MatteoTassinari answer as well, as you can mark it as global to access it, but global variables are generally not required, so it would be wise to re-think your coding.
Provide a path (myfolder in this case) and just run:
git diff myfolder/
Try this in Swift 3
array.remove(at: Index)
Instead of
array.removeAtIndex(index)
Update
"Declaration is only valid at file scope".
Make sure the object is in scope. You can give scope "internal", which is default.
index(of:<Object>)
to work, class should conform to Equatable
If the path you want is the one to the workbook running the macro, and that workbook has been saved, then
ThisWorkbook.Path
is what you would use.
very simple
$('#label-ID').text("label value which you want to set");
The Valery's answer helped me: https://stackoverflow.com/a/14265815/492457
WAMP uses different php.ini files in the CLI and for Apache. when you enable php_openssl through the WAMP UI, you enable it for Apache, not for the CLI. You need to modify C:\wamp\bin\php\php-5.4.3\php.ini to enable it for the CLI.
$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
// Echo out a sample image
echo '<img src="' . $src . '">';
Only static functions are called with class name.
classname::Staicfunction();
Non static functions have to be called using objects.
classname obj;
obj.Somefunction();
This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.
please try to do
make clean
(instead of make
), then
make
again.
I like this example, which for now, leaves out the check which you could add inside the while block:
ifstream iFile("input.txt"); // input.txt has integers, one per line
int x;
while (iFile >> x)
{
cerr << x << endl;
}
Not sure how safe it is...
I would add that HTMLElement has a built-in .blur
method as well.
Here's a demo using both .focus
and .blur
which work in similar ways.
const input = document.querySelector("#myInput");
_x000D_
<input id="myInput" value="Some Input">_x000D_
_x000D_
<button type="button" onclick="input.focus()">Focus</button>_x000D_
<button type="button" onclick="input.blur()">Lose focus</button>
_x000D_
You might include the implementation of itoa in your project.
Here's itoa modified to work with std::string: http://www.strudel.org.uk/itoa/
Please explain why same ng-model
is used? And what value is passed through ng- model
and how it is passed? To be more specific, if I use console.log(color)
what would be the output?
I this answer to setup a combo box from an enum attributes which was great.
I then needed to code the reverse so that I can get the selection from the box and return the enum in the correct type.
I also modified the code to handle the case where an attribute was missing
For the benefits of the next person, here is my final solution
public static class Program
{
static void Main(string[] args)
{
// display the description attribute from the enum
foreach (Colour type in (Colour[])Enum.GetValues(typeof(Colour)))
{
Console.WriteLine(EnumExtensions.ToName(type));
}
// Get the array from the description
string xStr = "Yellow";
Colour thisColour = EnumExtensions.FromName<Colour>(xStr);
Console.ReadLine();
}
public enum Colour
{
[Description("Colour Red")]
Red = 0,
[Description("Colour Green")]
Green = 1,
[Description("Colour Blue")]
Blue = 2,
Yellow = 3
}
}
public static class EnumExtensions
{
// This extension method is broken out so you can use a similar pattern with
// other MetaData elements in the future. This is your base method for each.
public static T GetAttribute<T>(this Enum value) where T : Attribute
{
var type = value.GetType();
var memberInfo = type.GetMember(value.ToString());
var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
// check if no attributes have been specified.
if (((Array)attributes).Length > 0)
{
return (T)attributes[0];
}
else
{
return null;
}
}
// This method creates a specific call to the above method, requesting the
// Description MetaData attribute.
public static string ToName(this Enum value)
{
var attribute = value.GetAttribute<DescriptionAttribute>();
return attribute == null ? value.ToString() : attribute.Description;
}
/// <summary>
/// Find the enum from the description attribute.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="desc"></param>
/// <returns></returns>
public static T FromName<T>(this string desc) where T : struct
{
string attr;
Boolean found = false;
T result = (T)Enum.GetValues(typeof(T)).GetValue(0);
foreach (object enumVal in Enum.GetValues(typeof(T)))
{
attr = ((Enum)enumVal).ToName();
if (attr == desc)
{
result = (T)enumVal;
found = true;
break;
}
}
if (!found)
{
throw new Exception();
}
return result;
}
}
}
It's kind of ugly if the resizing code is almost as long as the code for building the graph in first place. So instead of resizing every element of the existing chart, why not simply reloading it? Here is how it worked for me:
function data_display(data){
e = document.getElementById('data-div');
var w = e.clientWidth;
// remove old svg if any -- otherwise resizing adds a second one
d3.select('svg').remove();
// create canvas
var svg = d3.select('#data-div').append('svg')
.attr('height', 100)
.attr('width', w);
// now add lots of beautiful elements to your graph
// ...
}
data_display(my_data); // call on page load
window.addEventListener('resize', function(event){
data_display(my_data); // just call it again...
}
The crucial line is d3.select('svg').remove();
. Otherwise each resizing will add another SVG element below the previous one.
I've run across this issue a few times and in each case I was rebuilding a computer or switching to a new computer. My first step (besides updating the machine and installing Visual Studio) is to pull my projects down from Git and test them.
I hit this error each time because I tried to access my local code before compiling it. You see, I have Git and Subversion setup to ignore my bin/build folders, so after a pull from my repository I forgot to run a build which pulls required packages from Nuget (since I have Git/SVN ignore those too) and creates the DLLs needed to actually run my app.
I doubt this will resolve most people's issues, but I didn't see it on the list of potential solutions so I thought I'd add it.
If you're on Linux/Unix you could avoid call() altogether and not execute an entirely new instance of the Python executable and its environment.
import os
cpid = os.fork()
if not cpid:
import somescript
os._exit(0)
os.waitpid(cpid, 0)
For what it's worth.
Alternatively, you can use the method int integerValue = (int)Math.round(double a);
You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.
int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
// it's a valid integer => you could use the distance variable here
}
In my case not was working out, finally i restarted my oracle and TNS listener and everything worked. Was struggling for 2 days.
Above answer is good. Here is another way to do:-
function getMonthNumber($monthStr) {
//e.g, $month='Jan' or 'January' or 'JAN' or 'JANUARY' or 'january' or 'jan'
$m = ucfirst(strtolower(trim($monthStr)));
switch ($m) {
case "January":
case "Jan":
$m = "01";
break;
case "February":
case "Feb":
$m = "02";
break;
case "March":
case "Mar":
$m = "03";
break;
case "April":
case "Apr":
$m = "04";
break;
case "May":
$m = "05";
break;
case "June":
case "Jun":
$m = "06";
break;
case "July":
case "Jul":
$m = "07";
break;
case "August":
case "Aug":
$m = "08";
break;
case "September":
case "Sep":
$m = "09";
break;
case "October":
case "Oct":
$m = "10";
break;
case "November":
case "Nov":
$m = "11";
break;
case "December":
case "Dec":
$m = "12";
break;
default:
$m = false;
break;
}
return $m;
}
IIS now has
Idle Time-out Action : Suspend
setting
Suspending is just freezes the process and it is much more efficient than the destroying the process.
I have a slightly different setup, but think my solution will help you out.
I have a Windows 8 Machine, Python 2.7 installed and running my stuff through eclipse.
Some Background:
When I did an easy install
it tries to install MySQL-python 1.2.5
which failed with an error: Unable to find vcvarsall.bat
. I did an easy_install
of pip
and tried the pip
install which also failed with a similar error. They both reference vcvarsall.bat
which is something to do with visual studio, since I don't have visual studio on my machine, it left me looking for a different solution, which I share below.
The Solution:
After I did both of those installs I was able to query my MySQL db through eclipse.
In PHP you can add the headers:
<?php
header ("Access-Control-Allow-Origin: *");
header ("Access-Control-Expose-Headers: Content-Length, X-JSON");
header ("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header ("Access-Control-Allow-Headers: *");
...
Unfortunately, there is no standard way to print using Python on all platforms. So you'll need to write your own wrapper function to print.
You need to detect the OS your program is running on, then:
For Linux -
import subprocess
lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(your_data_here)
For Windows: http://timgolden.me.uk/python/win32_how_do_i/print.html
More resources:
Print PDF document with python's win32print module?
How do I print to the OS's default printer in Python 3 (cross platform)?
for me, I have to add
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
right after:
xmlns:android="http://schemas.android.com/apk/res/android"
in res/layout/main.xml
As @espinchi mentioned from 3.2 (API level 13) size groups are deprecated. Screen size ranges are the favored approach going forward.
In adition to the other answers mentioning the Tasks view:
It is also possible to filter the Tasks that are listed to only show the TODOs that contain the text // TODO Auto-generated method stub
.
To achieve this you can click on the Filters... button in the top right of the Tasks View and define custom filters like this:
This way it's a bit easier and faster to find only some of the TODOs in the project in the Tasks View, and you don't have to search for the text in all files using the eclipse search tool (which can take quite some time).
This will return TRUE
for #VALUE!
errors (ERROR.TYPE = 3) and FALSE
for anything else.
=IF(ISERROR(A1),ERROR.TYPE(A1)=3)
Stub of console in TypeScript:
if (!window.console) {
console = {
assert: () => { },
clear: () => { },
count: () => { },
debug: () => { },
dir: () => { },
dirxml: () => { },
error: () => { },
group: () => { },
groupCollapsed: () => { },
groupEnd: () => { },
info: () => { },
log: () => { },
msIsIndependentlyComposed: (e: Element) => false,
profile: () => { },
profileEnd: () => { },
select: () => { },
time: () => { },
timeEnd: () => { },
trace: () => { },
warn: () => { },
}
};
Very simple code to make jquery slider Here is two div first is the slider viewer and second is the image list container. Just copy paste the code and customise with css.
<div class="featured-image" style="height:300px">
<img id="thumbnail" src="01.jpg"/>
</div>
<div class="post-margin" style="margin:10px 0px; padding:0px;" id="thumblist">
<img src='01.jpg'>
<img src='02.jpg'>
<img src='03.jpg'>
<img src='04.jpg'>
</div>
<script type="text/javascript">
function changeThumbnail()
{
$("#thumbnail").fadeOut(200);
var path=$("#thumbnail").attr('src');
var arr= new Array(); var i=0;
$("#thumblist img").each(function(index, element) {
arr[i]=$(this).attr('src');
i++;
});
var index= arr.indexOf(path);
if(index==(arr.length-1))
path=arr[0];
else
path=arr[index+1];
$("#thumbnail").attr('src',path).fadeIn(200);
setTimeout(changeThumbnail, 5000);
}
setTimeout(changeThumbnail, 5000);
</script>
You may note that request.json or request.get_json() works only when the "Content-type: application/json" has been added in the header of the request. If you are unable to change the client request configuration, so you can get the body as json like this:
data = json.loads(request.data)
Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'
Select ProductName,
IsNull([1],0) as 'Week 1',
IsNull([2],0) as 'Week 2',
IsNull([3],0) as 'Week 3',
IsNull([4],0) as 'Week 4',
IsNull([5], 0) as 'Week 5'
From
(
Select ProductName,
DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, '2011-05-30'), 0), '2011-05-30') +1 as [Weeks],
Sale as 'Sale'
From dbo.WeekReport
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, '2011-05-30')= DatePart(Month, @DatePeriod)
)p
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv
OUTPUT LOOK LIKE THIS
a 0 0 0 0 20
b 0 0 0 0 4
c 0 0 0 0 3
You can try Alasql JavaScript library which can work together with XLSX.js library for easy export of Angular.js data. This is an example of controller with exportData() function:
function myCtrl($scope) {
$scope.exportData = function () {
alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
};
$scope.items = [{
name: "John Smith",
email: "[email protected]",
dob: "1985-10-10"
}, {
name: "Jane Smith",
email: "[email protected]",
dob: "1988-12-22"
}];
}
See full HTML and JavaScript code for this example in jsFiddle.
UPDATED Another example with coloring cells.
Also you need to include two libraries:
Use Console.KeyAvailable
so that you only call ReadKey
when you know it won't block:
Console.WriteLine("Press ESC to stop");
do {
while (! Console.KeyAvailable) {
// Do something
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
$(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
alert("Ctrl-S pressed");
event.preventDefault();
return false;
});
Key codes can differ between browsers, so you may need to check for more than just 115.
In the constructor of the Form or UserControl holding the TextBox write
SetStyle(ControlStyles.Selectable, false);
After the InitializeComponent(); Source: https://stackoverflow.com/a/4811938/5750078
Example:
public partial class Main : UserControl
{
public Main()
{
InitializeComponent();
SetStyle(ControlStyles.Selectable, false);
}
For Boto3 , use this code.
import boto3
from botocore.client import Config
s3 = boto3.resource('s3',
aws_access_key_id='xxxxxx',
aws_secret_access_key='xxxxxx',
region_name='us-south-1',
config=Config(signature_version='s3v4')
)
Please consider using HttpPost. Adopt from this: http://www.javaworld.com/javatips/jw-javatip34.html
URLConnection connection = new URL("http://webservice.companyname.com/login/dologin").openConnection();
// Http Method becomes POST
connection.setDoOutput(true);
// Encode according to application/x-www-form-urlencoded specification
String content =
"id=" + URLEncoder.encode ("username") +
"&num=" + URLEncoder.encode ("password") +
"&remember=" + URLEncoder.encode ("on") +
"&output=" + URLEncoder.encode ("xml");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Try this should be the length of you content.
// it is not neccessary equal to 48.
// content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters.
connection.setRequestProperty("Content-Length", content.getBytes().length);
// Write body
OutputStream output = connection.getOutputStream();
output.write(content.getBytes());
output.close();
You will need to catch the exception yourself.
Miguel Sanchez's response is the way it should be. The other way executing Rscript could be 'env' command to run the system wide RScript.
#!/usr/bin/env Rscript
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
This is my (heavily influenced by D.Jennings) generic implementation of the comparison method (in C#):
/// <summary>
/// Represents a service used to compare two collections for equality.
/// </summary>
/// <typeparam name="T">The type of the items in the collections.</typeparam>
public class CollectionComparer<T>
{
/// <summary>
/// Compares the content of two collections for equality.
/// </summary>
/// <param name="foo">The first collection.</param>
/// <param name="bar">The second collection.</param>
/// <returns>True if both collections have the same content, false otherwise.</returns>
public bool Execute(ICollection<T> foo, ICollection<T> bar)
{
// Declare a dictionary to count the occurence of the items in the collection
Dictionary<T, int> itemCounts = new Dictionary<T,int>();
// Increase the count for each occurence of the item in the first collection
foreach (T item in foo)
{
if (itemCounts.ContainsKey(item))
{
itemCounts[item]++;
}
else
{
itemCounts[item] = 1;
}
}
// Wrap the keys in a searchable list
List<T> keys = new List<T>(itemCounts.Keys);
// Decrease the count for each occurence of the item in the second collection
foreach (T item in bar)
{
// Try to find a key for the item
// The keys of a dictionary are compared by reference, so we have to
// find the original key that is equivalent to the "item"
// You may want to override ".Equals" to define what it means for
// two "T" objects to be equal
T key = keys.Find(
delegate(T listKey)
{
return listKey.Equals(item);
});
// Check if a key was found
if(key != null)
{
itemCounts[key]--;
}
else
{
// There was no occurence of this item in the first collection, thus the collections are not equal
return false;
}
}
// The count of each item should be 0 if the contents of the collections are equal
foreach (int value in itemCounts.Values)
{
if (value != 0)
{
return false;
}
}
// The collections are equal
return true;
}
}
Use list.sort
instead:
list.sort((o1, o2) -> o1.getItem().getValue().compareTo(o2.getItem().getValue()));
and make it more succinct using Comparator.comparing
:
list.sort(Comparator.comparing(o -> o.getItem().getValue()));
After either of these, list
itself will be sorted.
Your issue is that
list.stream.sorted
returns the sorted data, it doesn't sort in place as you're expecting.
Adding to all the answers already available for this question, I would like to add the steps I followed to install Python3 on AWS EC2 instance running CentOS 7. You can find the entire details at this link.
https://aws-labs.com/install-python-3-centos-7-2/
First, we need to enable SCL. SCL is a community project that allows you to build, install, and use multiple versions of software on the same system, without affecting system default packages.
sudo yum install centos-release-scl
Now that we have SCL repository, we can install the python3
sudo yum install rh-python36
To access Python 3.6 you need to launch a new shell instance using the Software Collection scl tool:
scl enable rh-python36 bash
If you check the Python version now you’ll notice that Python 3.6 is the default version
python --version
It is important to point out that Python 3.6 is the default Python version only in this shell session. If you exit the session or open a new session from another terminal Python 2.7 will be the default Python version.
Now, Install the python development tools by typing:
sudo yum groupinstall ‘Development Tools’
Now create a virtual environment so that the default python packages don't get messed up.
mkdir ~/my_new_project
cd ~/my_new_project
python -m venv my_project_venv
To use this virtual environment,
source my_project_venv/bin/activate
Now, you have your virtual environment set up with python3.
This is the answer, hope it helps someone :)
First there are two variations on how the xml can be written:
<row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row>
Answer:
SELECT
Tbl.Col.value('IdInvernadero[1]', 'smallint'),
Tbl.Col.value('IdProducto[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
Tbl.Col.value('Cantidad[1]', 'int'),
Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
Answer:
SELECT
Tbl.Col.value('@IdInvernadero', 'smallint'),
Tbl.Col.value('@IdProducto', 'smallint'),
Tbl.Col.value('@IdCaracteristica1', 'smallint'),
Tbl.Col.value('@IdCaracteristica2', 'smallint'),
Tbl.Col.value('@Cantidad', 'int'),
Tbl.Col.value('@Folio', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
Taken from:
Using pipes seems weird to me. Anyway you should use the logical and
Bash operator:
$ cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apples
If the cp
commands fail, the rm
will not be executed.
Or, you can make a more elaborated command line using a for
loop and cmp
.
Yes, a class can implement multiple interfaces. Each interface provides contract for some sort of behavior. I am attaching a detailed class diagram and shell interfaces and classes.
public interface Mammal {
void move();
boolean possessIntelligence();
}
public interface Animal extends Mammal {
void liveInJungle();
}
public interface Human extends Mammal, TwoLeggedMammal, Omnivore, Hunter {
void liveInCivilization();
}
public interface Carnivore {
void eatMeat();
}
public interface Herbivore {
void eatPlant();
}
public interface Omnivore extends Carnivore, Herbivore {
void eatBothMeatAndPlant();
}
public interface FourLeggedMammal {
void moveWithFourLegs();
}
public interface TwoLeggedMammal {
void moveWithTwoLegs();
}
public interface Hunter {
void huntForFood();
}
public class Kangaroo implements Animal, Herbivore, TwoLeggedMammal {
@Override
public void liveInJungle() {
System.out.println("I live in Outback country");
}
@Override
public void move() {
moveWithTwoLegs();
}
@Override
public void moveWithTwoLegs() {
System.out.println("I like to jump");
}
@Override
public void eat() {
eatPlant();
}
@Override
public void eatPlant() {
System.out.println("I like this grass");
}
@Override
public boolean possessIntelligence() {
return false;
}
}
public class Lion implements Animal, FourLeggedMammal, Hunter, Carnivore {
@Override
public void liveInJungle() {
System.out.println("I am king of the jungle!");
}
@Override
public void move() {
moveWithFourLegs();
}
@Override
public void moveWithFourLegs() {
System.out.println("I like to run sometimes.");
}
@Override
public void eat() {
eatMeat();
}
@Override
public void eatMeat() {
System.out.println("I like deer meat");
}
@Override
public boolean possessIntelligence() {
return false;
}
@Override
public void huntForFood() {
System.out.println("My females hunt often");
}
}
public class Teacher implements Human {
@Override
public void liveInCivilization() {
System.out.println("I live in an apartment");
}
@Override
public void moveWithTwoLegs() {
System.out.println("I wear shoes and walk with two legs one in front of the other");
}
@Override
public void move() {
moveWithTwoLegs();
}
@Override
public boolean possessIntelligence() {
return true;
}
@Override
public void huntForFood() {
System.out.println("My ancestors used to but now I mostly rely on cattle");
}
@Override
public void eat() {
eatBothMeatAndPlant();
}
@Override
public void eatBothMeatAndPlant() {
eatPlant();
eatMeat();
}
@Override
public void eatMeat() {
System.out.println("I like this bacon");
}
@Override
public void eatPlant() {
System.out.println("I like this broccoli");
}
}
Update for node.js v13
As @Tom pointed out, full icu support is built in v13 now. So the setup steps can be omitted. You can still customize how you want to build or use icu in runtime: https://nodejs.org/api/intl.html
For node.js on Windows, you can do the following:
Install full-icu if it has been installed, which applies date locales properly
npm i full-icu
or globally: npm i -g full-icu
Use toLocaleString() in your code, e.g.:
new Date().toLocaleString('en-AU', { timeZone: 'Australia/Melbourne' })
This will produce something like: 25/02/2019, 3:19:22 pm
. If you prefer 24 hours, 'en-GB' will produce: 25/02/2019, 15:19:22
For node.js as Azure web app, in addition to application settings of WEBSITE_TIME_ZONE, you also need to set NODE_ICU_DATA to e.g. <your project>\node_modules\full-icu
, of course after you've done the npm i full-icu. Installing the package globally on Azure is not suggested as that directory is temporary and can be wiped out.
Ref: 1. NodeJS not applying date locales properly
BackgroundTint works as color filter.
Try seeing the difference by comment tint/background and check the output when both are set.
Try making your changes in:
- (void) viewWillLayoutSubviews {}
The code will run at every orientation change as the subviews get laid out again.
You guys should also make sure that when you override onLayout
you HAVE to call super.onLayout
with all of the properties, or the view will not be inflated!
This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).
switch(test) {
case A:
case B:
do other stuff;
break;
default:
do stuff;
}
To get the file size of pages on the web I built a javascript bookmarklet to do the trick. It alerts the size in kb's. Change the alert to a prompt if you want to copy the filesize.
Here's the bookmarklet code for the alert.
<a href="javascript:a=document.getElementsByTagName('HTML')[0].outerHTML;b=a.length/1024;c=Math.round(b);alert(c+' kb');">Doc Size</a>
Here's the bookmarklet code for the prompt.
<a href="javascript:a=document.getElementsByTagName('HTML')[0].outerHTML;b=a.length/1024;c=Math.round(b);prompt('Page Size',c+' kb');">Doc Size</a>
See it in action at http://bookmarklets.to.g0.to/filesize.php
Google has a project called lovefield; just found out about it, and it looks interesting, though it is more involved than just dropping in underscore or lodash.
Lovefield is a relational query engine written in pure JavaScript. It also provides help with persisting data on the browser side, e.g. using IndexedDB to store data locally. It provides SQL-like syntax and works cross-browser (currently supporting Chrome 37+, Firefox 31+, IE 10+, and Safari 5.1+...
Another interesting recent entry in this space called jinqJs.
Briefly reviewing the examples, it looks promising, and the API document appears to be well written.
function isChild(row) {
return (row.Age < 18 ? 'Yes' : 'No');
}
var people = [
{Name: 'Jane', Age: 20, Location: 'Smithtown'},
{Name: 'Ken', Age: 57, Location: 'Islip'},
{Name: 'Tom', Age: 10, Location: 'Islip'}
];
var result = new jinqJs()
.from(people)
.orderBy('Age')
.select([{field: 'Name'},
{field: 'Age', text: 'Your Age'},
{text: 'Is Child', value: isChild}]);
jinqJs is a small, simple, lightweight and extensible javaScript library that has no dependencies. jinqJs provides a simple way to perform SQL like queries on javaScript arrays, collections and web services that return a JSON response. jinqJs is similar to Microsoft's Lambda expression for .Net, and it provides similar capabilities to query collections using a SQL like syntax and predicate functionality. jinqJs’s purpose is to provide a SQL like experience to programmers familiar with LINQ queries.
Note : If you are using iTunes 12.7.0 or above then use Solution 2 else use Solution 1. Solution 1 cannot be used with iTunes 12.7.0 or above since Apps section has been removed from iTunes by Apple
Solution 1 : Using iTunes 12.7 below
Tested on iTunes 12 with Mac OS X (Yosemite) 10.10.3
Also, tested on iTunes 12.3.2.35 with Mac OX X (El Capitan) 10.11.3
This process also applicable for iTunes 12.5.5 with Mac OS X (macOS Sierra) 10.12.3.
You can install IPA file using iTunes 12.x onto device using below steps :
Solution 2 : Using iTunes 12.7 and above
You can use diawi
for this purpose.
Drag-and-drop IPA
file in empty window. Make sure that last check mark are unselected
(recommended due to security concern)
Once the upload is completed then press Send
button
link
and QR code
as well. (You can share this link and QR code with Client)enter this link
(Note that link is case-sensitive) OR You can scan the QR using Bakodo iOS app
Once link is loaded you can see app details
Now select ‘Install application
’
Press on Install
.app installation begins
on screen.While the question does say 'Selectable' I believe the intentional results is to get the text to the clipboard. This can easily and elegantly be achieved by adding a Context Menu and menu item called copy that puts the Textblock Text property value in clipboard. Just an idea anyway.
function mySrvc() {
var callback = function() {
}
return {
onSaveClick: function(fn) {
callback = fn;
},
fireSaveClick: function(data) {
callback(data);
}
}
}
function controllerA($scope, mySrvc) {
mySrvc.onSaveClick(function(data) {
console.log(data)
})
}
function controllerB($scope, mySrvc) {
mySrvc.fireSaveClick(data);
}
you can use the following code to change color and text :
<org.jraf.android.backport.switchwidget.Switch
android:id="@+id/th"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:thumb="@drawable/apptheme_switch_inner_holo_light"
app:track="@drawable/apptheme_switch_track_holo_light"
app:textOn="@string/switch_yes"
app:textOff="@string/switch_no"
android:textColor="#000000"
/>
Create a xml named colors.xml in res/values folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#ff0000</color>
<color name="green">#00ff00</color>
</resources>
In drawable folder, create a xml file my_btn_toggle.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@color/red" />
<item android:state_checked="true" android:drawable="@color/green" />
</selector>
and in xml section defining your toggle button add:
android:background="@drawable/my_btn_toggle
to change the color of textOn
and textOff
use
android:switchTextAppearance="@style/Switch"
JSF is a beast. I may be missing something, but I used to solve similar problems by saving the desired message to a property of the bean, and then displaying the property via an outputText:
<h:outputText
value="#{CreateNewPasswordBean.errorMessage}"
render="#{CreateNewPasswordBean.errorMessage != null}" />
You could also try to add a key mapping witch auto select all the code in file and indent it:
'atom-text-editor':
'ctrl-alt-l': 'auto-indent:apply'
span.login-text {
font-size: 22px;
display:table;
margin-left: auto;
margin-right: auto;
}
<span class="login-text">Welcome To .....CMP</span>
For me it worked very well. try this also
If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)
So I have to use the following method.
CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.
Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.
Step2:
[Situation A]: target commit is the latest one.
1) In the git command console, input
git commit --amend -m "new comment message"
2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input
git push --force
[Situation B]: target commit is not the latest one.
1) In the git command console, input
git rebase -i HEAD~n
It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2.
This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq
to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq
to save&quit.
2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input
git push --force
Finally: In the sourcetree main window, Press F5
to refresh.
These are escape characters which are used to manipulate string.
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a form feed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
Read more about them from here.
http://docs.oracle.com/javase/tutorial/java/data/characters.html
Using the following Bash template should allow you to read one value at a time from a file and process it.
while read name; do
# Do what you want to $name
done < filename
Callback Function A function which passed to another function as an argument.
function test_function(){
alert("Hello world");
}
setTimeout(test_function, 2000);
Note: In above example test_function used as an argument for setTimeout function.
To push branches and tags (but not remotes):
git push origin 'refs/tags/*' 'refs/heads/*'
This would be equivalent to combining the --tags
and --all
options for git push
, which git does not seem to allow.
In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).
Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396
Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396
You have several options:
string[] items = { "Item1", "Item2", "Item3", "Item4" };
string[] items = new string[]
{
"Item1", "Item2", "Item3", "Item4"
};
string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
You can Use This One To get the selected ListItme Name ::
String selectedItem = ((ListBoxItem)ListBox.SelectedItem).Name.ToString();
Make sure that Your each ListBoxItem have a Name property
JMeter is using java SimpleDateFormat
For UTC with timezone use this
${__time(yyyy-MM-dd'T'hh:mm:ssX)}
JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.
prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.
I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.
The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.
I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.
My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.
class Basket extends Array
constructor: ->
add: (item) ->
@push(item)
remove: (item) ->
index = @indexOf(item)
@.splice(index, 1)
contains: (item) ->
@indexOf(item) isnt -1
indexOf: (item) ->
indexOf = -1
@.forEach (stored_item, index) ->
if (item.id is stored_item.id)
indexOf = index
return indexOf
Then you initialize this in your controller and create a function for that action:
$scope.basket = new Basket()
$scope.addItemToBasket = (item) ->
$scope.basket.add(item)
Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:
li ng-repeat="item in items"
a href="#" ng-click="addItemToBasket(item)"
Try this
if(!jsonObj.isNull("club")){
jsonObj.getString("club");
}
Little addition to Jason's answer:
ToShortDateString()
is culture-sensitive.From MSDN:
The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.MM.yyyy"; for the ja-JP culture, it is "yyyy/M/d". The specific format string on a particular computer can also be customized so that it differs from the standard short date format string.
That's mean it's better to use the ToString()
method and define format explicitly (as Jason said). Although if this string appeas in UI the ToShortDateString()
is a good solution because it returns string which is familiar to a user.
DateTime.Today
.I do it like this:
<div class="lazyload" style="width: 1000px; height: 600px" data-src="%s">
<img class="spinner" src="spinner.gif"/>
</div>
and load with
$(window).load(function(){
$('.lazyload').each(function() {
var lazy = $(this);
var src = lazy.attr('data-src');
$('<img>').attr('src', src).load(function(){
lazy.find('img.spinner').remove();
lazy.css('background-image', 'url("'+src+'")');
});
});
});
It also happens if you're trying to access an instance when you have a pointer, and vice versa:
struct foo
{
int x, y, z;
};
struct foo a, *b = &a;
b.x = 12; /* This will generate the error, should be b->x or (*b).x */
As pointed out in a comment, this can be made excruciating if someone goes and typedef
s a pointer, i.e. includes the *
in a typedef, like so:
typedef struct foo* Foo;
Because then you get code that looks like it's dealing with instances, when in fact it's dealing with pointers:
Foo a_foo = get_a_brand_new_foo();
a_foo->field = FANTASTIC_VALUE;
Note how the above looks as if it should be written a_foo.field
, but that would fail since Foo
is a pointer to struct. I strongly recommend against typedef
:ed pointers in C. Pointers are important, don't hide your asterisks. Let them shine.
I think the problem is that the browser could not load the jQueryUI image sprite that contains the X icon. Please use Fiddler, Firebug, or some other that can give you access to the HTTP requests the browser makes to the server and verify the image sprite is loaded successfully.
If you are not willing to try regex (which you should), you can use this:
s.replace('\n\n','\n')
Repeat this several times to make sure there is no blank line left. Or chaining the commands:
s.replace('\n\n','\n').replace('\n\n','\n')
Just to encourage you to use regex, here are two introductory videos that I find intuitive:
• Regular Expressions (Regex) Tutorial
• Python Tutorial: re Module
If you use IIS Express via Visual Studio instead of the builtin ASP.net host, you can achieve this.
Make sure the script with the "debugger;" statement in it is not blackboxed by Chrome. You can go to the Sources tab to check and turn off blackboxing if so.
EDIT: Added screenshot.
You can use pmap to report memory usage.
Synopsis:
pmap [ -x | -d ] [ -q ] pids...
There's also the ThreadStaticAttribute to make a static field unique per thread, so you can have strongly typed thread-local storage.
Even if extension methods aren't that secret (LINQ is based on them), it may not be so obvious as to how useful and more readable they can be for utility helper methods:
//for adding multiple elements to a collection that doesn't have AddRange
//e.g., collection.Add(item1, item2, itemN);
static void Add<T>(this ICollection<T> coll, params T[] items)
{ foreach (var item in items) coll.Add(item);
}
//like string.Format() but with custom string representation of arguments
//e.g., "{0} {1} {2}".Format<Custom>(c=>c.Name,"string",new object(),new Custom())
// result: "string {System.Object} Custom1Name"
static string Format<T>(this string format, Func<T,object> select, params object[] args)
{ for(int i=0; i < args.Length; ++i)
{ var x = args[i] as T;
if (x != null) args[i] = select(x);
}
return string.Format(format, args);
}
Use the following code, write it under onCreate()
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
This is the solution I use. It has more lines but it will only create the datepicker once.
$('#txtSearch').datepicker({
constrainInput:false,
beforeShow: function(){
var t = $('#ddlSearchType').val();
if( ['Required Date', 'Submitted Date'].indexOf(t) ) {
$('#txtSearch').prop('readonly', false);
return false;
}
else $('#txtSearch').prop('readonly', true);
}
});
The datepicker will not show unless the value of ddlSearchType is either "Required Date" or "Submitted Date"
This should do the work
import datetime
datetime.datetime.now().strftime("%H:%M:%S.%f")
It will print
HH:MM:SS.microseconds
like this e.g 14:38:19.425961