If you have
@Transactional // Spring Transactional
class MyDao extends Dao {
}
and super-class
class Dao {
public void save(Entity entity) { getEntityManager().merge(entity); }
}
and you call
@Autowired MyDao myDao;
myDao.save(entity);
you won't get a Spring TransactionInterceptor (that gives you a transaction).
This is what you need to do:
@Transactional
class MyDao extends Dao {
public void save(Entity entity) { super.save(entity); }
}
Unbelievable but true.
For following Error:
ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.
Run following NPM command:
$ npm install [email protected]
Source Link
Why use regex for that. String
implements IEnumerable<char>
, so you can just use LINQ.
test.Count(c => c == '&')
This is the easiest way to get image from gallery and crop ass well
step 1: StartActivity for result
imageUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
}
});
step 2:Handle the result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 1) {
final Bundle extras = data.getExtras();
if (extras != null) {
//Get image
Bitmap ProfilePic = extras.getParcelable("data");
imageUser.setImageBitmap(ProfilePic);
TextView t=(TextView)findViewById(R.id.textoverimage);
t.setText("image Selected");
}
}
}
You can open your command prompt as the intended user:
You will be prompted with login and password
Once CommandP Prompt starts you can double check which user you are running as by the command whoami
.
Now you can change directory to your project and run
dotnet run
I think you mean to update it back to the OLD
password, when the NEW one is not supplied.
DROP TRIGGER IF EXISTS upd_user;
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '') THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
However, this means a user can never blank out a password.
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
$("#div_element").load('script.php');
demo: http://sandbox.phpcode.eu/g/2ecbe/3
whole code:
<div id="submit">ajax</div>
<div id="div_element"></div>
<script>
$('#submit').click(function(event){
$("#div_element").load('script.php?html=some_arguments');
});
</script>
&
is a logical elementwise operator, while &&
is a logical short-circuiting operator (which can only operate on scalars).
For example (pardon my syntax).
If..
A = [True True False True]
B = False
A & B = [False False False False]
..or..
B = True
A & B = [True True False True]
For &&
, the right operand is only calculated if the left operand is true, and the result is a single boolean value.
x = (b ~= 0) && (a/b > 18.5)
Hope that's clear.
you declare like this
private boolean isSelectionRight;
write
out.writeInt(isSelectionRight ? 1 : 0);
read
isSelectionRight = in.readInt() != 0;
boolean type needs to be converted to something that Parcel supports and so we can convert it to int.
To add a touch event to a UIImageView, use the following in your .m file:
UITapGestureRecognizer *newTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTapMethod)];
[myImageView setUserInteractionEnabled:YES];
[myImageView addGestureRecognizer:newTap];
-(void)myTapMethod{
// Treat image tap
}
For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this
$data[$category]["test"] = $question
you can then call it (to test out the result by:
echo $data[$category]["test"];
which should print $question
You can create a variable with an application scope
Some tips:
About your questions:
An inputMethod is basically an Android Service
, so yes, you can do HTTP and all the stuff you can do in a Service
.
You can open Activities
and dialogs from the InputMethod
. Once again, it's just a Service
.
I've been developing an IME, so ask again if you run into an issue.
I had to do all of the following to completely remove it:
outline-style: none;
box-shadow: none;
border-color: transparent;
Example:
button {_x000D_
border-radius: 20px;_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
.no-focusborder:focus {_x000D_
outline-style: none;_x000D_
box-shadow: none;_x000D_
border-color: transparent;_x000D_
background-color: black;_x000D_
color: white;_x000D_
}
_x000D_
<p>Click in the white space, then press the "Tab" key.</p>_x000D_
<button>Button 1 (unchanged)</button>_x000D_
<button class="no-focusborder">Button 2 (no focus border, custom focus indicator to show focus is present but the unwanted highlight is gone)</button>_x000D_
<br/><br/><br/><br/><br/><br/>
_x000D_
Try this:
From this question.
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
Assuming that you don't have a library or system header that defines NULL
as for example (void*)0
or (char*)0
it's fine. I always tend to use 0 myself as it is by definition the null pointer. In c++0x you'll have nullptr
available so the question won't matter as much anymore.
var objectA = {}
is a lot quicker and, in my experience, more commonly used, so it's probably best to adopt the 'standard' and save some typing.
Open Task Manager and Kill both of these processes. They will autostart back up. Then try debugging your project again.
From the Javadoc:
The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed.
E.g., eager is more proactive than lazy. Lazy only happens on first use (if the provider takes the hint), whereas with eager things (may) get pre-fetched.
Another approach when you have many updates would be to use COALESCE:
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = COALESCE(@ABC, [ABC]),
[ABCD] = COALESCE(@ABCD, [ABCD])
I wrote a library to do this, you can view it here: https://codepen.io/nicetransition/pen/OyRwKq
to use in your case:
.selector {
scale($context, $base-size, $limit-size-min, $limit-size-max, $property: padding-right);
scale($context, $base-size, $limit-size-min, $limit-size-max, $property: padding-left);
}
$context
: Max-width of your container
$base-size
: Root font size
$limit-size-min
: The minimum size
$limit-size-max
: The maximum size
.selector { scale(1400px, 16px, 5px, 20px, $property: padding-right); scale(1400px, 16px, 5px, 20px, $property: padding-left); }
This would scale down to 5px and up to 20px, between 5-20 it is dynamic based of vw
I like the chosen answer. However, it tends to be slower than awk since 2 tools are needed to do the job.
$ wc -l file
49999998 file
$ time paste -sd+ file | bc
1448700364
real 1m36.960s
user 1m24.515s
sys 0m1.772s
$ time awk '{s+=$1}END{print s}' file
1448700364
real 0m45.476s
user 0m40.756s
sys 0m0.287s
int w =0 , l =0, d=0, i=0;
Scanner sc = new Scanner(System.in);
// try tentimes
while (i<10) {
System.out.println("scissor(1) ,Rock(2),Paper(3) ");
int n = sc.nextInt();
int m =(int)(Math.random()*3+1);
if(n==m){
System.out.println("Com:"+m +"so>>> " + "draw");
d++;
}else if ((n-1)%3==(m%3)){
w++;
System.out.println("Com:"+m +"so>>> " +"win");
}
else if(n >=4 )
{
System.out.println("pleas enter correct number)");
}
else {
System.out.println("Com:"+m +"so>>> " +"lose");
l++;
}
i++;
java.lang.Enum
defines several useful methods, which is available to all enumeration type in Java:
name()
method to get name of any Enum constants. String literal used to write enum constants is their name.values()
method can be used to get an array of all Enum constants from an Enum type.valueOf()
method to convert any String to Enum constant in Java, as shown below.public class EnumDemo06 {
public static void main(String args[]) {
Gender fromString = Gender.valueOf("MALE");
System.out.println("Gender.MALE.name() : " + fromString.name());
}
private enum Gender {
MALE, FEMALE;
}
}
Output:
Gender.MALE.name() : MALE
In this code snippet, valueOf()
method returns an Enum constant Gender.MALE, calling name on that returns "MALE"
.
It's possible you want overloading or default parameters - define the same function with defaulted parameters:
void doStuff( int a, double termstator = 1.0, bool useFlag = true )
{
// stuff
}
void doStuff( double std_termstator )
{
// assume the user always wants '1' for the a param
return doStuff( 1, std_termstator );
}
This will allow you to call the method with one of four different calls:
doStuff( 1 );
doStuff( 2, 2.5 );
doStuff( 1, 1.0, false );
doStuff( 6.72 );
... or you could be looking for the v_args calling conventions from C.
Single quotation marks won't do in that case. You have to add quotation marks around each path and also enclose the whole command in quotation marks:
cmd /C ""C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*""
I have to answer, too. The JIT generates tables together with the code from it's static analysis of variable usage. Those table entries are the "GC-Roots" in the current stack frame. As the instruction pointer advances, those table entries become invalid and so ready for garbage collection. Therefore: If it is a scoped variable, you don't need to set it to null - the GC will collect the object. If it is a member or a static variable, you have to set it to null
It probably came with a testing library that some of your code is using. Here's an example of one (chances are it's not the same library as your code is using, but it shows the general idea):
Put the table in the second image on Sheet2, columns D to F.
In Sheet1, cell D2 use the formula
=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")
copy across and down.
Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.
Don't need a regex
.
string[: string.find(' ')]
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
Here is an example of what Wilco suggested:
$cmd = 'nohup nice -n 10 /usr/bin/php -c /path/to/php.ini -f /path/to/php/file.php action=generate var1_id=23 var2_id=35 gen_id=535 > /path/to/log/file.log & echo $!';
$pid = shell_exec($cmd);
Basically this executes the PHP script at the command line, but immediately returns the PID and then runs in the background. (The echo $! ensures nothing else is returned other than the PID.) This allows your PHP script to continue or quit if you want. When I have used this, I have redirected the user to another page, where every 5 to 60 seconds an AJAX call is made to check if the report is still running. (I have a table to store the gen_id and the user it's related to.) The check script runs the following:
exec('ps ' . $pid , $processState);
if (count($processState) < 2) {
// less than 2 rows in the ps, therefore report is complete
}
There is a short post on this technique here: http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/
Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as
This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer
I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation
dependency with NSJSONSerialization
as Rob's comment with 15 upvotes suggests.
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];
NSLog(@"jsonRequest is %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *question = [jsonDict objectForKey:@"question"];
Is this not easier? For example within an onClickListener?
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/426253597411506"));
startActivity(intent);
} catch(Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com/appetizerandroid")));
}
PS. Get your id (the large number) from http://graph.facebook.com/[userName]
You cannot do this via Docker, but you can access the container's un-exposed port from the host machine.
If you have a container with something running on its port 8000, you can run
wget http://container_ip:8000
To get the container's IP address, run the 2 commands:
docker ps
docker inspect container_name | grep IPAddress
Internally, Docker shells out to call iptables when you run an image, so maybe some variation on this will work.
To expose the container's port 8000 on your localhost's port 8001:
iptables -t nat -A DOCKER -p tcp --dport 8001 -j DNAT --to-destination 172.17.0.19:8000
One way you can work this out is to setup another container with the port mapping you want, and compare the output of the iptables-save command (though, I had to remove some of the other options that force traffic to go via the docker proxy).
NOTE: this is subverting docker, so should be done with the awareness that it may well create blue smoke.
OR
Another alternative is to look at the (new? post 0.6.6?) -P option - which will use random host ports, and then wire those up.
OR
With 0.6.5, you could use the LINKs feature to bring up a new container that talks to the existing one, with some additional relaying to that container's -p flags? (I have not used LINKs yet.)
OR
With docker 0.11? you can use docker run --net host ..
to attach your container directly to the host's network interfaces (i.e., net is not namespaced) and thus all ports you open in the container are exposed.
It's better to use PathVariable annotation if you still want to get the uri which was called.
@PostMapping("/pub/{action:a|b|c}")
public JSONObject handlexxx(@PathVariable String action, @RequestBody String reqStr){
...
}
or parse it from request object.
Try this.
var dateAsString = DateTime.Now.ToString("dd/MM/yyyy");
// dateAsString = "09/07/2013"
Our HTML:
<div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
JS (writing to the txt file):
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
checking a particular row:
function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
Put these inside a .hta
file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.
Try this:
I used for Update and Delete buttons. It doesn't touch Edit button. You can use auto generated buttons.
protected void gvOperators_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType != DataControlRowType.DataRow) return;
var updateButton = (LinkButton)e.Row.Cells[0].Controls[0];
if (updateButton.Text == "Update")
{
updateButton.OnClientClick = "return confirm('Do you really want to update?');";
}
var deleteButton = (LinkButton)e.Row.Cells[0].Controls[2];
if (deleteButton.Text == "Delete")
{
deleteButton.OnClientClick = "return confirm('Do you really want to delete?');";
}
}
This is a follow up to the answer given by @EricWoodruff.
You could use netInfo
's getExtraInfo()
to get wifi SSID.
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals (action)) {
NetworkInfo netInfo = intent.getParcelableExtra (WifiManager.EXTRA_NETWORK_INFO);
if (ConnectivityManager.TYPE_WIFI == netInfo.getType ()) {
String ssid = info.getExtraInfo()
Log.d(TAG, "WiFi SSID: " + ssid)
}
}
If you are not using BroadcastReceiver check this answer to get SSID using Context
This is tested on Android Oreo 8.1.0
MD5 also benefits from SSE2 usage, check out BarsWF and then tell me that it doesn't. All it takes is a little assembler knowledge and you can craft your own MD5 SSE2 routine(s). For large amounts of throughput however, there is a tradeoff of the speed during hashing as opposed to the time spent rearranging the input data to be compatible with the SIMD instructions used.
For Visual Studio Express 2013 to get rid of these problem you have to do the following.
Right click on your project click Properties. In properties window from left menus select Configuration Properties->C/C++->General
In right side select
Treat Warning As Errors NO
and
SDL Checks NO
Assuming that your assembly/exe has FileIO permission is itself, well is not right. Your application may not run with admin rights. Its important to consider Code Access Security and requesting permissions Sample code:
FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
f2.Demand();
}
catch (SecurityException s)
{
Console.WriteLine(s.Message);
}
PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC
tells PDO to return the result as an associative array.
The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:
Array
(
[email] => '[email protected]'
[password] => 'yourpassword'
)
To read data from the 'email' column, do:
$user['email'];
and for 'password':
$user['password'];
User Defined Class Array List Example
import java.util.*;
public class UserDefinedClassInArrayList {
public static void main(String[] args) {
//Creating user defined class objects
Student s1=new Student(1,"AAA",13);
Student s2=new Student(2,"BBB",14);
Student s3=new Student(3,"CCC",15);
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
Program Output:
1 AAA 13
2 BBB 14
3 CCC 15
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
In case anybody is interested, I wrote a solution for this using Prototype. In order to get the button to appear correctly, I had to specify extraPlugins: 'ajaxsave'
from inside the CKEDITOR.replace()
method call.
Here is the plugin.js:
CKEDITOR.plugins.add('ajaxsave',
{
init: function(editor)
{
var pluginName = 'ajaxsave';
editor.addCommand( pluginName,
{
exec : function( editor )
{
new Ajax.Request('ajaxsave.php',
{
method: "POST",
parameters: { filename: 'index.html', editor: editor.getData() },
onFailure: function() { ThrowError("Error: The server has returned an unknown error"); },
on0: function() { ThrowError('Error: The server is not responding. Please try again.'); },
onSuccess: function(transport) {
var resp = transport.responseText;
//Successful processing by ckprocess.php should return simply 'OK'.
if(resp == "OK") {
//This is a custom function I wrote to display messages. Nicer than alert()
ShowPageMessage('Changes have been saved successfully!');
} else {
ShowPageMessage(resp,'10');
}
}
});
},
canUndo : true
});
editor.ui.addButton('ajaxsave',
{
label: 'Save',
command: pluginName,
className : 'cke_button_save'
});
}
});
I don't think you can tell with the std::string class. However, if you really need this information, you could always derive a class from std::string and give the derived class the ability to tell if it had been changed since construction (or some other arbitrary time). Or better yet, just write a new class that wraps std::string since deriving from std::string may not be a good idea given the lack of a base class virtual destructor. That's probably more work, but more work tends to be needed for an optimal solution.
Of course, you can always just assume if it contains something other than "" then it has been "set", this won't detect it manually getting set to "" though.
You need to use the scrollTop
property.
document.getElementById('box').scrollTop
Not glob
, but here's another way using a list comprehension:
extensions = 'txt mdown markdown'.split()
projectFiles = [f for f in os.listdir(projectDir)
if os.path.splitext(f)[1][1:] in extensions]
Hey there just ran into the same issue you did, the 3rd link down in google brought me to this bit of code that throws the error,
if (kernelFile == NULL) {
kernelFile = avdInfo_getKernelPath(avd);
if (kernelFile == NULL) {
derror( "This AVD's configuration is missing a kernel file!!" );
const char* sdkRootDir = getenv("ANDROID_SDK_ROOT");
if (sdkRootDir) {
derror( "ANDROID_SDK_ROOT is defined (%s) but cannot find kernel file in "
"%s" PATH_SEP "system-images" PATH_SEP
" sub directories", sdkRootDir, sdkRootDir);
} else {
derror( "ANDROID_SDK_ROOT is undefined");
}
exit(2);
to which the person wrote:
"/* If the kernel image name ends in "-armv7", then change the cpu * type automatically. This is a poor man's approach to configuration * management, but should allow us to get past building ARMv7 * system images with dex preopt pass"
So I went back in and downloaded the x86 intel atom version for my desired API level and was able to get the emulator up without the error. Hope it helps you too.....
A few answers here seem incomplete. Here are several variations:
<style>
.box {
height: 200px;
width: 200px;
border: 4px solid gray;
}
</style>
<!-- This works: .container>.row>.center-block.box -->
<div class="container">
<div class="row">
<div class="center-block bg-primary box">This div is centered with .center-block</div>
</div>
</div>
<!-- This does not work -->
<div class="container">
<div class="row">
<div class="center-block bg-primary box col-xs-4">This div is centered with .center-block</div>
</div>
</div>
<!-- This is the hybrid solution from other answers:
.container>.row>.col-xs-6>.center-block.box
-->
<div class="container">
<div class="row">
<div class="col-xs-6 bg-info">
<div class="center-block bg-primary box">This div is centered with .center-block</div>
</div>
</div>
</div>
To make it work with col-* classes, you need to wrap the .center-block inside a .col-* class, but remember to either add another class that sets the width (.box in this case), or to alter the .center-block itself by giving it a width.
Check it out on bootply.
Cascade will work when you delete something on table Courses
. Any record on table BookCourses
that has reference to table Courses
will be deleted automatically.
But when you try to delete on table BookCourses
only the table itself is affected and not on the Courses
follow-up question: why do you have CourseID
on table Category?
Maybe you should restructure your schema into this,
CREATE TABLE Categories
(
Code CHAR(4) NOT NULL PRIMARY KEY,
CategoryName VARCHAR(63) NOT NULL UNIQUE
);
CREATE TABLE Courses
(
CourseID INT NOT NULL PRIMARY KEY,
BookID INT NOT NULL,
CatCode CHAR(4) NOT NULL,
CourseNum CHAR(3) NOT NULL,
CourseSec CHAR(1) NOT NULL,
);
ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;
One more solution...
var strg= 'This is my string';
for(indx in strg){
alert(strg[indx]);
}
The third row you expect (the one with Powerpoint) is filtered out by the Computer.ID = 1
condition (try running the query with the Computer.ID = 1 or Computer.ID is null
it to see what happens).
However, dropping that condition would not make sense, because after all, we want the list for a given Computer.
The only solution I see is performing a UNION between your original query and a new query that retrieves the list of application that are not found on that Computer.
The query might look like this:
DECLARE @ComputerId int
SET @ComputerId = 1
-- your original query
SELECT Computer.ComputerName, Application.Name, Software.Version
FROM Computer
JOIN dbo.Software_Computer
ON Computer.ID = Software_Computer.ComputerID
JOIN dbo.Software
ON Software_Computer.SoftwareID = Software.ID
RIGHT JOIN dbo.Application
ON Application.ID = Software.ApplicationID
WHERE Computer.ID = @ComputerId
UNION
-- query that retrieves the applications not installed on the given computer
SELECT Computer.ComputerName, Application.Name, NULL as Version
FROM Computer, Application
WHERE Application.ID not in
(
SELECT s.ApplicationId
FROM Software_Computer sc
LEFT JOIN Software s on s.ID = sc.SoftwareId
WHERE sc.ComputerId = @ComputerId
)
AND Computer.id = @ComputerId
The second approach is right to execute JavaScript code after the page has finished loading - but you don't actually execute JavaScript code there, you inserted plain HTML.
The first thing works, but loads the JavaScript immediately and clears the page (so your tag will be there - but nothing else).
(Plus: language="javascript" has been deprecated for years, use type="text/javascript" instead!)
To get that working, you have to use the DOM manipulating methods included in JavaScript. Basically you'll need something like this:
var scriptElement=document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = filename;
document.head.appendChild(scriptElement);
The simplest way in laravel 5 is:
$listings=Listing::take(10)->get();
return view('view.name',compact('listings'));
If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.
EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
Either escape the double quotes with \
String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>"
or use single quotes instead
String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>"
Using a combination of SUBSTR, INSTR, and NVL (for strings without an underscore) will return what you want:
SELECT NVL(SUBSTR('ABC_blah', 0, INSTR('ABC_blah', '_')-1), 'ABC_blah') AS output
FROM DUAL
output
------
ABC
SELECT NVL(SUBSTR(t.column, 0, INSTR(t.column, '_')-1), t.column) AS output
FROM YOUR_TABLE t
If using Oracle10g+, you can use regex via REGEXP_SUBSTR.
You can use google's chart api to generate charts.
For the case I met, I found there are missing modules after make. So I did the following:
In Laravel 5.5 Soft Deleted works ( for me ).
Data Base
deleted_at Field, default NULL value
Model
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
use SoftDeletes;
}
Controller
public function destroy($id)
{
User::find($id)->delete();
}
I searched for hours, and I tried almost everything suggested.
This worked for almost every entity :
$input = "ažškunrukiš ? àéò ??? ©€ ?? ? ?? ? R?";
echo htmlentities($input, ENT_HTML5 , 'UTF-8');
result :
āžšķūņrūķīš ○ àéò ∀∂∋ ©€ ♣♦ ↠ ↔↛ ↙ ℜ℞rx;
All the answers work but they always traverse the whole list. If I understand your question, you only need the first match. So you don't have to consider the rest of the list if you found your first match:
mylist = ['abc123', 'def456', 'ghi789']
sub = 'abc'
next((s for s in mylist if sub in s), None) # returns 'abc123'
If the match is at the end of the list or for very small lists, it doesn't make a difference, but consider this example:
import timeit
mylist = ['abc123'] + ['xyz123']*1000
sub = 'abc'
timeit.timeit('[s for s in mylist if sub in s]', setup='from __main__ import mylist, sub', number=100000)
# for me 7.949463844299316 with Python 2.7, 8.568840944994008 with Python 3.4
timeit.timeit('next((s for s in mylist if sub in s), None)', setup='from __main__ import mylist, sub', number=100000)
# for me 0.12696599960327148 with Python 2.7, 0.09955992100003641 with Python 3.4
As you can see in the reference sources, NameValueCollection inherits from NameObjectCollectionBase.
So you take the base-type, get the private hashtable via reflection, and check if it contains a specific key.
For it to work in Mono as well, you need to see what the name of the hashtable is in mono, which is something you can see here (m_ItemsContainer), and get the mono-field, if the initial FieldInfo is null (mono-runtime).
Like this
public static class ParameterExtensions
{
private static System.Reflection.FieldInfo InitFieldInfo()
{
System.Type t = typeof(System.Collections.Specialized.NameObjectCollectionBase);
System.Reflection.FieldInfo fi = t.GetField("_entriesTable", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if(fi == null) // Mono
fi = t.GetField("m_ItemsContainer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
return fi;
}
private static System.Reflection.FieldInfo m_fi = InitFieldInfo();
public static bool Contains(this System.Collections.Specialized.NameValueCollection nvc, string key)
{
//System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
//nvc.Add("hello", "world");
//nvc.Add("test", "case");
// The Hashtable is case-INsensitive
System.Collections.Hashtable ent = (System.Collections.Hashtable)m_fi.GetValue(nvc);
return ent.ContainsKey(key);
}
}
for ultra-pure non-reflective .NET 2.0 code, you can loop over the keys, instead of using the hash-table, but that is slow.
private static bool ContainsKey(System.Collections.Specialized.NameValueCollection nvc, string key)
{
foreach (string str in nvc.AllKeys)
{
if (System.StringComparer.InvariantCultureIgnoreCase.Equals(str, key))
return true;
}
return false;
}
The reason for this is PHP doesn't recognise utf-8.
Here you can check it for all Special Characters in HTML
The *_test.go
file is a Go source like the others, you can initialize a new logger every time if you need to dump complex data structure, here an example:
// initZapLog is delegated to initialize a new 'log manager'
func initZapLog() *zap.Logger {
config := zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
config.EncoderConfig.TimeKey = "timestamp"
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logger, _ := config.Build()
return logger
}
Then, every time, in every test:
func TestCreateDB(t *testing.T) {
loggerMgr := initZapLog()
// Make logger avaible everywhere
zap.ReplaceGlobals(loggerMgr)
defer loggerMgr.Sync() // flushes buffer, if any
logger := loggerMgr.Sugar()
logger.Debug("START")
conf := initConf()
/* Your test here
if false {
t.Fail()
}*/
}
Here is a complete sample:
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API with Google Maps API</title>
<meta charset="UTF-8" />
</head>
<body>
<script>
function displayLocation(latitude,longitude){
var request = new XMLHttpRequest();
var method = 'GET';
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true';
var async = true;
request.open(method, url, async);
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
var data = JSON.parse(request.responseText);
var address = data.results[0];
document.write(address.formatted_address);
}
};
request.send();
};
var successCallback = function(position){
var x = position.coords.latitude;
var y = position.coords.longitude;
displayLocation(x,y);
};
var errorCallback = function(error){
var errorMessage = 'Unknown error';
switch(error.code) {
case 1:
errorMessage = 'Permission denied';
break;
case 2:
errorMessage = 'Position unavailable';
break;
case 3:
errorMessage = 'Timeout';
break;
}
document.write(errorMessage);
};
var options = {
enableHighAccuracy: true,
timeout: 1000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(successCallback,errorCallback,options);
</script>
</body>
</html>
This helped me at the end:
Quick guide:
Download Google USB Driver
Connect your device with Android Debugging enabled to your PC
Open Device Manager of Windows from System Properties.
Your device should appear under Other devices
listed as something like
Android ADB Interface
or 'Android Phone' or similar. Right-click that and
click on Update Driver Software...
Select Browse my computer for driver software
Select Let me pick from a list of device drivers on my computer
Double-click Show all devices
Press the Have disk
button
Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf
Select Android ADB Interface
from the list of device types.
Press the Yes
button
Press the Install
button
Press the Close
button
Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.
Check out the CharsetEncoder
and CharsetDecoder
API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder
:
reset
method, unless it has not been used before;encode
method zero or more times, as long as additional input may be available, passing false
for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;encode
method one final time, passing true
for the endOfInput argument; and thenflush
method so that the encoder can flush any internal state to the output buffer.By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.
Use ===
to equate the variables instead of ==
.
==
checks if the value of the variables is similar
===
checks if the value of the variables and the type of the variables are similar
Notice how
if(0===false) {
document.write("oh!!! that's true");
}?
and
if(0==false) {
document.write("oh!!! that's true");
}?
give different results
For Windows, try:
NBTSTAT -A 10.100.3.104
or
ping -a 10.100.3.104
For Linux, try:
nmblookup -A 10.100.3.104
They are almost same.
Imagine that we have 3 buttons for example
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
button2.setOnClickListener(mCorkyListener);
button3.setOnClickListener(mCorkyListener);
}
// Create an anonymous implementation of OnClickListener
private View.OnClickListener mCorkyListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
}
};
}
So what we will do?
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
button2.setOnClickListener(mCorkyListener);
button3.setOnClickListener(mCorkyListener);
}
// Create an anonymous implementation of OnClickListener
private View.OnClickListener mCorkyListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
};
}
Or we can do this:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when the corky is clicked
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when the corky2 is clicked
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when the corky3 is clicked
}
});
}
}
Or we can implement View.OnClickListener and i think it's the best way:
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
}
Finally there is no real differences here Just "Way better than the other"
Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:
It is also possible to change the default username "user" and the default password "live".
I tried the username user
and password live
and it did work. If you want to run commands as root you can preface each command with sudo
You can assign an iterable to side_effect
, and the mock will return the next value in the sequence each time it is called:
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'
Quoting the Mock()
documentation:
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
An iframe is used to embed another document inside a html page.
If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.
Set the target attribute of the form to the name of the iframe tag.
<form action="action" method="post" target="output_frame">
<!-- input elements here -->
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>
Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files
The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.
Exmaple
<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,
open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });
function startUpload()
{
$("#uploadDialog").dialog("open");
}
function stopUpload()
{
$("#uploadDialog").dialog("close");
}
</script>
<div id="uploadDialog" title="Please Wait!!!">
<center>
<img src="/imagePath/loading.gif" width="100" height="100"/>
<br/>
Loading Details...
</center>
</div>
<FORM ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()">
<!-- input file elements here-->
</FORM>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">
</iframe>
You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[]
in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer
(expecting Serializable
, and using ObjectOutputStream
). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.
I guess you can copy the entire package and make use of it.
border: 0
should be enough, but if it isn't, perhaps the button's browser-default styling in interfering. Have you tried setting appearance
to none
(e.g. -webkit-appearance: none
)
I'm assuming as a developer, you have some degree of administrative control over your machine. If so, from the command line, run msconfig.exe. You can remove many processes from even starting, thereby eliminating the need to kill them with the above mentioned solutions.
There is a way that may be suitable if the items you want to delete are always at the "beginning" of the dict iteration
while mydict:
key, value = next(iter(mydict.items()))
if should_delete(key, value):
del mydict[key]
else:
break
The "beginning" is only guaranteed to be consistent for certain Python versions/implementations. For example from What’s New In Python 3.7
the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.
This way avoids a copy of the dict that a lot of the other answers suggest, at least in Python 3.
A more up to date answer for anyone else who comes across this:
(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)
Compile automatically:
To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option
Show all errors in one place:
The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.
Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.
While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.
The new way of doing it with php7.4 is Spread operator [...]
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);
Spread operator should have better performance than array_merge
A significant advantage of Spread operator is that it supports any traversable objects, while the array_merge function only supports arrays.
I have same issue, just change from Navigator
to {Navigator}
import Navigator from 'react-native-deprecated-custom-components'
// to
import {Navigator} from 'react-native-deprecated-custom-components'
For UIViewController
just load your view again -
func rightButtonAction() {
if isEditProfile {
print("Submit Clicked, Call Update profile API")
isEditProfile = false
self.viewWillAppear(true)
} else {
print("Edit Clicked, Call Edit profile API")
isEditProfile = true
self.viewWillAppear(true)
}
}
I am loading my view controller on profile edit and view profile. According to the Bool value isEditProfile
updating the view in viewWillAppear
method.
I've just updated my blog post to correct the error in the script that you were having Jeff, you can see the updated script here: Search all fields in SQL Server Database
As requested, here's the script in case you want it but I'd recommend reviewing the blog post as I do update it from time to time
DECLARE @SearchStr nvarchar(100)
SET @SearchStr = '## YOUR STRING HERE ##'
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Updated and tested by Tim Gaunt
-- http://www.thesitedoctor.co.uk
-- http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx
-- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
-- Date modified: 03rd March 2011 19:00 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
DROP TABLE #Results
Also, you can use spring annotation RequestMapping above controller class for receveing application/json;utf-8 in all responses
@Controller
@RequestMapping(produces = {"application/json; charset=UTF-8","*/*;charset=UTF-8"})
public class MyController{
...
}
Shortest,
var theAnswerObj = _.findWhere(array, {id : 42});
Without purisms, I think that the best way to emulate scalar argument by reference in JavaScript is using object, like previous an answer tells.
However, I do a little bit different:
I've made the object assignment inside function call, so one can see the reference parameters near the function call. It increases the source readability.
In function declaration, I put the properties like a comment, for the very same reason: readability.
var r;
funcWithRefScalars(r = {amount:200, message:null} );
console.log(r.amount + " - " + r.message);
function funcWithRefScalars(o) { // o(amount, message)
o.amount *= 1.2;
o.message = "20% increase";
}
In the above example, null
indicates clearly an output reference parameter.
The exit:
240 - 20% Increase
On the client-side, console.log
should be replaced by alert
.
? ? ?
Another method that can be even more readable:
var amount, message;
funcWithRefScalars(amount = [200], message = [null] );
console.log(amount[0] + " - " + message[0]);
function funcWithRefScalars(amount, message) { // o(amount, message)
amount[0] *= 1.2;
message[0] = "20% increase";
}
Here you don't even need to create new dummy names, like r
above.
In Java8 you use the new Time API, and convert an Instant in to a ZonedDateTime Using the UTC TimeZone
_x000D_
table tbody_x000D_
{_x000D_
border:1px solid red;_x000D_
}_x000D_
table td_x000D_
{_x000D_
background:yellow;_x000D_
_x000D_
border-bottom:1px solid green;_x000D_
_x000D_
_x000D_
}_x000D_
.tr0{_x000D_
line-height:0;_x000D_
}_x000D_
.tr0 td{_x000D_
background:red;_x000D_
}
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr><td>test</td></tr>_x000D_
<tr><td>test</td></tr> _x000D_
<tr class="tr0"><td></td></tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
On Linux when you run a jar file from terminal, these both will return the same String
: "/home/CurrentUser", no matter, where youre jar file is. It depends just on what current directory are you using with your terminal, when you start the jar file.
Paths.get("").toAbsolutePath().toString();
System.getProperty("user.dir");
If your Class
with main
would be called MainClass
, then try:
MainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile();
This will return a String
with absolute path of the jar file.
This is a link to a great Case Study on the industry wide misunderstanding of controlling caches.
http://securityevaluators.com/knowledge/case_studies/caching/
In summary, according to this article, only Cache-Control: no-store
is recognized by Chrome, Firefox, and IE. IE recognizes other controls, but Chrome and Firefox do not.
If you are using Microsoft Drivers 3.1, 3.0, and 2.0.
Please check your PHP version already install with IIS.
Use this script to check the php version:
<?php echo phpinfo(); ?>
OR
If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.
Then:
If you are using new PHP version (5.6) please download Drivers from here
For PHP version Lower than 5.6 - please download Drivers from here
Then use the PHP Manager to add that downloaded drivers into php config
file.You can do it as shown below (browse the files and press OK).
Then Restart the IIS Server
If this method not work please change the php version and try to run your php script.
Tip:Change the php version
to lower and try to understand what happened.then you can download relevant drivers.
frame is the origin (top left corner) and size of the view in its super view's coordinate system , this means that you translate the view in its super view by changing the frame origin , bounds on the other hand is the size and origin in its own coordinate system , so by default the bounds origin is (0,0).
most of the time the frame and bounds are congruent , but if you have a view of frame ((140,65),(200,250)) and bounds ((0,0),(200,250))for example and the view was tilted so that it stands on its bottom right corner , then the bounds will still be ((0,0),(200,250)) , but the frame is not .
the frame will be the smallest rectangle that encapsulates/surrounds the view , so the frame (as in the photo) will be ((140,65),(320,320)).
another difference is for example if you have a superView whose bounds is ((0,0),(200,200)) and this superView has a subView whose frame is ((20,20),(100,100)) and you changed the superView bounds to ((20,20),(200,200)) , then the subView frame will be still ((20,20),(100,100)) but offseted by (20,20) because its superview coordinate system was offseted by (20,20).
i hope this helps somebody.
You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style
attribute. Apparently, it has to be one using the !important
specifier, which generally indicates poor logic and structure in styling.
Primarily, modify the style.css file so that it does not use !important
. Failing this, add !important
to the rule in style
attribute. But you should aim at reducing the use of !important
, not increasing it.
Try:
<xsl:value-of select="count(preceding-sibling::*) + 1" />
Edit - had a brain freeze there, position() is more straightforward!
If you can't put value on buttons. I have just a rough solution. Put a hidden field. And when one of the buttons are clicked before submitting, populate the value of hidden field with like say 1 when first button clicked and 2 if second one is clicked. and in submit page check for the value of this hidden field to determine which one is clicked.
Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).
If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel
public class ThisViewModel : ViewModelBase
{
TypeOfAncestorViewModel Parent { get; set; }
}
and bind against that directly instead.
<TextBox Text="{Binding Parent}" />
Your syntax is incorrect, you should pass the value as the second parameter:
jQuery(this).prev("li").attr("id","newId");
Spring's Environment holds this information for you.
@Autowired
Environment environment;
String port = environment.getProperty("local.server.port");
On the surface this looks identical to injecting a field annotated @Value("${local.server.port}")
(or @LocalServerPort
, which is identical), whereby an autowiring failure is thrown at startup as the value isn't available until the context is fully initialised. The difference here is that this call is implicitly being made in runtime business logic rather than invoked at application startup, and hence the 'lazy-fetch' of the port resolves ok.
You can do the access control at the Web server level using HTTP Basic authentication and htpasswd. There are a number of problems with this:
Unless you're building a site for internal use with few users, I wouldn't really recommend it.
An iframe is still the best way to download cross-domain visual content. With AJAX you can certainly download the HTML from a web page and stick it in a div (as others have mentioned) however the bigger problem is security. With iframes you'll be able to load the cross domain content but won't be able to manipulate it since the content doesn't actually belong to you. On the other hand with AJAX you can certainly manipulate any content you are able to download but the other domain's server needs to be setup in such a way that will allow you to download it to begin with. A lot of times you won't have access to the other domain's configuration and even if you do, unless you do that kind of configuration all the time, it can be a headache. In which case the iframe can be the MUCH easier alternative.
As others have mentioned you can also use the embed tag and the object tag but that's not necessarily more advanced or newer than the iframe.
HTML5 has gone more in the direction of adopting web APIs to get information from cross domains. Usually web APIs just return data though and not HTML.
I've create this script. It does not need tmuxinator, ruby or others. It is just a bash script, configurable:
A file named config should contains something like this:
combo=()
combo+=('logs' 'cd /var/log; clear; pwd')
combo+=('home' 'cd ~; clear; pwd')
and the bash code should be:
#!/bin/bash
if [ -r config ]; then
echo ""
echo "Loading custom file"
. config
else
. config.dist
fi
tmux start-server
window=0
windownumber=-1
for i in "${combo[@]}"; do
if [ $((window%2)) == 0 ]; then
name=${i}
((windownumber++))
else
command=${i}
fi
if [ ${combo[0]} == "${i}" ]; then
tmux new-session -d -s StarTmux -n "${name}"
else
if [ $((window%2)) == 0 ]; then
tmux new-window -tStarTmux:$windownumber -n "${name}"
fi
fi
if [ $((window%2)) == 1 ]; then
tmux send-keys -tStarTmux:$windownumber "${command}" C-m
fi
((window++))
done
tmux select-window -tStarTmux:0
tmux attach-session -d -tStarTmux
I think @Zack properly answered the question but just to cover all the bases:
Update myTable set MyColumn = NULL
This would set the entire column to null as the Question Title asks.
To set a specific row on a specific column to null use:
Update myTable set MyColumn = NULL where Field = Condition.
This would set a specific cell to null as the inner question asks.
FLAG_ACTIVITY_NO_HISTORY when starting the activity you wish to finish after the user goes to another one.
http://developer.android.com/reference/android/content/Intent.html#FLAG%5FACTIVITY%5FNO%5FHISTORY
I have found with VS2013 I get this error regularly. Something that seems to work reasonably well is to perform a Rebuild Solution prior trying to run the application. I found that performing a CLEAN sometimes works, but the Rebuild Solution seems to work more consistently.
* Very Easy Solution:
Go to IIS
Select your application from left Pane.
Double click on Directory Browsing in middle Pane.
Now go to right pane and under Action tab, Just click 'ENABLE'
That's all !!
People, try to understand the error: Config Error Cannot read configuration file due to insufficient permissions
With Winforms you can use Form.BackColor to do this.
From within the Form's code:
BackColor = Color.LightPink;
If you mean a WPF Window you can use the Background property.
From within the Window's code:
Background = Brushes.LightPink;
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";
//OR
$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}
You can simply use the command below to describe a table.
desc table-name
or
desc schema-name.table-name
Try this one:
-startup plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.2.R36x_v20101222
-showsplash org.eclipse.platform
--launcher.XXMaxPermSize 256m
--launcher.defaultAction openFile
-vm F:\Program Files\jdk1.6\bin\javaw.exe
-vmargs
-Xms512m
-Xmx512m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M
Basically if you follow the issues in this link for 0.2 you'll likely get yourself fixed, I had the same problems with 0.2
"Cannot invoke an expression whose type lacks a call signature."
In your code :
class Post extends Component {
public toggleBody: string;
constructor() {
this.toggleBody = this.setProp('showFullBody');
}
public showMore(): boolean {
return this.toggleBody(true);
}
public showLess(): boolean {
return this.toggleBody(false);
}
}
You have public toggleBody: string;
. You cannot call a string
as a function. Hence errors on : this.toggleBody(true);
and this.toggleBody(false);
Key file should not be publicly viewable so use permission 400
chmod 400 keyfile.pem
If above command shows permission error use
sudo chmod 400 keyfile.pem
Now ssh into the ec2 machine, if you still face the issue, use ec2-user
ssh -i keyfile.pem [email protected]
In the specific case of a String array you could initialize the array using the Split Function as it returns a String array rather than a Variant array:
Dim arrWsNames() As String
arrWsNames = Split("Value1,Value2,Value3", ",")
This allows you to avoid using the Variant data type and preserve the desired type for arrWsNames.
After struggling with this same issue for some time, I finally figured out a solution that meets all of my requirements:
The solution just takes one <div>
, which I call the "aligner":
CSS
.bottom_aligner {
display: inline-block;
height: 100%;
vertical-align: bottom;
width: 0px;
}
html
<div class="bottom_aligner"></div>
... Your content here ...
This trick works by creating a tall, skinny div, which pushes the text baseline to the bottom of the container.
Here is a complete example that achieves what the OP was asking for. I've made the "bottom_aligner" thick and red for demonstration purposes only.
CSS:
.outer-container {
border: 2px solid black;
height: 175px;
width: 300px;
}
.top-section {
background: lightgreen;
height: 50%;
}
.bottom-section {
background: lightblue;
height: 50%;
margin: 8px;
}
.bottom-aligner {
display: inline-block;
height: 100%;
vertical-align: bottom;
width: 3px;
background: red;
}
.bottom-content {
display: inline-block;
}
.top-content {
padding: 8px;
}
HTML:
<body>
<div class="outer-container">
<div class="top-section">
This text
<br> is on top.
</div>
<div class="bottom-section">
<div class="bottom-aligner"></div>
<div class="bottom-content">
I like it here
<br> at the bottom.
</div>
</div>
</div>
</body>
cout.fill('*');
cout << -12345 << endl; // print default value with no field width
cout << setw(10) << -12345 << endl; // print default with field width
cout << setw(10) << left << -12345 << endl; // print left justified
cout << setw(10) << right << -12345 << endl; // print right justified
cout << setw(10) << internal << -12345 << endl; // print internally justified
This produces the output:
-12345
****-12345
-12345****
****-12345
-****12345
As of API 21, you should use the getDrawable(int, Theme)
method instead of getDrawable(int)
, as it allows you to fetch a drawable
object associated with a particular resource ID
for the given screen density/theme
. Calling the deprecated
getDrawable(int)
method is equivalent to calling getDrawable(int, null)
.
You should use the following code from the support library instead:
ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
Using this method is equivalent to calling:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
I resolved this problem. I think it happened maybe because of https but I am not very sure. You can Switch remote URLs from HTTPS to SSH.
1.Pls refer to this link for details:https://help.github.com/articles/changing-a-remote-s-url/
Also I had to config the ssh key.
2.Follow this:https://help.github.com/articles/generating-ssh-keys/
I came across this problem because I replaced my mac, but I do the transfer of data,I think it is probably because the key reasons.
Put the default value in single quote and it will work as intended. An example of migration:
$table->increments('id');
$table->string('name');
$table->string('url');
$table->string('country');
$table->tinyInteger('status')->default('1');
$table->timestamps();
EDIT : in your case ->default('100.0');
I would modify a previously suggested reply:
rsync -avlzp /path/to/sfolder [email protected]:/path/to/remote/dfolder
as follows:
-a (for archive) implies -rlptgoD so the l and p above are superfluous. I also like to include -H, which copies hard links. It is not part of -a by default because it's expensive. So now we have this:
rsync -aHvz /path/to/sfolder [email protected]:/path/to/remote/dfolder
You also have to be careful about trailing slashes. You probably want
rsync -aHvz /path/to/sfolder/ [email protected]:/path/to/remote/dfolder
if the desire is for the contents of the source "sfolder" to appear in the destination "dfolder". Without the trailing slash, an "sfolder" subdirectory would be created in the destination "dfolder".
You can also use border-style: double
with background-clip: padding-box
, without the use of any extra (pseudo-)elements. It's probably the most compact solution, but not as flexible as the others.
<div class="circle">Some text goes here...</div>
.circle{
width: 100px;
height: 100px;
padding: 50px;
border-radius: 200px;
border: double 15px rgba(255,255,255,0.7);
background: rgba(255,255,255,0.7);
background-clip: padding-box;
}
If you look closely you can see that the edge between the border and the background is not perfect. This seems to be an issue in current browsers. But it's not that noticeable when the border is small.
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("foo.properties")) {
properties.load(stream);
/* or properties.loadFromXML(...) */
}
SQL Server doesn't allow you to pass parameters to a procedure that you haven't defined. I think the closest you can get to this sort of design is to use optional parameters like so:
CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@ID int = NULL
AS
BEGIN
-- SP Logic
END;
You would need to include every possible parameter that you might use in the definition. Then you'd be free to call the procedure either way:
EXEC GetTaskEvents @TaskName = 'TESTTASK', @ID = 2;
EXEC GetTaskEvents @TaskName = 'TESTTASK'; -- @ID gets NULL here
I am using this interceptors to get the error response.
const HttpClient = axios.create({
baseURL: env.baseUrl,
});
HttpClient.interceptors.response.use((response) => {
return response;
}, (error) => {
return Promise.resolve({ error });
});
in my case I have used -
(Hyphen) in my script name in case of Jenkinsfile Library.
Got resolved after replacing Hyphen(-) with Underscore(_)
ubar jar is also known as fat jar i.e. jar with dependencies.
There are three common methods for constructing an uber jar:
field.setInputType(InputType.TYPE_CLASS_TEXT);
Example using log4j (src\log4j.xml):
<?xml version="1.0" encoding="UTF-8" ?>
<appender name="CA" class="org.apache.log4j.AsyncAppender">
<param name="BufferSize" value="512"/>
<appender-ref ref="CA_OUTPUT"/>
</appender>
<appender name="CA_OUTPUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%p] %d %c %M - %m%n"/>
</layout>
</appender>
<logger name="org.hibernate.SQL" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="CA"/>
</logger>
<root>
<level value="WARN"/>
<appender-ref ref="CA"/>
</root>
I like the challenge and wanted to give an answer, which solves the issue, I think.
Detection of the cap is another issue. It can be either complicated or simple. If I were you, I would simply check the color histogram in the ROI for a simple decision.
Please, give the feedback if I am wrong. Thanks.
If you're having issues with IE, you could use the map() function which is supported from 9.0 onward:
var index = Data.map(item => item.name).indexOf("Nick");
In SQL 2005, this is simple: 1. Open SQL Server management studio and copy the sql statement you need into the TSQL , such as exec sp_whatever 2. Query->Results to Grid 3. Highlight the sql statement and run it 4. Highlight the data results (left-click on upper left area of results grid) 5. Now right-click and select Save Results As 6. Select CSV in the Save as type, enter a file name, select a location and click Save.
Easy!
Another reason can be that if you are running the service (API) and put a breakpoint in the service (and your code is stuck at some breakpoint (e.g Visual Studio solution is showing Debugging instead of Running)). and then hitting the API from the client code. So if the service code a paused on some breakpoint, you just hit F5 in VS.
Another simple way is to use the pivot
function to format the data as you need first.
df.plot()
does the rest
df = pd.DataFrame([
['red', 0, 0],
['red', 1, 1],
['red', 2, 2],
['red', 3, 3],
['red', 4, 4],
['red', 5, 5],
['red', 6, 6],
['red', 7, 7],
['red', 8, 8],
['red', 9, 9],
['blue', 0, 0],
['blue', 1, 1],
['blue', 2, 4],
['blue', 3, 9],
['blue', 4, 16],
['blue', 5, 25],
['blue', 6, 36],
['blue', 7, 49],
['blue', 8, 64],
['blue', 9, 81],
], columns=['color', 'x', 'y'])
df = df.pivot(index='x', columns='color', values='y')
df.plot()
pivot effectively turns the data into:
Use std::stringstream
. Its operator <<
is overloaded for all built-in types.
#include <sstream>
std::stringstream s;
s << "(" << c1 << "," << c2 << ")";
storedCorrect[count] = s.str();
This works like you'd expect - the same way you print to the screen with std::cout
. You're simply "printing" to a string instead. The internals of operator <<
take care of making sure there's enough space and doing any necessary conversions (e.g., double
to string
).
Also, if you have the Boost library available, you might consider looking into lexical_cast
. The syntax looks much like the normal C++-style casts:
#include <string>
#include <boost/lexical_cast.hpp>
using namespace boost;
storedCorrect[count] = "(" + lexical_cast<std::string>(c1) +
"," + lexical_cast<std::string>(c2) + ")";
Under the hood, boost::lexical_cast
is basically doing the same thing we did with std::stringstream
. A key advantage to using the Boost library is you can go the other way (e.g., string
to double
) just as easily. No more messing with atof()
or strtod()
and raw C-style strings.
The CSS box model is rather complicated, particularly when it comes to scrolling content. While the browser uses the values from your CSS to draw boxes, determining all the dimensions using JS is not straight-forward if you only have the CSS.
That's why each element has six DOM properties for your convenience: offsetWidth
, offsetHeight
, clientWidth
, clientHeight
, scrollWidth
and scrollHeight
. These are read-only attributes representing the current visual layout, and all of them are integers (thus possibly subject to rounding errors).
Let's go through them in detail:
offsetWidth
, offsetHeight
: The size of the visual box incuding all borders. Can be calculated by adding width
/height
and paddings and borders, if the element has display: block
clientWidth
, clientHeight
: The visual portion of the box content, not including borders or scroll bars , but includes padding . Can not be calculated directly from CSS, depends on the system's scroll bar size.scrollWidth
, scrollHeight
: The size of all of the box's content, including the parts that are currently hidden outside the scrolling area. Can not be calculated directly from CSS, depends on the content.Since offsetWidth
takes the scroll bar width into account, we can use it to calculate the scroll bar width via the formula
scrollbarWidth = offsetWidth - clientWidth - getComputedStyle().borderLeftWidth - getComputedStyle().borderRightWidth
Unfortunately, we may get rounding errors, since offsetWidth
and clientWidth
are always integers, while the actual sizes may be fractional with zoom levels other than 1.
Note that this
scrollbarWidth = getComputedStyle().width + getComputedStyle().paddingLeft + getComputedStyle().paddingRight - clientWidth
does not work reliably in Chrome, since Chrome returns width
with scrollbar already substracted. (Also, Chrome renders paddingBottom to the bottom of the scroll content, while other browsers don't)
If you are coming from winforms and you are looking for a tutorial. I recommend you the MVVM Trainning extension for visual studio: http://visualstudiogallery.msdn.microsoft.com/3ab5f02f-0c54-453c-b437-8e8d57eb9942 It´s a tutorial with code examples. The tutorial is divided in 3: Basic WPF app, the same app in MVVM and the same using Inversion of control. Quite useful in your case :)
I also like these ones http://msdn.microsoft.com/en-us/magazine/dd419663.aspx http://karlshifflett.wordpress.com/mvvm/
and this one is with Prism. http://www.developmentalmadness.com/archive/2009/10/03/mvvm-with-prism-101-ndash-part-1-the-bootstrapper.aspx It may be worth it to take a view to Prism if you are thinking to program WPF apps with MVVM
Use (keyup.enter)
.
Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter
pseudo-event.
Your result is currently in string format, you need to parse it as json.
var obj = $.parseJSON(result);
alert(obj[0].category);
Additionally, if you set the dataType of the ajax call you are making to json
, you can skip the $.parseJSON()
step.
If you are using windows8:
command prompt
command prompt
and click Run as administrator
. Then execute the keytool command.Check that the web server has permissions to write to the "images/" directory
For Photoshop you need to download Photoshop portable.... Load image e press "w" click in image e suave as png or gif....
Since the aggregates string can be longer than 4000 bytes, you can't use the LISTAGG
function. You could potentially create a user-defined aggregate function that returns a CLOB
rather than a VARCHAR2
. There is an example of a user-defined aggregate that returns a CLOB
in the original askTom discussion that Tim links to from that first discussion.
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
I have SQL2008 / Windows 2008 Enterprise and this is what I had to do to correct the rs.accessdenied
, 404, 401 and 503 errors:
The Margin
property returns a Thickness
structure, of which Left
is a property. What the statement does is copying the structure value from the Margin
property and setting the Left
property value on the copy. You get an error because the value that you set will not be stored back into the Margin
property.
(Earlier versions of C# would just let you do it without complaining, causing a lot of questions in newsgroups and forums on why a statement like that had no effect at all...)
To set the property you would need to get the Thickness
structure from the Margin
property, set the value and store it back:
Thickness m = MyControl.Margin;
m.Left = 10;
MyControl.Margin = m;
If you are going to set all the margins, just create a Thickness
structure and set them all at once:
MyControl.Margin = new Thickness(10, 10, 10, 10);
If you're using Rails and ActiveAdmin, this is going to be your problem: https://github.com/seyhunak/twitter-bootstrap-rails/issues/450 Basically, a conflict with active_admin.js
This is the solution: https://stackoverflow.com/a/11745446/264084 (Karen's answer) tldr: Move active_admin assets into the "vendor" directory.
This error can occur for lots of reasons, and the last time, I solved it by modifying the Reference.svcmap
file, and changing how the WSDL file is referenced.
Throwing exception:
<MetadataSource Address="C:\Users\Me\Repo\Service.wsdl" Protocol="file" SourceId="1" />
<MetadataFile FileName="Service.wsdl" ... SourceUrl="file:///C:/Users/Me/Repo/Service.wsdl" />
Working fine:
<MetadataSource Address="https://server.domain/path/Service.wsdl" Protocol="http" SourceId="1" />
<MetadataFile FileName="Service.wsdl" ... SourceUrl="https://server.domain/path/Service.wsdl" />
This seems weird, but I have reproduced it. This was in a console application on .NET 4.5 and 4.7, as well as a .NET WebAPI site on 4.7.
If you want to rename a single column and keep the rest as it is:
from pyspark.sql.functions import col
new_df = old_df.select(*[col(s).alias(new_name) if s == column_to_change else s for s in old_df.columns])
You can also use:
$ sudo gem install rvm
It should give you the following output:
Fetching: rvm-1.11.3.9.gem (100%)
Successfully installed rvm-1.11.3.9
Parsing documentation for rvm-1.11.3.9
Installing ri documentation for rvm-1.11.3.9
1 gem installed
In windows with anaconda, just go on conda prompt and use this command
conda install --channel https://conda.anaconda.org/conda-forge keras
In case you get this error, it might also be related to how you included the JavaScript file into your html page. When loading modules, you have to explicitly declare those files as such. Here's an example:
//module.js:
function foo(){
return "foo";
}
var bar = "bar";
export { foo, bar };
When you include the script like this:
<script src="module.js"></script>
You will get the error:
Uncaught SyntaxError: Unexpected token export
You need to include the file with a type attribute set to "module":
<script type="module" src="module.js"></script>
then it should work as expected and you are ready to import your module in another module:
import { foo, bar } from "./module.js";
console.log( foo() );
console.log( bar );
One way you can achieve this is setting display: inline-block;
on the div
. It is by default a block
element, which will always fill the width it can fill (unless specifying width
of course).
inline-block
's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline
elements, but there are hacks to solve this problem.
There are other options you have, you can either float
it, or set position: absolute
on it, but these also have other effects on layout, you need to decide which one fits your situation better.
Use this way instead of your way.
addslashes(trim($_POST['username']));
You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.
You can test if a string ends with work followed by one character like this:
theString.matches(".*work.$");
If the trailing character is optional you can use this:
theString.matches(".*work.?$");
To make sure the last character is a period .
or a slash /
you can use this:
theString.matches(".*work[./]$");
To test for work followed by an optional period or slash you can use this:
theString.matches(".*work[./]?$");
To test for work surrounded by periods or slashes, you could do this:
theString.matches(".*[./]work[./]$");
If the tokens before and after work must match each other, you could do this:
theString.matches(".*([./])work\\1$");
Your exact requirement isn't precisely defined, but I think it would be something like this:
theString.matches(".*work[,./]?$");
In other words:
,
.
OR /
Explanation of various regex items:
. -- any character
* -- zero or more of the preceeding expression
$ -- the end of the line/input
? -- zero or one of the preceeding expression
[./,] -- either a period or a slash or a comma
[abc] -- matches a, b, or c
[abc]* -- zero or more of (a, b, or c)
[abc]? -- zero or one of (a, b, or c)
enclosing a pattern in parentheses is called "grouping"
([abc])blah\\1 -- a, b, or c followed by blah followed by "the first group"
Here's a test harness to play with:
class TestStuff {
public static void main (String[] args) {
String[] testStrings = {
"work.",
"work-",
"workp",
"/foo/work.",
"/bar/work",
"baz/work.",
"baz.funk.work.",
"funk.work",
"jazz/junk/foo/work.",
"funk/punk/work/",
"/funk/foo/bar/work",
"/funk/foo/bar/work/",
".funk.foo.bar.work.",
".funk.foo.bar.work",
"goo/balls/work/",
"goo/balls/work/funk"
};
for (String t : testStrings) {
print("word: " + t + " ---> " + matchesIt(t));
}
}
public static boolean matchesIt(String s) {
return s.matches(".*([./,])work\\1?$");
}
public static void print(Object o) {
String s = (o == null) ? "null" : o.toString();
System.out.println(o);
}
}
If you absolutely must use HTML to give your text color, you have to use the (deprecated) <font>
-tag:
<h2><font color="#006699">Process Report</font></h2>
But otherwise, I strongly recommend you to do as rekire said: use CSS.
read the file and then do whatever you want java8 Files.lines(Paths.get("c://lines.txt")).collect(Collectors.toList());
You should be using iostream
without the .h
.
Early implementations used the .h
variants but the standard mandates the more modern style.
Use the response.info()
method to get the headers.
From the urllib2 docs:
urllib2.urlopen(url[, data][, timeout])
...
This function returns a file-like object with two additional methods:
- geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed
- info() — return the meta-information of the page, such as headers, in the form of an httplib.HTTPMessage instance (see Quick Reference to HTTP Headers)
So, for your example, try stepping through the result of response.info().headers
for what you're looking for.
Note the major caveat to using httplib.HTTPMessage is documented in python issue 4773.
let date = Date()
let units: Set<Calendar.Component> = [.hour, .day, .month, .year]
let comps = Calendar.current.dateComponents(units, from: date)
You should create a connection as service then reuse it when need.
// db.service.js
import { MongoClient } from "mongodb";
import database from "../config/database";
const dbService = {
db: undefined,
connect: callback => {
MongoClient.connect(database.uri, function(err, data) {
if (err) {
MongoClient.close();
callback(err);
}
dbService.db = data;
console.log("Connected to database");
callback(null);
});
}
};
export default dbService;
my App.js sample
// App Start
dbService.connect(err => {
if (err) {
console.log("Error: ", err);
process.exit(1);
}
server.listen(config.port, () => {
console.log(`Api runnning at ${config.port}`);
});
});
and use it wherever you want with
import dbService from "db.service.js"
const db = dbService.db
For the bourne shell:
sh myscript.sh
For bash:
bash myscript.sh
One another possible reason is, you might have exceeded their plan limit.
To fix this issue and restore write access to the repo, either your account plan will need to be upgraded, or some of your collaborators will need to be removed.
If you just want to determine whether a particular named lock is currently held, you can use IS_USED_LOCK
:
SELECT IS_USED_LOCK('foobar');
If some connection holds the lock, that connection's ID will be returned; otherwise, the result is NULL
.
You can use rsplit
string.rsplit('delimeter',1)[1]
To get the string from reverse.
uncomment "curl=cainfo"
in the php.ini
document
This helped me when installing Prestashop when all other methods still did not work.
While the instructions on the Boost web site are helpful, here is a condensed version that also builds x64 libraries.
This installs the Boost header files under C:\Boost\include\boost-(version)
, and the 32-bit libraries under C:\Boost\lib\i386
. Note that the default location for the libraries is C:\Boost\lib
but you’ll want to put them under an i386
directory if you plan to build for multiple architectures.
bootstrap
Run: b2 toolset=msvc-12.0 --build-type=complete --libdir=C:\Boost\lib\i386 install
toolset=msvc-11.0
toolset=msvc-10.0
toolset=msvc-14.1
Add C:\Boost\include\boost-(version)
to your include path.
C:\Boost\lib\i386
to your libs path.This installs the Boost header files under C:\Boost\include\boost-(version)
, and the 64-bit libraries under C:\Boost\lib\x64
. Note that the default location for the libraries is C:\Boost\lib
but you’ll want to put them under an x64
directory if you plan to build for multiple architectures.
bootstrap
b2 toolset=msvc-12.0 --build-type=complete --libdir=C:\Boost\lib\x64 architecture=x86 address-model=64 install
toolset=msvc-11.0
toolset=msvc-10.0
C:\Boost\include\boost-(version)
to your include path.C:\Boost\lib\x64
to your libs path.It works in bootstrap 4, there were some changes in documentation.We don't need prefix col-, just offset-md-3 e.g.
<div class="row">
<div class="offset-md-3 col-md-6"> Some content...
</div>
</div>
Here doc.
I struggled with this 'fully loaded' issue for some time but found the following solution worked for me. I'm using IE7, so I'm not sure if this works in other versions, but worth a look.
I split the problem into two parts; first I needed a message from the DocumentComplete event;
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
fullyLoaded = True
End Sub
Then in the part of code where I need to wait till the web page has fully loaded I call another sub that does this;
Private Sub holdBrowserPage()
fullyLoaded = False
Do While fullyLoaded = False
DoEvents
Loop
fullyLoaded = False
End Sub
In addition, I also needed to do the same thing whilst waiting for javascript code to complete. For instance on one page when you select an item from an html drop down list, it populated the next drop down list, but took a while to reveal itself. In that instance I found calling this;
Private Sub holdBrowser()
Do While WebBrowser1.Busy Or WebBrowser1.ReadyState <> READYSTATE_COMPLETE
DoEvents
Loop
End Sub
was enough to hold the browser. Not sure if this will help everyone, as a combination of IE7, the website I was loading, and the javascript that the page was running alone might have allowed this solution, but certainly worth a try.
The command build
in pipeline is there to trigger other jobs in jenkins.
The job must exist in Jenkins and can be parametrized. As for the branch, I guess you can read it from git
Until modules are implemented you can use the Babel "transpiler" to run your code:
npm install --save babel-cli babel-preset-node6
and then
./node_modules/babel-cli/bin/babel-node.js --presets node6 ./your_script.js
If you dont want to type --presets node6
you can save it .babelrc file by:
{
"presets": [
"node6"
]
}
See https://www.npmjs.com/package/babel-preset-node6 and https://babeljs.io/docs/usage/cli/
I've had issues with using SELECT last_insert_rowid()
in a multithreaded environment. If another thread inserts into another table that has an autoinc, last_insert_rowid will return the autoinc value from the new table.
Here's where they state that in the doco:
If a separate thread performs a new INSERT on the same database connection while the sqlite3_last_insert_rowid() function is running and thus changes the last insert rowid, then the value returned by sqlite3_last_insert_rowid() is unpredictable and might not equal either the old or the new last insert rowid.
That's from sqlite.org doco
From the error, I infer that referenceElement
is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).
>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'
You probably meant either for element in referenceElement.keys()
or for element in json['referenceElement'].keys()
. With more context on what types json
and referenceElement
are and what they contain, we will be able to better help you if neither solution works.
yes - take a look at setInterval
and setTimeout
for executing code at certain times. setInterval would be the one to use to execute code periodically.
See a demo and answer here for usage
All Func delegates return something; all the Action delegates return void.
Func<TResult>
takes no arguments and returns TResult:
public delegate TResult Func<TResult>()
Action<T>
takes one argument and does not return a value:
public delegate void Action<T>(T obj)
Action
is the simplest, 'bare' delegate:
public delegate void Action()
There's also Func<TArg1, TResult>
and Action<TArg1, TArg2>
(and others up to 16 arguments). All of these (except for Action<T>
) are new to .NET 3.5 (defined in System.Core).
Please see the example below
public partial class Form1 : Form
{
[ThreadStatic()]
static Microsoft.Office.Interop.Word.Application wordObj = null;
public Form1()
{
InitializeComponent();
}
public bool OpenDoc(string documentName)
{
bool bSuccss = false;
System.Threading.Thread newThread;
int iRetryCount;
int iWait;
int pid = 0;
int iMaxRetry = 3;
try
{
iRetryCount = 1;
TRY_OPEN_DOCUMENT:
iWait = 0;
newThread = new Thread(() => OpenDocument(documentName, pid));
newThread.Start();
WAIT_FOR_WORD:
Thread.Sleep(1000);
iWait = iWait + 1;
if (iWait < 60) //1 minute wait
goto WAIT_FOR_WORD;
else
{
iRetryCount = iRetryCount + 1;
newThread.Abort();
//'-----------------------------------------
//'killing unresponsive word instance
if ((wordObj != null))
{
try
{
Process.GetProcessById(pid).Kill();
Marshal.ReleaseComObject(wordObj);
wordObj = null;
}
catch (Exception ex)
{
}
}
//'----------------------------------------
if (iMaxRetry >= iRetryCount)
goto TRY_OPEN_DOCUMENT;
else
goto WORD_SUCCESS;
}
}
catch (Exception ex)
{
bSuccss = false;
}
WORD_SUCCESS:
return bSuccss;
}
private bool OpenDocument(string docName, int pid)
{
bool bSuccess = false;
Microsoft.Office.Interop.Word.Application tWord;
DateTime sTime;
DateTime eTime;
try
{
tWord = new Microsoft.Office.Interop.Word.Application();
sTime = DateTime.Now;
wordObj = new Microsoft.Office.Interop.Word.Application();
eTime = DateTime.Now;
tWord.Quit(false);
Marshal.ReleaseComObject(tWord);
tWord = null;
wordObj.Visible = false;
pid = GETPID(sTime, eTime);
//now do stuff
wordObj.Documents.OpenNoRepairDialog(docName);
//other code
if (wordObj != null)
{
wordObj.Quit(false);
Marshal.ReleaseComObject(wordObj);
wordObj = null;
}
bSuccess = true;
}
catch
{ }
return bSuccess;
}
private int GETPID(System.DateTime startTime, System.DateTime endTime)
{
int pid = 0;
try
{
foreach (Process p in Process.GetProcessesByName("WINWORD"))
{
if (string.IsNullOrEmpty(string.Empty + p.MainWindowTitle) & p.HasExited == false && (p.StartTime.Ticks >= startTime.Ticks & p.StartTime.Ticks <= endTime.Ticks))
{
pid = p.Id;
break;
}
}
}
catch
{
}
return pid;
}
I had the same problem, Here is my code before modification :
package com.asagaama
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD
/**
* Created by asagaama on 16/02/2017.
*/
object Word {
def countWords(sc: SparkContext) = {
// Load our input data
val input = sc.textFile("/Users/Documents/spark/testscase/test/test.txt")
// Split it up into words
val words = input.flatMap(line => line.split(" "))
// Transform into pairs and count
val counts = words.map(word => (word, 1)).reduceByKey { case (x, y) => x + y }
// Save the word count back out to a text file, causing evaluation.
counts.saveAsTextFile("/Users/Documents/spark/testscase/test/result.txt")
}
def main(args: Array[String]) = {
val conf = new SparkConf().setAppName("wordCount")
val sc = new SparkContext(conf)
countWords(sc)
}
}
And after replacing :
val conf = new SparkConf().setAppName("wordCount")
With :
val conf = new SparkConf().setAppName("wordCount").setMaster("local[*]")
It worked fine !
Because if people can get at your object instance (ie: your this
) pointer, then they can also try to lock that same object. Now they might not be aware that you're locking on this
internally, so this may cause problems (possibly a deadlock)
In addition to this, it's also bad practice, because it's locking "too much"
For example, you might have a member variable of List<int>
, and the only thing you actually need to lock is that member variable. If you lock the entire object in your functions, then other things which call those functions will be blocked waiting for the lock. If those functions don't need to access the member list, you'll be causing other code to wait and slow down your application for no reason at all.
Try using
img.style.webkitTransform = "rotate(60deg)"
use StickyTableHeaders.js for this.
Header was transparent . so try to add this css .
thead {
border-top: none;
border-bottom: none;
background-color: #FFF;
}
>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')
For most it is a breeze, however like you I had a difficult time installing jq
The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/
However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system
What worked for me was removing all previous installs then pip install jq
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
Adds a fading gradient to an overflowing HTML table element to better indicate there is more content to be scrolled.
See the live example below:
$("#scrolltable").html("<table id='cell'><tbody></tbody></table>");_x000D_
$("#cell").append("<thead><tr><th><div>First col</div></th><th><div>Second col</div></th></tr></thead>");_x000D_
_x000D_
for (var i = 0; i < 40; i++) {_x000D_
$("#scrolltable > table > tbody").append("<tr><td>" + "foo" + "</td><td>" + "bar" + "</td></tr>");_x000D_
}
_x000D_
/* Table with fixed header */_x000D_
_x000D_
table,_x000D_
thead {_x000D_
width: 100%;_x000D_
text-align: left;_x000D_
}_x000D_
_x000D_
#scrolltable {_x000D_
margin-top: 50px;_x000D_
height: 120px;_x000D_
overflow: auto;_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
#scrolltable table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
#scrolltable tr:nth-child(even) {_x000D_
background: #EEE;_x000D_
}_x000D_
_x000D_
#scrolltable th div {_x000D_
position: absolute;_x000D_
margin-top: -30px;_x000D_
}_x000D_
_x000D_
_x000D_
/* Custom scrollbar */_x000D_
_x000D_
::-webkit-scrollbar {_x000D_
width: 8px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-track {_x000D_
box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);_x000D_
border-radius: 10px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-thumb {_x000D_
border-radius: 10px;_x000D_
box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
_x000D_
/* Overflow scroll gradient */_x000D_
_x000D_
.overflow-scroll-gradient {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.overflow-scroll-gradient::after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
width: 240px;_x000D_
height: 25px;_x000D_
background: linear-gradient( rgba(255, 255, 255, 0.001), white);_x000D_
pointer-events: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="overflow-scroll-gradient">_x000D_
<div id="scrolltable">_x000D_
</div>_x000D_
</div>
_x000D_
int[]
and int*
are represented the same way, except int[] allocates (IIRC).
ap
is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.
when you try to access it (x = *ap
), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.
You can make this.
CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]
@CODE XML
,@ERRFLAG CHAR(1) = '0' OUTPUT
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DELETE tb_SampleTest WHERE CODE IN( SELECT Item.value('.', 'VARCHAR(20)') FROM @CODE.nodes('RecordList/ID') AS x(Item) )
IF @@ROWCOUNT = 0 SET @ERRFLAG = 200
SET NOCOUNT OFF
If the answer marked as correct does not work, it is because you need to identify yourself as a super user.
sudo gradle wrapper --gradle-version 2.13
It worked for me.
To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 tr
from rule one and add it to rule two.
table.rule1 tr td {
background-color: #ff0000;
}
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.
If you just want to use AWT, then use Graphics.getFontMetrics
(optionally specifying the font, for a non-default one) to get a FontMetrics
and then FontMetrics.stringWidth
to find the width for the specified string.
For example, if you have a Graphics
variable called g
, you'd use:
int width = g.getFontMetrics().stringWidth(text);
For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.
Combine the SUBSTRING()
, LEFT()
, and CHARINDEX()
functions.
SELECT LEFT(SUBSTRING(YOUR_FIELD,
CHARINDEX(';', YOUR_FIELD) + 1, 100),
CHARINDEX('[', YOUR_FIELD) - 1)
FROM YOUR_TABLE;
This assumes your field length will never exceed 100, but you can make it smarter to account for that if necessary by employing the LEN()
function. I didn't bother since there's enough going on in there already, and I don't have an instance to test against, so I'm just eyeballing my parentheses, etc.
I am using the following code to write vertical text in a page. Firefox 3.5+, webkit, opera 10.5+ and IE
.rot-neg-90 {
-moz-transform:rotate(-270deg);
-moz-transform-origin: bottom left;
-webkit-transform: rotate(-270deg);
-webkit-transform-origin: bottom left;
-o-transform: rotate(-270deg);
-o-transform-origin: bottom left;
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
}
Create a method that returns all digits, and another that counts them:
public static int GetNumberOfDigits(this long value)
{
return value.GetDigits().Count();
}
public static IEnumerable<int> GetDigits(this long value)
{
do
{
yield return (int)(value % 10);
value /= 10;
} while (value != 0);
}
This felt like the more intuitive approach to me when tackling this problem. I tried the Log10
method first due to its apparent simplicity, but it has an insane amount of corner cases and precision problems.
I also found the if
-chain proposed in the other answer to a bit ugly to look at.
I know this is not the most efficient method, but it gives you the other extension to return the digits as well for other uses (you can just mark it private
if you don't need to use it outside the class).
Keep in mind that it does not consider the negative sign as a digit.
Apple has provided official guide in this doc: how-to-call-objective-c-code-from-swift
Here is the relevant part:
To import a set of Objective-C files into Swift code within the same app target, you rely on an Objective-C bridging header file to expose those files to Swift. Xcode offers to create this header when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.
If you accept, Xcode creates the bridging header file along with the file you were creating, and names it by using your product module name followed by "-Bridging-Header.h". Alternatively, you can create a bridging header yourself by choosing File > New > File > [operating system] > Source > Header File
Edit the bridging header to expose your Objective-C code to your Swift code:
Any public Objective-C headers listed in the bridging header are visible to Swift.