instruction
stringlengths 22
34.6k
| input
stringclasses 1
value | output
stringlengths 70
4.33k
|
---|---|---|
Xcode MyProjectName-Bridging-Header.h does not exist <sep> I want to start using Swift in my Objective-C project. So i added a swift class: <code>import Foundation @objc class System : NSObject { @objc func printSome() { println("Print line System"); } } </code> And imported it into a .m file: <code>#import "MyProjectName-Swift.h"</code> When building my project i get the following error: <code>Bridging header 'PathToMyProject/MyProjectName-Bridging-Header.h' does not exist </code> NOTE: Under "Build Settings->Swift Compiler - Code Generation->Objective-C Briding Header" is set to MyProjectName-Bridging-Header.h What should i do to solve this issue? Any help is much appreciated. EDIT: Bridging-Header file: #if defined(__has_include) && __has_include() # include #endif <code>#include <objc/NSObject.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #if defined(__has_include) && __has_include(<uchar.h>) # include <uchar.h> #elif __cplusplus < 201103L typedef uint_least16_t char16_t; typedef uint_least32_t char32_t; #endif #if !defined(SWIFT_PASTE) # define SWIFT_PASTE_HELPER(x, y) x##y # define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) #endif #if !defined(SWIFT_METATYPE) # define SWIFT_METATYPE(X) Class #endif #if defined(__has_attribute) && __has_attribute(objc_runtime_name) # define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) #else # define SWIFT_RUNTIME_NAME(X) #endif #if !defined(SWIFT_CLASS_EXTRA) # define SWIFT_CLASS_EXTRA #endif #if !defined(SWIFT_PROTOCOL_EXTRA) # define SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_CLASS) # if defined(__has_attribute) && __has_attribute(objc_subclassing_restricted) # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA # else # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # endif #endif #if !defined(SWIFT_PROTOCOL) # define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_EXTENSION) # define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) #endif #if !defined(OBJC_DESIGNATED_INITIALIZER) # if defined(__has_attribute) && __has_attribute(objc_designated_initializer) # define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) # else # define OBJC_DESIGNATED_INITIALIZER # endif #endif #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" #if defined(__has_feature) && __has_feature(modules) #endif #pragma clang diagnostic pop </code> | If the bridging file is created at the same level as the other classes, you might need to add the relative path, as these pictures show. Note here that the bridging file is created at the same level as the other classes: I have the name entered correctly in the Build Settings, but the compiler doesn't find the file. Therefore, if I add the relative path from the root of the project (that is, I add `./ProjectName/BridgerFileName.h`), now it compiles and I can call a method in my Objective-C class. |
|
Do something every x minutes in Swift <sep> How can I run a function every minute? In JavaScript I can do something like <code>setInterval</code>, does something similar exist in Swift? Wanted output: Hello World once a minute... | If you can allow for some time drift, here's a simple solution: executing some code every minute.
```swift
private func executeRepeatedly() {
// put your code here
DispatchQueue.main.asyncAfter(deadline: .now() + 60.0) { [weak self] in
self?.executeRepeatedly()
}
}
```
Just run `executeRepeatedly()` once, and it'll be executed every minute. The execution stops when the owning object ( `self` ) is released. You also can use a flag to indicate that the execution must stop. |
|
time data does not match format <sep> I get the following error: <code>time data '07/28/2014 18:54:55.099000' does not match format '%d/%m/%Y %H:%M:%S.%f' </code> But I cannot see what parameter is wrong in <code>%d/%m/%Y %H:%M:%S.%f</code> ? This is the code I use. <code>from datetime import datetime time_value = datetime.strptime(csv_line[0] + '000', '%d/%m/%Y %H:%M:%S.%f') </code> I have added and removed the <code>000</code> but I get the same error. | While the above answer is 100% helpful and correct, I'd like to add the following since only a combination of the above answer and reading through the pandas doc helped me: 2-digit/4-digit year.
It is noteworthy that in order to parse through a 2-digit year, e.g., '90' rather than '1990', a `%y` is required instead of a `%Y`.
Infer the datetime automatically. If parsing with a pre-defined format still doesn't work for you, try using the flag `infer_datetime_format=True`, for example: `yields_df['Date'] = pd.to_datetime(yields_df['Date'], infer_datetime_format=True)`.
Be advised that this solution is slower than using a pre-defined format. |
|
Why java.util.Optional is not Serializable, how to serialize the object with such fields <sep> The Enum class is Serializable so there is no problem to serialize object with enums. The other case is where class has fields of java.util.Optional class. In this case the following exception is thrown: java.io.NotSerializableException: java.util.Optional How to deal with such classes, how to serialize them? Is it possible to send such objects to Remote EJB or through RMI? This is the example: <code>import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Optional; import org.junit.Test; public class SerializationTest { static class My implements Serializable { private static final long serialVersionUID = 1L; Optional<Integer> value = Optional.empty(); public void setValue(Integer i) { this.i = Optional.of(i); } public Optional<Integer> getValue() { return value; } } //java.io.NotSerializableException is thrown @Test public void serialize() { My my = new My(); byte[] bytes = toBytes(my); } public static <T extends Serializable> byte[] toBytes(T reportInfo) { try (ByteArrayOutputStream bstream = new ByteArrayOutputStream()) { try (ObjectOutputStream ostream = new ObjectOutputStream(bstream)) { ostream.writeObject(reportInfo); } return bstream.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } } </code> | This answer is in response to the question in the title, "Shouldn't `Optional` be Serializable?". The short answer is that the Java Lambda (JSR-335) expert group considered and rejected it.
That note, and this one and this one, indicate that the primary design goal for `Optional` is to be used as the return value of functions when a return value might be absent. The intent is that the caller immediately check the `Optional` and extract the actual value if it's present. If the value is absent, the caller can substitute a default value, throw an exception, or apply some other policy. This is typically done by chaining fluent method calls off the end of a stream pipeline (or other methods) that return `Optional` values.
It was never intended for `Optional` to be used other ways, such as for optional method arguments or to be stored as a field in an object. And by extension, making `Optional` serializable would enable it to be stored persistently or transmitted across a network, both of which encourage uses far beyond its original design goal.
Usually, there are better ways to organize the data than to store an `Optional` in a field. If a getter (such as the `getValue` method in the question) returns the actual `Optional` from the field, it forces every caller to implement some policy for dealing with an empty value. This will likely lead to inconsistent behavior across callers. It's often better to have whatever code sets that field apply some policy at the time it's set.
Sometimes people want to put `Optional` into collections, like `List<Optional<X>>` or `Map<Key,Optional<Value>>`. This too is usually a bad idea. It's often better to replace these usages of `Optional` with Null-Object values (not actual `null` references), or simply to omit these entries from the collection entirely. |
|
Read specific columns with pandas or other python module <sep> I have a csv file from this webpage. I want to read some of the columns in the downloaded file (the csv version can be downloaded in the upper right corner). Let's say I want 2 columns: 59 which in the header is <code>star_name</code> 60 which in the header is <code>ra</code>. However, for some reason the authors of the webpage sometimes decide to move the columns around. In the end I want something like this, keeping in mind that values can be missing. <code>data = #read data in a clever way names = data['star_name'] ras = data['ra'] </code> This will prevent my program to malfunction when the columns are changed again in the future, if they keep the name correct. Until now I have tried various ways using the <code>csv</code> module and resently the <code>pandas</code> module. Both without any luck. EDIT (added two lines + the header of my datafile. Sorry, but it's extremely long.) <code># name, mass, mass_error_min, mass_error_max, radius, radius_error_min, radius_error_max, orbital_period, orbital_period_err_min, orbital_period_err_max, semi_major_axis, semi_major_axis_error_min, semi_major_axis_error_max, eccentricity, eccentricity_error_min, eccentricity_error_max, angular_distance, inclination, inclination_error_min, inclination_error_max, tzero_tr, tzero_tr_error_min, tzero_tr_error_max, tzero_tr_sec, tzero_tr_sec_error_min, tzero_tr_sec_error_max, lambda_angle, lambda_angle_error_min, lambda_angle_error_max, impact_parameter, impact_parameter_error_min, impact_parameter_error_max, tzero_vr, tzero_vr_error_min, tzero_vr_error_max, K, K_error_min, K_error_max, temp_calculated, temp_measured, hot_point_lon, albedo, albedo_error_min, albedo_error_max, log_g, publication_status, discovered, updated, omega, omega_error_min, omega_error_max, tperi, tperi_error_min, tperi_error_max, detection_type, mass_detection_type, radius_detection_type, alternate_names, molecules, star_name, ra, dec, mag_v, mag_i, mag_j, mag_h, mag_k, star_distance, star_metallicity, star_mass, star_radius, star_sp_type, star_age, star_teff, star_detected_disc, star_magnetic_field 11 Com b,19.4,1.5,1.5,,,,326.03,0.32,0.32,1.29,0.05,0.05,0.231,0.005,0.005,0.011664,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1,2008,2011-12-23,94.8,1.5,1.5,2452899.6,1.6,1.6,Radial Velocity,,,,,11 Com,185.1791667,17.7927778,4.74,,,,,110.6,-0.35,2.7,19.0,G8 III,,4742.0,, 11 UMi b,10.5,2.47,2.47,,,,516.22,3.25,3.25,1.54,0.07,0.07,0.08,0.03,0.03,0.012887,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1,2009,2009-08-13,117.63,21.06,21.06,2452861.05,2.06,2.06,Radial Velocity,,,,,11 UMi,229.275,71.8238889,5.02,,,,,119.5,0.04,1.8,24.08,K4III,1.56,4340.0,, </code> | According to the latest pandas documentation, you can read a CSV file selecting only the columns you want to read.
```python
import pandas as pd
df = pd.read_csv('some_data.csv', usecols=['col1', 'col2'], low_memory=True)
```
Here we use `usecols` which reads only selected columns into a DataFrame. We are using `low_memory` so that we internally process the file in chunks. |
|
JavaScript Possible Iteration Over Unexpected <sep> I have the following code: <code> for (i in awards) { if (awards[i] instanceof Array === false) { console.log(awards[i]); httpFactory.patch(awards[i], {"read": true}, false); } } </code> My IDE shows this error relating to the code above: <blockquote> Possible iteration over unexpected (custom / inherited) members, probably missing hasOwnProperty check Checks for any instances of unfiltered for-in loops in JavaScript. The use of this construct results in processing inherited or unexpected properties. You need to filter own properties with hasOwnProperty() method. The validation works in JavaScript, html or jsp files. </blockquote> Could you explain in more detail what is meant by this statement? | The IDE is recommending that you add a test: `if (awards.hasOwnProperty(i)) { ... }` inside the `for` loop. I personally recommend not doing this and disabling the warning if possible. There's simply no need in most code, and even less need in ES5 code where you can safely add non-enumerable properties to an object using `Object.defineProperty`. The `hasOwnProperty` check is only necessary if you have unsafely added new (enumerable) properties to `Object.prototype`, so the simplest fix is: don't do that. jQuery doesn't perform this test; they explicitly document that jQuery will break if `Object.prototype` is unsafely modified. |
|
Correct way to write loops for promise. <sep> How to correctly construct a loop to make sure the following promise call and the chained logger.log(res) runs synchronously through iteration? (bluebird) <code>db.getUser(email).then(function(res) { logger.log(res); }); // this is a promise </code> I tried the following way (method from http://blog.victorquinn.com/javascript-promise-while-loop ) <code>var Promise = require('bluebird'); var promiseWhile = function(condition, action) { var resolver = Promise.defer(); var loop = function() { if (!condition()) return resolver.resolve(); return Promise.cast(action()) .then(loop) .catch(resolver.reject); }; process.nextTick(loop); return resolver.promise; }); var count = 0; promiseWhile(function() { return count < 10; }, function() { return new Promise(function(resolve, reject) { db.getUser(email) .then(function(res) { logger.log(res); count++; resolve(); }); }); }).then(function() { console.log('all done'); }); </code> Although it seems to work, but I don't think it guarantees the order of calling logger.log(res); Any suggestions? | If you really want a general `promiseWhen()` function for this and other purposes, then by all means do so, using Berg's simplifications. However, because of the way promises work, passing callbacks in this way is generally unnecessary and forces you to jump through complex hoops. As far as I can tell, you're trying: to asynchronously fetch a series of user details for a collection of email addresses (at least, that's the only scenario that makes sense); to do so by building a `.then()` chain via recursion; to maintain the original order when handling the returned results. Defined thus, the problem is actually the one discussed under "The Collection Kerfuffle" in Promise Anti-patterns, which offers two simple solutions: parallel asynchronous calls using `Array.prototype.map()`, and serial asynchronous calls using `Array.prototype.reduce()`. The parallel approach will (straightforwardly) give you the issue that you are trying to avoid—that the order of the responses is uncertain. The serial approach will build the required `.then()` chain—flat—no recursion.
```javascript
function fetchUserDetails(arr) {
return arr.reduce(function(promise, email) {
return promise.then(function() {
return db.getUser(email).done(function(res) {
logger.log(res);
});
});
}, Promise.resolve());
}
```
Call as follows:
```javascript
// Compose here, by whatever means, an array of email addresses.
var arrayOfEmailAddys = [...];
fetchUserDetails(arrayOfEmailAddys).then(function() {
console.log('all done');
});
```
As you can see, there's no need for the ugly outer `var count` or its associated `condition` function. The limit (of 10 in the question) is determined entirely by the length of the array `arrayOfEmailAddys`. |
|
How to plot ROC curve in Python <sep> I am trying to plot a ROC curve to evaluate the accuracy of a prediction model I developed in Python using logistic regression packages. I have computed the true positive rate as well as the false positive rate; however, I am unable to figure out how to plot these correctly using <code>matplotlib</code> and calculate the AUC value. How could I do that? | ```python
from sklearn import svm, datasets
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
import matplotlib.pyplot as plt
# Load Breast Cancer Dataset
breast_cancer = load_breast_cancer()
X = breast_cancer.data
y = breast_cancer.target
# Split the Dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=44)
# Model
clf = LogisticRegression(penalty='l2', C=0.1)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
# Accuracy
print("Accuracy", metrics.accuracy_score(y_test, y_pred))
# AUC Curve
y_pred_proba = clf.predict_proba(X_test)[:, 1]
fpr, tpr, _ = metrics.roc_curve(y_test, y_pred_proba)
auc = metrics.roc_auc_score(y_test, y_pred_proba)
plt.plot(fpr, tpr, label="ROC curve (area = %0.2f)" % auc)
plt.legend(loc=4)
plt.show()
``` |
|
How to Export Certificate from Chrome on a Mac? <sep> How do I export a security certificate from Chrome v37 on a Mac? Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear. Not so anymore! | You should make the following steps: show certificate details on the Chrome browser on macOS, drag the large certificate icon onto the certificate details window, drop the icon onto the desktop, and you're done! You've created a domain certificate `.cer` file on the desktop. |
|
How can I get the output of a matplotlib plot as an SVG? <sep> I need to take the output of a matplotlib plot and turn it into an SVG path that I can use on a laser cutter. <code>import matplotlib.pyplot as plt import numpy as np x = np.arange(0,100,0.00001) y = x*np.sin(2*pi*x) plt.plot(y) plt.show() </code> For example, below you see a waveform. I would like to be able to output or save this waveform as an SVG path that I can later work with in a program such as Adobe Illustrator. I am aware of an SVG library called "Cairo" that matplotlib can use (<code>matplotlib.use('Cairo')</code>), however it's not clear to me that this will give me access to the SVG path that I need, even though matplotlib will now be using Cairo to generate the plot. I do have cairo working on my system, and can successfully draw an example composed of SVG paths that I can indeed edit in Illustrator, but I don't have a way to take my equation above into an SVG path. <code>import cairo from cairo import SVGSurface, Context, Matrix s = SVGSurface('example1.svg', WIDTH, HEIGHT) c = Context(s) # Transform to normal cartesian coordinate system m = Matrix(yy=-1, y0=HEIGHT) c.transform(m) # Set a background color c.save() c.set_source_rgb(0.3, 0.3, 1.0) c.paint() c.restore() # Draw some lines c.move_to(0, 0) c.line_to(2 * 72, 2* 72) c.line_to(3 * 72, 1 * 72) c.line_to(4 * 72, 2 * 72) c.line_to(6 * 72, 0) c.close_path() c.save() c.set_line_width(6.0) c.stroke_preserve() c.set_source_rgb(0.3, 0.3, 0.3) c.fill() c.restore() # Draw a circle c.save() c.set_line_width(6.0) c.arc(1 * 72, 3 * 72, 0.5 * 72, 0, 2 * pi) c.stroke_preserve() c.set_source_rgb(1.0, 1.0, 0) c.fill() c.restore() # Save as a SVG and PNG s.write_to_png('example1.png') s.finish() </code> (note that the image displayed here is a png, as stackoverflow doesn't accept svg graphics for display) | You will most probably want to fix the image size and get rid of all sorts of backgrounds and axis markers:
```python
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=[6, 6])
x = np.arange(0, 100, 0.00001)
y = x*np.sin(2*np.pi * x)
plt.plot(y)
plt.axis('off')
plt.gca().set_position([0, 0, 1, 1])
plt.savefig("test.svg")
```
The resulting SVG file contains only one extra element, as `savefig` really wants to save the figure background. The color of this background is easy to change to 'none', but it does not seem to get rid of it. Anyway, the SVG is very clean otherwise and in the correct scale (1/72" per unit). |
|
Scroll to a specific Element Using html <sep> Is there a method in html which makes the webpage scroll to a specific Element using HTML !? | You should mention whether you want it to smoothly scroll or simply jump to an element. Jumping is easy and can be done just with HTML or JavaScript. The simplest is to use anchors. The limitation is that every element you want to scroll to has to have an `id`. A side effect is that `#theID` will be appended to the URL.
`<a href="#scroll">Go to Title</a>
<div>
<h1 id="scroll">Title</h1>
</div>`
You can add CSS effects to the target when the link is clicked with the CSS `:target` selector. With some basic JavaScript, you can do more, namely the method `scrollIntoView()`. Your elements don't need an `id`, though it is still easier, e.g.,
`function onLinkClick() {
document.getElementsByTagName('h2')[3].scrollIntoView(); // will scroll to 4th h3 element
}`
Finally, if you need smooth scrolling, you should have a look at JS Smooth Scroll or this snippet for jQuery. (NB: there are probably many more). |
|
How to find Unused Amazon EC2 Security groups <sep> I'm try to find a way to determine orphan security groups so I can clean up and get rid of them. Does anyone know of a way to discover unused security groups. Either through the console or with the command line tools will work (Running command line tools on linux and OSX machines). | Using the newer AWS CLI tool, I found an easy way to get what I need:
First, get a list of all security groups:
```
aws ec2 describe-security-groups --query 'SecurityGroups[*].GroupId' --output text | tr '\t' '\n'
```
Then get all security groups tied to an instance, then piped to `sort` then `uniq`:
```
aws ec2 describe-instances --query 'Reservations[*].Instances[*].SecurityGroups[*].GroupId' --output text | tr '\t' '\n' | sort | uniq
```
Then put it together and compare the 2 lists and see what's not being used from the master list:
```
comm -23 <(aws ec2 describe-security-groups --query 'SecurityGroups[*].GroupId' --output text | tr '\t' '\n'| sort) <(aws ec2 describe-instances --query 'Reservations[*].Instances[*].SecurityGroups[*].GroupId' --output text | tr '\t' '\n' | sort | uniq)
``` |
|
Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device." <sep> So I started getting errors in my ADB logs which, I think, are causing my device to now display any logcat output for my app. I am getting all the logcat output except the one from the app itself. <code>PropertyFetcher: AdbCommandRejectedException getting properties for device 04799057970ed1fc: device offline PropertyFetcher: AdbCommandRejectedException getting properties for device 03799467970ed5fg: device unauthorized. Please check the confirmation dialog on your device. </code> | I experienced the same issue. To ensure that your Android device is expecting the correct fingerprint from the system (e.g., after switching Android SDK installations—different adb server running!), do the following (actually, this did the magic for me): unplug your Android device, revoke USB debugging authorizations in Android Developer Options, plug your device back in. You can then accept the fingerprint again. |
|
Loop through childNodes <sep> I'm trying to loop through childNodes like this: <code>var children = element.childNodes; children.forEach(function(item){ console.log(item); }); </code> However, it output <code>Uncaught TypeError: undefined is not a function</code> due to <code>forEach</code> function. I also try to use <code>children</code> instead of <code>childNodes</code> but nothing changed. Does anybody know what's going on? | I'm very late to the party, but since `element.lastChild.nextSibling === null`, the following seems like the most straightforward option to me: `for (var child = element.firstChild; child !== null; child = child.nextSibling) { console.log(child); }` |
|
What's the reason for "Error:Cannot determine Java VM executable in selected JDK"? <sep> I am using IntelliJ IDEA 13.1.4 and also tried the latest release 14. Running SBT I get the following error: <code>Error:Cannot determine Java VM executable in selected JDK </code> I have JDK 1.7 installed on my machine and on PATH. In the logs (<code>~/Library/Logs/IntelliJIdea14/idea.log</code> on MacOS) there's the following stack trace: <code>2014-11-03 11:22:05,054 [4896641] WARN - nal.AbstractExternalSystemTask - Cannot determine Java VM executable in selected JDK com.intellij.openapi.externalSystem.model.ExternalSystemException: Cannot determine Java VM executable in selected JDK at org.jetbrains.sbt.project.SbtExternalSystemManager$$anonfun$10.apply(SbtExternalSystemManager.scala:97) at org.jetbrains.sbt.project.SbtExternalSystemManager$$anonfun$10.apply(SbtExternalSystemManager.scala:97) at scala.Option.getOrElse(Option.scala:120) at org.jetbrains.sbt.project.SbtExternalSystemManager$.executionSettingsFor(SbtExternalSystemManager.scala:96) at org.jetbrains.sbt.project.SbtExternalSystemManager$$anonfun$getExecutionSettingsProvider$1.apply(SbtExternalSystemManager.scala:54) at org.jetbrains.sbt.project.SbtExternalSystemManager$$anonfun$getExecutionSettingsProvider$1.apply(SbtExternalSystemManager.scala:54) at org.jetbrains.sbt.package$$anon$3.fun(package.scala:29) at org.jetbrains.sbt.package$$anon$3.fun(package.scala:28) at com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.getExecutionSettings(ExternalSystemApiUtil.java:590) at com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager.a(ExternalSystemFacadeManager.java:201) at com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager.a(ExternalSystemFacadeManager.java:178) at com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager.doInvoke(ExternalSystemFacadeManager.java:133) at com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager$MyHandler.invoke(ExternalSystemFacadeManager.java:270) at com.sun.proxy.$Proxy57.getResolver(Unknown Source) at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:48) at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:137) at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:123) at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:475) at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$1.run(ExternalSystemUtil.java:543) at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:609) at com.intellij.openapi.progress.impl.ProgressManagerImpl$7.run(ProgressManagerImpl.java:410) at com.intellij.openapi.progress.impl.ProgressManagerImpl$3.run(ProgressManagerImpl.java:194) at com.intellij.openapi.progress.impl.ProgressManagerImpl.a(ProgressManagerImpl.java:281) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:233) at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:181) at com.intellij.openapi.application.impl.ApplicationImpl$10$1.run(ApplicationImpl.java:640) at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56) </code> What can be the reason for this? | The issue is usually caused by a wrong JDK version in ".idea/sbt.xml", e.g.:
`<option name="jdk" value="1.7" />`. This option is not updated accordingly when the Project SDK is changed (see SCL-10085). If you have the other JDK (1.7 in my example) generally configured, no error will occur, but the Project SDK will silently be changed back. Otherwise, this error occurs. The problem can easily be resolved by manually editing the value in ".idea/sbt.xml" to the correct JDK version. |
|
bootstrap modal removes scroll bar <sep> When I trigger a modal view in my page it triggers the scroll bar to disappear. It's an annoying effect because the background page starts moving when the modal moves in / disappears. Is there a cure for that effect? | I think "inherit" is better than "scroll" because when you open a modal, it will always open with scroll, but when you don't have any scrolls you will get the same problem. So I just do this:
`.modal-open { overflow: inherit; }` |
|
Status bar height in Swift <sep> How can I get the status bar's height programmatically in Swift? In Objective-C, it's like this: <code>[UIApplication sharedApplication].statusBarFrame.size.height. </code> | ```swift
func getStatusBarHeight() -> CGFloat {
var statusBarHeight: CGFloat = 0
if #available(iOS 13.0, *) {
let window = UIApplication.shared.windows.filter { $0.isKeyWindow }.first
statusBarHeight = window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
} else {
statusBarHeight = UIApplication.shared.statusBarFrame.height
}
return statusBarHeight
}
Happy Coding!
``` |
|
SHA256 in swift <sep> I want to use sha256 in my project, but I had some troubles rewriting objC code to swift code. Help me please. I used this answer: How can I compute a SHA-2 (ideally SHA 256 or SHA 512) hash in iOS? Here's my code <code>var hash : [CUnsignedChar] CC_SHA256(data.bytes, data.length, hash) var res : NSData = NSData.dataWithBytes(hash, length: CC_SHA256_DIGEST_LENGTH) </code> it gives me error everything because swift cannot convert <code>Int</code> to <code>CC_LONG</code>, for example. | With `CryptoKit` added in iOS 13, we now have a native Swift API:
```swift
import Foundation
import CryptoKit
extension Digest {
var bytes: [UInt8] { Array(makeIterator()) }
var data: Data { Data(bytes) }
var hexStr: String { bytes.map { String(format: "%02X", $0) }.joined() }
}
func example() {
guard let data = "hello world".data(using: .utf8) else { return }
let digest = SHA256.hash(data: data)
print(digest.data) // 32 bytes
print(digest.hexStr) // B94D27B9934D3E08A52E52D7DA7DABFAC484EFE37A5380EE9088F7ACE2EFCDE9
}
```
Because utils are defined for the `Digest` protocol, you can use them for all digest types in `CryptoKit`, like `SHA384Digest`, `SHA512Digest`, `SHA1Digest`, `MD5Digest`... |
|
Multi flavor app based on multi flavor library in Android Gradle <sep> My app has several flavors for several markets in-app-billing systems. I have a single library which shares the base code for all of my projects. So I decided to add those payment systems to this library as product flavors. The question is can android library have product flavors? If so, how can I include different flavors in respective flavor of the app? I searched a lot, and I couldn't find anything about this scenario. The only close thing I found was this in http://tools.android.com/tech-docs/new-build-system/user-guide: <code>dependencies { flavor1Compile project(path: ':lib1', configuration: 'flavor1Release') flavor2Compile project(path: ':lib1', configuration: 'flavor2Release') } </code> I changed configuration to different things but it did not work! I'm using android studio 0.8.2. | Update for Android Plugin 3.0.0 and higher
According to the official Android Documentation - Migrate dependency configurations for local modules:
> With variant-aware dependency resolution, you no longer need to use variant-specific configurations, such as `freeDebugImplementation`, for local module dependencies. The plugin takes care of this for you. You should instead configure your dependencies as follows:
```groovy
dependencies {
// This is the old method and no longer works for local
// library modules:
// debugImplementation project(path: ':library', configuration: 'debug')
// releaseImplementation project(path: ':library', configuration: 'release')
// Instead, simply use the following to take advantage of
// variant-aware dependency resolution. You can learn more about
// the 'implementation' configuration in the section about
// new dependency configurations.
implementation project(':library')
// You can, however, keep using variant-specific configurations when
// targeting external dependencies. The following line adds 'app-magic'
// as a dependency to only the "debug" version of your module.
debugImplementation 'com.example.android:app-magic:12.3'
}
```
So in Ali's answer, change
```groovy
dependencies {
market1Compile project(path: ':lib', configuration: 'market1Release')
market2Compile project(path: ':lib', configuration: 'market2Release')
}
```
to
```groovy
implementation project(':lib')
```
And the plugin will take care of variant-specific configurations automatically.
Hope it helps others upgrading Android Studio Plugin to 3.0.0 and higher. |
|
Using the Swift if let with logical AND operator && <sep> We know that we can use an <code>if let</code> statement as a shorthand to check for an optional nil then unwrap. However, I want to combine that with another expression using the logical AND operator <code>&&</code>. So, for example, here I do optional chaining to unwrap and optionally downcast my rootViewController to tabBarController. But rather than have nested if statements, I'd like to combine them. <code>if let tabBarController = window!.rootViewController as? UITabBarController { if tabBarController.viewControllers.count > 0 { println("do stuff") } } </code> Combined giving: <code>if let tabBarController = window!.rootViewController as? UITabBarController && tabBarController.viewControllers.count > 0 { println("do stuff") } } </code> The above gives the compilation error Use of unresolved identifier 'tabBarController' Simplifying: <code>if let tabBarController = window!.rootViewController as? UITabBarController && true { println("do stuff") } </code> This gives a compilation error Bound value in a conditional binding must be of Optional type. Having attempted various syntactic variations, each gives a different compiler error. I've yet to find the winning combination of order and parentheses. So, the question is, is it possible and if so what is correct syntax? Note that I want to do this with an <code>if</code> statement not a <code>switch</code> statement or a ternary <code>?</code> operator. | As of Swift 1.2, this is now possible. The Swift 1.2 and Xcode 6.3 beta release notes state:
> More powerful optional unwrapping with `if let`
>
> The `if let` construct can now unwrap multiple optionals at once, as well as include intervening boolean conditions. This lets you express conditional control flow without unnecessary nesting.
With the statement above, the syntax would then be:
```swift
if let tabBarController = window!.rootViewController as? UITabBarController where tabBarController.viewControllers.count > 0 {
println("do stuff")
}
```
This uses the `where` clause. Another example, this time casting `AnyObject` to `Int`, unwrapping the optional, and checking that the unwrapped optional meets the condition:
```swift
if let w = width as? Int where w < 500 {
println("success!")
}
```
For those now using Swift 3, "where" has been replaced by a comma. The equivalent would therefore be:
```swift
if let w = width as? Int, w < 500 {
println("success!")
}
``` |
|
How to iterate over consecutive chunks of Pandas dataframe efficiently <sep> I have a large dataframe (several million rows). I want to be able to do a groupby operation on it, but just grouping by arbitrary consecutive (preferably equal-sized) subsets of rows, rather than using any particular property of the individual rows to decide which group they go to. The use case: I want to apply a function to each row via a parallel map in IPython. It doesn't matter which rows go to which back-end engine, as the function calculates a result based on one row at a time. (Conceptually at least; in reality it's vectorized.) I've come up with something like this: <code># Generate a number from 0-9 for each row, indicating which tenth of the DF it belongs to max_idx = dataframe.index.max() tenths = ((10 * dataframe.index) / (1 + max_idx)).astype(np.uint32) # Use this value to perform a groupby, yielding 10 consecutive chunks groups = [g[1] for g in dataframe.groupby(tenths)] # Process chunks in parallel results = dview.map_sync(my_function, groups) </code> But this seems very long-winded, and doesn't guarantee equal sized chunks. Especially if the index is sparse or non-integer or whatever. Any suggestions for a better way? Thanks! | ```python
import numpy as np
import pandas as pd
data = pd.DataFrame(np.random.rand(10, 3))
for chunk in np.array_split(data, 5):
assert len(chunk) == len(data) // 5, "This assert may fail for the last chunk if the data length isn't divisible by 5"
``` |
|
Android Studio Gradle project "Unable to start the daemon process /initialization of VM" <sep> Version of Android Studio (Beta) 0.8.4 OS version: Windows 8 Java JRE/JDK version: 1.8.0_11 <code>Error:Unable to start the daemon process. This problem might be caused by incorrect configuration of the daemon. For example, an unrecognized jvm option is used. Please refer to the user guide chapter on the daemon at http://gradle.org/docs/1.12/userguide/gradle_daemon.html ----------------------- Error occurred during initialization of VM Could not reserve enough space for 1048576KB object heap Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0 </code> | The Solution Worked: 1. Open the project's Gradle.properties file in Android Studio. 2. Add this line at the end of the file: org.gradle.jvmargs=-Xmx1024m & Save the file. 3. Close & reopen the project, or just Clean and rebuild it. |
|
Rstudio rmarkdown: both portrait and landscape layout in a single PDF <sep> I wonder how to use <code>rmarkdown</code> to generate a pdf which has both portrait and landscape layout in the same document. If there is a pure <code>rmarkdown</code> option that would be even better than using latex. Here's a small, reproducible example. First, rendering this <code>.Rmd</code> in RStudio (press Knit PDF button) results in a pdf with all pages in landscape layout: <code>--- title: "All pages landscape" output: pdf_document classoption: landscape --- ```{r} summary(cars) ``` \newpage ```{r} summary(cars) ``` </code> Then an attempt to create a document which mixes portrait and landscape layout. The basic setup in the <code>YAML</code> is done according to the 'Includes' section here. The <code>in_header</code> file 'header.tex' only contains <code>\usepackage{lscape}</code>, a package suggested for <code>knitr</code> landscape layout here. The <code>.tex</code> file is in the same directory as the <code>.Rmd</code> file. <code>--- title: "Mixing portrait and landscape" output: pdf_document: includes: in_header: header.tex --- Portrait: ```{r} summary(cars) ``` \newpage \begin{landscape} Landscape: ```{r} summary(cars) ``` \end{landscape} \newpage More portrait: ```{r} summary(cars) ``` </code> However, this code results in an error: <code># ! You can't use `macro parameter character #' in horizontal mode. # l.116 # # pandoc.exe: Error producing PDF from TeX source # Error: pandoc document conversion failed with error 43 </code> Any help is much appreciated. | ```yaml
---
title: "Mixing portrait and landscape WITHOUT a header.tex file"
header-includes:
- \usepackage{pdflscape}
- \newcommand{\blandscape}{\begin{landscape}}
- \newcommand{\elandscape}{\end{landscape}}
output: pdf_document
---
Portrait ```{r} summary(cars) ```
\newpage
\blandscape Landscape ```{r} summary(cars) ```
\elandscape
\newpage
More portrait ```{r} summary(cars) ```
``` |
|
How to stop /#/ in browser with react-router? <sep> Any way to prevent <code>/#/</code> from showing in the browser's address bar when using react-router? That's with ReactJS. i.e. Clicking on links to go to a new route shows <code>localhost:3000/#/</code> or <code>localhost:3000/#/about</code>. Depending on the route. | The answer to this question has changed dramatically over the years as React Router has been refactored again and again. Here is a breakdown of how to solve the issue with each version.
**Version 6**
The idea is to set the router to be a "browser router", which is created using the `createBrowserRouter()` function. This router is then added to the root element of the React app.
```javascript
import React from "react";
import ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider, Route } from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
element: ...,
},
]);
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
```
Source: react-router Version 6 Docs: `createBrowserRouter`
**Version 4**
For version 4 of react-router, the syntax is very different, and it is required to use `BrowserRouter` as the router root tag.
```javascript
import { BrowserRouter } from 'react-router';
ReactDOM.render(
<BrowserRouter>
...
</BrowserRouter>,
document.body
);
```
Note that this will work in version 6, but it's not recommended, and the `BrowserRouter` component doesn't support the new React Router data APIs.
Source: React Router Version 4 Docs
**Versions 2 and 3**
For versions 1, 2, and 3 of React Router, the correct way to set the route to URL mapping scheme is by passing a history implementation into the `history` parameter of `<Router>`.
From the histories documentation:
> In a nutshell, a history knows how to listen to the browser's address bar for changes and parses the URL into a location object that the router can use to match routes and render the correct set of components.
In react-router 2 and 3, your route configuration code will look something like this:
```javascript
import { browserHistory } from 'react-router';
ReactDOM.render(
<Router history={browserHistory}>
...
</Router>,
document.body
);
```
**Version 1**
In version 1.x, you will instead use the following:
```javascript
import createBrowserHistory from 'history/lib/createBrowserHistory';
ReactDOM.render(
<Router history={createBrowserHistory()}>
...
</Router>,
document.body
);
```
Source: Version 2.0 Upgrade Guide |
|
Set visibility of progress bar gone on completion of image loading using Glide library <sep> Hi I want to have a progress bar for image which will shown while image loading but when image loading will be completed I want to set it to gone. Earlier I was using Picasso library for this. But I don't know how to use it with Glide library. I have idea that some resource ready function is there but I don't know how to use it. Can anyone help me? Code for Picasso Library <code>Picasso.with(mcontext).load(imgLinkArray.get(position).mUrlLink) .into(imageView, new Callback() { @Override public void onSuccess() { progressBar.setVisibility(View.GONE); } @Override public void onError() { } }) ; </code> Now How Can I do this with Glide? <code>Glide.with(mcontext).load(imgLinkArray.get(position).mUrlLink) .into(imageView); </code> I am able to load image by this with Glide but how can I write <code>progressBar.setVisibility(View.GONE);</code> somewhere in code if image get loaded? | ```kotlin
Glide.with(context)
.load(url)
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
//TODO: something on exception
}
override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
Log.d(TAG, "OnResourceReady")
//do something when picture already loaded
return false
}
})
.into(imgView)
``` |
|
Is it possible to always show up/down arrows for input "number"? <sep> I want to always show up/down arrows for input "number" field. Is this possible? So far I haven't had any luck... http://jsfiddle.net/oneeezy/qunbnL6u/ HTML: <code><input type="number" /> </code> CSS: <code>input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: "Always Show Up/Down Arrows"; } </code> | You can achieve this (in Chrome at least) by using the `opacity` property:
```css
input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { opacity: 1; }
```
As stated above, this will likely only work in Chrome. So be careful using this code in the wild without a fallback for other browsers. |
|
Swift - Problems with corner radius and drop shadow <sep> I'm trying to create a button with rounded corners and a drop shadow. No matter how I switch up, the button will not display correctly. I've tried <code>masksToBounds = false</code> and <code>masksToBounds = true</code>, but either the corner radius works and the shadow does not or the shadow works and the corner radius doesn't clip the corners of the button. <code>import UIKit import QuartzCore @IBDesignable class Button : UIButton { @IBInspectable var masksToBounds: Bool = false {didSet{updateLayerProperties()}} @IBInspectable var cornerRadius : CGFloat = 0 {didSet{updateLayerProperties()}} @IBInspectable var borderWidth : CGFloat = 0 {didSet{updateLayerProperties()}} @IBInspectable var borderColor : UIColor = UIColor.clearColor() {didSet{updateLayerProperties()}} @IBInspectable var shadowColor : UIColor = UIColor.clearColor() {didSet{updateLayerProperties()}} @IBInspectable var shadowOpacity: CGFloat = 0 {didSet{updateLayerProperties()}} @IBInspectable var shadowRadius : CGFloat = 0 {didSet{updateLayerProperties()}} @IBInspectable var shadowOffset : CGSize = CGSizeMake(0, 0) {didSet{updateLayerProperties()}} override func drawRect(rect: CGRect) { updateLayerProperties() } func updateLayerProperties() { self.layer.masksToBounds = masksToBounds self.layer.cornerRadius = cornerRadius self.layer.borderWidth = borderWidth self.layer.borderColor = borderColor.CGColor self.layer.shadowColor = shadowColor.CGColor self.layer.shadowOpacity = CFloat(shadowOpacity) self.layer.shadowRadius = shadowRadius self.layer.shadowOffset = shadowOffset } } </code> | My custom button with some shadow and rounded corners, I use it directly within the `Storyboard` with no need to touch it programmatically. <blockquote>Swift 4</blockquote>
```swift
class RoundedButtonWithShadow: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
self.layer.masksToBounds = false
self.layer.cornerRadius = self.frame.height / 2
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).cgPath
self.layer.shadowOffset = CGSize(width: 0.0, height: 3.0)
self.layer.shadowOpacity = 0.5
self.layer.shadowRadius = 1.0
}
}
``` |
|
onClick works but onDoubleClick is ignored on React component <sep> I am building a Minesweeper game with React and want to perform a different action when a cell is single or double clicked. Currently, the <code>onDoubleClick</code> function will never fire, the alert from <code>onClick</code> is shown. If I remove the <code>onClick</code> handler, <code>onDoubleClick</code> works. Why don't both events work? Is it possible to have both events on an element? <code>/** @jsx React.DOM */ var Mine = React.createClass({ render: function(){ return ( <div className="mineBox" id={this.props.id} onDoubleClick={this.props.onDoubleClick} onClick={this.props.onClick}></div> ) } }); var MineRow = React.createClass({ render: function(){ var width = this.props.width, row = []; for (var i = 0; i < width; i++){ row.push(<Mine id={String(this.props.row + i)} boxClass={this.props.boxClass} onDoubleClick={this.props.onDoubleClick} onClick={this.props.onClick}/>) } return ( <div>{row}</div> ) } }) var MineSweeper = React.createClass({ handleDoubleClick: function(){ alert('Double Clicked'); }, handleClick: function(){ alert('Single Clicked'); }, render: function(){ var height = this.props.height, table = []; for (var i = 0; i < height; i++){ table.push(<MineRow width={this.props.width} row={String.fromCharCode(97 + i)} onDoubleClick={this.handleDoubleClick} onClick={this.handleClick}/>) } return ( <div>{table}</div> ) } }) var bombs = ['a0', 'b1', 'c2']; React.renderComponent(<MineSweeper height={5} width={5} bombs={bombs}/>, document.getElementById('content')); </code> | Instead of using `ondoubleclick`, you can use `event.detail` to get the current click count. It's the number of times the mouse has been clicked in the same area in a short time.
```javascript
const handleClick = (e) => {
switch (e.detail) {
case 1:
console.log("click");
break;
case 2:
console.log("double click");
break;
case 3:
console.log("triple click");
break;
}
};
return <button onClick={handleClick}>Click me</button>;
```
In the example above, if you triple-click the button, it will print all 3 cases: `click double click triple click`.
Live Demo |
|
Attributed string with custom fonts in storyboard does not load correctly <sep> We are using custom fonts in our project. It works well in Xcode 5. In Xcode 6, it works in plain text, attributed string in code. But those attributed strings set in storyboard all revert to Helvetica when running on simulator or device, although they look all right in storyboard. I'm not sure if it's a bug of Xcode 6 or iOS 8 SDK, or the way to use custom fonts is changed in Xcode 6 / iOS 8? | The simplest answer that worked for me was to drag the fonts into FontBook. If the fonts are in your project but not in your computer's FontBook, IB sometimes has trouble finding them. Weird, but it has worked for me on several occasions. |
|
What does &> do in bash? <sep> I was looking at pre-commit hook and discovered the following line because I was wondering why I always got an empy file called <code>1</code> in my directory after doing a commit. <code>git status 2&>1 > /dev/null </code> I believe the intent was to write the following, and I corrected it. <code>git status 2>&1 > /dev/null </code> However, I was curious about what the following syntax does exactly, so I looked up the man page. <code>git status 2&>1 </code> Here is the man page. <code> Redirecting Standard Output and Standard Error This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file whose name is the expansion of word. There are two formats for redirecting standard output and standard error: &>word and >&word Of the two forms, the first is preferred. This is semantically equiva lent to >word 2>&1 </code> However, this man page implies that the two are equivalent, which does not seem to be the case. Can someone clarify the man page and explain exactly what is happening with this syntax? | The operators we are using here are: `>` Syntax: file_descriptoropt `>` file_name `>&` Syntax: file_descriptoropt `>&` file_descriptor `&>` Syntax: `&>` file_name
If the file descriptor is omitted, the default is `0` (stdin) for input, or `1` (stdout) for output. `2` means stderr.
So we have: `>`name` means `1>name` -- redirect stdout to the file `name` `&>name` is like `1>name 2>name` -- redirect stdout and stderr to the file `name` (however, `name` is only opened once; if you actually wrote `1>name 2>name` it'd try to open `name` twice and perhaps malfunction).
So when you write `git status 2&>1`, it is therefore like `git status 2 1>1 2>1`, i.e. the first `2` actually gets passed as an argument to `git status`. stdout is redirected to the file named `1` (not the file descriptor 1), stderr is redirected to the file named `1`. This command should actually create a file called `1` with the contents being the result of `git status 2` -- i.e. the status of the file called `2` which is probably "Your branch is up to date, nothing to commit, working directory clean", presuming you do not actually track a file called `2`. |
|
Xcode 6 - Launch simulator from command line <sep> I want to launch iPhone simulator from command line. until now I have been using the below command <blockquote> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone Simulator.app/Contents/MacOS/iPhone Simulator -SimulateDevice </blockquote> -SimulateDevice is used to launch a specific device type Now with Xcode 6 the path and the app has been changed to <blockquote> /Applications/Xcode.app/Contents/Developer/Applications/iOS Simulator.app/Contents/MacOS/iOS Simulator </blockquote> but sadly -SimulateDevice option is not working now. I can launch the simulator, but dont have an option to specify which one to launch Anyone found any alternatives for this with Xcode 6? | With Xcode 6, if you want the iOS Simulator.app to boot a specific device when it launches, you can run this from the command line: `open -a "iOS Simulator" --args -CurrentDeviceUDID <DEVICE UDID>`, where you can figure out the UDID of the device you want to boot from: `xcrun simctl list`.
With Xcode 7, the application was renamed to Simulator.app, so you should update the above accordingly to: `open -a Simulator --args -CurrentDeviceUDID <DEVICE UDID>`. |
|
What is the meaning of android.intent.action.MAIN? <sep> I have seen so many different confusing explenations.. <code><intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </code> What is the meaning of <code><action android:name="android.intent.action.MAIN" /> </code> and <code> <category android:name="android.intent.category.LAUNCHER" /> </code> and <code> <category android:name="android.intent.category.DEFAULT" /> </code> | `ACTION_MAIN` is considered an entry point for the application. Usually, it is combined with `CATEGORY_LAUNCHER` in an `<intent-filter>` to indicate an activity that should appear in the home screen's launcher, or in anything else that considers itself a launcher. Such "launchers" can query `PackageManager`, using `queryIntentActivities()`, to find such activities and display them to the user. However, `ACTION_MAIN` can be used in combination with other categories for other specialized purposes. For example, `CATEGORY_CAR_DOCK` with `ACTION_MAIN` indicates an activity that should be considered a candidate to be shown when the user drops their phone into a manufacturer-supplied car dock. When an `Intent` is used with `startActivity()`, if it is not already placed into a category, it is placed into `CATEGORY_DEFAULT`. Hence, an `<activity>` `<intent-filter>` needs to specify some `<category>`, using `<category android:name="android.intent.category.DEFAULT" />` if nothing else. |
|
Test if code is executed from within a py.test session <sep> I'd like to connect to a different database if my code is running under py.test. Is there a function to call or an environment variable that I can test that will tell me if I'm running under a py.test session? What's the best way to handle this? | A simpler solution I came to: `import sys if "pytest" in sys.modules: ...`
Pytest's runner will always load the `pytest` module, making it available in `sys.modules`. Of course, this solution only works if the code you're trying to test does not use `pytest` itself. |
|
How can I find all hard coded strings in my project in Android Studio <sep> I need to find and extract all hard coded strings in my project in Android Studio (beta) 0.84. I need a static analysis tool like Find Bugs do this for me in one shot and allow me to step through each message and extract the string to resource files. Even better would be if the entire process is automated. In Android Studio (beta) 0.84 the File / Setting /FindBugs-IDEA shows I18N as an option under Reporting tab. But I just cannot figure out how to make it work. Thanks for any suggestions. | Since Android Studio 1.2.2, there is a new option in "Analyse > Run inspection By Name" => "Hardcoded strings". I used it and it seems much more reliable with the current version than "hardcoded text" (that checks only XML files). See this link. |
|
Progress bar in console application <sep> I'm writing a simple c# console app that uploads files to sftp server. However, the amount of files are large. I would like to display either percentage of files uploaded or just the number of files upload already from the total number of files to be upload. First, I get all the files and the total number of files. <code>string[] filePath = Directory.GetFiles(path, "*"); totalCount = filePath.Length; </code> Then I loop through the file and upload them one by one in foreach loop. <code>foreach(string file in filePath) { string FileName = Path.GetFileName(file); //copy the files oSftp.Put(LocalDirectory + "/" + FileName, _ftpDirectory + "/" + FileName); //Console.WriteLine("Uploading file..." + FileName); drawTextProgressBar(0, totalCount); } </code> In the foreach loop I have a progress bar which I have issues with. It doesn't display properly. <code>private static void drawTextProgressBar(int progress, int total) { //draw empty progress bar Console.CursorLeft = 0; Console.Write("["); //start Console.CursorLeft = 32; Console.Write("]"); //end Console.CursorLeft = 1; float onechunk = 30.0f / total; //draw filled part int position = 1; for (int i = 0; i < onechunk * progress; i++) { Console.BackgroundColor = ConsoleColor.Gray; Console.CursorLeft = position++; Console.Write(" "); } //draw unfilled part for (int i = position; i <= 31 ; i++) { Console.BackgroundColor = ConsoleColor.Green; Console.CursorLeft = position++; Console.Write(" "); } //draw totals Console.CursorLeft = 35; Console.BackgroundColor = ConsoleColor.Black; Console.Write(progress.ToString() + " of " + total.ToString() + " "); //blanks at the end remove any excess } </code> The output is just [ ] 0 out of 1943 What am I doing wrong here? EDIT: I'm trying to display the progress bar while I'm loading and exporting XML files. However, it's going through a loop. After it finishes the first round it goes to the second and so on. <code>string[] xmlFilePath = Directory.GetFiles(xmlFullpath, "*.xml"); Console.WriteLine("Loading XML files..."); foreach (string file in xmlFilePath) { for (int i = 0; i < xmlFilePath.Length; i++) { //ExportXml(file, styleSheet); drawTextProgressBar(i, xmlCount); count++; } } </code> It never leaves the for loop...Any suggestions? | I know this is an old thread, and I apologize for the self-promotion, however I've recently written an open-source console library available on NuGet: Goblinfactory.Konsole. It has thread-safe, multiple progress bar support, which might help anyone new to this page needing one that doesn't block the main thread.
It's somewhat different from the answers above as it allows you to kick off downloads and tasks in parallel and continue with other tasks. Cheers, hope this is helpful.
```csharp
var t1 = Task.Run(() =>
{
var p = new ProgressBar("downloading music", 10);
// ... do stuff
});
var t2 = Task.Run(() =>
{
var p = new ProgressBar("downloading video", 10);
// ... do stuff
});
var t3 = Task.Run(() =>
{
var p = new ProgressBar("starting server", 10);
// ... do stuff
// calling p.Refresh(n);
});
Task.WaitAll(new[] { t1, t2, t3 }, 20000);
Console.WriteLine("all done.");
```
This type of output can be achieved.
The NuGet package also includes utilities for writing to a windowed section of the console with full clipping and wrapping support, plus `PrintAt` and various other helpful classes.
I wrote the NuGet package because I constantly ended up writing lots of common console routines whenever I wrote build and ops console scripts and utilities. If I was downloading several files, I used to slowly `Console.Write` to the screen on each thread and used to try various tricks to make reading the interleaved output on the screen easier to read, e.g., different colors or numbers.
I eventually wrote the windowing library so that output from different threads could simply be printed to different windows, and it cut down a ton of boilerplate code in my utility scripts.
For example, this code:
```csharp
var con = new Window(200, 50);
con.WriteLine("starting client server demo");
var client = new Window(1, 4, 20, 20, ConsoleColor.Gray, ConsoleColor.DarkBlue, con);
var server = new Window(25, 4, 20, 20, con);
client.WriteLine("CLIENT");
client.WriteLine("------");
server.WriteLine("SERVER");
server.WriteLine("------");
client.WriteLine("<-- PUT some long text to show wrapping");
server.WriteLine(ConsoleColor.DarkYellow, "--> PUT some long text to show wrapping");
server.WriteLine(ConsoleColor.Red, "<-- 404|Not Found|some long text to show wrapping|");
client.WriteLine(ConsoleColor.Red, "--> 404|Not Found|some long text to show wrapping|");
con.WriteLine("starting names demo"); // let's open a window with a box around it by using Window.Open
var names = Window.Open(50, 4, 40, 10, "names");
TestData.MakeNames(40).OrderByDescending(n => n).ToList()
.ForEach(n => names.WriteLine(n));
con.WriteLine("starting numbers demo");
var numbers = Window.Open(50, 15, 40, 10, "numbers", LineThickNess.Double, ConsoleColor.White, ConsoleColor.Blue);
Enumerable.Range(1, 200).ToList()
.ForEach(i => numbers.WriteLine(i.ToString())); // shows scrolling
```
produces this output.
You can also create progress bars inside a window just as easily as writing to the windows (mix and match). |
|
Spring-Boot: How do I set JDBC pool properties like maximum number of connections? <sep> Spring-Boot is a pretty awesome tool, but the documentation is a bit sparse when it comes to more advanced configuration. How can I set properties like the maximum size for my database connection pool? Spring-Boot supports <code>tomcat-jdbc</code>, <code>HikariCP</code> and <code>Commons DBCP</code> natively are they all configured the same way? | At the current version of Spring Boot (1.4.1.RELEASE), each pooling datasource implementation has its own prefix for properties. For instance, if you are using tomcat-jdbc, `spring.datasource.tomcat.max-wait=10000` is the correct syntax. You can find the explanation here: `spring.datasource.max-wait=10000`. This has no effect anymore. |
|
Gulp command not found after install <sep> I installed gulp(globally) and it looks like it worked because it ran this code: <code> tildify@0.2.0 interpret@0.3.5 pretty-hrtime@0.2.1 deprecated@0.0.1 archy@0.0.2 minimist@0.2.0 semver@2.3.2 orchestrator@0.3.7 (stream-consume@0.1.0, sequencify@0.0.7, end-of-stream@0.1.5) chalk@0.5.1 (escape-string-regexp@1.0.1, ansi-styles@1.1.0, supports-color@0.2.0, strip-ansi@0.3.0, has-ansi@0.1.0) gulp-util@2.2.20 (lodash._reinterpolate@2.4.1, dateformat@1.0.8-1.2.3, vinyl@0.2.3, through2@0.5.1, multipipe@0.1.1, lodash.template@2.4.1) liftoff@0.12.0 (extend@1.2.1, minimist@0.1.0, resolve@0.7.4, findup-sync@0.1.3) vinyl-fs@0.3.5 (graceful-fs@3.0.2, lodash@2.4.1, mkdirp@0.5.0, strip-bom@0.3.1, vinyl@0.2.3, through2@0.5.1, glob-watcher@0.0.6, glob-stream@3.1.14) </code> But when I type <code>gulp</code> it says <code>-bash: gulp: command not found</code> Any idea what's going on? | If you're using `tcsh` (which is my default shell on Mac OS X), you probably just need to type `rehash` into the shell just after the install completes: `npm install -g gulp` followed immediately by: `rehash`. Otherwise, if this is your very first time installing `gulp`, your shell may not recognize that there's a new executable installed -- so you either need to start a new shell, or type `rehash` in the current shell. (This is basically a one-time thing for each globally installed command.) |
|
Mocking EF DbContext with Moq <sep> I'm trying to create a unit test for my service with a mocked DbContext. I created an interface <code>IDbContext</code> with the following functions: <code>public interface IDbContext : IDisposable { IDbSet<T> Set<T>() where T : class; DbEntityEntry<T> Entry<T>(T entity) where T : class; int SaveChanges(); } </code> My real context implements this interface <code>IDbContext</code> and <code>DbContext</code>. Now I'm trying to mock the <code>IDbSet<T></code> in the context, so it returns a <code>List<User></code> instead. <code>[TestMethod] public void TestGetAllUsers() { // Arrange var mock = new Mock<IDbContext>(); mock.Setup(x => x.Set<User>()) .Returns(new List<User> { new User { ID = 1 } }); UserService userService = new UserService(mock.Object); // Act var allUsers = userService.GetAllUsers(); // Assert Assert.AreEqual(1, allUsers.Count()); } </code> I always get this error on <code>.Returns</code>: <code>The best overloaded method match for 'Moq.Language.IReturns<AuthAPI.Repositories.IDbContext,System.Data.Entity.IDbSet<AuthAPI.Models.Entities.User>>.Returns(System.Func<System.Data.Entity.IDbSet<AuthAPI.Models.Entities.User>>)' has some invalid arguments </code> | In case anyone is still interested, I was having the same problem and found this article very helpful: Entity Framework Testing with a Mocking Framework (EF6 onwards). It only applies to Entity Framework 6 or newer, but it covers everything from simple SaveChanges tests to async query testing, all using Moq (and a few manual classes). |
|
Golang : Is conversion between different struct types possible? <sep> Let's say I have two similar types set this way : <code>type type1 []struct { Field1 string Field2 int } type type2 []struct { Field1 string Field2 int } </code> Is there a direct way to write values from a type1 to a type2, knowing that they have the same fields ? (other than writing a loop that will copy all the fields from the source to the target) Thanks. | To give a reference to OneOfOne's answer, see the Conversions section of the spec. It states that:
> A non-constant value `x` can be converted to type `T` in any of these cases:
> `x` is assignable to `T`.
> `x`'s type and `T` have identical underlying types.
> `x`'s type and `T` are unnamed pointer types and their pointer base types have identical underlying types.
> `x`'s type and `T` are both integer or floating-point types.
> `x`'s type and `T` are both complex types.
> `x` is an integer or a slice of bytes or runes and `T` is a string type.
> `x` is a string and `T` is a slice of bytes or runes.
The first and highlighted case is your case. Both types have the underlying type `[]struct { Field1 string; Field2 int }`. An underlying type is defined as:
> If `T` is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is `T` itself. Otherwise, `T`'s underlying type is the underlying type of the type to which `T` refers in its type declaration. (spec, Types)
You are using a type literal to define your type, so this type literal is your underlying type. |
|
Cordova 3.5.0 Install Error- Please Install Android Target 19 <sep> I try to get this working and it's driving me nuts: <code>$ cordova platform add android </code> The output is: <code>Creating android project... /Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:126 throw e; ^ Error: Please install Android target 19 (the Android newest SDK). Make sure you have the latest Android tools installed as well. Run "android" from your command-line to install/update any missing SDKs or tools. at /Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/lib/check_reqs.js:80:29 at _fulfilled (/Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:798:54) at self.promiseDispatch.done (/Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:827:30) at Promise.promise.promiseDispatch (/Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:760:13) at /Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:574:44 at flush (/Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/node_modules/q/q.js:108:17) at process._tickCallback (node.js:419:13) Error: /Users/doekewartena/.cordova/lib/android/cordova/3.5.0/bin/create: Command failed with exit code 8 at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:135:23) at ChildProcess.emit (events.js:98:17) at maybeClose (child_process.js:755:16) at Process.ChildProcess._handle.onexit (child_process.js:822:5) </code> If did run the command <code>android</code> this are all the things I installed: I also did: <code>open ~/.bash_profile</code> And added: <code>export PATH=${PATH}:/Users/doekewartena/Documents/adt-bundle-mac-x86_64-20140702/sdk/platform-tools:/Users/doekewartena/Documents/adt-bundle-mac-x86_64-20140702/sdk/tools</code> But it doesn't help :( Could someone help. | Went into the SDK Manager (typing `android` into the terminal, assuming it's in your file path). Selected the box next to Android 4.4.2 (API 19) and clicked the "Install 8 packages" button. Ran the original command (in this example, `cordova platform add android`, although it could be `ionic platform add android`, depending on what you're working with). |
|
Changing the development language in Xcode <sep> I need to set Spanish as development language for an iOS app. I'm already using Xcode 6, and I changed the <code>Localization native development region</code> entry in app's <code>Info.plist</code> (<code>CFBundleDevelopmentRegion</code>) from "en" to "es". However, in Project > Info > Localizations, English remains set as Development Language. As said in Information Property List Key Reference, <code>CFBundleDevelopmentRegion</code> specifies the default language. I need to set Spanish to the default language, what am I missing? Thanks | Here's how you can do this: Add the language you want to be your base language first. Uncheck all of the files that Xcode offers to localize for you. In the `Info.plist`, change the development region to the language that you want to be your base language. Note that the property is a bit misnamed, because its value should be a language code (with an optional country code), rather than a region or country code. Close your project in Xcode. In another code editor, open `projectname.xcodeproj/project.pbxproj` and search for `developmentRegion`. You should see a line like `developmentRegion = English;`. Change this to reference the same language you put in your `Info.plist` file. Reopen the project in Xcode. Go through all your localizable files and check the boxes next to English to generate the localizable resources. Note that for storyboards and xibs, Xcode might create a storyboard instead of a strings file. If that happens, just change the file type to strings file. Here's an example of the result for me using `fr` as the base language: |
|
Importing correctly with pytest <sep> I just got set up to use pytest with Python 2.6. It has worked well so far with the exception of handling "import" statements: I can't seem to get pytest to respond to imports in the same way that my program does. My directory structure is as follows: <code>src/ main.py util.py test/ test_util.py geom/ vector.py region.py test/ test_vector.py test_region.py </code> To run, I call <code>python main.py</code> from src/. In main.py, I import both vector and region with <code>from geom.region import Region from geom.vector import Vector </code> In vector.py, I import region with <code>from geom.region import Region </code> These all work fine when I run the code in a standard run. However, when I call "py.test" from src/, it consistently exits with import errors. Some Problems and My Solution Attempts My first problem was that, when running "test/test_foo.py", py.test could not "import foo.py" directly. I solved this by using the "imp" tool. In "test_util.py": <code>import imp util = imp.load_source("util", "util.py") </code> This works great for many files. It also seems to imply that when pytest is running "path/test/test_foo.py" to test "path/foo.py", it is based in the directory "path". However, this fails for "test_vector.py". Pytest can find and import the <code>vector</code> module, but it cannot locate any of <code>vector</code>'s imports. The following imports (from "vector.py") both fail when using pytest: <code>from geom.region import * from region import * </code> These both give errors of the form <code>ImportError: No module named [geom.region / region] </code> I don't know what to do next to solve this problem; my understanding of imports in Python is limited. What is the proper way to handle imports when using pytest? Edit: Extremely Hacky Solution In <code>vector.py</code>, I changed the import statement from <code>from geom.region import Region </code> to simply <code>from region import Region </code> This makes the import relative to the directory of "vector.py". Next, in "test/test_vector.py", I add the directory of "vector.py" to the path as follows: <code>import sys, os sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/..")) </code> This enables Python to find "../region.py" from "geom/test/test_vector.py". This works, but it seems extremely problematic because I am adding a ton of new directories to the path. What I'm looking for is either 1) An import strategy that is compatible with pytest, or 2) An option in pytest that makes it compatible with my import strategy So I am leaving this question open for answers of these kinds. | The issue here is that Pytest walks the filesystem to discover files that contain tests, but then needs to generate a module name that will cause `import` to load that file. (Remember, files are not modules.) Pytest comes up with this test package name by finding the first directory at or above the level of the file that does not include an `__init__.py` file and declaring that the "basedir" for the module tree containing a module generated from this file. It then adds the basedir to `sys.path` and imports using the module name that will find that file relative to the basedir.
There are some implications of this that you should beware of:
* The basepath may not match your intended basepath, in which case the module will have a name that doesn't match what you would normally use.
* For example, what you think of as `geom.test.test_vector` will actually be named just `test_vector` during the Pytest run because it found no `__init__.py` in `src/geom/test/` and so added that directory to `sys.path`.
* You may run into module naming collisions if two files in different directories have the same name.
* For example, lacking `__init__.py` files anywhere, adding `geom/test/test_util.py` will conflict with `test/test_util.py` because both are loaded as `import test_util.py`, with both `test/` and `geom/test/` in the path.
The system you're using here, without explicit `__init__.py` modules, is having Python create implicit namespace packages for your directories. (A package is a module with submodules.) Ideally, we'd configure Pytest with a path from which it would also generate this, but it doesn't seem to know how to do that.
The easiest solution here is simply to add empty `__init__.py` files to all of the subdirectories under `src/`; this will cause Pytest to import everything using package/module names that start with directory names under `src/`. The question "How do I Pytest a project using PEP 420 namespace packages?" discusses other solutions to this. |
|
Android: Internet connectivity change listener <sep> I already have this code which listens to connectivity change - <code>public class NetworkStateReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Log.d("app","Network connectivity change"); if(intent.getExtras() != null) { NetworkInfo ni = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO); if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) { Log.i("app", "Network " + ni.getTypeName() + " connected"); } } if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) { Log.d("app", "There's no network connectivity"); } } } </code> And I check Internet connectivity using this code - Internet Check But the problem is that if network suddenly loses internet connection without any connectivity change, this code is useless. Is there any way to create Broadcast Receiver listener for Internet connectivity change? I have a web app and sudden Internet connectivity changes can cause problems. | ConnectivityAction is deprecated in API 28+. Instead, you can use `registerDefaultNetworkCallback` as long as you support API 24+. In Kotlin:
```kotlin
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let { it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
//take action when network connection is gained
}
override fun onLost(network: Network?) {
//take action when network connection is lost
}
}) }
``` |
|
Multiple cursors / highlight next instance of currently highlighted word <sep> In Sublime Text, it's easy to select the next instance of a word by pressing command + d and also place multiple cursors by pressing command & clicking. I know I'm not alone in saying this is an incredibly useful function in editors. I haven't had any luck in finding any key mappings or Alcatraz plugins for this, so I was interested to see if either there is a way to do this in xcode 5 which I might have missed or if there are plans to implement this in xcode 6? If there isn't, and any xcode developers see this, would love to see this as a feature and hear your opinions on it :) | It is possible starting from Xcode 10 Beta 3:
> You can add selections for the next and previous find results using the Find and Select Next and Find and Select Previous menu commands. Additionally, you can quickly add selections for the next and previous occurrences of the current selected text using the Select Next Occurrence and Select Previous Occurrence menu commands.
E to select next occurrence of currently selected text, E to select previous occurrence of currently selected text, G to find and select next G, G to find and select previous. You can also use the `Find` menu to find these actions. Of course, feel free to bind them to different hotkeys! |
|
Counting number of documents using Elasticsearch <sep> If one wants to count the number of documents in an index (of Elasticsearch) then there are (at least?) two possibilities: Direct <code>count</code> POST my_index/_count should return the number of documents in <code>my_index</code>. Using <code>search</code> Here one can use the <code>count</code> as the <code>search_type</code> or some other type. In either of the cases the total count can be extracted from the field <code>['hits']['total']</code> My questions are: what is the difference between the different approaches? Which one should I prefer? I raise this question because I'm experiencing different results depending on the chosen method. I'm now in the process of debugging the issue, and this question popped up. | If `_search` must be used instead of `_count`, and you're on Elasticsearch 7.0+, setting `size: 0` and `track_total_hits: true` will provide the same info as `_count`.
```json
GET my-index/_search
{
"query": {
"term": {
"field": {
"value": "xyz"
}
}
},
"size": 0,
"track_total_hits": true
}
```
```json
{
"took" : 612,
"timed_out" : false,
"_shards" : {
"total" : 629,
"successful" : 629,
"skipped" : 524,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 29349466,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
}
}
```
See Elasticsearch 7.0 Breaking Changes |
|
De-activate a maven profile from command line <sep> I have a profile activated by default in my maven setting file ~/.m2/settings.xml. Is it possible to deactivate it from the command line by doing something like this: <code>mvn -P!profileActivatedByDefault </code> | On a Mac, I got the following error attempting to use '!' :
`mvn groupId:artifactId:goal -P!profile-1 -bash: !profile: event not found`
Doing the following works with the '-':
`mvn groupId:artifactId:goal -P-profile1`
Alternatively you can do:
`mvn groupId:artifactId:goal -P\!profile1` |
|
Getting device orientation in Swift <sep> I was wondering how I can get the current device orientation in Swift? I know there are examples for Objective-C, however I haven't been able to get it working in Swift. I am trying to get the device orientation and put that into an if statement. This is the line that I am having the most issues with: <code>[[UIApplication sharedApplication] statusBarOrientation] </code> | ```swift
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
var text = ""
switch UIDevice.current.orientation {
case .portrait:
text = "Portrait"
case .portraitUpsideDown:
text = "PortraitUpsideDown"
case .landscapeLeft:
text = "LandscapeLeft"
case .landscapeRight:
text = "LandscapeRight"
default:
text = "Another"
}
NSLog("You have moved: \(text)")
}
// or
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
// ...
}
// with Notification
// NOTE: didRotateFromInterfaceOrientation is Deprecated. Use viewWillTransitionToSize for iOS 2.0 and later.
if UIApplication.shared.statusBarOrientation.isLandscape {
// activate landscape changes
} else {
// activate portrait changes
}
```
**Explanation of Changes:**
* **Swift 3 Update:** The code was updated to reflect Swift 3 syntax.
* **Function Name:** Changed `didRotateFromInterfaceOrientation` to `didRotate(from:)` as per Swift 3.
* **`UIDevice.currentDevice()`:** Replaced with `UIDevice.current`.
* **.`orientation`:** Added `.orientation` to access the device orientation.
* **Case Names:** Consistently used lowercase for case names (e.g., `.portrait` instead of `.Portrait`).
* **`NSTimeInterval`:** Changed to `TimeInterval` for Swift 3 compatibility.
* **`UIApplication.shared.statusBarOrientation`:** Used to check for landscape/portrait changes, as the `UIDevice.current.orientation` property doesn't always work reliably for Face Up/Face Down.
Let me know if you have any other code snippets you'd like me to review! |
|
How shouldChangeCharactersInRange works in Swift? <sep> I'm using shouldChangeCharactersInRange as a way of using on-the-fly type search. However I'm having a problem, shouldChangeCharactersInRange gets called before the text field actually updates: In Objective C, I solved this using using below: <code>-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string]; return YES; } </code> However, I've tried writing this in Swift: <code>func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { let txtAfterUpdate:NSString = self.projectSearchTxtFld.text as NSString txtAfterUpdate.stringByReplacingCharactersInRange(range, withString: string) self.callMyMethod(txtAfterUpdate) return true } </code> The method still gets called before I get a value? | ```swift
Swift 4, Swift 5
This method doesn't use `NSString`.
// MARK: - UITextFieldDelegate extension
MyViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text, let textRange = Range(range, in: text) {
let updatedText = text.replacingCharacters(in: textRange, with: string)
myValidator(text: updatedText)
}
return true
}
}
Note: Be careful when you use a secure text field.
``` |
|
How to read files and stdout from a running Docker container <sep> How would I go about starting an application in my host machine in order to read files and stdout from a running docker container? Essentially I want to do this: <code>docker start containerid ./myapp // This app will *somehow* have access files and stdout generated by the container I just stared. </code> How would I go about doing that? To be more specific with where I am trying to go with this; I want to read the logs and stdout of a docker container and have those logs processed somewhere else. I am also willing to create another docker container which can read files and stdout from another container, but I don't know if that's possible. | The stdout of the process started by the Docker container is available through the `docker logs $containerid` command (use `-f` to keep it going forever). Another option would be to stream the logs directly through the Docker remote API. For accessing log files (only if you must; consider logging to stdout or other standard solutions like syslogd), your only real-time option is to configure a volume (like Marcus Hughes suggests) so the logs are stored outside the container and available for processing from the host or another container. If you do not need real-time access to the logs, you can export the files (in tar format) with `docker export`. |
|
How do I run two separate instances of Spyder <sep> I want to be able to have two instances which are completely independent in the sense that I can be working on two separate unrelated projects in different folders without any interference. | (Spyder maintainer here) This is easy. You need to go to: **Tools > Preferences > Application** in Spyder 5, or **Tools > Preferences > General** in Spyder 4, click the "Advanced Settings" tab, and deactivate the option called **[ ] Use a single instance**. Then every time you start Spyder, a new window will be opened. If you want the old behavior back, just activate that option again. |
|
SyntaxError: non-default argument follows default argument <sep> <code>from os import system def a(len1,hgt=len1,til,col=0): system('mode con cols='+len1,'lines='+hgt) system('title',til) system('color',col) a(64,25,"hi","0b") input() </code> When I run this, it rejects "def a(..." and highlights "(" in red. I have no clue why. | Let me clarify two points here: Firstly, a non-default argument should not follow a default argument; you cannot define `(a='b', c)` in a function. The correct order of defining parameters in a function is:
1. Positional parameters or non-default parameters (e.g., `(a, b, c)`)
2. Keyword parameters or default parameters (e.g., `(a='b', r='j')`)
3. Keyword-only parameters (e.g., `(*args)`)
4. Var-keyword parameters (e.g., `(**kwargs)`)
```python
def example(a, b, c=None, r="w", d=[], *ae, **ab):
(a, b) are positional parameters
(c=None) is an optional parameter
(r="w") is a keyword parameter
(d=[]) is a list parameter
(*ae) is keyword-only
(*ab) is a var-keyword parameter
```
The second thing is that you have to define `len1` when you are doing `hgt = len1`. The `len1` argument is not defined when default values are saved. Python computes and saves default values when you define the function. `len1` does not exist when this happens (it exists only when the function is executed). So, remove `"len1 = hgt"`; it's not allowed in Python. Keep in mind the difference between arguments and parameters. |
|
Java 8: Formatting lambda with newlines and indentation <sep> What I would like to achieve with lambda indentation is the following: Multi-line statement: <code>String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des (M)", "Rick (M)" }; List<String> strings = Arrays.stream(ppl) .filter( (x) -> { return x.contains("(M)"); } ).collect(Collectors.toList()); strings.stream().forEach(System.out::println); </code> Single-line statement: <code>List<String> strings = Arrays.stream(ppl) .map((x) -> x.toUpperCase()) .filter((x) -> x.contains("(M)")) .collect(Collectors.toList()); </code> Currently, Eclipse is auto-formatting to the following: Multi-line statement: <code>String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des (M)", "Rick (M)" }; List<String> strings = Arrays.stream(ppl).filter((x) -> { return x.contains("(M)"); }).collect(Collectors.toList()); strings.stream().forEach(System.out::println); </code> Single-line statement: <code>String[] ppl = new String[] { "Karen (F)", "Kevin (M)", "Lee (M)", "Joan (F)", "Des(M)", "Rick (M)" }; List<String> strings = Arrays.stream(ppl).map((x) -> x.toUpperCase()) .filter((x) -> x.contains("(M)")).collect(Collectors.toList()); strings.stream().forEach(System.out::println); </code> And I find this really messy, because of how the <code>collect</code> call is directly underneath the <code>return</code> and there's no space inbetween at all. I would prefer it if I could start the lambda in a new line indented, and so that the <code>.filter(</code> call would be right above the <code>.collect(</code> call. However, the only thing that can be customized with standard Java-8 Eclipse Formatter is the brace at the start of the lambda body, but nothing for the <code>()</code> brackets beforehand, nor the indentation. And in the case of single-line calls, it just uses the basic line-wrap and makes it be a chained mess. I don't think I need to explain why this is hard to decrypt afterwards. Is there any way to somehow customize the formatting more and achieve the first formatting type in Eclipse? (Or, optionally, in another IDE like IntelliJ IDEA.) EDIT: The closest I could get was with IntelliJ IDEA 13 Community Edition (read: free edition :P) which was the following (defined by continuous indentation which in this case is 8): <code>public static void main(String[] args) { int[] x = new int[] {1, 2, 3, 4, 5, 6, 7}; int sum = Arrays.stream(x) .map((n) -> n * 5) .filter((n) -> { System.out.println("Filtering: " + n); return n % 3 != 0; }) .reduce(0, Integer::sum); List<Integer> list = Arrays.stream(x) .filter((n) -> n % 2 == 0) .map((n) -> n * 4) .boxed() .collect(Collectors.toList()); list.forEach(System.out::println); System.out.println(sum); </code> It also allows to "align" the chained method invocation like this: <code> int sum = Arrays.stream(x) .map((n) -> n * 5) .filter((n) -> { System.out.println("Filtering: " + n); return n % 3 != 0; }) .reduce(0, Integer::sum); List<Integer> list = Arrays.stream(x) .filter((n) -> n % 2 == 0) .map((n) -> n * 4) .boxed() .collect(Collectors.toList()); list.forEach(System.out::println); System.out.println(sum); } </code> I personally find that while it makes more sense, the second version pushes it far too away, so I prefer the first one. The setup responsible for the first setup is the following: <code><?xml version="1.0" encoding="UTF-8"?> <code_scheme name="Zhuinden"> <option name="JD_ALIGN_PARAM_COMMENTS" value="false" /> <option name="JD_ALIGN_EXCEPTION_COMMENTS" value="false" /> <option name="JD_ADD_BLANK_AFTER_PARM_COMMENTS" value="true" /> <option name="JD_ADD_BLANK_AFTER_RETURN" value="true" /> <option name="JD_P_AT_EMPTY_LINES" value="false" /> <option name="JD_PARAM_DESCRIPTION_ON_NEW_LINE" value="true" /> <option name="WRAP_COMMENTS" value="true" /> <codeStyleSettings language="JAVA"> <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" /> <option name="BRACE_STYLE" value="2" /> <option name="CLASS_BRACE_STYLE" value="2" /> <option name="METHOD_BRACE_STYLE" value="2" /> <option name="ELSE_ON_NEW_LINE" value="true" /> <option name="WHILE_ON_NEW_LINE" value="true" /> <option name="CATCH_ON_NEW_LINE" value="true" /> <option name="FINALLY_ON_NEW_LINE" value="true" /> <option name="ALIGN_MULTILINE_PARAMETERS" value="false" /> <option name="SPACE_WITHIN_BRACES" value="true" /> <option name="SPACE_BEFORE_IF_PARENTHESES" value="false" /> <option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false" /> <option name="SPACE_BEFORE_FOR_PARENTHESES" value="false" /> <option name="SPACE_BEFORE_TRY_PARENTHESES" value="false" /> <option name="SPACE_BEFORE_CATCH_PARENTHESES" value="false" /> <option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false" /> <option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false" /> <option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" /> <option name="METHOD_PARAMETERS_WRAP" value="1" /> <option name="EXTENDS_LIST_WRAP" value="1" /> <option name="THROWS_LIST_WRAP" value="1" /> <option name="EXTENDS_KEYWORD_WRAP" value="1" /> <option name="THROWS_KEYWORD_WRAP" value="1" /> <option name="METHOD_CALL_CHAIN_WRAP" value="2" /> <option name="BINARY_OPERATION_WRAP" value="1" /> <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" /> <option name="ASSIGNMENT_WRAP" value="1" /> <option name="IF_BRACE_FORCE" value="3" /> <option name="DOWHILE_BRACE_FORCE" value="3" /> <option name="WHILE_BRACE_FORCE" value="3" /> <option name="FOR_BRACE_FORCE" value="3" /> <option name="PARAMETER_ANNOTATION_WRAP" value="1" /> <option name="VARIABLE_ANNOTATION_WRAP" value="1" /> <option name="ENUM_CONSTANTS_WRAP" value="2" /> </codeStyleSettings> </code_scheme> </code> I tried to make sure everything is reasonable, but I might have messed something up, so it might need minor adjustments. If you're Hungarian like me and you're using a Hungarian layout, then this keymap might be of use to you, so that you don't end up not being able to use AltGR+F, AltGR+G, AltGR+B, AltGR+N and AltGR+M (which correspond to Ctrl+Alt). <code><?xml version="1.0" encoding="UTF-8"?> <keymap version="1" name="Default copy" parent="$default"> <action id="ExtractMethod"> <keyboard-shortcut first-keystroke="shift control M" /> </action> <action id="GotoImplementation"> <mouse-shortcut keystroke="control alt button1" /> </action> <action id="GotoLine"> <keyboard-shortcut first-keystroke="shift control G" /> </action> <action id="Inline"> <keyboard-shortcut first-keystroke="shift control O" /> </action> <action id="IntroduceField"> <keyboard-shortcut first-keystroke="shift control D" /> </action> <action id="Mvc.RunTarget"> <keyboard-shortcut first-keystroke="shift control P" /> </action> <action id="StructuralSearchPlugin.StructuralReplaceAction" /> <action id="Synchronize"> <keyboard-shortcut first-keystroke="shift control Y" /> </action> </keymap> </code> While IntelliJ doesn't seem to provide a way to put the opening brace of the lambda in a new line, otherwise it's a fairly reasonable way of formatting, so I'll mark this as accepted. | In Eclipse, for single-line statements: In your project or global preferences, go to `Java -> Code Style -> Formatter -> Edit -> Line Wrapping -> Function Calls -> Qualified Invocations`, set `Wrap all elements, except first if not necessary` and tick `Force split, even if line shorter than maximum line width`. |
|
Flexbox column align self to bottom <sep> Im trying to use Flexbox. http://css-tricks.com/almanac/properties/a/align-content/ this shows nice alignment options; but i would actually want a Top-top-bottom situation. I want a div to stick to the bottom of the parent div using flexbox. With <code>flex-direction: column</code> and <code>align-content: Space-between</code> i can do this, but the middle div will align in the center, i want the middle one to be sticked to the top as well. [top] [middle] - - - [bottom] <code>align-self: flex-end</code> will make it float right, not bottom. complete flexbox docs: http://css-tricks.com/snippets/css/a-guide-to-flexbox/ | I'm a bit late to the party, but this might be relevant for others trying to accomplish the same. You should be able to do it by setting `margin-top: auto` on the element in question, and it should go to the bottom. This should work in Firefox, Chrome, and Safari. |
|
Read a file/URL line-by-line in Swift <sep> I am trying to read a file given in an <code>NSURL</code> and load it into an array, with items separated by a newline character <code>\n</code>. Here is the way I've done it so far: <code>var possList: NSString? = NSString.stringWithContentsOfURL(filePath.URL) as? NSString if var list = possList { list = list.componentsSeparatedByString("\n") as NSString[] return list } else { //return empty list } </code> I'm not very happy with this for a couple of reasons. One, I'm working with files that range from a few kilobytes to hundreds of MB in size. As you can imagine, working with strings this large is slow and unwieldy. Secondly, this freezes up the UI when it's executing--again, not good. I've looked into running this code in a separate thread, but I've been having trouble with that, and besides, it still doesn't solve the problem of dealing with huge strings. What I'd like to do is something along the lines of the following pseudocode: <code>var aStreamReader = new StreamReader(from_file_or_url) while aStreamReader.hasNextLine == true { currentline = aStreamReader.nextLine() list.addItem(currentline) } </code> How would I accomplish this in Swift? A few notes about the files I'm reading from: All files consist of short (<255 chars) strings separated by either <code>\n</code> or <code>\r\n</code>. The length of the files range from ~100 lines to over 50 million lines. They may contain European characters, and/or characters with accents. | ```swift
import Foundation
/// Read text file line by line in an efficient way
public class LineReader {
public let path: String
private let file: UnsafeMutablePointer<FILE>!
init?(path: String) {
self.path = path
file = fopen(path, "r")
guard file != nil else { return nil }
}
public var nextLine: String? {
var line: UnsafeMutablePointer<CChar>? = nil
var linecap: Int = 0
defer { free(line) }
return getline(&line, &linecap, file) > 0 ? String(cString: line!) : nil
}
deinit {
fclose(file)
}
}
extension LineReader: Sequence {
public func makeIterator() -> AnyIterator<String> {
return AnyIterator<String> { return self.nextLine }
}
}
// Usage:
guard let reader = LineReader(path: "/Path/to/file.txt") else { return; // cannot open file }
for line in reader {
print("> " + line.trimmingCharacters(in: .whitespacesAndNewlines))
}
```
Repository on github |
|
Django 1.7 - "No migrations to apply" when run migrate after makemigrations <sep> I use Django1.7 with Mezzanine. I create simple profile (according to Mezzanine documentation) stored in separate app "profiles": <code>class RoadmapProfile(models.Model): user = models.OneToOneField("auth.User") fullname = models.CharField(max_length=100, verbose_name="Full name") </code> Creation of migrations returns: <code> Migrations for 'profiles': 0001_initial.py: - Create model RoadmapProfile </code> When I run "migrate profiles": <code>Operations to perform: Apply all migrations: profiles Running migrations: No migrations to apply. </code> The issue is, when I try to open any page related to mezzanine.accounts (for example update account), it crashes with: <code>OperationalError at /accounts/update/ no such column: profiles_roadmapprofile.fullname </code> What I have done wrong? | In a MySQL database, delete the row `'profiles'` from the table `'django_migrations'`. Delete all migration files in the `migrations` folder. Then, try again with the commands `python manage.py makemigrations` and `python manage.py migrate`. |
|
How to check if a radiobutton is checked in a radiogroup in Android? <sep> I need to set validation that user must fill / select all details in a page. If any fields are empty wanna show <code>Toast message to fill.</code> Now I need set validation for <code>RadioButton</code> in the <code>RadioGroup.</code> I tried this code but didn't work properly. Suggest me correct way. Thankyou. <code>// get selected radio button from radioGroup int selectedId = gender.getCheckedRadioButtonId(); // find the radiobutton by returned id selectedRadioButton = (RadioButton)findViewById(selectedId); // do what you want with radioButtonText (save it to database in your case) radioButtonText = selectedRadioButton.getText().toString(); if(radioButtonText.matches("")) { Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show(); Log.d("QAOD", "Gender is Null"); } else { Log.d("QAOD", "Gender is Selected"); } </code> | If you want to check on just one `RadioButton`, you can use the `isChecked` function: `if (radioButton.isChecked()) { // is checked } else { // not checked }`. And if you have a `RadioGroup`, you can use: `if (radioGroup.getCheckedRadioButtonId() == -1) { // no radio buttons are checked } else { // one of the radio buttons is checked }`. |
|
Xamarin.Forms ListView: Set the highlight color of a tapped item <sep> Using Xamarin.Forms, how can I define the highlight/background color of a selected/tapped ListView item? (My list has a black background and white text color, so the default highlight color on iOS is too bright. In contrast, on Android there is no highlighting at all - up to a subtle horizontal gray line.) Example: (left: iOS, right: Android; while pressing "Barn2") | To change the color of a selected `ViewCell`, there is a simple process without using a custom renderer. Make the `Tapped` event of your `ViewCell` as below:
`<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Tapped="ViewCell_Tapped">
<Label Text="{Binding StudentName}" TextColor="Black" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>`
In your ContentPage or .cs file, implement the event:
```csharp
private void ViewCell_Tapped(object sender, System.EventArgs e)
{
if (lastCell != null)
{
lastCell.View.BackgroundColor = Color.Transparent;
}
var viewCell = (ViewCell)sender;
if (viewCell.View != null)
{
viewCell.View.BackgroundColor = Color.Red;
lastCell = viewCell;
}
}
```
Declare `lastCell` at the top of your `ContentPage` like this:
```csharp
ViewCell lastCell;
``` |
|
How do you add items to .dockerignore? <sep> I'm not able to find many examples of what a .dockerignore file should look like. Using puppet to install a few packages on a docker container causes the image to explode from 600MB to 3GB. I'm trying to use a <code>.dockerignore</code> file to keep the size to a minumum <code>$ cat Dockerfile FROM centos:centos6 #Work around selinux problem on cent images RUN yum install -y --enablerepo=centosplus libselinux-devel RUN yum install -y wget git tar openssh-server; yum -y clean all Add Puppetfile / RUN librarian-puppet install RUN puppet apply --modulepath=/modules -e "class { 'buildslave': jenkins_slave => true,}" RUN librarian-puppet clean </code> If I run <code>docker images --tree</code> I can see that the image instantlly grows by several GB <code>$ docker images --tree e289570b5555 Virtual Size: 387.7 MB a7646acf90d0 Virtual Size: 442.5 MB d7bc6e1fbe43 Virtual Size: 442.5 MB 772e6b204e3b Virtual Size: 627.5 MB 599a7b5226f4 Virtual Size: 627.5 MB 9fbffccda8bd Virtual Size: 2.943 GB ee46af013f6b Virtual Size: 2.943 GB 3e4fe065fd07 Virtual Size: 2.943 GB de9ec3eba39e Virtual Size: 2.943 GB 31cba2716a12 Virtual Size: 2.943 GB 52cbc742d3c4 Virtual Size: 2.943 GB 9a857380258c Virtual Size: 2.943 GB c6d87a343807 Virtual Size: 2.964 GB f664124e0080 Virtual Size: 2.964 GB e6cc212038b9 Virtual Size: 2.964 GB Tags: foo/jenkins-centos6-buildslave:latest </code> I believe the reason that the image grows so large, is because <code>librarian-puppet</code> clones a puppet module to <code>/modules</code> which breaks the build cache I've tried the following <code>.dockerignore</code> files with no luck. <code>$ cat .dockerignore /modules /modules/ /modules/* </code> Is this the correct syntax for a <code>.dockerignore</code> file? Are there any other ways to prevent these containers from growing so large? Additional information: http://kartar.net/2013/12/building-puppet-apps-inside-docker/ http://danielmartins.ninja/posts/a-week-of-docker.html | The `.dockerignore` file is similar to the `.gitignore` syntax. Here are some example rules:
```
# Ignore a file or directory in the context root named "modules"
modules
# Ignore any files or directories within the subdirectory named "modules"
# in the context root
modules/*
# Ignore any files or directories in the context root beginning with "modules"
modules*
# Ignore any files or directories one level down from the context root named
# "modules"
*/modules
# Ignore any files or directories at any level, including the context root,
# named modules
**/modules
# Ignore every file in the entire build context (see next rule for how this
# could be used)
*
# Re-include the file or directory named "src" that may have been previously
# excluded. Note that you cannot re-include files in subdirectories that have
# been previously excluded at a higher level
!src
```
Note that "build context" is the directory you pass at the end of your build command, typically a `.` to indicate the current directory. This directory is packaged from the Docker client, excluding any files you have ignored with `.dockerignore`, and sent to the Docker daemon to perform the build. Even when the daemon is on the same host as your client, the build only works from this context and not directly from the folders.
There is only a single `.dockerignore` for a build, and it must be in the root of the build context. It will not work if it is in your home directory (assuming you build from a subdirectory), and it will not work from a subdirectory of your build context.
To test what is in your current build context and verify your `.dockerignore` file is behaving correctly, you can copy/paste the following (this assumes you do not have an image named `test-context`, it will be overwritten and then deleted if you do):
```
# create an image that includes the entire build context
docker build -t test-context -f - . <<EOF
FROM busybox
COPY . /context
WORKDIR /context
CMD find .
EOF
# run the image which executes the find command
docker container run --rm test-context
# cleanup the built image
docker image rm test-context
``` |
|
How to set textColor of UILabel in Swift <sep> When I try setting the color of a UILabel to the color of another UILabel using the code <code>myLabel.textColor = otherLabel.textColor </code> It doesn't change the color. When I use this code, however, <code>myLabel.textColor = UIColor.redColor() </code> It changes the color correctly. What's the issue with the first line? | The easiest workaround is to create dummy labels in IB, give them the text and color you like, and set them to hidden. You can then reference this color in your code to set your label to the desired color.
```yourLabel.textColor = hiddenLabel.textColor
```
The only way I could change the text color programmatically was by using the standard colors, `UIColor.white`, `UIColor.green`... |
|
Enable LogCat on Release Build in Android Studio <sep> By default, when I change <code>Build Variants</code> to <code>release</code> I don't get any Logs on the logcat, but I do need to read release logs of my app, how can I enable this? | You should add `android { buildTypes { release { debuggable true }}`
In this case, you can use `Log.` or `System.out.println` and see logs. If you cannot run the release version (the `app` is disabled), and an error is shown: "apk is not signed. Please configure the signing information for the selected flavor using the Project Structure dialog", see app-release-unsigned.apk is not signed. |
|
Paramiko : Error reading SSH protocol banner <sep> Recently, I made a code that connect to work station with different usernames (thanks to a private key) based on paramiko. I never had any issues with it, but today, I have that : <code>SSHException: Error reading SSH protocol banner</code> This is strange because it happens randomly on any connections. Is there any way to fix it ? | Adding to TinBane's answers, suggesting to edit `transport.py` is no longer necessary. Since Paramiko v. 1.15.0, released in 2015 (this PR, to be precise), you can configure that value when creating a Paramiko connection, like this: `client = SSHClient() client.connect('ssh.example.com', banner_timeout=200)`.
In the current version of Paramiko (as of writing these words), v. 2.7.1, you have 2 more timeouts you can configure when calling the `connect` method, for a total of 3 (source):
* `banner_timeout`: an optional timeout (in seconds) to wait for the SSH banner to be presented.
* `timeout`: an optional timeout (in seconds) for the TCP connect.
* `auth_timeout`: an optional timeout (in seconds) to wait for an authentication response. |
|
React component not re-rendering on state change <sep> I have a React Class that's going to an API to get content. I've confirmed the data is coming back, but it's not re-rendering: <code>var DealsList = React.createClass({ getInitialState: function() { return { deals: [] }; }, componentDidMount: function() { this.loadDealsFromServer(); }, loadDealsFromServer: function() { var newDeals = []; chrome.runtime.sendMessage({ action: "findDeals", personId: this.props.person.id }, function(deals) { newDeals = deals; }); this.setState({ deals: newDeals }); }, render: function() { var dealNodes = this.state.deals.map(function(deal, index) { return ( <Deal deal={deal} key={index} /> ); }); return ( <div className="deals"> <table> <thead> <tr> <td>Name</td> <td>Amount</td> <td>Stage</td> <td>Probability</td> <td>Status</td> <td>Exp. Close</td> </tr> </thead> <tbody> {dealNodes} </tbody> </table> </div> ); } }); </code> However, if I add a <code>debugger</code> like below, <code>newDeals</code> are populated, and then once I continue, i see the data: <code> loadDealsFromServer: function() { var newDeals = []; chrome.runtime.sendMessage({ action: "findDeals", personId: this.props.person.id }, function(deals) { newDeals = deals; }); debugger this.setState({ deals: newDeals }); }, </code> This is what's calling deals list: <code>var Gmail = React.createClass({ render: function() { return ( <div className="main"> <div className="panel"> <DealsList person={this.props.person} /> </div> </div> ); } }); </code> | My scenario was a little different. And I think that many newbies like me would be stumped—so sharing here. My state variable is an array of JSON objects being managed with `useState` as below:
```javascript
const [toCompare, setToCompare] = useState([]);
```
However, when I update `toCompare` with `setToCompare` as in the below function—the re-render won't fire. And moving it to a different component didn't work either. Only when some other event would fire did the re-render—and the updated list—show up.
```javascript
const addUniversityToCompare = async (chiptoadd) => {
var currentToCompare = toCompare;
currentToCompare.push(chiptoadd);
setToCompare(currentToCompare);
};
```
This was the solution for me. Basically, assigning the array was copying the reference—and React wouldn't see that as a change—since the ref to the array isn't being changed—only the content within it.
So, in the below code—I just copied the array using `slice`—without any change—and assigned it back after mods. Works perfectly fine.
```javascript
const addUniversityToCompare = async (chiptoadd) => {
var currentToCompare = toCompare.slice();
currentToCompare.push(chiptoadd);
setToCompare(currentToCompare);
};
```
Hope it helps someone like me. Anybody, please let me know if you feel I am wrong—or there is some other approach. Thanks in advance. |
|
Get the height of an element minus padding, margin, border widths <sep> Does anyone know if it's possible to get just the height of an element (minus vertical padding, border, and margin) when there is no inline height declaration? I need to support IE8 and above. <code>el.style.height</code> doesn't work because the styles are set in an external style sheet. <code>el.offsetHeight</code> or <code>el.clientHeight</code> doesn't work because they include more than just the element's height. And I can't just subtract the element's padding, etc. because those values are also set in a CSS stylesheet, and not inline (and so <code>el.style.paddingTop</code> doesn't work). Also can't do <code>window.getComputedStyle(el)</code> because IE8 doesn't support this. jQuery has the height() method, which offers this, but I'm not using jQuery in this project, plus I just want to know how to do this in pure JavaScript. Anyone have any thoughts? Much appreciated. | Here's the solution that works for both cases of `box-sizing`: `content-box` and `border-box`.
```javascript
var computedStyle = getComputedStyle(element);
elementHeight = element.clientHeight; // height with padding
elementWidth = element.clientWidth; // width with padding
elementHeight -= parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
elementWidth -= parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.paddingRight);
```
Works in IE9+. You can use feature detection:
```javascript
if (!getComputedStyle) {
alert('Not supported');
}
```
This will not work if the element's `display` is `inline`. Use `inline-block` or use `getBoundingClientRect`. |
|
Qt Designer vs Qt Quick Designer vs Qt Creator? <sep> I have seen references to all three of these applications on various parts of the Qt website but am completely unclear as to the exact differences between them and whether they are actually separate things or just different names for the same thing, or the name changed over time? Or is one no longer supported? What's the deal with these? | I will explain the difference between these tools based on their usage:
**Qt Designer:** A sub-tool used to create/edit widget files (.ui). You can use it to create graphical layouts (.ui files only). Its primary use is designing the graphical elements in PyQt applications. It is installed when you install Qt, for example, at the path: Qt5.13.1\5.13.1\mingw73_64\bin\designer.exe. It can also be used to edit any .ui file of a Qt C++ application, although it is very limited since it only allows editing of the graphical elements (not C++ logic).
**Qt Quick Designer (it refers to Qt Creator):** It does not exist as a separate tool; it is integrated into Qt Creator (see below). While it is common to say that Qt Quick Designer allows editing of QML files (.qml), it is now integrated into Qt Creator.
**Qt Creator:** This is the de facto and most powerful IDE for creating Qt applications natively (C++ with the Qt engine). It allows you to create, edit source code, debug applications, etc. In addition, you can open a .ui or .qml file in Qt Creator, and it will open and allow you to edit it. For example, if you open a .ui file, it will show you the Qt Designer application embedded within the full integrated Qt Creator IDE.
In summary, you can use Qt Creator to open/edit any .ui or .qml file and create Qt/C++ applications. Of course, if the file is .ui, Qt Creator will display the Qt Designer tool; if it is .qml, it will allow you to edit the QML. |
|
How can I include css files using node, express, and ejs? <sep> I'm trying to follow the instructions to https://stackoverflow.com/a/18633827/2063561, but I still can't get my styles.css to load. From app.js <code>app.use(express.static(path.join(__dirname, 'public'))); </code> In my .ejs, I have tried both of these lines <code><link rel="stylesheet" type="text/css" href="/css/style.css" /> <link rel="stylesheet" type="text/css" href="/public/css/style.css" /> </code> Neither loads the css. I've gone into the developer's console noticed the type is set to 'text/html' instead of 'text/css'. My path looks like <code>. ./app.js ./public /css /style.css </code> | 1. Create a new folder named 'public' if none exists.
2. Create a new folder named 'css' under the newly created 'public' folder.
3. Create your CSS file under the `public/css` path.
4. On your HTML, link the CSS:
```html
<link rel="stylesheet" type="text/css" href="/css/style.css">
```
// Note: the href uses a slash (/) before the filename and you do not need to include 'public'.
5. On your `app.js`, include:
```javascript
app.use(express.static('public'));
```
Boom! It works! |
|
What is the difference between nginx daemon on/off option? <sep> This is my first web-server administration experience and I want to build docker container which uses nginx as a web-server. In all docker tutorial <code>daemon off;</code> option is put into main <code>.conf</code> file but explanation about it is omitted. I search on the internet about it and I don't understand what is the difference between <code>daemon on;</code> and <code>daemon off;</code> options. Some people mentioned that <code>daemon off;</code> is for production, why? Can you explain, what is the difference between this two options, and why I should use <code>daemon off;</code> on production? | For normal production (on a server), use the default `daemon on;` directive so the Nginx server will start in the background. In this way, Nginx and other services are running and talking to each other. One server runs many services. For Docker containers (or for debugging), the `daemon off;` directive tells Nginx to stay in the foreground. For containers, this is useful as best practice is one container = one process. One server (container) has only one service. Setting `daemon off;` is also useful if there's a third-party tool like Supervisor controlling your services. Supervisor lets you stop/start/get status for bunches of services at once. I use `daemon off;` for tweaking my Nginx config, then cleanly killing the service and restarting it. This lets me test configurations rapidly. When done, I use the default `daemon on;`. |
|
Generate int unique id as android notification id <sep> When I send multiple push notifications, I need them to be all shown in the notification bar ordered by the time sent desc. I know I should use unique notification - I tried to generate random number but that did not solve my problem since I need them to be ordered. I tried to use <code>AtomicInt</code> and still don't have the desired result. <code>package com.mypackage.lebadagency; import java.util.concurrent.atomic.AtomicInteger; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.SystemClock; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.RemoteViews; import com.google.android.gms.gcm.GoogleCloudMessaging; public class GCMNotificationIntentService extends IntentService { private AtomicInteger c = new AtomicInteger(0); public int NOTIFICATION_ID = c.incrementAndGet(); private NotificationManager mNotificationManager; NotificationCompat.Builder builder; public GCMNotificationIntentService() { super("GcmIntentService"); } public static final String TAG = "GCMNotificationIntentService"; @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR .equals(messageType)) { sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED .equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE .equals(messageType)) { for (int i = 0; i < 3; i++) { Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime()); try { Thread.sleep(5000); } catch (InterruptedException e) { } } Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); sendNotification("" + extras.get(Config.MESSAGE_KEY)); Log.i(TAG, "Received: " + extras.toString()); } } GcmBroadcastReceiver.completeWakefulIntent(intent); } private void sendNotification(String msg) { Log.d(TAG, "Preparing to send notification...: " + msg); mNotificationManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE); //here start Intent gcmintent = new Intent(this, AppGcmStation.class); gcmintent.putExtra("ntitle", msg); gcmintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); int requestID = (int) System.currentTimeMillis(); //here end PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, gcmintent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( this).setSmallIcon(R.drawable.ic_launcher) .setContentTitle("my title") .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) .setContentText(msg); mBuilder.setAutoCancel(true); mBuilder.setTicker(msg); mBuilder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }); mBuilder.setLights(Color.RED, 3000, 3000); mBuilder.setContentIntent(contentIntent); mBuilder.setDefaults(Notification.DEFAULT_SOUND); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); Log.d(TAG, "Notification sent successfully."); } } </code> I need the BEST and simplest way to generate an int id which is incremental to assign it as the notification id. | Maybe not the best, but definitely the simplest is to use the current time.
```java
int oneTimeID = (int) SystemClock.uptimeMillis();
mNotificationManager.notify(oneTimeID, mBuilder.build());
```
The good: this is the easiest way to get increasing IDs. The bad: time is a `long` and we're truncating it to half of that. This means that the counter will wrap around every 2,147,483,647 / 1000 (ms->s) / 60 (s->m) / 60 (m->h) / 24 (h->d) =~ 25 days.
`SystemClock.uptimeMillis()` has two advantages over `currentTimeMillis()`:
* It discounts all the milliseconds spent at deep sleep, which decreases the amount of wraparounds.
* It starts at 0 when the phone is restarted. |
|
iPhone / iOS : Presenting HTML 5 Keyboard for Postal Codes <sep> There are several tricks for displaying different keyboards on mobile devices for HTML 5 inputs (i.e. <code><input></code> tags). For example, some are documented on Apple's website, Configuring the Keyboard for Web Views. These are great for usability, but when it comes to an input for for international postal codes (mostly numeric, but letters allowed), we're left with some poor options. Most people recommend using the <code>pattern="\d*"</code> trick to show the numeric keyboard, but that doesn't allow for letter input. The <code>type="number"</code> input type shows the regular keyboard but shifted to the numeric layout: This works well for iOS devices, but it makes Chrome think the input must be a number and even changes the input's behavior (up/down increment and decrement the value). Is there any way to get iOS to default to the numeric layout, but still allow for alphanumeric input? Basically, I want the iOS behavior for <code>type="number"</code> but I want the field to behave like a regular text field on desktop browsers. Is this possible? UPDATE: Sniffing the user-agent for iOS and using the <code>type="number"</code> input type is not an option. <code>type="number"</code> is not meant for string values (like postal codes), and it has other side effects (like stripping leading zeros, comma delimiters, etc) that make it less than ideal for postal codes. | Will this work? HTML: `<input type="tel" pattern="[0-9]*" novalidate> `
This should give you the nice numeric keyboard on Android/iOS phone browsers, disable browser form validation on desktop browsers, not show any arrow spinners, allow leading zeros, and allow commas and letters on desktop browsers, as well as on iPad.
Android/iOS phones:
Desktop:
iPad: |
|
App "does not contain the correct beta entitlement" <sep> I submitted an application for review and I notice that the build that I submitted has an issue associated with it saying that <code>Build 168 does not contain the correct beta entitlement.</code> I wasn't able to find information on this error anywhere. What does it mean and will it inhibit the review process? My app was submitted today with Xcode 5.1.1 for iOS 7 (not the Xcode GM). Perhaps this relates to Testflight? | Please regenerate your provisioning profile. It will fix this problem because the missing entitlement is now there: `beta-reports-active = 1`. After creating the new provisioning profile, make sure the entitlement is there. Here's how it should look when you click in Organizer "Export..." -> "Save for iOS App Store Deployment": |
|
Resetting MySQL Root Password with XAMPP on Localhost <sep> So for the past hour I've been trying to figure out how to reset my 'root' password for MySQL as I cannot log into PHPMyAdmin. I've tried changing the password in the config.inc.php file and searching through other methods. I cannot find a successful way. A few months ago I changed it as a test password but now I forget what it was. If anyone can help, that would be great. (I'm running on a Windows computer). | Steps:
1. Open your phpMyAdmin dashboard, go to User Accounts in the User section.
2. Get the root user and click "Edit privileges." In the top section, you will find the "Change password" button. Click on it.
3. Make a good password and fill in the two password fields. Now hit the "Go" button.
4. Now open your XAMPP dir (c:/xampp).
5. Go to the phpMyAdmin dir [C:\xampp\phpMyAdmin] and open the `config.inc.php` file with any text editor.
6. Find the line `$cfg['Servers'][$i]['auth_type'] = 'config';` and replace `'config'` with `'cookie'`.
7. Go to the line `$cfg['Servers'][$i]['AllowNoPassword'] = true;` and change `true` to `false`.
8. Last: save the file.
Here is a video link in case you want to see it in action: [Click Here] |
|
Converting Object to Array using ES6 features <sep> Given a javascript object, how can I convert it to an array in ECMAScript-6 ? For example, given: <code> var inputObj = {a:'foo', b:[1,2,3], c:null, z:55}; </code> The expected output would be: <code> ['foo', [1,2,3], null, 55] </code> The order of the elements in the result is not important to me. | Use (ES5) `Array.map` over the `keys` with an arrow function (for short syntax only, not functionality): `let arr = Object.keys(obj).map((k) => obj[k])`. True ES6 style would be to write a generator, and convert that iterable into an array: `function* values(obj) { for (let prop of Object.keys(obj)) { // own properties, you might use // for (let prop in obj) yield obj[prop]; } } let arr = Array.from(values(obj));`. Regrettably, no object iterator has made it into the ES6 natives. |
|
Why are complex numbers in Python denoted with 'j' instead of 'i'? <sep> I know this is an electrical engineering convention, but I'm still wondering why it was chosen for Python. I don't know other programming languages with complex-number literals, so I don't have anything to compare against, but does anyone know any that do use i? | It appears to be, as you guessed, because Python follows the electrical engineering convention. Here's an exchange from the Python bug tracker Issue 10562:
>Botjan Mejak: In Python, the letter 'j' denotes the imaginary unit. It would be great if we would follow mathematics in this regard and let the imaginary unit be denoted with an 'i'.
>Michael Foord: We follow engineering which uses j. (I was about to close this as wontfix but Antoine is particularly keen that Mark deals with this issue...)
>Mark Dickinson: Just to add my own thoughts: 'j' for a (not the) square root of -1 has, as Michael points out, a history of use in engineering (particularly electrical engineering) and physics. Personally, I would have preferred 'i' to 'j' here, but changing it now would cause (IMO) gratuitous breakage. It really doesn't seem a big enough issue to be worth making a fuss about.
... Much later:
>Guido van Rossum: This will not be fixed. For one thing, the letter 'i' or uppercase 'I' look too much like digits. The way numbers are parsed—either by the language parser (in source code) or by the built-in functions (int, float, complex)—should not be localizable or configurable in any way; that's asking for huge disappointments down the road. If you want to parse complex numbers using 'i' instead of 'j', you have plenty of solutions available already. |
|
Pandas: Return Hour from Datetime Column Directly <sep> Assume I have a DataFrame <code>sales</code> of timestamp values: <code>timestamp sales_office 2014-01-01 09:01:00 Cincinnati 2014-01-01 09:11:00 San Francisco 2014-01-01 15:22:00 Chicago 2014-01-01 19:01:00 Chicago </code> I would like to create a new column <code>time_hour</code>. I can create it by writing a short function as so and using <code>apply()</code> to apply it iteratively: <code>def hr_func(ts): return ts.hour sales['time_hour'] = sales['timestamp'].apply(hr_func) </code> I would then see this result: <code>timestamp sales_office time_hour 2014-01-01 09:01:00 Cincinnati 9 2014-01-01 09:11:00 San Francisco 9 2014-01-01 15:22:00 Chicago 15 2014-01-01 19:01:00 Chicago 19 </code> What I'd like to achieve is some shorter transformation like this (which I know is erroneous but gets at the spirit): <code>sales['time_hour'] = sales['timestamp'].hour </code> Obviously the column is of type <code>Series</code> and as such doesn't have those attributes, but it seems there's a simpler way to make use of matrix operations. Is there a more-direct approach? | Assuming `timestamp` is the index of the DataFrame, you can just do the following:
```python
hours = sales.index.hour
```
If you want to add that to your sales DataFrame, just do:
```python
import pandas as pd
pd.concat([sales, pd.DataFrame(hours, index=sales.index)], axis=1)
```
Edit: If you have several columns of datetime objects, it's the same process. If you have a column `'date'` in your DataFrame, and assuming that `'date'` has datetime values, you can access the hour from the `'date'` as:
```python
hours = sales['date'].hour
```
Edit2: If you want to adjust a column in your DataFrame, you have to include `dt`:
```python
sales['datehour'] = sales['date'].dt.hour
``` |
|
How can I create an utility class? <sep> I want to create a class with utility methods, for example <code>public class Util { public static void f (int i) {...} public static int g (int i, int j) {...} } </code> Which is the best method to create an utility class? Should I use a private constructor? Should I make the utility class for abstract class? Should I do nothing? | For a completely stateless utility class in Java, I suggest the class be declared `public` and `final`, and have a private constructor to prevent instantiation. The `final` keyword prevents subclassing and can improve efficiency at runtime. The class should contain all `static` methods and should not be declared `abstract` (as that would imply the class is not concrete and has to be implemented in some way). The class should be given a name that corresponds to its set of provided utilities (or "Util" if the class is to provide a wide range of uncategorized utilities). The class should not contain a nested class unless the nested class is to be a utility class as well (though this practice is potentially complex and hurts readability). Methods in the class should have appropriate names. Methods only used by the class itself should be private. The class should not have any non-final/non-static class fields. The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project, however).
Example:
```java
public final class ExampleUtilities {
// Example Utility method
public static int foo(int i, int j) {
int val; //Do stuff
return val;
}
// Example Utility method overloaded
public static float foo(float i, float j) {
float val; //Do stuff
return val;
}
// Example Utility method calling private method
public static long bar(int p) {
return hid(p) * hid(p);
}
// Example private method
private static long hid(int i) {
return i * 2 + 1;
}
}
```
Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often, so it's good to have high-quality documentation to complement the code. |
|
Node.js MSSQL tedius ConnectionError: Failed to connect to localhost:1433 - connect ECONNREFUSED <sep> I am trying to connect to MSSQL 2012 using NodeJS with the mssql connection interface. When attempting to connect I get the following error: <code>{ [ConnectionError: Failed to connect to localhost:1433 - connect ECONNREFUSED] name: 'ConnectionError', message: 'Failed to conncet to localhost:1433 - connect ECONNREFUSED', code: 'ESOCKET' } </code> Any ideas on how to fix this? | If, after enabling the TCP connection, your configuration is still not working, here's my own configuration:
```javascript
var config = {
"user": 'admin',
"password": 'password',
"server": 'WINDOWS-PC',
"database": 'database_name',
"port": 61427, // make sure to change port
"dialect": "mssql",
"dialectOptions": {
"instanceName": "SQLEXPRESS"
}
};
``` |
|
How do I update MongoDB document fields only if they don't exist? <sep> I have collection <code>foo</code> with documents like: <code>{site_id: 'xxx', title: {ru: 'a', en: 'b'}, content: {ru: 'a', en: 'b'}} {site_id: 'xxx', title: {ru: 'c', de: 'd'}, content: {ru: 'c', de: 'd'}} </code> I need to update multiple fields which are can exists or not: <code>db.foo.update( { site_id: 'xxx'}, { $set: {'title.de': '', 'content.de': ''}}, {multi: true} ) </code> But I need something like <code>$set</code> which will not overwrite value if it exists. | Starting MongoDB 4.2, `db.collection.update()` can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field. This way, we can move field checks within the update stage rather than within the match stage, thus making it a one-pass update:
```javascript
// { site_id: "xxx", title: { ru: "a", en: "b" }, content: {} }
// { site_id: "xxx", title: { ru: "c", de: "d" }, content: { ru: "c" } }
db.collection.updateMany(
{ site_id: "xxx" },
[
{ $set: {
"title.de": { $cond: [ { $not: ["$title.de"] }, "", "$title.de" ] },
"content.ru": { $cond: [ { $not: ["$content.ru"] }, "", "$content.ru" ] }
}}
]
)
// { site_id: "xxx", title: { ru: "a", en: "b", de: "" }, content: { ru: "" } }
// { site_id: "xxx", title: { ru: "c", de: "d" }, content: { ru: "c" } }
```
The first part `{ site_id: "xxx" }` is the match query, filtering which documents to update. The second part `[{ $set: { ... } }]` is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). `$set` is a new aggregation operator and an alias of `$addFields`. The rest of this stage checks with `$cond` if the `title.de` exists, and if yes, then keep it as it is, or otherwise create it as an `''`. |
|
Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot <sep> I'm trying to import a flat file into an oledb target sql server database. here's the field that's giving me trouble: here are the properties of that flat file connection, specifically the field: here's the error message: <blockquote> [Source - 18942979103_txt [424]] Error: Data conversion failed. The data conversion for column "recipient-name" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page.". </blockquote> What am I doing wrong? | Here is what fixed the problem for me. I did not have to convert to Excel. Just modify the DataType when choosing the data source to "text stream" (Figure 1). You can also check the "Edit Mappings" dialog to verify the change to the size (Figure 2).
Figure 1
Figure 2 |
|
What does numpy.gradient do? <sep> So I know what the gradient of a (mathematical) function is, so I feel like I should know what <code>numpy.gradient</code> does. But I don't. The documentation is not really helpful either: <blockquote> Return the gradient of an N-dimensional array. </blockquote> What is the gradient of an array? When is <code>numpy.gradient</code> useful? | Here's what's going on. The Taylor series expansion guides us on how to approximate the derivative, given the value at nearby points. The simplest comes from the first-order Taylor series expansion for a C² function (two continuous derivatives)... f(x+h) = f(x) + f'(x)h + f''(xi)h²/2. One can solve for f'(x)... f'(x) = [f(x+h) - f(x)]/h + O(h). Can we do better? Yes, indeed. If we assume C³, then the Taylor expansion is f(x+h) = f(x) + f'(x)h + f''(x)h²/2 + f'''(xi)h³/6, and f(x-h) = f(x) - f'(x)h + f''(x)h²/2 - f'''(xi)h³/6. Subtracting these (both the h⁰ and h² terms drop out!) and solving for f'(x): f'(x) = [f(x+h) - f(x-h)]/(2h) + O(h²). So, if we have a discretized function defined on equally spaced partitions: x = x₀, x₀+h (=x₁),...., xₙ = x₀+h*n, then NumPy's `gradient` will yield a "derivative" array using the first-order estimate on the ends and the better estimates in the middle.
**Example 1.** If you don't specify any spacing, the interval is assumed to be 1. So, if you call `f = np.array([5, 7, 4, 8])`, what you're saying is that f(0) = 5, f(1) = 7, f(2) = 4, and f(3) = 8. Then `np.gradient(f)` will be: f'(0) = (7 - 5)/1 = 2, f'(1) = (4 - 5)/(2*1) = -0.5, f'(2) = (8 - 7)/(2*1) = 0.5, f'(3) = (8 - 4)/1 = 4.
**Example 2.** If you specify a single spacing, the spacing is uniform but not 1. For example, if you call `np.gradient(f, 0.5)`, this is saying that h = 0.5, not 1, i.e., the function is really f(0) = 5, f(0.5) = 7, f(1.0) = 4, f(1.5) = 8. The net effect is to replace h = 1 with h = 0.5, and all the results will be doubled.
**Example 3.** Suppose the discretized function f(x) is not defined on uniformly spaced intervals, for instance f(0) = 5, f(1) = 7, f(3) = 4, f(3.5) = 8, then there is a messier discretized differentiation function that the NumPy `gradient` function uses, and you will get the discretized derivatives by calling `np.gradient(f, np.array([0,1,3,3.5]))`.
Lastly, if your input is a 2D array, then you are thinking of a function f of x, y defined on a grid. The NumPy `gradient` will output the arrays of "discretized" partial derivatives in x and y. |
|
Populating a Boolean Array in Java <sep> As a fairly green Java coder I've set myself the hefty challenge of trying to write a simple text adventure. Unsurprisingly, I've encountered difficulties already! I'm trying to give my Location class a property to store which exits it contains. I've used a boolean array for this, to essentially hold true/false values representing each exit. I'm not entirely convinced that a) this is the most efficient way to do this and b) that I'm using the right code to populate the array. I would appreciate any and all feedback, even if it is for a complete code over-haul! At present, when instantiating a Location I generate a String which I send through to the setExits method: <code> String e = "N S U"; secretRoom.setExits(e); </code> In the Location class, setExits looks like this: <code>public void setExits(String e) { if (e.contains("N")) bexits[0] = true; else if (e.contains("W")) bexits[1] = true; else if (e.contains("S")) bexits[2] = true; else if (e.contains("E")) bexits[3] = true; else if (e.contains("U")) bexits[4] = true; else if (e.contains("D")) bexits[5] = true; } </code> I'll be honest, I think this looks particularly clunky, but I couldn't think of another way to do it. I'm also not entirely sure now how to write the getExits method... Any help would be welcome! | The most efficient and expressive way is the following: Use `enum`s as Exits and use an `EnumSet` to store them. `EnumSet` is an efficient `Set` implementation that uses a bit field to represent the enum constants. Here is how you can do it:
```java
public enum Exit { North, West, South, East, Up, Down }
EnumSet<Exit> set = EnumSet.noneOf(Exit.class); // An empty set.
// Now you can simply add or remove exits, everything will be stored compactly
set.add(Exit.North); // Add exit
set.contains(Exit.West); // Test if an exit is present
set.remove(Exit.South); //Remove an exit
```
Enum set will store all exits in a single `long` internally, so your code is expressive, fast, and saves a lot of memory. |
|
How to hash NSString with SHA1 in Swift? <sep> In objective-c it looks like this: <code>#include <sys/xattr.h> @implementation NSString (reverse) -(NSString*)sha1 { NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding]; uint8_t digest[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(data.bytes, (int)data.length, digest); NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]]; return output; } @end </code> I need something like this with Swift, is it possible? Please, show work example. | ```swift
With `CryptoKit` added in iOS 13, we now have a native Swift API: `import Foundation
import CryptoKit`
// CryptoKit.Digest utils extension
extension Digest {
var bytes: [UInt8] {
Array(makeIterator())
}
var data: Data {
Data(bytes)
}
var hexStr: String {
bytes.map { String(format: "%02X", $0) }.joined()
}
}
func example() {
guard let data = "hello world".data(using: .utf8) else {
return
}
let digest = Insecure.SHA1.hash(data: data)
print(digest.data) // 20 bytes
print(digest.hexStr) // 2AAE6C35C94FCFB415DBE95F408B9CE91EE846ED
}
``` |
|
iOS 8 - Screen blank after dismissing view controller with custom presentation <sep> When dismissing various view controllers using <code>UIModalPresentationCustom</code>, the screen turns black after the view controller is dismissed, as if all the view controllers had been removed from the view hierarchy. The transitioning delegate is set properly, the animationControllerForPresentedController is asked for and passed correctly, and the transition is completed once the animation is over. This exact code works perfectly when compiled with the iOS 7 SDK, but is broken when compiled with iOS 8b5 | This is because you are most likely adding both the presenting `[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey]` and the presented `[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey]` view controllers to your containerView in the (void)animateTransition:(id)transitionContext method of your animation controller. Since you are using a custom modal presentation, the presenting view controller is still shown beneath the presented view controller. Now since it's still visible, you don't need to add it to the container view. Instead, only add the presented view controller to the containerView.
Should look something like this inside of your animateTransition: method:
```
UIView *containerView = [transitionContext containerView];
UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
// Boolean value to determine presentation or dismissal animation
if (self.presenting) {
[transitionContext.containerView addSubview:toViewController.view];
// Your presenting animation code
} else {
// Your dismissal animation code
}
``` |
|
How can I cast an NSMutableArray to a Swift array of a specific type? <sep> I am migrating my iOS project to Swift. I am doing this class by class. When I call Objective C methods from Swift, a lot of Objective C types are converted to their Swift counterparts. In my case an Objective C <code>NSMutableArray</code> gets converted to Swift's <code>Array<AnyObject></code>. Now here comes my problem. Within my Swift class, I get such an array back from an Objective C object. Now that I am in the Swift world, I would like to cast this array to a specific type instead of <code>AnyObject</code>, because I know for sure what kind of objects exist in this array. The compiler won't let me do that! Let me simplify my problem by saying I want to cast to an array containing strings. This is what I tried: <code>var strings = myObjcObject.getStrings() as [String] </code> I get the following error from the compiler: <blockquote> 'String' is not identical to 'AnyObject' </blockquote> I would have to agree with the compiler, since String is indeed not identical to AnyObject. But I don't see why that is a problem. I can downcast AnyObject to String if I want, right? I also tried: <code>var strings = myObjcObject.getStrings() as? [String] </code> This seems to be a step in the right direction, but getStrings() returns an <code>NSMutableArray</code> so I get the following error: <blockquote> 'NSArray' is not a subtype of 'NSMutableArray' </blockquote> Is there any way to do what I am trying to do here? | `compactMap` is your friend in Swift 4.1 and above, as well as in Swift 3.3-3.4 for that matter. This means that you don't have any double or forced casting.
`let mutableArray = NSMutableArray(array: ["a", "b", "c"])`
`let swiftArray: [String] = mutableArray.compactMap { $0 as? String }`
In previous versions of Swift, 2.0-3.2 and 4.0, you'll want to use `flatMap` for this purpose. The usage is the same as `compactMap`:
`let swiftArray: [String] = mutableArray.flatMap { $0 as? String }` |
|
Swift - Must call a designated initializer of the superclass SKSpriteNode error <sep> This code worked on first XCode 6 Beta, but on latest Beta it's not working and gives such errors <code>Must call a designated initializer of the superclass SKSpriteNode</code>: <code>import SpriteKit class Creature: SKSpriteNode { var isAlive:Bool = false { didSet { self.hidden = !isAlive } } var livingNeighbours:Int = 0 init() { // throws: must call a designated initializer of the superclass SKSpriteNode super.init(imageNamed:"bubble") self.hidden = true } init(texture: SKTexture!) { // throws: must call a designated initializer of the superclass SKSpriteNode super.init(texture: texture) } init(texture: SKTexture!, color: UIColor!, size: CGSize) { super.init(texture: texture, color: color, size: size) } } </code> and that's how this class is initialiazed: <code>let creature = Creature() creature.anchorPoint = CGPoint(x: 0, y: 0) creature.position = CGPoint(x: Int(posX), y: Int(posY)) self.addChild(creature) </code> I'm stuck with it.. what will be the easiest fix? | ```swift
class Creature: SKSpriteNode {
var isAlive: Bool = false {
didSet {
self.hidden = !isAlive
}
}
var livingNeighbours: Int = 0
init() {
let texture = SKTexture(imageNamed: "bubble")
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
self.hidden = true
}
init(texture: SKTexture!) {
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
}
init(texture: SKTexture!, color: UIColor!, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
}
```
Furthermore, I would consolidate all of these into a single initializer. |
|
iOS: Delete ALL Core Data Swift <sep> I am a little confused as to how to delete all core data in swift. I have created a button with an <code>IBAction</code> linked. On the click of the button I have the following: <code>let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate let context: NSManagedObjectContext = appDel.managedObjectContext </code> Then I've messed around with various methods to try and delete all the core data content but I can't seem to get it to work. I've used removeAll to delete from a stored array but still can't delete from the core data. I assume I need some type of for loop but unsure how to go about making it from the request. I have tried applying the basic principle of deleting a single row <code>func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate let context:NSManagedObjectContext = appDel.managedObjectContext if editingStyle == UITableViewCellEditingStyle.Delete { if let tv = tblTasks { context.deleteObject(myList[indexPath!.row] as NSManagedObject) myList.removeAtIndex(indexPath!.row) tv.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade) } var error: NSError? = nil if !context.save(&error) { abort() } } } </code> However, the issue with this is that when I click a button, I don't have the indexPath value and also I need to loop through all the values which I can't seem to do with context. | ```swift
public func clearDatabase() {
guard let url = persistentContainer.persistentStoreDescriptions.first?.url else { return }
let persistentStoreCoordinator = persistentContainer.persistentStoreCoordinator
do {
try persistentStoreCoordinator.destroyPersistentStore(at: url, ofType: NSSQLiteStoreType, options: nil)
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
print("Attempted to clear persistent store: \(error.localizedDescription)")
}
}
``` |
|
Edit package.json from command line <sep> I'm trying to add or edit a variable in my package.json from a shell script. So if i have a package.json like this: <code>{ "name": "my-project", "description": "Project by @DerZyklop", "version": "0.0.0", ... </code> I want acommand like <code>npm config set foo bar </code> that adds a new field like <code>{ "name": "my-project", "description": "Project by @DerZyklop", "foo": "bar", "version": "0.0.0", ... </code> ...but unfortunately <code>npm config set</code> just edits the <code>~/.npmrc</code> and not my package.json. | You do have a native NPM command: `npm pkg set 'scripts.test'='jest'`. Which is really helpful when you want to share a command. Instead of asking someone to install some CLI tool, you can simply share this. BTW, it's even more helpful when you use NPM workspaces, in which case you can change all the packages together: `npm pkg set 'scripts.test'='jest' -ws`. |
|
Swift pass data through navigation controller <sep> One of my segues transitions from a view controller to a tableview controller. I want to pass an array between the two, but with a navigation controller before the tableview controller, I can't figure out how to pass the array. How do you pass data through a navigatiom controller to a tableview controller? | ```swift
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "yourSegueIdentifier" {
if let navController = segue.destination as? UINavigationController {
if let childVC = navController.topViewController as? YourViewController {
// TODO: access here chid VC like childVC.yourTableViewArray = localArrayValue
}
}
}
}
``` |
|
How to set name of AAR output from Gradle <sep> I have a project with several modules in it one of which is a Android Library named (poorly) as <code>sdk</code>. When I build the project it outputs an AAR named <code>sdk.aar</code>. I haven't been able to find anything in the Android or Gradle documentation that allows me to change the name of the AAR output. I would like it to have a basename + version number like the Jar tasks do, but I can't work out how to do the same for the AAR because all the config for it seems to be hidden in the android.library plugin. Renaming the module isn't an option at this stage and that still wouldn't add the version number to the final AAR. How can I change the name of the AAR generated by <code>com.android.library</code> in Gradle? Gradle solution <code>defaultConfig { minSdkVersion 9 targetSdkVersion 19 versionCode 4 versionName '1.3' testFunctionalTest true project.archivesBaseName = "Project name" project.version = android.defaultConfig.versionName } </code> | For Android Studio 3 with Gradle 4 and Android Plugin for Gradle 3.0.0, you have to change the configuration of `qix` to the following:
```
android {
libraryVariants.all { variant ->
variant.outputs.all { output ->
if (outputFile != null && outputFileName.endsWith('.aar')) {
outputFileName = "${archivesBaseName}-${version}.aar"
}
}
}
}
``` |
|
Static functions outside classes <sep> Could someone tell me what's the purpose of declaring static functions outside classes? What's the difference between this 2? Are there any benefits for using static in this situation? <code>static void someRandomFunction(); int main() { someRandomFunction(); return 0; } </code> and <code>void someRandomFunction(); int main() { someRandomFunction(); return 0; } </code> | At namespace scope, `static` gives a name internal linkage, meaning that it is only accessible within the translation unit that contains the definition. Without `static`, it has external linkage, and is accessible in any translation unit. So you'd use `static` (or, alternatively, an unnamed namespace) when writing a function that's only intended for use within this unit; the internal linkage means that other units can define different functions with the same name without causing naming conflicts. Non-static functions (and global names in general) are better declared in a header to make sure that every translation unit that uses them gets the same declaration. |
|
Disable iOS8 Quicktype Keyboard programmatically on UITextView <sep> I'm trying to update an app for iOS8, which has a chat interface, but the new Quicktype keyboard hides the text view, so I would like to turn it off programmatically or in interface builder. Is it possible somehow or only the users can turn it off in the device settings? I know there is a question/answer which solves this problem with a <code>UITextfield</code>, but I need to do it with a <code>UITextView</code>. | You may disable the keyboard suggestions/autocomplete/QuickType for a `UITextView`, which can block the text on smaller screens like the 4S, as shown in this example with the following line: `myTextView.autocorrectionType = UITextAutocorrectionTypeNo;`.
And further, if you'd like to do this only on a specific screen, such as targeting the 4S, use:
```objectivec
if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
if (screenHeight == 568) {
// iPhone 5 screen
} else if (screenHeight < 568) {
// smaller than iPhone 5 screen (thus 4S)
}
}
``` |
|
Adding underline to UILabel attributed string from the storyboard fails <sep> From the storyboard I select the UILabel in question Then in Attribute Inspector > Label > [I choose] Attributed Also in Attribute Inspector > Label > Text> [I select the content] Then I click on the font icon and choose underline Basically, any change that I select from the Fonts window that pops up does not take effect. Has anyone ever successfully add underline from the storyboard? Note: I already know how to do this in code. I want to avoid adding code. | Select label -> Attribute editor -> Title = Attributed. Select the text of the label in the text view of the editor -> Right click -> Font -> check Underline. If the change is not visible, resize the label. |
|
How to crash R? <sep> Is there a simple way to trigger a crash in R? This is for testing purposes only, to see how a certain program that uses R in the background reacts to a crash and help determine if some rare problems are due to crashes or not. | There is an entire package on GitHub dedicated to this: <blockquote>crash R package that purposely crashes an R session. WARNING: intended for testing. </blockquote> How to install a package from GitHub is covered in other questions. |
|
package android.support.v4.app does not exist ; in Android studio 0.8 <sep> I've recently updated the android studio IDE to 0.8 to work with the new android L SDK. To start I imported a finished android project that receives no errors in the older version of android studio. In version 0.8 i lines such as <code>import android.support.v4.app.Fragment; </code> get: Support cannot be resolved causing the rest of the code to have errors. The logcat returns 101 instances of <code>Error:(8, 30) error: package android.support.v4.app does not exist </code> 1 for each time I call the support library in an import statement. I've tried reinstalling the IDE deleting contents of idea folder re installing all the SDK's - including the support libraries syncing the gradle copying the support library into the libs folder manually rebuilding the project as well as creating a new project to test the library not entirely sure what's left to do. | None of the above solutions worked for me. What finally worked was: Instead of `import android.support.v4.content.FileProvider;` use this `import androidx.core.content.FileProvider;`. This path is updated as of AndroidX (the repackaged Android Support Library). |
|
How do we embed images in sphinx docs? <sep> I am quite new in using sphinx, Doing documentation for the first time for the python project. How to embed image for example in the sphinx documentation ? | From the documentation:
There are two image directives: `image` and `figure`. An `image` is a simple picture. A `figure` consists of image data (including image options), an optional caption (a single paragraph), and an optional legend (arbitrary body elements). For page-based output media, figures might float to a different position if this helps the page layout.
Example for `image` usage:
`.. image:: picture.jpg :width: 200px :height: 100px :scale: 50% :alt: alternate text :align: right `
Example for `figure` usage:
`.. figure:: picture.png :scale: 50% :alt: map to buried treasure
This is the caption of the figure (a simple paragraph).` |
|
Plotting CDF of a pandas series in python <sep> Is there a way to do this? I cannot seem an easy way to interface pandas series with plotting a CDF. | In case you are also interested in the values, not just the plot.
```python
import pandas as pd
# If you are in jupyter %matplotlib inline
```
This will always work (discrete and continuous distributions)
```python
# Define your series
s = pd.Series([9, 5, 3, 5, 5, 4, 6, 5, 5, 8, 7], name='value')
df = pd.DataFrame(s)
```
```python
# Get the frequency, PDF and CDF for each value in the series
# Frequency
stats_df = df \
.groupby('value') \
['value'] \
.agg('count') \
.pipe(pd.DataFrame) \
.rename(columns={'value': 'frequency'})
# PDF
stats_df['pdf'] = stats_df['frequency'] / sum(stats_df['frequency'])
# CDF
stats_df['cdf'] = stats_df['pdf'].cumsum()
stats_df = stats_df.reset_index()
stats_df
```
```python
# Plot the discrete Probability Mass Function and CDF.
# Technically, the 'pdf label in the legend and the table the should be 'pmf'
# (Probability Mass Function) since the distribution is discrete.
# If you don't have too many values / usually discrete case
stats_df.plot.bar(x='value', y=['pdf', 'cdf'], grid=True)
```
Alternative example with a sample drawn from a continuous distribution or you have a lot of individual values:
```python
# Define your series
s = pd.Series(np.random.normal(loc=10, scale=0.1, size=1000), name='value')
```
```python
# ... all the same calculation stuff to get the frequency, PDF, CDF
# Plot
stats_df.plot(x='value', y=['pdf', 'cdf'], grid=True)
```
For continuous distributions only
Please note if it is very reasonable to make the assumption that there is only one occurrence of each value in the sample (typically encountered in the case of continuous distributions) then the `groupby()` + `agg('count')` is not necessary (since the count is always 1). In this case, a percent rank can be used to get to the CDF directly. Use your best judgment when taking this kind of shortcut! :)
```python
# Define your series
s = pd.Series(np.random.normal(loc=10, scale=0.1, size=1000), name='value')
df = pd.DataFrame(s)
```
```python
# Get to the CDF directly
df['cdf'] = df.rank(method='average', pct=True)
# Sort and plot
df.sort_values('value').plot(x='value', y='cdf', grid=True)
``` |
|
Android Studio logcat history/buffer size <sep> Does anyone know if there a way to increase the size of the logcat history/buffer in Android Studio? I remember there was a way to do it in Eclipse and was hoping Android Studio had a similar setting. | You can also do this per project, via the IDE: Settings -> Editor -> General -> Console: tick "Override console cycle buffer size". Enter your desired size in the text box. Finally, restart Android Studio for the changes to take effect. |
|
Python Argparse conditionally required arguments <sep> I have done as much research as possible but I haven't found the best way to make certain cmdline arguments necessary only under certain conditions, in this case only if other arguments have been given. Here's what I want to do at a very basic level: <code>p = argparse.ArgumentParser(description='...') p.add_argument('--argument', required=False) p.add_argument('-a', required=False) # only required if --argument is given p.add_argument('-b', required=False) # only required if --argument is given </code> From what I have seen, other people seem to just add their own check at the end: <code>if args.argument and (args.a is None or args.b is None): # raise argparse error here </code> Is there a way to do this natively within the argparse package? | I've been searching for a simple answer to this kind of question for some time. All you need to do is check if `'--argument'` is in `sys.argv`. So, for your code sample, you could just do:
```python
import argparse
import sys
if __name__ == '__main__':
p = argparse.ArgumentParser(description='...')
p.add_argument('--argument', required=False)
p.add_argument('-a', required='--argument' in sys.argv) # only required if --argument is given
p.add_argument('-b', required='--argument' in sys.argv) # only required if --argument is given
args = p.parse_args()
```
This way, `required` receives either `True` or `False` depending on whether the user has used `--argument`. I've already tested it; it seems to work and guarantees that `-a` and `-b` have an independent behavior between each other. |
|
How do I make an UIImage/-View with rounded corners CGRect (Swift) <sep> How do I make a UIImageView with rounded corners on a Swift iOS Playground? Inside it needs to be filled with a color. | ```swift
For a rounded circle image frame in Swift, what worked for me was:
`self.profileImageView.image = UIImage(named: "profileUser")`
`self.profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2`
`self.profileImageView.clipsToBounds = true`
And for adding a shadow:
`self.profileImageView.layer.masksToBounds = false`
`self.profileImageView.layer.cornerRadius = 8`
`self.profileImageView.shadowOffset = CGSizeMake(5.0, 5.0)`
`self.profileImageView.shadowRadius = 5`
`self.profileImageView.shadowOpacity = 0.5`
``` |
|
Getting wider output in PyCharm's built-in console <sep> I'm relatively new to using the PyCharm IDE, and have been unable to find a way to better shape the output when in a built-in console session. I'm typically working with pretty wide dataframes, that would fit easily across my monitor, but the display is cutting and wrapping them much sooner than needed. Does anyone know of a setting to change this behavior to take advantage of the full width of my screen? Edit: I don't have enough reputation to post a screenshot, but link is below: http://imgur.com/iiBK3iU I would like to prevent it from wrapping after only a few columns (for example, the column 'ReadmitRate' should be immediately to the right of 'SNFDaysPerSNFCase') | For me, just setting `'display.width'` wasn't enough in PyCharm; it kept displaying in truncated form. However, adding the option `pd.set_option("display.max_columns", 10)` together with `display.width` worked, and I was able to see the whole DataFrame printed in the "run" output. In summary:
```python
import pandas as pd
pd.set_option('display.width', 400)
pd.set_option('display.max_columns', 10)
``` |
|
pytz - Converting UTC and timezone to local time <sep> I have a <code>datetime</code> in utc time zone, for example: <code>utc_time = datetime.datetime.utcnow() </code> And a pytz timezone object: <code>tz = timezone('America/St_Johns') </code> What is the proper way to convert <code>utc_time</code> to the given timezone? | I think I got it: `pytz.utc.localize(utc_time, is_dst=None).astimezone(tz)`. This line first converts the naive (time zone unaware) `utc_time` `datetime` object to a `datetime` object that contains a timezone (UTC). Then it uses the `astimezone` function to adjust the time according to the requested time zone. |
|
Java ElasticSearch None of the configured nodes are available <sep> Just downloaded and installed elasticsearch 1.3.2 in past hour Opened IP tables to port 9200 and 9300:9400 Set my computer name and ip in /etc/hosts Head Module and Paramedic Installed and running smoothly curl on localhost works flawlessy copied all jars from download into eclipse so same version client --Java-- <code>import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.index.query.QueryBuilders; public class Test{ public static void main(String[] args) { Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "elastictest").build(); TransportClient transportClient = new TransportClient(settings); Client client = transportClient.addTransportAddress(new InetSocketTransportAddress("143.79.236.xxx",9300));//just masking ip with xxx for SO Question try{ SearchResponse response = client.prepareSearch().setQuery(QueryBuilders.matchQuery("url", "twitter")).setSize(5).execute().actionGet();//bunch of urls indexed String output = response.toString(); System.out.println(output); }catch(Exception e){ e.printStackTrace(); } client.close(); } } </code> --Output-- <code>log4j:WARN No appenders could be found for logger (org.elasticsearch.plugins). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: [] at org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:298) at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:214) at org.elasticsearch.client.transport.support.InternalTransportClient.execute(InternalTransportClient.java:105) at org.elasticsearch.client.support.AbstractClient.search(AbstractClient.java:330) at org.elasticsearch.client.transport.TransportClient.search(TransportClient.java:421) at org.elasticsearch.action.search.SearchRequestBuilder.doExecute(SearchRequestBuilder.java:1097) at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:91) at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:65) at Test.main(Test.java:20) </code> Update: Now I am REALLY confused. I just pressed run in eclipse 3 times. 2 times received the error above. 1 time the search worked!?? Brand new Centos 6.5 vps, brand new jdk installed. Then installed elasticsearch, have done nothing else to box. Update: After running ./bin/elasticsearch console <code>[2014-09-18 08:56:13,694][INFO ][node ] [Acrobat] version[1.3.2], pid[2978], build[dee175d/2014-08-13T14:29:30Z] [2014-09-18 08:56:13,695][INFO ][node ] [Acrobat] initializing ... [2014-09-18 08:56:13,703][INFO ][plugins ] [Acrobat] loaded [], sites [head, paramedic] [2014-09-18 08:56:15,941][WARN ][common.network ] failed to resolve local host, fallback to loopback java.net.UnknownHostException: elasticsearchtest: elasticsearchtest: Name or service not known at java.net.InetAddress.getLocalHost(InetAddress.java:1473) at org.elasticsearch.common.network.NetworkUtils.<clinit>(NetworkUtils.java:54) at org.elasticsearch.transport.netty.NettyTransport.<init>(NettyTransport.java:204) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at org.elasticsearch.common.inject.DefaultConstructionProxyFactory$1.newInstance(DefaultConstructionProxyFactory.java:54) at org.elasticsearch.common.inject.ConstructorInjector.construct(ConstructorInjector.java:86) at org.elasticsearch.common.inject.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:98) at org.elasticsearch.common.inject.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:45) at org.elasticsearch.common.inject.InjectorImpl.callInContext(InjectorImpl.java:837) at org.elasticsearch.common.inject.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:42) at org.elasticsearch.common.inject.Scopes$1$1.get(Scopes.java:57) at org.elasticsearch.common.inject.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:45) at org.elasticsearch.common.inject.FactoryProxy.get(FactoryProxy.java:52) at org.elasticsearch.common.inject.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:45) at org.elasticsearch.common.inject.InjectorImpl.callInContext(InjectorImpl.java:837) at org.elasticsearch.common.inject.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:42) at org.elasticsearch.common.inject.Scopes$1$1.get(Scopes.java:57) at org.elasticsearch.common.inject.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:45) at org.elasticsearch.common.inject.SingleParameterInjector.inject(SingleParameterInjector.java:42) at org.elasticsearch.common.inject.SingleParameterInjector.getAll(SingleParameterInjector.java:66) at org.elasticsearch.common.inject.ConstructorInjector.construct(ConstructorInjector.java:85) at org.elasticsearch.common.inject.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:98) at org.elasticsearch.common.inject.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:45) at org.elasticsearch.common.inject.InjectorImpl.callInContext(InjectorImpl.java:837) at org.elasticsearch.common.inject.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:42) at org.elasticsearch.common.inject.Scopes$1$1.get(Scopes.java:57) at org.elasticsearch.common.inject.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:45) at org.elasticsearch.common.inject.SingleParameterInjector.inject(SingleParameterInjector.java:42) at org.elasticsearch.common.inject.SingleParameterInjector.getAll(SingleParameterInjector.java:66) at org.elasticsearch.common.inject.ConstructorInjector.construct(ConstructorInjector.java:85) at org.elasticsearch.common.inject.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:98) at org.elasticsearch.common.inject.FactoryProxy.get(FactoryProxy.java:52) at org.elasticsearch.common.inject.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:45) at org.elasticsearch.common.inject.InjectorImpl.callInContext(InjectorImpl.java:837) at org.elasticsearch.common.inject.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:42) at org.elasticsearch.common.inject.Scopes$1$1.get(Scopes.java:57) at org.elasticsearch.common.inject.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:45) at org.elasticsearch.common.inject.SingleParameterInjector.inject(SingleParameterInjector.java:42) at org.elasticsearch.common.inject.SingleParameterInjector.getAll(SingleParameterInjector.java:66) at org.elasticsearch.common.inject.ConstructorInjector.construct(ConstructorInjector.java:85) at org.elasticsearch.common.inject.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:98) at org.elasticsearch.common.inject.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:45) at org.elasticsearch.common.inject.InjectorImpl.callInContext(InjectorImpl.java:837) at org.elasticsearch.common.inject.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:42) at org.elasticsearch.common.inject.Scopes$1$1.get(Scopes.java:57) at org.elasticsearch.common.inject.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:45) at org.elasticsearch.common.inject.InjectorBuilder$1.call(InjectorBuilder.java:200) at org.elasticsearch.common.inject.InjectorBuilder$1.call(InjectorBuilder.java:193) at org.elasticsearch.common.inject.InjectorImpl.callInContext(InjectorImpl.java:830) at org.elasticsearch.common.inject.InjectorBuilder.loadEagerSingletons(InjectorBuilder.java:193) at org.elasticsearch.common.inject.InjectorBuilder.injectDynamically(InjectorBuilder.java:175) at org.elasticsearch.common.inject.InjectorBuilder.build(InjectorBuilder.java:110) at org.elasticsearch.common.inject.Guice.createInjector(Guice.java:93) at org.elasticsearch.common.inject.Guice.createInjector(Guice.java:70) at org.elasticsearch.common.inject.ModulesBuilder.createInjector(ModulesBuilder.java:59) at org.elasticsearch.node.internal.InternalNode.<init>(InternalNode.java:192) at org.elasticsearch.node.NodeBuilder.build(NodeBuilder.java:159) at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:70) at org.elasticsearch.bootstrap.Bootstrap.main(Bootstrap.java:203) at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:32) Caused by: java.net.UnknownHostException: elasticsearchtest: Name or service not known at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:901) at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1293) at java.net.InetAddress.getLocalHost(InetAddress.java:1469) ... 62 more [2014-09-18 08:56:16,937][INFO ][node ] [Acrobat] initialized [2014-09-18 08:56:16,937][INFO ][node ] [Acrobat] starting ... [2014-09-18 08:56:17,110][INFO ][transport ] [Acrobat] bound_address {inet[/0:0:0:0:0:0:0:0:9300]}, publish_address {inet[/143.79.236.31:9300]} [2014-09-18 08:56:17,126][INFO ][discovery ] [Acrobat] elastictest/QvSNFajjQ9SFjU7WOdjaLw [2014-09-18 08:56:20,145][INFO ][cluster.service ] [Acrobat] new_master [Acrobat][QvSNFajjQ9SFjU7WOdjaLw][localhost][inet[/143.79.236.31:9300]], reason: zen-disco-join (elected_as_master) [2014-09-18 08:56:20,212][INFO ][http ] [Acrobat] bound_address {inet[/0:0:0:0:0:0:0:0:9200]}, publish_address {inet[/143.79.236.31:9200]} [2014-09-18 08:56:20,214][INFO ][node ] [Acrobat] started </code> --cluster config in elasticsearch.yml-- <code>################################### Cluster ################################### # Cluster name identifies your cluster for auto-discovery. If you're running # multiple clusters on the same network, make sure you're using unique names. # cluster.name: elastictest </code> | Possible problems:
* **Wrong port:** If you use a Java or Scala client, the correct port is `9300`, not `9200`.
* **Wrong cluster name:** Make sure the cluster name you set in your code is the same as the `cluster.name` you set in `$ES_HOME/config/elasticsearch.yml`.
* **Sniff option:** Set `client.transport.sniff` to `true`.
* **Can't connect to all nodes:** If you can't connect to all nodes in the ES cluster, this can also cause the problem. See the ES documentation for more information. |